Instruction:
Can you tell what is the following Python 3 function doing
def format_repr(obj, attributes) -> str:

    attribute_repr = ', '.join(('{}={}'.format(attr, repr(getattr(obj, attr)))
                                for attr in attributes))
    return "{0}({1})".format(obj.__class__.__qualname__, attribute_repr)

Response: Format an object s repr method with specific attributes.


Instruction:
Write a Python 3 function that can
build a list of the decription of all the inputs of an object that have user defined parameters.

Response:
def build_parameter_descriptions(obj, user_p=None, output="csv", show_none=True, ignore=None, plist=None):
    """
    Creates a list of the decription of all the inputs of an object

    :param obj: object, that has parameters
    :param user_p: dict, user defined parameter descriptions
    :param show_none: if false, only shows descriptions of parameters that are not None
    :param ignore: list of parameters to not build
    :return:
    """
    if user_p is None:
        user_p = {}
    if ignore is None:
        ignore = []
    para = [[obj.__class__.__name__ + " inputs:", "", ""]]
    if plist is None:
        if not hasattr(obj, 'inputs'):
            raise exceptions.ModelError("Object must contain parameter 'inputs' or set plist as an input")
        plist = obj.inputs

    p_dict = {}
    if hasattr(obj, 'ancestor_types'):
        bt = obj.ancestor_types
        for otype in bt:  # cycles from lowest class, so descriptions get overridden
            if otype in vp:
                for item in vp[otype]:
                    p_dict[item] = vp[otype][item]
        for item in user_p:  # user defined definitions override base ones
            p_dict[item] = user_p[item]
    else:
        p_dict = user_p

    for item in plist:
        if show_none is False and getattr(obj, item) is None:
            continue
        if item in ignore:
            continue
        if item in p_dict:
            para.append([item, p_dict[item][1], p_dict[item][0]])
        else:
            para.append([item, "", ""])
    if output == "csv":
        out_obj = []
        for i in range(len(para)):
            out_obj.append(",".join(para[i]))
    elif output == "list":
        out_obj = para
    elif output == "dict":
        out_obj = OrderedDict()
        for i in range(len(para)):
            out_obj[para[i][0]] = {"description": para[i][2], "units": para[i][1]}
    else:
        raise ValueError("output must be either: 'csv', 'dict' or 'list'.")
    return out_obj


Instruction:
Can you tell what is the following Python 3 function doing
def all_descriptions():
    para = []
    para += build_parameter_descriptions(models.Soil()) + [",,\n"]
    para += build_parameter_descriptions(models.SoilProfile()) + [",,\n"]
    para += build_parameter_descriptions(models.Foundation()) + [",,\n"]
    para += build_parameter_descriptions(models.PadFoundation()) + [",,\n"]
    para += build_parameter_descriptions(models.SDOFBuilding()) + [",,\n"]
    para += build_parameter_descriptions(models.FrameBuilding2D(1, 1))

    return para

Response: Generates a list of descriptions of all the models


Instruction:
Write a Python 3 script for
plotting shapes from table or data frame where each row corresponds to a vertex of .

Response:
def plot_shapes(df_shapes, shape_i_columns, axis=None, autoxlim=True,
                autoylim=True, **kwargs):
    '''
    Plot shapes from table/data-frame where each row corresponds to a vertex of
    a shape.  Shape vertices are grouped by `shape_i_columns`.

    For example, consider the following dataframe:

            shape_i  vertex_i  x          y
        0   0        0         81.679949  264.69306
        1   0        1         81.679949  286.51788
        2   0        2         102.87004  286.51788
        3   0        3         102.87004  264.69306
        4   1        0         103.11417  264.40011
        5   1        1         103.11417  242.72177
        6   1        2         81.435824  242.72177
        7   1        3         81.435824  264.40011
        8   2        0         124.84134  264.69306
        9   2        1         103.65125  264.69306
        10  2        2         103.65125  286.37141
        11  2        3         124.84134  286.37141

    This dataframe corresponds to three shapes, with (ordered) shape vertices
    grouped by `shape_i`.  Note that the column `vertex_i` is not required.
    '''
    if axis is None:
        fig, axis = plt.subplots()
    props = itertools.cycle(mpl.rcParams['axes.prop_cycle'])
    color = kwargs.pop('fc', None)

    # Cycle through default colors to set face color, unless face color was set
    # explicitly.
    patches = [Polygon(df_shape_i[['x', 'y']].values, fc=props.next()['color']
                       if color is None else color, **kwargs)
               for shape_i, df_shape_i in df_shapes.groupby(shape_i_columns)]

    collection = PatchCollection(patches)

    axis.add_collection(collection)

    xy_stats = df_shapes[['x', 'y']].describe()
    if autoxlim:
        axis.set_xlim(*xy_stats.x.loc[['min', 'max']])
    if autoylim:
        axis.set_ylim(*xy_stats.y.loc[['min', 'max']])
    return axis


Instruction:
Can you write a function in Python 3 where it
plots the polygon shapes colored based on values mapped onto the color map.

Response:
def plot_shapes_heat_map(df_shapes, shape_i_columns, values, axis=None,
                         vmin=None, vmax=None, value_formatter=None,
                         color_map=None):
    '''
    Plot polygon shapes, colored based on values mapped onto
    a colormap.

    Args
    ----

        df_shapes (pandas.DataFrame) : Polygon table containing
            the columns `'id', 'x', 'y'`.  Coordinates must be
            ordered to be grouped by `'id'`.
        values (pandas.Series) : Numeric values indexed by `'id'`.
            These values are used to look up color in the color map.
        axis : A matplotlib axis.  If `None`, an axis is created.
        vmin : Minimum value to clip values at.
        vmax : Maximum value to clip values at.
        color_map : A matplotlib color map (see `matplotlib.cm`).

    Returns
    -------

        (tuple) : First element is heat map axis, second element
            is colorbar axis.
    '''
    df_shapes = df_shapes.copy()

    # Matplotlib draws from bottom to top, so invert `y` coordinates.
    df_shapes.loc[:, 'y'] = df_shapes.y.max() - df_shapes.y.copy().values

    aspect_ratio = ((df_shapes.x.max() - df_shapes.x.min()) /
                    (df_shapes.y.max() - df_shapes.y.min()))

    if vmin is not None or vmax is not None:
        norm = mpl.colors.Normalize(vmin=vmin or min(values),
                                    vmax=vmax or max(values))
    else:
        norm = None

    if axis is None:
        fig, axis = plt.subplots(figsize=(10, 10 * aspect_ratio))
    else:
        fig = axis.get_figure()

    patches = OrderedDict([(id, Polygon(df_shape_i[['x', 'y']].values))
                           for id, df_shape_i in
                           df_shapes.groupby(shape_i_columns)])
    patches = pd.Series(patches)

    collection = PatchCollection(patches.values, cmap=color_map,
                                 norm=norm)
    collection.set_array(values.ix[patches.index])

    axis.add_collection(collection)

    axis_divider = make_axes_locatable(axis)

    # Append color axis to the right of `axis`, with 10% width of `axis`.
    color_axis = axis_divider.append_axes("right", size="10%", pad=0.05)

    colorbar = fig.colorbar(collection, format=value_formatter,
                            cax=color_axis)

    tick_labels = colorbar.ax.get_yticklabels()
    if vmin is not None:
        tick_labels[0] = '$\leq$%s' % tick_labels[0].get_text()
    if vmax is not None:
        tick_labels[-1] = '$\geq$%s' % tick_labels[-1].get_text()
    colorbar.ax.set_yticklabels(tick_labels)

    axis.set_xlim(df_shapes.x.min(), df_shapes.x.max())
    axis.set_ylim(df_shapes.y.min(), df_shapes.y.max())
    return axis, colorbar


Instruction:
Can you generate the documentation for the following Python 3 function
def plot_color_map_bars(values, vmin=None, vmax=None, color_map=None,
                        axis=None, **kwargs):
    '''
    Plot bar for each value in `values`, colored based on values mapped onto
    the specified color map.

    Args
    ----

        values (pandas.Series) : Numeric values to plot one bar per value.
        axis : A matplotlib axis.  If `None`, an axis is created.
        vmin : Minimum value to clip values at.
        vmax : Maximum value to clip values at.
        color_map : A matplotlib color map (see `matplotlib.cm`).
        **kwargs : Extra keyword arguments to pass to `values.plot`.

    Returns
    -------

        (axis) : Bar plot axis.
    '''
    if axis is None:
        fig, axis = plt.subplots()

    norm = mpl.colors.Normalize(vmin=vmin or min(values),
                                vmax=vmax or max(values), clip=True)
    if color_map is None:
        color_map = mpl.rcParams['image.cmap']
    colors = color_map(norm(values.values).filled())

    values.plot(kind='bar', ax=axis, color=colors, **kwargs)
    return axis

Response: Plots a series of numeric values on a matplotlib axis colored based on values mapped onto the specified color map.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def find_in_paths(name, paths):
    for path in paths:
        file_ = osp.join(path, name)
        if osp.exists(file_) and not osp.isdir(file_):
            abs_file = osp.abspath(file_)
            if os.access(file_, os.X_OK):
                return abs_file

Response: Find an executable is a list of directories


Instruction:
Given the following Python 3 function, write the documentation
def find_executable(name, names=None, required=True):
    path_from_env = os.environ.get(name.upper())
    if path_from_env is not None:
        return path_from_env
    names = [name] + (names or [])
    for _name in names:
        if osp.isabs(_name):
            return _name
        paths = os.environ.get('PATH', '').split(os.pathsep)
        eax = find_in_paths(_name, paths)
        if eax:
            return eax
    if required:
        raise NameError('Could not find %s executable' % name)
    else:
        return name

Response: Utility function to find an executable in PATH


Instruction:
Write a Python 3 script for
getting cpus identifiers for instance set([ 0 1 2 3 )

Response:
def physical_cpus():
    """Get cpus identifiers, for instance set(["0", "1", "2", "3"])

    :return Number of physical CPUs available
    :rtype: int
    """
    if platform.system() == 'Darwin':
        ncores = subprocess.check_output(
            ['/usr/sbin/sysctl', '-n', 'hw.ncpu'], shell=False
        )
        return int(ncores.strip())

    sockets = set()
    with open('/proc/cpuinfo') as istr:
        for line in istr:
            if line.startswith('physical id'):
                sockets.add(line.split(':')[-1].strip())
    return len(sockets)


Instruction:
How would you explain what the following Python 3 function does
def showLayer(self, title='', debugText=''):
		img = PIL.Image.fromarray(self.data, 'RGBA')
		if debugText!='':
			draw = PIL.ImageDraw.Draw(img)
			font = PIL.ImageFont.truetype("DejaVuSansMono.ttf", 24)
			draw.text((0, 0),debugText,(255,255,255),font=font)
		img.show(title=title)

Response: Shows the single layer.


Instruction:
Given the following Python 3 function, write the documentation
def make_converters(data_types) -> dict:

    return {k: TYPE_CASTERS.get(v, v) for k, v in data_types.items()}

Response:
Returns a mapping between data type names and casting functions and
    or class definitions to convert text into its Python object.


Instruction:
Explain what the following Python 3 code does
def parse_broken_json(json_text: str) -> dict:

    # Add spacing between Key and Value to prevent parsing error
    json_text = json_text.replace(":", ": ")
    json_dict = yaml.load(json_text)

    return json_dict

Response: Parses broken JSON that the standard Python JSON module cannot parse.


Instruction:
Can you write a function in Python 3 where it
creates shell - script in charge of executing the benchmark and return its path.

Response:
def _executor_script(self):
        """Create shell-script in charge of executing the benchmark
        and return its path.
        """
        fd, path = tempfile.mkstemp(suffix='.sh', dir=os.getcwd())
        os.close(fd)
        with open(path, 'w') as ostr:
            self._write_executor_script(ostr)
        mode = os.stat(path).st_mode
        os.chmod(path, mode | stat.S_IEXEC | stat.S_IRGRP | stat.S_IRUSR)
        return path


Instruction:
How would you implement a function in Python 3 that
returns the Jinja template of the shell - script executor

Response:
def _jinja_executor_template(self):
        """:return Jinja template of the shell-script executor"""
        template = self.campaign.process.executor_template
        if template.startswith('#!'):
            return jinja_environment.from_string(template)
        else:
            return jinja_environment.get_template(template)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _write_executor_script(self, ostr):
        environment = self.execution.get('environment') or {}
        if not isinstance(environment, Mapping):
            msg = 'Expected mapping for environment but got '
            msg += str(type(environment))
            raise Exception(msg)
        escaped_environment = dict(
            (var, six.moves.shlex_quote(str(value)))
            for var, value in environment.items()
        )
        modules = self.execution.get('modules') or []
        properties = dict(
            command=self.command,
            cwd=os.getcwd(),
            modules=modules,
            environment=escaped_environment,
        )
        self._jinja_executor_template.stream(**properties).dump(ostr)

Response: Write the shell script in charge of executing the command


Instruction:
Make a summary of the following Python 3 code
def command(self):
        exec_prefix = self.parent.parent.parent.config.get('exec_prefix', [])
        command = self.execution['command']
        if isinstance(command, SEQUENCES):
            command = [arg.format(**self.command_expansion_vars) for arg in command]
        else:
            command = command.format(**self.command_expansion_vars)
        if self.execution.get('shell', False):
            if not isinstance(exec_prefix, six.string_types):
                exec_prefix = ' '.join(exec_prefix)
            if not isinstance(command, six.string_types):
                msg = "Expected string for shell command, not {type}: {value}"
                msg = msg.format(type=type(command).__name__, value=repr(command))
                raise Exception(msg)
            eax = [exec_prefix + command]
        else:
            if not isinstance(exec_prefix, SEQUENCES):
                exec_prefix = shlex.split(exec_prefix)
            if not isinstance(command, SEQUENCES):
                eax = exec_prefix + shlex.split(command)
            else:
                eax = exec_prefix + command
            eax = [six.moves.shlex_quote(arg) for arg in eax]
        return eax

Response: return command to execute inside the generated shell - script


Instruction:
How would you explain what the following Python 3 function does
def command_str(self):
        if isinstance(self.command, six.string_types):
            return self.command
        return ' '.join(map(six.moves.shlex_quote, self.command))

Response: get command to execute properly escaped


Instruction:
Create a Python 3 function for
building popen object to run

Response:
def popen(self, stdout, stderr):
        """Build popen object to run

        :rtype: subprocess.Popen
        """
        self.logger.info('Executing command: %s', self.command_str)
        return subprocess.Popen([self._executor_script], stdout=stdout, stderr=stderr)


Instruction:
Given the following Python 3 function, write the documentation
def srun_cartesian_product(cls, campaign, config):
        options = copy.copy(cls.common_srun_options(campaign))
        options.update(config.get('srun') or {})
        options_tuple = []
        for k, v in options.items():
            if not isinstance(v, SEQUENCES):
                v = [v]
            options_tuple.append([(k, e) for e in v])
        return [dict(combination) for combination in itertools.product(*options_tuple)]

Response: returns a list of dicts with the srun options for a given campaign and configuration


Instruction:
How would you implement a function in Python 3 that
gets path to srun executable

Response:
def srun(self):
        """Get path to srun executable

        :rtype: string
        """
        commands = self.campaign.process.get('commands', {})
        srun = find_executable(commands.get('srun', 'srun'))
        if six.PY2:
            srun = srun.encode('utf-8')
        return srun


Instruction:
Given the following Python 3 function, write the documentation
def common_srun_options(cls, campaign):
        default = dict(campaign.process.get('srun') or {})
        default.update(output='slurm-%N-%t.stdout', error='slurm-%N-%t.error')
        return default

Response: Get options to be given to all srun commands


Instruction:
Can you tell what is the following Python 3 function doing
def command(self):
        srun_optlist = build_slurm_arguments(self.parent.command.srun or {})
        if not isinstance(self.root.network.nodes(self.tag), ConstraintTag):
            pargs = parse_constraint_in_args(srun_optlist)
            self.command_expansion_vars['process_count'] = pargs.ntasks
            if not pargs.constraint:
                # Expand nodelist if --constraint option is not specified
                # in srun options
                srun_optlist += [
                    '--nodelist=' + ','.join(self.srun_nodes),
                    '--nodes=' + str(len(self.srun_nodes)),
                ]
        command = super(SrunExecutionDriver, self).command
        return [self.srun] + srun_optlist + command

Response:
get command to execute
MimeType


Instruction:
Can you write a function in Python 3 where it
gets list of nodes where to execute the command

Response:
def srun_nodes(self):
        """Get list of nodes where to execute the command
        """
        count = self.execution.get('srun_nodes', 0)
        if isinstance(count, six.string_types):
            tag = count
            count = 0
        elif isinstance(count, SEQUENCES):
            return count
        else:
            assert isinstance(count, int)
            tag = self.tag
        nodes = self._srun_nodes(tag, count)
        if 'srun_nodes' in self.execution:
            self.execution['srun_nodes'] = nodes
            self.execution['srun_nodes_count'] = len(nodes)
        return nodes


Instruction:
Implement a Python 3 function for
cleaning up a graph by removing it

Response:
def clear_graph(identifier=None):
    """ Clean up a graph by removing it

    :param identifier: Root identifier of the graph
    :return:
    """
    graph = get_graph()
    if identifier:
        graph.destroy(identifier)
    try:
        graph.close()
    except:
        warn("Unable to close the Graph")


Instruction:
Can you tell what is the following Python 3 function doing
def generate_alchemy_graph(alchemy_uri, prefixes=None, identifier="NautilusSparql"):
    registerplugins()
    ident = URIRef(identifier)
    uri = Literal(alchemy_uri)
    store = plugin.get("SQLAlchemy", Store)(identifier=ident)
    graph = Graph(store, identifier=ident)
    graph.open(uri, create=True)

    for prefix, ns in (prefixes or GRAPH_BINDINGS).items():
        if prefix == "":
            prefix = "cts"  # Fix until ALchemy Store accepts empty prefixes
        graph.bind(prefix, ns)

    return graph, identifier, uri

Response: Generate a graph and change the global graph to this one


Instruction:
Write a Python 3 script for
generating a Graph object and bind it to the one we have

Response:
def generate_sleepy_cat_graph(filepath, prefixes=None, identifier="NautilusSparql"):
    """ Generate a graph and change the global graph to this one

    :param filepath: A Uri for the graph
    :param prefixes: A dictionary of prefixes and namespaces to bind to the graph
    :param identifier: An identifier that will identify the Graph root
    """
    registerplugins()
    ident = URIRef(identifier)
    graph = Graph('Sleepycat', identifier=ident)
    graph.open(filepath, create=True)

    for prefix, ns in (prefixes or GRAPH_BINDINGS).items():
        if prefix == "":
            prefix = "cts"  # Fix until ALchemy Store accepts empty prefixes
        graph.bind(prefix, ns)

    return graph, identifier, filepath


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_label(self, label, lang):
        try:
            self.metadata.add(SKOS.prefLabel, Literal(label, lang=lang))
            self.graph.addN([
                (self.asNode(), RDFS.label, Literal(label, lang=lang), self.graph),
            ])
        except Exception as E:
            pass

Response: Add the label of the collection in given lang


Instruction:
Can you generate the documentation for the following Python 3 function
def members(self):
        return list(
            [
                self.children_class(child)
                for child in self.graph.subjects(RDF_NAMESPACES.DTS.parent, self.asNode())
            ]
        )

Response: Returns a list of all the items in the collection.


Instruction:
Here you have a function in Python 3, explain what it does
def parent(self):
        parent = list(self.graph.objects(self.asNode(), RDF_NAMESPACES.DTS.parent))
        if parent:
            return self.parent_class(parent[0])
        return None

Response: Returns the parent of the current object


Instruction:
How would you code a function in Python 3 to
compile & Run the experiment with - O3 enabled.

Response:
def actions_for_project(self, project):
        """Compile & Run the experiment with -O3 enabled."""
        project.cflags = ["-O3", "-fno-omit-frame-pointer"]
        project.runtime_extension = time.RunWithTime(
            run.RuntimeExtension(project, self))
        return self.default_runtime_actions(project)


Instruction:
Write a Python 3 script for
converting a function return to a list of StepResults.

Response:
def to_step_result(func):
    """Convert a function return to a list of StepResults.

    All Step subclasses automatically wrap the result of their
    __call__ method's result with this wrapper.
    If the result is not a list of StepResult values, one will
    be generated.

    result of `[StepResult.OK]`, or convert the given result into
    a list.

    Args:
        func: The function to wrap.
    """

    @ft.wraps(func)
    def wrapper(*args, **kwargs):
        """Wrapper stub."""
        res = func(*args, **kwargs)
        if not res:
            res = [StepResult.OK]

        if not hasattr(res, "__iter__"):
            res = [res]
        return res

    return wrapper


Instruction:
Implement a function in Python 3 to
print the beginning and the end of a `func`.

Response:
def notify_step_begin_end(func):
    """Print the beginning and the end of a `func`."""

    @ft.wraps(func)
    def wrapper(self, *args, **kwargs):
        """Wrapper stub."""
        cls = self.__class__
        on_step_begin = cls.ON_STEP_BEGIN
        on_step_end = cls.ON_STEP_END

        for begin_listener in on_step_begin:
            begin_listener(self)

        res = func(self, *args, **kwargs)

        for end_listener in on_step_end:
            end_listener(self, func)
        return res

    return wrapper


Instruction:
Implement a Python 3 function for
logging customized stirng before & after running func.

Response:
def log_before_after(name: str, desc: str):
    """Log customized stirng before & after running func."""

    def func_decorator(f):
        """Wrapper stub."""

        @ft.wraps(f)
        def wrapper(*args, **kwargs):
            """Wrapper stub."""
            LOG.info("\n%s - %s", name, desc)
            res = f(*args, **kwargs)
            if StepResult.ERROR not in res:
                LOG.info("%s - OK\n", name)
            else:
                LOG.error("%s - ERROR\n", name)
            return res

        return wrapper

    return func_decorator


Instruction:
Can you generate the documentation for the following Python 3 function
def quickview(filename,
              noIFFT=False):
    '''
    Display processed MRI data from `.hdf5`, `.npz`, or `.dat` files.  No arguments displays the IFFT of the k-space data.  The type of file is guessed by the file extension (i.e., if extension is `.dat` then readMeasData15 will be run to get the data).

    Command-line Options:
    -nifft (no IFFT)
                 Display k-space data, log magnitude and phase plots.

    '''

    if filename.endswith('.npz'):
        data = np.load(filename)
    elif filename.endswith('.dat'):
        from rawdatarinator.readMeasDataVB15 import readMeasDataVB15 as rmd
        data = rmd(filename)
    elif filename.endswith('.mat'):
        import scipy.io
        data = scipy.io.loadmat('file.mat')
    else:
        data = h5py.File(filename,'r')

    if 'kSpace' in data:
        key = 'kSpace'
    else:
        key = 'imSpace'
        noIFFT = not noIFFT

    # Average over all the averages, use first coil
    coil = 0
    num_avgs = data[key].shape[2]
    avg = (np.squeeze(np.sum(data[key],axis=2))/num_avgs)[:,:,coil]

    if noIFFT is False:
        imData = np.fft.ifftshift(np.fft.ifft2(avg))
        plt.imshow(np.absolute(imData),cmap='gray')
        plt.title('Image Data')
    else:
        mag = np.log(np.absolute(avg))
        phase = np.angle(avg)
        f,(ax1,ax2) = plt.subplots(1,2,sharey=True)
        ax1.imshow(mag,cmap='gray')
        ax2.imshow(phase,cmap='gray')
        ax1.set_title('log(Magnitude)')
        ax2.set_title('Phase')

    plt.show()

Response: Quick view of the MRI data from. hdf5. npz or. dat files.


Instruction:
Can you implement a function in Python 3 that
returns the Greatest Common Divisor of a and b

Response:
def euclid(a, b):
    """returns the Greatest Common Divisor of a and b"""
    a = abs(a)
    b = abs(b)
    if a < b:
        a, b = b, a
    while b != 0:
        a, b = b, a % b
    return a


Instruction:
Write a Python 3 script to
return True if all the values in the list L are all co - prime otherwise returns False.

Response:
def coPrime(l):
    """returns 'True' if the values in the list L are all co-prime
       otherwise, it returns 'False'. """
    for i, j in combinations(l, 2):
        if euclid(i, j) != 1:
            return False
    return True


Instruction:
Can you generate the documentation for the following Python 3 function
def extendedEuclid(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, y, x = extendedEuclid(b % a, a)
        return g, x - (b // a) * y, y

Response:
extendedEuclid returns a tuple of three values x y z such that x is
    the GCD of a and b is extendedEuclid the GCD of b and x is extendedEuclid the GCD of a and b.


Instruction:
Can you implement a function in Python 3 that
returns the multiplicative inverse of a in modulo m as a positive value between zero and m - 1

Response:
def modInv(a, m):
    """returns the multiplicative inverse of a in modulo m as a
       positive value between zero and m-1"""
    # notice that a and m need to co-prime to each other.
    if coPrime([a, m]):
        linearCombination = extendedEuclid(a, m)
        return linearCombination[1] % m
    else:
        return 0


Instruction:
Given the following Python 3 function, write the documentation
def extractTwos(m):
    # the problem can be break down to count how many '0's are there in
    # the end of bin(m). This can be done this way: m & a stretch of '1's
    # which can be represent as (2 ** n) - 1.
    assert m >= 0
    i = 0
    while m & (2 ** i) == 0:
        i += 1
    return i, m >> i

Response:
m is a positive integer. A tuple s of integers is returned
    such that m = 2^n and d = 2^n.


Instruction:
How would you explain what the following Python 3 function does
def int2baseTwo(x):
    # repeating x >>= 1 and x & 1 will do the trick
    assert x >= 0
    bitInverse = []
    while x != 0:
        bitInverse.append(x & 1)
        x >>= 1
    return bitInverse

Response: Convert an integer x to base two.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def modExp(a, d, n):
    assert d >= 0
    assert n >= 0
    base2D = int2baseTwo(d)
    base2DLength = len(base2D)
    modArray = []
    result = 1
    for i in range(1, base2DLength + 1):
        if i == 1:
            modArray.append(a % n)
        else:
            modArray.append((modArray[i - 2] ** 2) % n)
    for i in range(0, base2DLength):
        if base2D[i] == 1:
            result *= base2D[i] * modArray[i]
    return result % n

Response: returns a ** d n


Instruction:
Make a summary of the following Python 3 code
def millerRabin(n, k):
    assert n >= 1
    # ensure n is bigger than 1
    assert k > 0
    # ensure k is a positive integer so everything down here makes sense

    if n == 2:
        return True
    # make sure to return True if n == 2

    if n % 2 == 0:
        return False
    # immediately return False for all the even numbers bigger than 2

    extract2 = extractTwos(n - 1)
    s = extract2[0]
    d = extract2[1]
    assert 2 ** s * d == n - 1

    def tryComposite(a):
        """Inner function which will inspect whether a given witness
        will reveal the true identity of n. Will only be called within
        millerRabin"""
        x = modExp(a, d, n)
        if x == 1 or x == n - 1:
            return None
        else:
            for j in range(1, s):
                x = modExp(x, 2, n)
                if x == 1:
                    return False
                elif x == n - 1:
                    return None
            return False

    for i in range(0, k):
        a = random.randint(2, n - 2)
        if tryComposite(a) == False:
            return False
    return True

Response: Returns True if n is likely a pseudo - prime and False otherwise.


Instruction:
Can you write a function in Python 3 where it
returns a list with length k + 1 showing the prime of the archive

Response:
def primeSieve(k):
    """return a list with length k + 1, showing if list[i] == 1, i is a prime
    else if list[i] == 0, i is a composite, if list[i] == -1, not defined"""

    def isPrime(n):
        """return True is given number n is absolutely prime,
        return False is otherwise."""
        for i in range(2, int(n ** 0.5) + 1):
            if n % i == 0:
                return False
        return True
    result = [-1] * (k + 1)
    for i in range(2, int(k + 1)):
        if isPrime(i):
            result[i] = 1
        else:
            result[i] = 0
    return result


Instruction:
Can you write a function in Python 3 where it
finds a pseudo prime number roughly between a and b. Raise ValueError if cannot find a pseudo prime number.

Response:
def findAPrime(a, b, k):
    """Return a pseudo prime number roughly between a and b,
    (could be larger than b). Raise ValueError if cannot find a
    pseudo prime after 10 * ln(x) + 3 tries. """
    x = random.randint(a, b)
    for i in range(0, int(10 * math.log(x) + 3)):
        if millerRabin(x, k):
            return x
        else:
            x += 1
    raise ValueError


Instruction:
Explain what the following Python 3 code does
def newKey(a, b, k):
    try:
        p = findAPrime(a, b, k)
        while True:
            q = findAPrime(a, b, k)
            if q != p:
                break
    except:
        raise ValueError

    n = p * q
    m = (p - 1) * (q - 1)

    while True:
        e = random.randint(1, m)
        if coPrime([e, m]):
            break

    d = modInv(e, m)
    return (n, e, d)

Response: Generate public and private keys for RSA encryption.


Instruction:
Explain what the following Python 3 code does
def numList2blocks(l, n):
    # Note that ASCII printable characters range is 0x20 - 0x7E
    returnList = []
    toProcess = copy.copy(l)
    ''' copy message ascii list'''
    if len(toProcess) % n != 0:
        for i in range(0, n - len(toProcess) % n):
            ''' append rand str to list'''
            toProcess.append(random.randint(32, 126))
    toProcess[len(l)] = 0  # 0 after origin message list

    ''' generate int from ascii number list'''
    for i in range(0, len(toProcess), n):
        block = 0
        for j in range(0, n):
            block += toProcess[i + j] << (8 * (n - j - 1))
        returnList.append(block)
    return returnList

Response:
Take a list of integers each between 0 and 127 and generates them
    into a list of blocks of size n using base 256.


Instruction:
Make a summary of the following Python 3 code
def blocks2numList(blocks, n):
    toProcess = copy.copy(blocks)
    returnList = []
    for numBlock in toProcess:
        inner = []
        for i in range(0, n):
            inner.append(numBlock % 256)
            numBlock >>= 8
        inner.reverse()
        returnList.extend(inner)
    return returnList

Response: inverse function of numList2blocks.


Instruction:
Implement a Python 3 function for
giving a string message public keys and blockSize encrypt using RSA algorithms.

Response:
def encrypt(message, modN, e, blockSize):
    """given a string message, public keys and blockSize, encrypt using
    RSA algorithms."""
    numList = string2numList(message)
    numBlocks = numList2blocks(numList, blockSize)  # only one block
    message = numBlocks[0]
    # return [modExp(blocks, e, modN) for blocks in numBlocks]
    return modExp(message, e, modN)


Instruction:
Implement a Python 3 function for
reversing function of encrypt

Response:
def decrypt(secret, modN, d, blockSize):
    """reverse function of encrypt"""
    numBlocks = [modExp(blocks, d, modN) for blocks in secret]
    numList = blocks2numList(numBlocks, blockSize)
    return numList2string(numList)


Instruction:
Explain what the following Python 3 code does
def match_files(files, pattern: Pattern):

    for name in files:
        if re.match(pattern, name):
            yield name

Response: Yields file name if matches a regular expression pattern.


Instruction:
Here you have a function in Python 3, explain what it does
def match_zipfile_members(zipfile_path: str, pattern: Pattern):

    with ZipFile(zipfile_path, mode='r') as zfile:
        members = zfile.namelist()

    yield from match_files(members, pattern)

Response: Match files to a pattern within a zip file s content.


Instruction:
How would you explain what the following Python 3 function does
def directory_files(path):

    for entry in os.scandir(path):
        if not entry.name.startswith('.') and entry.is_file():
            yield entry.name

Response: Yields the names of all files in a directory.


Instruction:
Implement a function in Python 3 to
return sha256 string for group of FTP listings.

Response:
def get_file_listing_sha(listing_paths: Iterable) -> str:
    """Return sha256 string for group of FTP listings."""

    return sha256(''.join(sorted(listing_paths)).encode('utf-8')).hexdigest()


Instruction:
Can you implement a function in Python 3 that
sets the finger number to button number mapping for tap - to - click.

Response:
def set_button_map(self, button_map):
		"""Set the finger number to button number mapping for tap-to-click.

		The default mapping on most devices is to have a 1, 2 and 3 finger tap
		to map to the left, right and middle button, respectively. A device may
		permit changing the button mapping but disallow specific maps. In this
		case :attr:`~libinput.constant.ConfigStatus.UNSUPPORTED` is returned,
		the caller is expected to handle this case correctly.

		Changing the button mapping may not take effect immediately, the device
		may wait until it is in a neutral state before applying any changes.

		The mapping may be changed when tap-to-click is disabled. The new
		mapping takes effect when tap-to-click is enabled in the future.

		If :attr:`finger_count` is 0, this method raises :exc:`AssertionError`.

		Args:
			button_map (~libinput.constant.TapButtonMap): The new
				finger-to-button number mapping.
		Returns:
			~libinput.constant.ConfigStatus: A config status code.
		Raises:
			AssertionError
		"""

		assert self.finger_count > 0, 'This device does not support tapping'
		return self._libinput.libinput_device_config_tap_set_button_map(
			self._handle, button_map)


Instruction:
Given the following Python 3 function, write the documentation
def set_matrix(self, matrix):

		matrix = (c_float * 6)(*matrix)
		return self._libinput.libinput_device_config_calibration_set_matrix(
			self._handle, matrix)

Response: This function applies the 3x3 transformation matrix to absolute device coordinates.


Instruction:
How would you explain what the following Python 3 function does
def matrix(self):

		matrix = (c_float * 6)()
		rc = self._libinput.libinput_device_config_calibration_get_matrix(
			self._handle, matrix)
		return rc, tuple(matrix)

Response: Returns the current calibration matrix for this device.


Instruction:
Explain what the following Python 3 code does
def name(self):

		pchar = self._libinput.libinput_device_get_name(self._handle)
		return string_at(pchar).decode()

Response:
The descriptive device name as advertised by the kernel
	and or the hardware itself.


Instruction:
Create a Python 3 function to
change the logical seat name associated with this device.

Response:
def set_seat_logical_name(self, seat):
		"""Change the logical seat associated with this device by removing
		the device and adding it to the new seat.

		This command is identical to physically unplugging the device, then
		re-plugging it as a member of the new seat. libinput will generate
		a :attr:`~libinput.constant.EventType.DEVICE_REMOVED` event and this
		:class:`Device` is considered removed from the context; it will not
		generate further events.
		A :attr:`~libinput.constant.EventType.DEVICE_ADDED` event is
		generated with a new :class:`Device`. It is the caller's
		responsibility to update references to the new device accordingly.

		If the logical seat name already exists in the device's physical seat,
		the device is added to this seat. Otherwise, a new seat is created.

		Note:
			This change applies to this device until removal or
			:meth:`~libinput.LibInput.suspend`, whichever happens earlier.
		Args:
			seat (str): The new logical seat name.
		Raises:
			AssertionError
		"""

		rc = self._libinput.libinput_device_set_seat_logical_name(
			self._handle, seat.encode())
		assert rc == 0, 'Cannot assign device to {}'.format(seat)


Instruction:
Write a Python 3 function for
checking if this device has a given button.

Response:
def has_button(self, button):
		"""Check if this device has a given button.

		Args:
			button (int): Button to check for, see ``input.h`` for button
				definitions.
		Returns:
			bool: :obj:`True` if the device has this button, :obj:`False` if
			it does not.
		Raises:
			AssertionError
		"""

		rc = self._libinput.libinput_device_pointer_has_button(
			self._handle, button)
		assert rc >= 0, 'This device is not a pointer device'
		return bool(rc)


Instruction:
Implement a Python 3 function for
checking if a keyboard device has a given key.

Response:
def has_key(self, key):
		"""Check if a :attr:`~libinput.constant.DeviceCapability.KEYBOARD`
		device has a given key.

		Args:
			key (int): Key to check for, see ``input.h`` for key definitions.
		Returns:
			bool: :obj:`True` if the device has this key, :obj:`False` if
			it does not.
		Raises:
			AssertionError
		"""

		rc = self._libinput.libinput_device_keyboard_has_key(self._handle, key)
		assert rc >= 0, 'This device is not a keyboard device'
		return bool(rc)


Instruction:
Can you generate the documentation for the following Python 3 function
def num_rings(self):

		num = self._libinput.libinput_device_tablet_pad_get_num_rings(
			self._handle)
		if num < 0:
			raise AttributeError('This device is not a tablet pad device')
		return num

Response:
The number of rings a device with
	the : attr : ~libinput. constant. DeviceCapability. TABLET_PAD_HAS_RINGS.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def num_strips(self):

		num = self._libinput.libinput_device_tablet_pad_get_num_strips(
			self._handle)
		if num < 0:
			raise AttributeError('This device is not a tablet pad device')
		return num

Response:
The number of strips a device with
	the : attr : ~libinput. DeviceCapability. TABLET_PAD_HAS_STRIPS.


Instruction:
Explain what the following Python 3 code does
def num_mode_groups(self):

		num = self._libinput.libinput_device_tablet_pad_get_num_mode_groups(
			self._handle)
		if num < 0:
			raise AttributeError('This device is not a tablet pad device')
		return num

Response: Returns the number of mode groups available on this device.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_mode_group(self, group):

		hmodegroup = self._libinput.libinput_device_tablet_pad_get_mode_group(
			self._handle, group)
		if hmodegroup:
			return TabletPadModeGroup(hmodegroup, self._libinput)
		return None

Response: Returns the mode group with the given index or None if the group is invalid.


Instruction:
Write a Python 3 script for
returning the logical name of the seat.

Response:
def logical_name(self):
		"""The logical name of the seat.

		This is an identifier to group sets of devices within the compositor.

		Returns:
			str: The logical name of this seat.
		"""

		pchar = self._libinput.libinput_seat_get_logical_name(self._handle)
		return string_at(pchar).decode()


Instruction:
Here you have a function in Python 3, explain what it does
def configure():
    log_levels = {
        5: logging.NOTSET,
        4: logging.DEBUG,
        3: logging.INFO,
        2: logging.WARNING,
        1: logging.ERROR,
        0: logging.CRITICAL
    }

    logging.captureWarnings(True)
    root_logger = logging.getLogger()
    if settings.CFG["debug"]:
        details_format = logging.Formatter(
            '%(name)s (%(filename)s:%(lineno)s) [%(levelname)s] %(message)s')
        details_hdl = logging.StreamHandler()
        details_hdl.setFormatter(details_format)
        root_logger.addHandler(details_hdl)
    else:
        brief_format = logging.Formatter('%(message)s')
        console_hdl = logging.StreamHandler()
        console_hdl.setFormatter(brief_format)
        root_logger.addHandler(console_hdl)
    root_logger.setLevel(log_levels[int(settings.CFG["verbosity"])])

    configure_plumbum_log()
    configure_migrate_log()
    configure_parse_log()

Response: Load logging configuration from our own defaults.


Instruction:
How would you explain what the following Python 3 function does
def get_number(self):
        '''
        .. versionchanged:: 0.9.2
            Add support for float exponent strings (e.g., ``3.435e-7``).

            Fixes `issue #4 <https://github.com/wheeler-microfluidics/svg-model/issues/4>`.
        '''
        number = None
        start = self.get_char('0123456789.-')
        if start:
            number = start
            finish = self.get_chars('-e0123456789.')
            if finish:
                number += finish
        if any(c in number for c in '.e'):
            return float(number)
        else:
            return int(number)

Response: Get the number of the ISO - 8601 ISO - 8601 ISO - 8601 ISO - 8601.


Instruction:
How would you explain what the following Python 3 function does
def to_tuples(self, data):
        '''
        path_data : string, from an svg path tag's 'd' attribute, eg:
            'M 46,74 L 35,12 l 53,-13 z'
        returns the same data collected in a list of tuples, eg:
            [ ('M', 46, 74), ('L', 35, 12), ('l', 53, -13), ('z') ],
        The input data may have floats instead of ints, this will be reflected
        in the output. The input may have its whitespace stripped out, or its
        commas replaced by whitespace.
        '''
        self.data = data
        self.pos = 0
        parsed = []
        command = []

        while self.pos < len(self.data):
            indicator = self.data[self.pos]
            if indicator == ' ':
                self.pos += 1
            elif indicator == ',':
                if len(command) >= 2:
                    self.pos += 1
                else:
                    msg = 'unexpected comma at %d in %r' % (self.pos, self.data)
                    raise ParseError(msg)
            elif indicator in '0123456789.-':
                if command:
                    command.append(self.get_number())
                else:
                    msg = 'missing command at %d in %r' % (self.pos, self.data)
                    raise ParseError(msg)
            else:
                if command:
                    parsed.append(tuple(command))
                command = [indicator]
                self.pos += 1

        if command:
            parsed.append(tuple(command))

        if parsed[0][0] == 'M' and parsed[-1][0] == 'L'\
                and parsed[0][1:] == parsed[-1][1:]:
            parsed[-1] = ('z',)
        return parsed

Response: Parse the data into a list of tuples.


Instruction:
Write a Python 3 function that can
convert a list of command characters to a list of loops.

Response:
def to_loops(self, commands):
        '''
        commands : list of tuples, as output from to_tuples() method, eg:
            [('M', 1, 2), ('L', 3, 4), ('L', 5, 6), ('z')]
        Interprets the command characters at the start of each tuple to return
        a list of loops, where each loop is a closed list of verts, and each
        vert is a pair of ints or floats, eg:
            [[1, 2, 3, 4, 5, 6]]
        Note that the final point of each loop is eliminated if it is equal to
        the first.
        SVG defines commands:
            M x,y: move, start a new loop
            L x,y: line, draw boundary
            H x: move horizontal
            V y: move vertical
            Z: close current loop - join to start point
        Lower-case command letters (eg 'm') indicate a relative offset.
        See http://www.w3.org/TR/SVG11/paths.html
        '''
        lookup = {
            'M': self.onMove,
            'L': self.onLine,
            'H': self.onHorizontalMove,
            'h': self.onHorizontalMove,
            'V': self.onVerticalMove,
            'v': self.onVerticalMove,
            'Z': self.onClose,
            'z': self.onClose,
        }
        self.loops = []
        self.current_loop = None

        for command in commands:
            action = command[0]
            if action in lookup:
                lookup[action](command)
            else:
                self.onBadCommand(action)
        return self.loops


Instruction:
Implement a function in Python 3 to
parse a color string into a tuple of integers.

Response:
def parse_color(self, color):
        '''
        color : string, eg: '#rrggbb' or 'none'
        (where rr, gg, bb are hex digits from 00 to ff)
        returns a triple of unsigned bytes, eg: (0, 128, 255)
        '''
        if color == 'none':
            return None
        return (
            int(color[1:3], 16),
            int(color[3:5], 16),
            int(color[5:7], 16))


Instruction:
Explain what the following Python 3 code does
def parse_style(self, style):
        '''
        style : string, eg:
            fill:#ff2a2a;fill-rule:evenodd;stroke:none;stroke-width:1px;
            stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1
        returns color as a triple of unsigned bytes: (r, g, b), or None
        '''
        style_elements = style.split(';')
        while style_elements:
            element = style_elements.pop()
            if element.startswith('fill:'):
                return self.parse_color(element[5:])
        return None

Response: Parses a style string into a color tuple.


Instruction:
Write a Python 3 function that can
parse the XML tag and returns the id attribute and path attribute of the current level.

Response:
def parse(self, tag):
        '''
        returns (id, path)
        where:  'id' is the path tag's id attribute
                'path' is a populated instance of SvgPath

        >>> from lxml import etree
        >>> from lxml.builder import E
        >>> path_tag = etree.XML("""
        ...     <path id="path0"
        ...         style="fill:#0000ff;stroke:#000000;stroke-width:0.10000000000000001;stroke-miterlimit:4;stroke-dasharray:none"
        ...         d="M 525.93385,261.47322 L 525.933 85,269.65826 L 534.07239,269.65826 L 534.07239,261.47322 L 525.93385,261.47322" />
        ... """)
        >>> path_parser = PathParser()
        >>> id, svg_path = path_parser.parse(path_tag)
        >>> id
        'path0'
        >>> svg_path.color
        (0, 0, 255)
        >>> len(svg_path.loops)
        1
        >>> svg_path.loops[0].verts
        [(534.07239, 261.47322), (534.07239, 269.65826), (525.933, 85), (525.93385, 261.47322)]

        Note that only absolute commands (i.e., uppercase) are currently supported.  For example:
        paths will throw a ParseError exception.  For example:

        >>> path_tag = E.path(id="path0", d="M 636.0331,256.9345 l 636.0331,256.9345")
        >>> print etree.tostring(path_tag)
        <path d="M 636.0331,256.9345 l 636.0331,256.9345" id="path0"/>
        >>> path_parser.parse(path_tag)
        Traceback (most recent call last):
        ...
        ParseError: unsupported svg path command: l
        >>>
        '''
        id = self.get_id(tag.attrib)

        parser = PathDataParser()
        path_data = tag.attrib['d']
        path_tuple = parser.to_tuples(path_data)

        tracer = LoopTracer()
        loops = tracer.to_loops(path_tuple)
        path = ColoredPath(loops)

        if 'style' in list(tag.attrib.keys()):
            style_data = tag.attrib['style']
            path.color = self.parse_style(style_data)

        return id, path


Instruction:
How would you explain what the following Python 3 function does
def _validate_response(response):
        try:
            response.raise_for_status()
        except requests.RequestException:
            raise RequestException(
                code=response.status_code,
                url=response.url,
                description=response.text)
        else:
            return response

Response: Validate the response and raise RequestException if not ok


Instruction:
How would you explain what the following Python 3 function does
def _validate_request(endpoint, file_type='json', data=None, params=None):
        if not isinstance(endpoint, string_types) or endpoint.strip() == '':
            raise ClientException("Must submit `endpoint` for DHIS2 API")
        if not isinstance(file_type, string_types) or file_type.lower() not in ('json', 'csv', 'xml', 'pdf', 'xlsx'):
            raise ClientException("Invalid file_type: {}".format(file_type))
        if params:
            if not isinstance(params, (dict, list)):
                raise ClientException("`params` must be a dict or list of tuples, not {}".format(params.__class__.__name__))
            if isinstance(params, list) and not all([isinstance(elem, tuple) for elem in params]):
                raise ClientException("`params` list must all be tuples")
        if data and not isinstance(data, dict):
            raise ClientException("`data` must be a dict, not {}".format(data.__class__.__name__))

Response: Validate request before calling API


Instruction:
Write a Python 3 function that can
make a request to DHIS2 API.

Response:
def _make_request(self, method, endpoint, **kwargs):
        """
        Do the actual request with supplied HTTP method
        :param method: HTTP method
        :param endpoint: DHIS2 API endpoint
        :param kwargs: keyword args
        :return: response if ok, RequestException if not
        """
        if isinstance(kwargs.get('file_type'), string_types):
            file_type = kwargs['file_type'].lower()
        else:
            file_type = 'json'
        params = kwargs.get('params')

        data = kwargs.get('data', kwargs.get('json', None))
        url = '{}/{}'.format(self.api_url, endpoint)
        self._validate_request(endpoint, file_type, data, params)

        if method == 'get':
            stream = kwargs.get('stream', False)
            url = '{}.{}'.format(url, file_type)
            r = self.session.get(url, params=params, stream=stream)

        elif method == 'post':
            r = self.session.post(url=url, json=data, params=params)

        elif method == 'put':
            r = self.session.put(url=url, json=data, params=params)

        elif method == 'patch':
            r = self.session.patch(url=url, json=data, params=params)

        elif method == 'delete':
            r = self.session.delete(url=url, params=params)

        else:
            raise ClientException("Non-supported HTTP method: {}".format(method))

        return self._validate_response(r)


Instruction:
Make a summary of the following Python 3 code
def get(self, endpoint, file_type='json', params=None, stream=False):
        return self._make_request('get', endpoint, params=params, file_type=file_type, stream=stream)

Response: Get from DHIS2 API


Instruction:
Given the following Python 3 function, write the documentation
def post(self, endpoint, json=None, params=None, **kwargs):
        json = kwargs['data'] if 'data' in kwargs else json
        return self._make_request('post', endpoint, data=json, params=params)

Response: POST to DHIS2 API endpoint


Instruction:
Can you generate a brief explanation for the following Python 3 code
def put(self, endpoint, json=None, params=None, **kwargs):
        json = kwargs['data'] if 'data' in kwargs else json
        return self._make_request('put', endpoint, data=json, params=params)

Response: This method is used to put a set of unique identifiers.


Instruction:
Can you tell what is the following Python 3 function doing
def patch(self, endpoint, json=None, params=None, **kwargs):
        json = kwargs['data'] if 'data' in kwargs else json
        return self._make_request('patch', endpoint, data=json, params=params)

Response: PATCH to DHIS2 API endpoint


Instruction:
Can you generate a brief explanation for the following Python 3 code
def delete(self, endpoint, json=None, params=None, **kwargs):
        json = kwargs['data'] if 'data' in kwargs else json
        return self._make_request('delete', endpoint, data=json, params=params)

Response:
DELETE from DHIS2
        :param endpoint: DHIS2 API endpoint
        :param json: HTTP payload
        :param params: HTTP parameters (dict)
        :return: requests.Response object


Instruction:
Can you generate the documentation for the following Python 3 function
def get_paged(self, endpoint, params=None, page_size=50, merge=False):
        try:
            if not isinstance(page_size, (string_types, int)) or int(page_size) < 1:
                raise ValueError
        except ValueError:
            raise ClientException("page_size must be > 1")

        params = {} if not params else params
        if 'paging' in params:
            raise ClientException("Can't set paging manually in `params` when using `get_paged`")
        params['pageSize'] = page_size
        params['page'] = 1
        params['totalPages'] = True

        collection = endpoint.split('/')[0]  # only use e.g. events when submitting events/query as endpoint

        def page_generator():
            """Yield pages"""
            page = self.get(endpoint=endpoint, file_type='json', params=params).json()
            page_count = page['pager']['pageCount']
            yield page

            while page['pager']['page'] < page_count:
                params['page'] += 1
                page = self.get(endpoint=endpoint, file_type='json', params=params).json()
                yield page

        if not merge:
            return page_generator()
        else:
            data = []
            for p in page_generator():
                data.append(p[collection])
            return {collection: list(chain.from_iterable(data))}

Response: Get all DHIS2 objects in a single page.


Instruction:
Make a summary of the following Python 3 code
def get_sqlview(self, uid, execute=False, var=None, criteria=None, merge=False):
        params = {}
        sqlview_type = self.get('sqlViews/{}'.format(uid), params={'fields': 'type'}).json().get('type')
        if sqlview_type == 'QUERY':
            if not isinstance(var, dict):
                raise ClientException("Use a dict to submit variables: e.g. var={'key1': 'value1', 'key2': 'value2'}")
            var = ['{}:{}'.format(k, v) for k, v in var.items()]
            params['var'] = var
            if execute:
                raise ClientException("SQL view of type QUERY, no view to create (no execute=True)")

        else:  # MATERIALIZED_VIEW / VIEW
            if criteria:
                if not isinstance(criteria, dict):
                    raise ClientException("Use a dict to submit criteria: { 'col1': 'value1', 'col2': 'value2' }")
                criteria = ['{}:{}'.format(k, v) for k, v in criteria.items()]
                params['criteria'] = criteria

            if execute:  # materialize
                self.post('sqlViews/{}/execute'.format(uid))

        def page_generator():
            with closing(self.get('sqlViews/{}/data'.format(uid), file_type='csv', params=params, stream=True)) as r:
                # do not need to use unicodecsv.DictReader as data comes in bytes already
                reader = DictReader(codecs.iterdecode(r.iter_lines(), 'utf-8'), delimiter=',', quotechar='"')
                for row in reader:
                    yield row

        if not merge:
            return page_generator()
        else:
            return list(page_generator())

Response: GET SQL View data


Instruction:
Can you tell what is the following Python 3 function doing
def post_partitioned(self, endpoint, json, params=None, thresh=1000):

        if not isinstance(json, dict):
            raise ClientException('Parameter `json` must be a dict')
        if not isinstance(thresh, int) or thresh < 2:
            raise ClientException("`thresh` must be integer of 2 or larger")

        try:
            key = next(iter(json))  # the (only) key in the payload
        except StopIteration:
            raise ClientException("`json` is empty")
        else:
            if len(json.keys()) != 1:
                raise ClientException('Must submit exactly one key in payload - e.g. json={"dataElements": [...]"}')
            if not json.get(key):
                raise ClientException("payload for key '{}' is empty".format(key))
            else:
                for data in partition_payload(data=json, key=key, thresh=thresh):
                    yield self.post(endpoint, json=data, params=params)

Response: Post a payload in chunks to prevent Request Entity Too Large Timeout errors


Instruction:
Can you implement a function in Python 3 that
returns a DataFrame with the 3x3 transformation matrix resulting in specified x y and scale.

Response:
def get_transform(offset, scale):
    '''
    Parameters
    ----------
    offset : pandas.Series
        Cartesian ``(x, y)`` coordinate of offset origin.
    scale : pandas.Series
        Scaling factor for ``x`` and ``y`` dimensions.

    Returns
    -------
    pandas.DataFrame
        3x3 transformation matrix resulting in specified `x/y` offset and
        scale.  **Note that third row label is ``w`` and not ``z``).**
    '''
    return pd.DataFrame([[scale, 0, offset.x], [0, scale, offset.y],
                         [0, 0, 1]], index=['x', 'y', 'w'])


Instruction:
Implement a function in Python 3 to
look up shape based on canvas coordinates.

Response:
def find_shape(self, canvas_x, canvas_y):
        '''
        Look up shape based on canvas coordinates.
        '''
        shape_x, shape_y, w = self.canvas_to_shapes_transform.dot([canvas_x,
                                                                   canvas_y,
                                                                   1])
        if hasattr(self.space, 'point_query_first'):
            # Assume `pymunk<5.0`.
            shape = self.space.point_query_first((shape_x, shape_y))
        else:
            # Assume `pymunk>=5.0`, where `point_query_first` method has been
            # deprecated.
            info = self.space.point_query_nearest((shape_x, shape_y), 0,
                                                  [pymunk.ShapeFilter
                                                   .ALL_CATEGORIES])
            shape = info.shape if info else None

        if shape:
            return self.bodies[shape.body]
        return None


Instruction:
How would you code a function in Python 3 to
return a pandas. Series indexed by shape_i_columns containing the area of each shape.

Response:
def get_shape_areas(df_shapes, shape_i_columns, signed=False):
    '''
    Return a `pandas.Series` indexed by `shape_i_columns` (i.e., each entry
    corresponds to a single shape/polygon), containing the following columns
    the area of each shape.

    If `signed=True`, a positive area value corresponds to a clockwise loop,
    whereas a negative area value corresponds to a counter-clockwise loop.
    '''
    # Make a copy of the SVG data frame since we need to add columns to it.
    df_i = df_shapes.copy()
    df_i['vertex_count'] = (df_i.groupby(shape_i_columns)['x']
                            .transform('count'))
    df_i['area_a'] = df_i.x
    df_i['area_b'] = df_i.y

    # Vector form of [Shoelace formula][1].
    #
    # [1]: http://en.wikipedia.org/wiki/Shoelace_formula
    df_i.loc[df_i.vertex_i == df_i.vertex_count - 1, 'area_a'] *= df_i.loc[df_i.vertex_i == 0, 'y'].values
    df_i.loc[df_i.vertex_i < df_i.vertex_count - 1, 'area_a'] *= df_i.loc[df_i.vertex_i > 0, 'y'].values

    df_i.loc[df_i.vertex_i == df_i.vertex_count - 1, 'area_b'] *= df_i.loc[df_i.vertex_i == 0, 'x'].values
    df_i.loc[df_i.vertex_i < df_i.vertex_count - 1, 'area_b'] *= df_i.loc[df_i.vertex_i > 0, 'x'].values

    area_components = df_i.groupby(shape_i_columns)[['area_a', 'area_b']].sum()
    shape_areas = .5 * (area_components['area_b'] - area_components['area_a'])

    if not signed:
        shape_areas.name = 'area'
        return shape_areas.abs()
    else:
        shape_areas.name = 'signed_area'
        return shape_areas


Instruction:
Can you generate the documentation for the following Python 3 function
def get_bounding_boxes(df_shapes, shape_i_columns):
    '''
    Return a `pandas.DataFrame` indexed by `shape_i_columns` (i.e., each row
    corresponds to a single shape/polygon), containing the following columns:

     - `width`: The width of the widest part of the shape.
     - `height`: The height of the tallest part of the shape.
    '''
    xy_groups = df_shapes.groupby(shape_i_columns)[['x', 'y']]
    xy_min = xy_groups.agg('min')
    xy_max = xy_groups.agg('max')

    shapes = (xy_max - xy_min).rename(columns={'x': 'width', 'y': 'height'})
    return xy_min.join(shapes)

Response: Return a pandas. DataFrame indexed by shape_i_columns containing the minimum and maximum bounding boxes of the shape.


Instruction:
Write a Python 3 function that can
return a pandas. DataFrame indexed by shape_i_columns containing the information about the shape.

Response:
def get_shape_infos(df_shapes, shape_i_columns):
    '''
    Return a `pandas.DataFrame` indexed by `shape_i_columns` (i.e., each row
    corresponds to a single shape/polygon), containing the following columns:

     - `area`: The area of the shape.
     - `width`: The width of the widest part of the shape.
     - `height`: The height of the tallest part of the shape.
    '''
    shape_areas = get_shape_areas(df_shapes, shape_i_columns)
    bboxes = get_bounding_boxes(df_shapes, shape_i_columns)
    return bboxes.join(pd.DataFrame(shape_areas))


Instruction:
Can you write a function in Python 3 where it
calculates the bounding box of all points in a data frame.

Response:
def get_bounding_box(df_points):
    '''
    Calculate the bounding box of all points in a data frame.
    '''
    xy_min = df_points[['x', 'y']].min()
    xy_max = df_points[['x', 'y']].max()

    wh = xy_max - xy_min
    wh.index = 'width', 'height'
    bbox = pd.concat([xy_min, wh])
    bbox.name = 'bounding_box'
    return bbox


Instruction:
Can you generate the documentation for the following Python 3 function
def json_decoder_hook(dct, str_decoders=STRING_DECODERS,
                      converters=MappingProxyType(dict())) -> dict:
    """Decoder for parsing typical objects like uuid's and dates."""

    for k, v in dct.items():
        if k in converters:
            parse_func = converters[k]
            dct[k] = parse_func(v)

        elif isinstance(v, str):
            for decode_func in str_decoders:
                v = decode_func(v)

                if not isinstance(v, str):
                    break

            dct[k] = v
        elif isinstance(v, collections.Mapping):
            dct[k] = json_decoder_hook(v, str_decoders, converters)

    return dct

Response: Decoder for parsing typical objects like uuid s and dates.


Instruction:
Can you tell what is the following Python 3 function doing
def make_json_decoder_hook(str_decoders=STRING_DECODERS,
                           extra_str_decoders=tuple(),
                           converters=MappingProxyType(dict())) -> Callable:
    """Customize JSON string decoder hooks.

    Object hook for typical deserialization scenarios.

    Notes
    -----
    Specifying a field in converters will ensure custom decoding/passthrough.

    Parameters
    ----------
    str_decoders: functions for decoding strings to objects.
    extra_str_decoders: appends additional string decoders to str_decoders.
    converters: field / parser function mapping.
    """

    str_decoders = tuple(chain(str_decoders, extra_str_decoders))
    object_hook = partial(json_decoder_hook, str_decoders=str_decoders,
                          converters=converters)

    return object_hook

Response: Create a JSON decoder hook for typical deserialization scenarios.


Instruction:
Can you tell what is the following Python 3 function doing
def wait_for_completion(report, interval=10):
    for jobid in report.collect('jobid'):
        try:
            if not Job.finished(jobid):
                logging.info('waiting for SLURM job %s', jobid)
                time.sleep(interval)
                while not Job.finished(jobid):
                    time.sleep(interval)
            yield Job.fromid(jobid)._asdict()
        except OSError as e:
            if e.errno == errno.ENOENT:
                yield dict(id=str(jobid))
            else:
                raise e

Response: Wait for asynchronous jobs to complete in the given campaign.


Instruction:
How would you code a function in Python 3 to
return a list of colors with one main color and two opposite color evenly spread apart from the main one.

Response:
def getColors_Triad(hue=None, sat = 1, val = 1, spread = 60):
	"""
	Create a palette with one main color and two opposite color evenly spread apart from the main one.

	:param hue: A 0-1 float with the starting hue value.
	:param sat: A 0-1 float with the palette saturation.
	:param val: A 0-1 float with the palette value.
	:param val: An int with the spread in degrees from the opposite color.
	:rtype: A list of :py:class:`Color` objects.
	"""
	palette = list()
	if hue==None:
		leadHue = randFloat(0, 1)
	else:
		leadHue = hue
	palette.append(Color(0,0,0,1).set_HSV(leadHue, sat, val))
	palette.append(Color(0,0,0,1).set_HSV((leadHue + 0.5 + spread/360) % 1, sat, val))
	palette.append(Color(0,0,0,1).set_HSV((leadHue + 0.5 - spread/360) % 1, sat, val))
	return palette


Instruction:
Can you generate a brief explanation for the following Python 3 code
def default_job_name(self):
        name = ''
        if not self.root.existing_campaign:
            campaign_file = osp.basename(self.root.campaign_file)
            campaign = osp.splitext(campaign_file)[0]
            name += campaign + '/'
        name += self.tag
        return name

Response: Returns the default job name if not already specified in the batch section.


Instruction:
Create a Python 3 function to
return the Jinja sbatch template for the current tag

Response:
def sbatch_template(self):
        """:return Jinja sbatch template for the current tag"""
        template = self.sbatch_template_str
        if template.startswith('#!'):
            # script is embedded in YAML
            return jinja_environment.from_string(template)
        return jinja_environment.get_template(template)


Instruction:
Can you write a function in Python 3 where it
returns Jinja sbatch template for the current tag as string

Response:
def sbatch_template_str(self):
        """:return Jinja sbatch template for the current tag as string"""
        templates = self.campaign.process.sbatch_template
        if isinstance(templates, Mapping):
            # find proper template according to the tag
            template = templates.get(self.tag)
            if template is None:
                template = templates.get('*')
            if template is None:
                template = SBATCH_JINJA_TEMPLATE
        else:
            template = templates
        return template


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _create_sbatch(self, ostr):
        properties = dict(
            sbatch_arguments=self.sbatch_args, hpcbench_command=self.hpcbench_cmd
        )
        try:
            self.sbatch_template.stream(**properties).dump(ostr)
        except jinja2.exceptions.UndefinedError:
            self.logger.error('Error while generating SBATCH template:')
            self.logger.error('%%<--------' * 5)
            for line in self.sbatch_template_str.splitlines():
                self.logger.error(line)
            self.logger.error('%%<--------' * 5)
            self.logger.error('Template properties: %s', properties)
            raise

Response: Write the SBATCH template to the output stream


Instruction:
Given the following Python 3 function, write the documentation
def _execute_sbatch(self):
        commands = self.campaign.process.get('commands', {})
        sbatch = find_executable(commands.get('sbatch', 'sbatch'))
        sbatch_command = [sbatch, '--parsable', self.sbatch_filename]
        try:
            self.logger.debug(
                'Executing command: %s',
                ' '.join(map(six.moves.shlex_quote, sbatch_command)),
            )
            sbatch_out = subprocess.check_output(
                sbatch_command, universal_newlines=True
            )
        except subprocess.CalledProcessError as cpe:
            self.logger.error(
                "SBATCH return non-zero exit" "status %d for tag %s",
                cpe.returncode,
                self.tag,
            )
            sbatch_out = cpe.output
        jobidre = re.compile(r'^([\d]+)(?:;\S*)?$')
        jobid = None
        for line in sbatch_out.splitlines():
            res = jobidre.match(line)
            if res is not None:
                jobid = res.group(1)
                self.logger.info("Submitted SBATCH job %s for tag %s", jobid, self.tag)
            elif line:
                self.logger.warning("SBATCH: %s", line)
        if jobid is None:
            self.logger.error("SBATCH submission failed for tag %s", self.tag)
            return -1
        else:
            return int(jobid)

Response: Execute the SBATCH command and return the job id


Instruction:
How would you code a function in Python 3 to
partition ordered sequence by key.

Response:
def partition_ordered(sequence, key=None):
    """Partition ordered sequence by key.

    Sequence is expected to already be ordered.

    Parameters
    ----------
    sequence: iterable data.
    key: partition key function

    Yields
    -------
    iterable tuple(s) of partition key, data list pairs.

    Examples
    --------
    1. By object attributes.

    Partition sequence of objects by a height and weight attributes
    into an ordered dict.

    >> attributes = ('height', 'weight')
    >> OrderedDict(partition_ordered(sequence, attrgetter(*attributes)))

    2. By index items.

    Partition sequence by the first character index of each element.

    >> index = 0
    >> sequence = ['112', '124', '289', '220', 'Z23']
    >> list(partition_ordered(sequence, itemgetter(index)))
    """

    yield from ((k, list(g)) for k, g in groupby(sequence, key=key))


Instruction:
Can you tell what is the following Python 3 function doing
def partition(predicate, iterable):

    t1, t2 = tee(iterable)

    return filterfalse(predicate, t1), filter(predicate, t2)

Response: Use a predicate to partition true and false entries.


Instruction:
Write a Python 3 function that can
create a new dynamic portage project.

Response:
def PortageFactory(name, NAME, DOMAIN, BaseClass=autoportage.AutoPortage):
    """
    Create a new dynamic portage project.

    Auto-Generated projects can only be used for compilie-time experiments,
    because there simply is no run-time test defined for it. Therefore,
    we implement the run symbol as a noop (with minor logging).

    This way we avoid the default implementation for run() that all projects
    inherit.

    Args:
        name: Name of the dynamic class.
        NAME: NAME property of the dynamic class.
        DOMAIN: DOMAIN property of the dynamic class.
        BaseClass: Base class to use for the dynamic class.

    Returns:
        A new class with NAME,DOMAIN properties set, unable to perform
        run-time tests.

    Examples:
        >>> from benchbuild.projects.gentoo.portage_gen import PortageFactory
        >>> from benchbuild.experiments.empty import Empty
        >>> c = PortageFactory("test", "NAME", "DOMAIN")
        >>> c
        <class '__main__.test'>
        >>> i = c(Empty())
        >>> i.NAME
        'NAME'
        >>> i.DOMAIN
        'DOMAIN'
    """

    def run_not_supported(self, *args, **kwargs):
        """Dynamic projects don't support a run() test."""
        del args, kwargs  # Unused

        LOG.warning(
            "Runtime testing not supported on auto-generated projects.")
        return

    newclass = type(
        name, (BaseClass, ), {
            "NAME": NAME,
            "DOMAIN": DOMAIN,
            "SRC_FILE": "none",
            "VERSION": BaseClass.VERSION,
            "GROUP": "auto-gentoo",
            "run": run_not_supported,
            "__module__": "__main__"
        })
    return newclass


Instruction:
How would you implement a function in Python 3 that
applies the units schema to the data and return the result as a pint. Quantity object

Response:
def apply_unitschema(data, uschema, as_quantity=True,
                     raise_outerr=False, convert_base=False,
                     use_wildcards=False, list_of_dicts=False):
    """ apply the unit schema to the data

    Parameters
    ----------
    data : dict
    uschema : dict
        units schema to apply
    as_quantity : bool
        if true, return values as pint.Quantity objects
    raise_outerr : bool
        raise error if a unit cannot be found in the outschema
    convert_to_base : bool
        rescale units to base units
    use_wildcards : bool
        if true, can use * (matches everything) and ? (matches any single character)
    list_of_dicts: bool
        treat list of dicts as additional branches

    Examples
    --------
    >>> from pprint import pprint

    >>> data = {'energy':1,'x':[1,2],'other':{'y':[4,5]},'y':[4,5],'meta':None}
    >>> uschema =   {'energy':'eV','x':'nm','other':{'y':'m'},'y':'cm'}
    >>> data_units = apply_unitschema(data,uschema)
    >>> pprint(data_units)
    {'energy': <Quantity(1, 'electron_volt')>,
     'meta': None,
     'other': {'y': <Quantity([4 5], 'meter')>},
     'x': <Quantity([1 2], 'nanometer')>,
     'y': <Quantity([4 5], 'centimeter')>}

    >>> newschema = {'energy':'kJ','other':{'y':'nm'},'y':'m'}
    >>> new_data = apply_unitschema(data_units,newschema)
    >>> str(new_data["energy"])
    '1.60217653e-22 kilojoule'
    >>> new_data["other"]["y"].magnitude.round(3).tolist(), str(new_data["other"]["y"].units)
    ([4000000000.0, 5000000000.0], 'nanometer')

    >>> old_data = apply_unitschema(new_data,uschema,as_quantity=False)
    >>> old_data["energy"]
    1.0
    >>> old_data["other"]["y"].round(3).tolist()
    [4.0, 5.0]

    """  # noqa: E501
    try:
        from pint import UnitRegistry
        ureg = UnitRegistry()
        from pint.quantity import _Quantity
    except ImportError:
        raise ImportError('please install pint to use this module')
    list_of_dicts = '__list__' if list_of_dicts else None

    # flatten edict
    uschema_flat = flatten(uschema, key_as_tuple=True)
    # sorted by longest key size, to get best match first
    uschema_keys = sorted(uschema_flat, key=len, reverse=True)
    data_flat = flatten(data, key_as_tuple=True, list_of_dicts=list_of_dicts)

    for dkey, dvalue in data_flat.items():
        converted = False
        for ukey in uschema_keys:

            if not len(ukey) == len(dkey[-len(ukey):]):
                continue

            if use_wildcards:
                match = all(
                    [fnmatch(d, u) for u, d in zip(ukey, dkey[-len(ukey):])])
            else:
                match = ukey == dkey[-len(ukey):]

            if match:
                # handle that it return an numpy object type if list of floats
                if isinstance(dvalue, (list, tuple)):
                    dvalue = np.array(dvalue)
                    if dvalue.dtype == np.object:
                        dvalue = dvalue.astype(float)

                if isinstance(dvalue, _Quantity):
                    quantity = dvalue.to(uschema_flat[ukey])
                else:
                    quantity = ureg.Quantity(dvalue, uschema_flat[ukey])

                if convert_base:
                    quantity = quantity.to_base_units()

                if as_quantity:
                    data_flat[dkey] = quantity
                else:
                    data_flat[dkey] = quantity.magnitude
                break

        if not converted and raise_outerr:
            raise KeyError('could not find units for {}'.format(dkey))

    return unflatten(data_flat, list_of_dicts=list_of_dicts)


Instruction:
Can you create a Python 3 function that
splits quantities into a single object

Response:
def split_quantities(data, units='units', magnitude='magnitude',
                     list_of_dicts=False):
    """ split pint.Quantity objects into <unit,magnitude> pairs

    Parameters
    ----------
    data : dict
    units : str
        name for units key
    magnitude : str
        name for magnitude key
    list_of_dicts: bool
        treat list of dicts as additional branches

    Examples
    --------
    >>> from pprint import pprint

    >>> from pint import UnitRegistry
    >>> ureg = UnitRegistry()
    >>> Q = ureg.Quantity

    >>> qdata = {'energy': Q(1.602e-22, 'kilojoule'),
    ...          'meta': None,
    ...          'other': {'y': Q([4,5,6], 'nanometer')},
    ...          'x': Q([1,2,3], 'nanometer'),
    ...          'y': Q([8,9,10], 'meter')}
    ...
    >>> split_data = split_quantities(qdata)
    >>> pprint(split_data)
    {'energy': {'magnitude': 1.602e-22, 'units': 'kilojoule'},
     'meta': None,
     'other': {'y': {'magnitude': array([4, 5, 6]), 'units': 'nanometer'}},
     'x': {'magnitude': array([1, 2, 3]), 'units': 'nanometer'},
     'y': {'magnitude': array([ 8,  9, 10]), 'units': 'meter'}}

    """
    try:
        from pint.quantity import _Quantity
    except ImportError:
        raise ImportError('please install pint to use this module')
    list_of_dicts = '__list__' if list_of_dicts else None
    data_flatten = flatten(data, list_of_dicts=list_of_dicts)
    for key, val in data_flatten.items():
        if isinstance(val, _Quantity):
            data_flatten[key] = {units: str(val.units),
                                 magnitude: val.magnitude}
    return unflatten(data_flatten, list_of_dicts=list_of_dicts)


Instruction:
Here you have a function in Python 3, explain what it does
def combine_quantities(data, units='units', magnitude='magnitude',
                       list_of_dicts=False):
    """ combine <unit,magnitude> pairs into pint.Quantity objects

    Parameters
    ----------
    data : dict
    units : str
        name of units key
    magnitude : str
        name of magnitude key
    list_of_dicts: bool
        treat list of dicts as additional branches

    Examples
    --------
    >>> from pprint import pprint

    >>> sdata = {'energy': {'magnitude': 1.602e-22, 'units': 'kilojoule'},
    ...          'meta': None,
    ...          'other': {'y': {'magnitude': [4, 5, 6], 'units': 'nanometer'}},
    ...          'x': {'magnitude': [1, 2, 3], 'units': 'nanometer'},
    ...          'y': {'magnitude': [8,9,10], 'units': 'meter'}}
    ...
    >>> combined_data = combine_quantities(sdata)
    >>> pprint(combined_data)
    {'energy': <Quantity(1.602e-22, 'kilojoule')>,
     'meta': None,
     'other': {'y': <Quantity([4 5 6], 'nanometer')>},
     'x': <Quantity([1 2 3], 'nanometer')>,
     'y': <Quantity([ 8  9 10], 'meter')>}

    """  # noqa: E501
    try:
        from pint import UnitRegistry
        ureg = UnitRegistry()
    except ImportError:
        raise ImportError('please install pint to use this module')
    list_of_dicts = '__list__' if list_of_dicts else None

    data_flatten2d = flatten2d(data, list_of_dicts=list_of_dicts)
    new_dict = {}
    for key, val in list(data_flatten2d.items()):
        if units in val and magnitude in val:
            quantity = ureg.Quantity(val.pop(magnitude), val.pop(units))
            if not val:
                data_flatten2d.pop(key)
            new_dict[key] = quantity
    final_dict = merge([data_flatten2d, new_dict])
    # olddict = unflatten(data_flatten2d,list_of_dicts=list_of_dicts)
    # new_dict = unflatten(new_dict,list_of_dicts=list_of_dicts)
    return unflatten(
        final_dict, list_of_dicts=list_of_dicts)

Response: Combine quantities into single object.


Instruction:
Can you tell what is the following Python 3 function doing
def get_version_from_cache_dir(src_file):
    if src_file is None:
        return None

    tmp_dir = local.path(str(CFG["tmp_dir"]))
    if tmp_dir.exists():
        cache_file = tmp_dir / src_file
        dir_hash = get_hash_of_dirs(cache_file)
        if dir_hash is None:
            return None
        if len(str(dir_hash)) <= 7:
            return str(dir_hash)
        return str(dir_hash)[:7]
    return None

Response: Returns a version of a project from the cache directory.


Instruction:
Explain what the following Python 3 code does
def get_git_hash(from_url):
    from benchbuild.utils.cmd import git
    if from_url is None:
        return ""

    if not path.exists(from_url):
        return ""

    with local.cwd(from_url):
        return git("rev-parse", "HEAD", retcode=None)

Response: Get the git commit hash of HEAD from a file system url.


Instruction:
Explain what the following Python 3 code does
def fetch_time_output(marker, format_s, ins):
    from parse import parse

    timings = [x for x in ins if marker in x]
    res = [parse(format_s, t) for t in timings]
    return [_f for _f in res if _f]

Response: Fetch the output of a.


Instruction:
How would you explain what the following Python 3 function does
def path_to_list(pathstr):
    return [elem for elem in pathstr.split(os.path.pathsep) if elem]

Response: Conver a path string to a list of path elements.


Instruction:
Create a Python 3 function to
borrow from wxglade. py

Response:
def determine_path():
    """Borrowed from wxglade.py"""
    root = __file__
    if os.path.islink(root):
        root = os.path.realpath(root)
    return os.path.dirname(os.path.abspath(root))


Instruction:
Create a Python 3 function for
returning a list of filenames found at path.

Response:
def template_files(path, exts=None):
    """
    Return a list of filenames found at @path.

    The list of filenames can be filtered by extensions.

    Arguments:
        path: Existing filepath we want to list.
        exts: List of extensions to filter by.

    Returns:
        A list of filenames found in the path.
    """
    if not os.path.isabs(path):
        _path = os.path.join(determine_path(), path)
    if not (os.path.exists(_path) and os.path.isdir(_path)):
        return []
    if not exts:
        exts = []
    files = os.listdir(_path)
    files = [f for f in files if os.path.splitext(f)[-1] in exts]
    files = [os.path.join(path, f) for f in files]
    return files


Instruction:
Implement a function in Python 3 to
read a template file from the resources and return it as str.

Response:
def template_str(template):
    """Read a template file from the resources and return it as str."""
    tmpl_file = os.path.join(determine_path(), template)
    with open(tmpl_file, mode='r') as tmpl_strm:
        return "".join(tmpl_strm.readlines())


Instruction:
Explain what the following Python 3 code does
def mkfile_uchroot(filepath, root="."):
    from benchbuild.utils.uchroot import no_args, uretry

    uchroot = no_args()
    uchroot = uchroot["-E", "-A", "-C", "-w", "/", "-r"]
    uchroot = uchroot[os.path.abspath(root)]
    uretry(uchroot["--", "/bin/touch", filepath])

Response: Create a file inside a uchroot container.


Instruction:
Implement a function in Python 3 to
create a file inside a uchroot container.

Response:
def mkdir_uchroot(dirpath, root="."):
    """
    Create a file inside a uchroot env.

    You will want to use this when you need to create a file with apropriate
    rights inside a uchroot container with subuid/subgid handling enabled.

    Args:
        dirpath:
            The dirpath that should be created. Absolute inside the
            uchroot container.
        root:
            The root PATH of the container filesystem as seen outside of
            the container.
    """
    from benchbuild.utils.uchroot import no_args, uretry

    uchroot = no_args()
    uchroot = uchroot["-E", "-A", "-C", "-w", "/", "-r"]
    uchroot = uchroot[os.path.abspath(root)]
    uretry(uchroot["--", "/bin/mkdir", "-p", dirpath])


Instruction:
Can you create a Python 3 function that
creates a directory if required.

Response:
def mkdir_interactive(dirpath):
    """
    Create a directory if required.

    This will query the user for a confirmation.

    Args:
        dirname: The path to create.
    """
    from benchbuild.utils.cmd import mkdir
    if os.path.exists(dirpath):
        return

    response = ui.ask(
        "The directory {dirname} does not exist yet. "
        "Should I create it?".format(dirname=dirpath),
        default_answer=True,
        default_answer_str="yes")

    if response:
        mkdir("-p", dirpath)
        print("Created directory {0}.".format(dirpath))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_val_by_text(root,search):

    found_flag = False
    for el in root.iter():
        if found_flag:
            return(el)
        if el.text == search:
            # We want the next el
            found_flag = True

Response: From MeasYaps XML root find next sibling of node matching search.