Instruction:
Write a Python 3 function for
returning the shapes of the summation arrays linearshape fullshape

Response:
def sum_shapes(self, data1, data2):
        """
        Return the shapes of the summation arrays,
        given the input data and shape of the bins
        """
        # the linear shape (put extra dimensions first)
        linearshape = [-1] + list(self.shape)

        # determine the full shape
        subshapes = [list(d.subshape) for d in [data1, data2] if isinstance(d, field)]
        subshape = []
        if len(subshapes) == 2:
            assert subshapes[0] == subshapes[1]
            subshape = subshapes[0]
        elif len(subshapes) == 1:
            subshape = subshapes[0]
        fullshape = subshape + list(self.shape)

        # prepend the shape for different channels
        if self.channels:
            fullshape = [len(self.channels)] + fullshape

        return linearshape, fullshape


Instruction:
Can you tell what is the following Python 3 function doing
def _update_mean_coords(self, dig, N, centers_sum, **paircoords):
        if N is None or centers_sum is None: return

        N.flat[:] += utils.bincount(dig, 1., minlength=N.size)
        for i, dim in enumerate(self.dims):
            size = centers_sum[i].size
            centers_sum[i].flat[:] += utils.bincount(dig, paircoords[dim], minlength=size)

Response: Update the mean coordinate sums


Instruction:
How would you explain what the following Python 3 function does
def work(self, i):
        n1, n2 = self.p[i]

        # initialize the total arrays for this process
        sum1 = numpy.zeros_like(self.sum1g)
        sum2 = 1.
        if not self.pts_only: sum2 = numpy.zeros_like(self.sum2g)

        if self.compute_mean_coords:
            N = numpy.zeros_like(self.N)
            centers_sum = [numpy.zeros_like(c) for c in self.centers]
        else:
            N = None; centers_sum = None

        if self.bins.enable_fast_node_count:
            # field x points is not supported.
            # because it is more likely need to deal
            # with broadcasting
            sum1attrs = [ d.attr for d in self.data ]

            counts, sum1c = n1.count(n2, self.bins.edges,
                                attrs=sum1attrs)
            sum1[..., :-1] = sum1c
            sum1[..., -1] = 0
        else:

            def callback(r, i, j):
                # just call the binning function, passing the
                # sum arrays to fill in
                self.bins.update_sums(r, i, j, self.data[0], self.data[1], sum1, sum2, N=N, centers_sum=centers_sum)

            n1.enum(n2, self.bins.Rmax, process=callback)

        if not self.compute_mean_coords:
            return sum1, sum2
        else:
            return sum1, sum2, N, centers_sum

Response: Internal function that performs the pair - counting


Instruction:
Can you generate a brief explanation for the following Python 3 code
def reduce(self, sum1, sum2, *args):
        self.sum1g[...] += sum1
        if not self.pts_only: self.sum2g[...] += sum2

        if self.compute_mean_coords:
            N, centers_sum = args
            self.N[...] += N
            for i in range(self.bins.Ndim):
                self.centers[i][...] += centers_sum[i]

Response: This function sums the results from various processors and updates the internal statistics of the internal statistics.


Instruction:
How would you explain what the following Python 3 function does
def gpdfitnew(x, sort=True, sort_in_place=False, return_quadrature=False):
    if x.ndim != 1 or len(x) <= 1:
        raise ValueError("Invalid input array.")

    # check if x should be sorted
    if sort is True:
        if sort_in_place:
            x.sort()
            xsorted = True
        else:
            sort = np.argsort(x)
            xsorted = False
    elif sort is False:
        xsorted = True
    else:
        xsorted = False

    n = len(x)
    PRIOR = 3
    m = 30 + int(np.sqrt(n))

    bs = np.arange(1, m + 1, dtype=float)
    bs -= 0.5
    np.divide(m, bs, out=bs)
    np.sqrt(bs, out=bs)
    np.subtract(1, bs, out=bs)
    if xsorted:
        bs /= PRIOR * x[int(n/4 + 0.5) - 1]
        bs += 1 / x[-1]
    else:
        bs /= PRIOR * x[sort[int(n/4 + 0.5) - 1]]
        bs += 1 / x[sort[-1]]

    ks = np.negative(bs)
    temp = ks[:,None] * x
    np.log1p(temp, out=temp)
    np.mean(temp, axis=1, out=ks)

    L = bs / ks
    np.negative(L, out=L)
    np.log(L, out=L)
    L -= ks
    L -= 1
    L *= n

    temp = L - L[:,None]
    np.exp(temp, out=temp)
    w = np.sum(temp, axis=1)
    np.divide(1, w, out=w)

    # remove negligible weights
    dii = w >= 10 * np.finfo(float).eps
    if not np.all(dii):
        w = w[dii]
        bs = bs[dii]
    # normalise w
    w /= w.sum()

    # posterior mean for b
    b = np.sum(bs * w)
    # Estimate for k, note that we return a negative of Zhang and
    # Stephens's k, because it is more common parameterisation.
    temp = (-b) * x # pylint: disable=invalid-unary-operand-type
    np.log1p(temp, out=temp)
    k = np.mean(temp)
    if return_quadrature:
        np.negative(x, out=temp)
        temp = bs[:, None] * temp
        np.log1p(temp, out=temp)
        ks = np.mean(temp, axis=1)
    # estimate for sigma
    sigma = -k / b * n / (n - 0)
    # weakly informative prior for k
    a = 10
    k = k * n / (n+a) + a * 0.5 / (n+a)
    if return_quadrature:
        ks *= n / (n+a)
        ks += a * 0.5 / (n+a)

    if return_quadrature:
        return k, sigma, ks, w
    else:
        return k, sigma

Response: Estimate the parameter values for the Generalized Pareto Distribution.


Instruction:
Implement a function in Python 3 to
inverse Generalised Pareto distribution function.

Response:
def gpinv(p, k, sigma):
    """Inverse Generalised Pareto distribution function."""
    x = np.empty(p.shape)
    x.fill(np.nan)
    if sigma <= 0:
        return x
    ok = (p > 0) & (p < 1)
    if np.all(ok):
        if np.abs(k) < np.finfo(float).eps:
            np.negative(p, out=x)
            np.log1p(x, out=x)
            np.negative(x, out=x)
        else:
            np.negative(p, out=x)
            np.log1p(x, out=x)
            x *= -k
            np.expm1(x, out=x)
            x /= k
        x *= sigma
    else:
        if np.abs(k) < np.finfo(float).eps:
            # x[ok] = - np.log1p(-p[ok])
            temp = p[ok]
            np.negative(temp, out=temp)
            np.log1p(temp, out=temp)
            np.negative(temp, out=temp)
            x[ok] = temp
        else:
            # x[ok] = np.expm1(-k * np.log1p(-p[ok])) / k
            temp = p[ok]
            np.negative(temp, out=temp)
            np.log1p(temp, out=temp)
            temp *= -k
            np.expm1(temp, out=temp)
            temp /= k
            x[ok] = temp
        x *= sigma
        x[p == 0] = 0
        if k >= 0:
            x[p == 1] = np.inf
        else:
            x[p == 1] = -sigma / k
    return x


Instruction:
Can you generate a brief explanation for the following Python 3 code
def sumlogs(x, axis=None, out=None):
    maxx = x.max(axis=axis, keepdims=True)
    xnorm = x - maxx
    np.exp(xnorm, out=xnorm)
    out = np.sum(xnorm, axis=axis, out=out)
    if isinstance(out, np.ndarray):
        np.log(out, out=out)
    else:
        out = np.log(out)
    out += np.squeeze(maxx)
    return out

Response: Sum of vector where numbers are represented by their logarithms.


Instruction:
Write a Python 3 function for
adding functions from a library module to the internal dictionary.

Response:
def add_library(self, library):
        """
        Adds functions from a library module
        :param library: the library module
        :return:
        """
        for fn in library.__dict__.copy().values():
            # ignore imported methods and anything beginning __
            if inspect.isfunction(fn) and inspect.getmodule(fn) == library and not fn.__name__.startswith('__'):
                name = fn.__name__.lower()

                # strip preceding _ chars used to avoid conflicts with Java keywords
                if name.startswith('_'):
                    name = name[1:]

                self._functions[name] = fn


Instruction:
Can you tell what is the following Python 3 function doing
def invoke_function(self, ctx, name, arguments):
        from temba_expressions import EvaluationError, conversions

        # find function with given name
        func = self.get_function(name)
        if func is None:
            raise EvaluationError("Undefined function: %s" % name)

        args, varargs, defaults = self._get_arg_spec(func)

        call_args = []
        passed_args = list(arguments)

        for arg in args:
            if arg == 'ctx':
                call_args.append(ctx)
            elif passed_args:
                call_args.append(passed_args.pop(0))
            elif arg in defaults:
                call_args.append(defaults[arg])
            else:
                raise EvaluationError("Too few arguments provided for function %s" % name)

        if varargs is not None:
            call_args.extend(passed_args)
            passed_args = []

        # any unused arguments?
        if passed_args:
            raise EvaluationError("Too many arguments provided for function %s" % name)

        try:
            return func(*call_args)
        except Exception as e:
            pretty_args = []
            for arg in arguments:
                if isinstance(arg, str):
                    pretty = '"%s"' % arg
                else:
                    try:
                        pretty = conversions.to_string(arg, ctx)
                    except EvaluationError:
                        pretty = str(arg)
                pretty_args.append(pretty)

            raise EvaluationError("Error calling function %s with arguments %s" % (name, ', '.join(pretty_args)), e)

Response: Invoke the function with the given name and arguments.


Instruction:
Create a Python 3 function for
building a listing of all functions sorted A - Z with their names and descriptions.

Response:
def build_listing(self):
        """
        Builds a listing of all functions sorted A-Z, with their names and descriptions
        """
        def func_entry(name, func):
            args, varargs, defaults = self._get_arg_spec(func)

            # add regular arguments
            params = [{'name': str(a), 'optional': a in defaults, 'vararg': False} for a in args if a != 'ctx']

            # add possible variable argument
            if varargs:
                params += [{'name': str(varargs), 'optional': False, 'vararg': True}]

            return {'name': str(name.upper()),
                    'description': str(func.__doc__).strip(),
                    'params': params}

        listing = [func_entry(f_name, f) for f_name, f in self._functions.items()]
        return sorted(listing, key=lambda l: l['name'])


Instruction:
Here you have a function in Python 3, explain what it does
def _get_arg_spec(func):
        args, varargs, keywords, defaults = inspect.getargspec(func)

        # build a mapping from argument names to their default values, if any:
        if defaults is None:
            defaults = {}
        else:
            defaulted_args = args[-len(defaults):]
            defaults = {name: val for name, val in zip(defaulted_args, defaults)}

        return args, varargs, defaults

Response: Gets the argument spec of the given function returning defaults as a dict of param names to values


Instruction:
Can you generate a brief explanation for the following Python 3 code
def check_ocrmypdf(input_file, output_file, *args, env=None):
    "Run ocrmypdf and confirmed that a valid file was created"

    p, out, err = run_ocrmypdf(input_file, output_file, *args, env=env)
    if p.returncode != 0:
        print('stdout\n======')
        print(out)
        print('stderr\n======')
        print(err)
    #assert p.returncode == 0
    #assert os.path.exists(output_file), "Output file not created"
    #assert os.stat(output_file).st_size > 100, "PDF too small or empty"
    return output_file

Response: Run ocrmypdf and confirmed that a valid file was created


Instruction:
Can you create a Python 3 function that
runs ocrmypdf and let caller deal with results

Response:
def run_ocrmypdf(input_file, output_file, *args, env=None):
    "Run ocrmypdf and let caller deal with results"

    if env is None:
        env = os.environ

    p_args = OCRMYPDF + list(args) + [input_file, output_file]
    p = Popen(
        p_args, close_fds=True, stdout=PIPE, stderr=PIPE,
        universal_newlines=True, env=env)
    out, err = p.communicate()
    return p, out, err


Instruction:
Explain what the following Python 3 code does
def standardizeMapName(mapName):
    #print("foreignName: %s  (%s)"%(mapName, mapName in c.mapNameTranslations))
    #if mapName in c.mapNameTranslations:
    #    return c.mapNameTranslations[mapName]
    newName = os.path.basename(mapName)
    newName = newName.split(".")[0]
    newName = newName.split("(")[0]
    newName = re.sub("[LT]E+$", "", newName)
    newName = re.sub("-", "", newName)
    newName = re.sub(' ', '', newName, flags=re.UNICODE)
    foreignName = newName#bytes(mapName, 'utf-16')
    #print("foreignName: %s  (%s)"%(foreignName, foreignName in c.mapNameTranslations))
    if foreignName in c.mapNameTranslations:
        return c.mapNameTranslations[foreignName]
    return newName

Response: pretty - fine the name for pysc2 map lookup


Instruction:
Implement a Python 3 function for
returning a string that contains the Python version and runtime path.

Response:
def env_info():
    '''
    Returns a string that contains the Python version and runtime path.
    '''
    v = sys.version_info
    pyver = f'Python {v.major}.{v.minor}.{v.micro}'
    if v.releaselevel == 'alpha':
        pyver += 'a'
    if v.releaselevel == 'beta':
        pyver += 'b'
    if v.releaselevel == 'candidate':
        pyver += 'rc'
    if v.releaselevel != 'final':
        pyver += str(v.serial)
    return f'{pyver} (env: {sys.prefix})'


Instruction:
Here you have a function in Python 3, explain what it does
def dict2kvlist(o):
    '''
    Serializes a dict-like object into a generator of the flatten list of
    repeating key-value pairs.  It is useful when using HMSET method in Redis.

    Example:
    >>> list(dict2kvlist({'a': 1, 'b': 2}))
    ['a', 1, 'b', 2]
    '''
    return chain.from_iterable((k, v) for k, v in o.items())

Response: Serializes a dict - like object into a generator of the flatten list of key - value pairs.


Instruction:
Can you generate the documentation for the following Python 3 function
def nmget(o, key_path, def_val=None, path_delimiter='.', null_as_default=True):
    '''
    A short-hand for retrieving a value from nested mappings
    ("nested-mapping-get").  At each level it checks if the given "path"
    component in the given key exists and return the default value whenever
    fails.

    Example:
    >>> o = {'a':{'b':1}, 'x': None}
    >>> nmget(o, 'a', 0)
    {'b': 1}
    >>> nmget(o, 'a.b', 0)
    1
    >>> nmget(o, 'a/b', 0, '/')
    1
    >>> nmget(o, 'a.c', 0)
    0
    >>> nmget(o, 'x', 0)
    0
    >>> nmget(o, 'x', 0, null_as_default=False)
    None
    '''
    pieces = key_path.split(path_delimiter)
    while pieces:
        p = pieces.pop(0)
        if o is None or p not in o:
            return def_val
        o = o[p]
    if o is None and null_as_default:
        return def_val
    return o

Response:
A short - hand for retrieving a value from nested mappings
   .


Instruction:
How would you code a function in Python 3 to
patch __init__. py to remove version check and append hard - coded version.

Response:
def patch_init_py(base_dir, name, version):
    """Patch __init__.py to remove version check and append hard-coded version."""
    # Ensure main package dir is there (may be absent in script-only packages)
    package_dir = os.path.join(base_dir, name)
    if not os.path.isdir(package_dir):
        os.makedirs(package_dir)
    # Open top-level __init__.py and read whole file
    init_py = os.path.join(package_dir, '__init__.py')
    log.info("patching %s to bake in version '%s'" % (init_py, version))
    with open(init_py, 'r+') as init_file:
        lines = init_file.readlines()
        # Search for sentinels indicating version checking block
        try:
            begin = lines.index("# BEGIN VERSION CHECK\n")
            end = lines.index("# END VERSION CHECK\n")
        except ValueError:
            begin = end = len(lines)
        # Delete existing repo version checking block in file
        init_file.seek(0)
        init_file.writelines(lines[:begin] + lines[end+1:])
        # Append new version attribute to ensure it is authoritative, but only
        # if it is not already there (this happens in pip sdist installs)
        version_cmd = "__version__ = '{0}'\n".format(version)
        if not lines or lines[-1] != version_cmd:
            init_file.write("\n# Automatically added by katversion\n")
            init_file.write(version_cmd)
        init_file.truncate()


Instruction:
Write a Python 3 function for
checking if machine is in given state.

Response:
def is_(self, state):
    """Check if machine is in given state."""
    translator = self._meta['translator']
    state = translator.translate(state)
    return self.actual_state == state


Instruction:
Write a Python 3 script for
checking if machine can transit to given state.

Response:
def can_be_(self, state):
    """Check if machine can transit to given state."""
    translator = self._meta['translator']
    state = translator.translate(state)

    if self._meta['complete']:
        return True

    if self.actual_state is None:
        return True

    transitions = self._meta['transitions'][self.actual_state]
    return state in transitions


Instruction:
Given the following Python 3 function, write the documentation
def force_set(self, state):
    translator = self._meta['translator']
    state = translator.translate(state)
    attr = self._meta['state_attribute_name']
    setattr(self, attr, state)

Response: Set new state without checking if transition is allowed.


Instruction:
Here you have a function in Python 3, explain what it does
def set_(self, state):
    if not self.can_be_(state):
        state = self._meta['translator'].translate(state)
        raise TransitionError(
            "Cannot transit from '{actual_value}' to '{value}'."
            .format(actual_value=self.actual_state.value, value=state.value)
        )

    self.force_set(state)

Response: Set new state for the current machine.


Instruction:
Explain what the following Python 3 code does
def generate_getter(value):
    @property
    @wraps(is_)
    def getter(self):
        return self.is_(value)

    return getter

Response: Generate getter for given value.


Instruction:
Create a Python 3 function to
generate state checker for given value.

Response:
def generate_checker(value):
    """Generate state checker for given value."""
    @property
    @wraps(can_be_)
    def checker(self):
        return self.can_be_(value)

    return checker


Instruction:
Implement a Python 3 function for
generating setter for given value.

Response:
def generate_setter(value):
    """Generate setter for given value."""
    @wraps(set_)
    def setter(self):
        self.set_(value)

    return setter


Instruction:
Can you tell what is the following Python 3 function doing
def translate(self, value):
        if self._check_if_already_proper(value):
            return value

        try:
            return self.search_table[value]
        except KeyError:
            raise ValueError("Value {value} doesn't match any state.".format(
                value=value
            ))

Response: Translate value to enum instance.


Instruction:
Can you generate the documentation for the following Python 3 function
def _query(self, text):
        params = (
            ('v', self.api_version),
            ('query', text),
            ('lang', self.language),
            ('sessionId', self.session_id),
            ('timezone', self.timezone),
        )
        # store query_response if required
        if self.query_response:
            self.previous_query_response = self.query_response

        self.query_response = result = self.session.get(url=self.query_url, params=params).json()

        return result

Response: Query the API for the specified natural language text and returns information as JSON.


Instruction:
Create a Python 3 function to
check whether this workspace is a virtualenv.

Response:
def is_venv():
    """Check whether if this workspace is a virtualenv.
    """
    dir_path = os.path.dirname(SRC)
    is_venv_flag = True

    if SYS_NAME == "Windows":
        executable_list = ["activate", "pip.exe", "python.exe"]
    elif SYS_NAME in ["Darwin", "Linux"]:
        executable_list = ["activate", "pip", "python"]

    for executable in executable_list:
        path = os.path.join(dir_path, BIN_SCRIPTS, executable)
        if not os.path.exists(path):
            is_venv_flag = False

    return is_venv_flag


Instruction:
Explain what the following Python 3 code does
def find_linux_venv_py_version():
    available_python_version = [
        "python2.6",
        "python2.7",
        "python3.3",
        "python3.4",
        "python3.5",
        "python3.6",
    ]
    dir_path = os.path.dirname(SRC)
    for basename in os.listdir(os.path.join(dir_path, BIN_SCRIPTS)):
        for python_version in available_python_version:
            if python_version in basename:
                return python_version
    raise Exception("Can't find virtualenv python version!")

Response: Find the python version used in this virtualenv.


Instruction:
Write a Python 3 function for
finding where this package should be installed to in this virtualenv.

Response:
def find_venv_DST():
    """Find where this package should be installed to in this virtualenv.

    For example: ``/path-to-venv/lib/python2.7/site-packages/package-name``
    """
    dir_path = os.path.dirname(SRC)

    if SYS_NAME == "Windows":
        DST = os.path.join(dir_path, "Lib", "site-packages", PKG_NAME)
    elif SYS_NAME in ["Darwin", "Linux"]:
        python_version = find_linux_venv_py_version()
        DST = os.path.join(dir_path, "lib", python_version, "site-packages", PKG_NAME)

    return DST


Instruction:
Can you tell what is the following Python 3 function doing
def find_DST():
    if SYS_NAME == "Windows":
        return os.path.join(site.getsitepackages()[1], PKG_NAME)
    elif SYS_NAME in ["Darwin", "Linux"]:
        return os.path.join(site.getsitepackages()[0], PKG_NAME)

Response: Find where this package should be installed to.


Instruction:
Can you write a function in Python 3 where it
returns md5 value of a file.

Response:
def md5_of_file(abspath):
    """Md5 value of a file.
    """
    chunk_size = 1024 * 1024
    m = hashlib.md5()
    with open(abspath, "rb") as f:
        while True:
            data = f.read(chunk_size)
            if not data:
                break
            m.update(data)
    return m.hexdigest()


Instruction:
Here you have a function in Python 3, explain what it does
def check_need_install():
    need_install_flag = False
    for root, _, basename_list in os.walk(SRC):
        if os.path.basename(root) != "__pycache__":
            for basename in basename_list:
                src = os.path.join(root, basename)
                dst = os.path.join(root.replace(SRC, DST), basename)
                if os.path.exists(dst):
                    if md5_of_file(src) != md5_of_file(dst):
                        return True
                else:
                    return True
    return need_install_flag

Response: Check if installed package are exactly the same to this one.


Instruction:
How would you explain what the following Python 3 function does
def install():
    # check installed package
    print("Compare to '%s' ..." % DST)
    need_install_flag = check_need_install()
    if not need_install_flag:
        print("    package is up-to-date, no need to install.")
        return
    print("Difference been found, start installing ...")

    # remove __pycache__ folder and *.pyc file
    print("Remove *.pyc file ...")
    pyc_folder_list = list()
    for root, _, basename_list in os.walk(SRC):
        if os.path.basename(root) == "__pycache__":
            pyc_folder_list.append(root)

    for folder in pyc_folder_list:
        shutil.rmtree(folder)
    print("    all *.pyc file has been removed.")

    # install this package to all python version
    print("Uninstall %s from %s ..." % (PKG_NAME, DST))
    try:
        shutil.rmtree(DST)
        print("    Successfully uninstall %s" % PKG_NAME)
    except Exception as e:
        print("    %s" % e)

    print("Install %s to %s ..." % (PKG_NAME, DST))
    shutil.copytree(SRC, DST)
    print("    Complete!")

Response: Manual install main script.


Instruction:
Can you tell what is the following Python 3 function doing
async def login(
        sess: aiohttp.ClientSession,
        registry_url: yarl.URL,
        credentials: dict,
        scope: str) -> dict:
    '''
    Authorize to the docker registry using the given credentials and token scope, and returns a set
    of required aiohttp.ClientSession.request() keyword arguments for further API requests.

    Some registry servers only rely on HTTP Basic Authentication without token-based access controls
    (usually via nginx proxy). We do support them also. :)
    '''
    if credentials.get('username') and credentials.get('password'):
        basic_auth = aiohttp.BasicAuth(
            credentials['username'], credentials['password'],
        )
    else:
        basic_auth = None
    realm = registry_url / 'token'  # fallback
    service = 'registry'            # fallback
    async with sess.get(registry_url / 'v2/', auth=basic_auth) as resp:
        ping_status = resp.status
        www_auth_header = resp.headers.get('WWW-Authenticate')
        if www_auth_header:
            match = re.search(r'realm="([^"]+)"', www_auth_header)
            if match:
                realm = match.group(1)
            match = re.search(r'service="([^"]+)"', www_auth_header)
            if match:
                service = match.group(1)
    if ping_status == 200:
        log.debug('docker-registry: {0} -> basic-auth', registry_url)
        return {'auth': basic_auth, 'headers': {}}
    elif ping_status == 404:
        raise RuntimeError(f'Unsupported docker registry: {registry_url}! '
                           '(API v2 not implemented)')
    elif ping_status == 401:
        params = {
            'scope': scope,
            'offline_token': 'true',
            'client_id': 'docker',
            'service': service,
        }
        async with sess.get(realm, params=params, auth=basic_auth) as resp:
            log.debug('docker-registry: {0} -> {1}', registry_url, realm)
            if resp.status == 200:
                data = json.loads(await resp.read())
                token = data.get('token', None)
                return {'auth': None, 'headers': {
                    'Authorization': f'Bearer {token}'
                }}
    raise RuntimeError('authentication for docker registry '
                       'f{registry_url} failed')

Response: Login to the given docker registry using the given credentials and token scope.


Instruction:
Implement a Python 3 function for
returning True if this is a git repo.

Response:
def is_git(path):
    """Return True if this is a git repo."""
    try:
        repo_dir = run_cmd(path, 'git', 'rev-parse', '--git-dir')
        return True if repo_dir else False
    except (OSError, RuntimeError):
        return False


Instruction:
Write a Python 3 function for
generating a version string based on the SCM type and the date.

Response:
def date_version(scm=None):
    """Generate a version string based on the SCM type and the date."""
    dt = str(time.strftime('%Y%m%d%H%M'))
    if scm:
        version = "0.0+unknown.{0}.{1}".format(scm, dt)
    else:
        version = "0.0+unknown." + dt
    return version


Instruction:
Can you generate the documentation for the following Python 3 function
def get_git_cleaned_branch_name(path):
    # Get name of current branch (or 'HEAD' for a detached HEAD)
    branch_name = run_cmd(path, 'git', 'rev-parse', '--abbrev-ref', 'HEAD')
    branch_name = re.sub(r"[^A-Za-z0-9]+", ".", branch_name.strip())
    return branch_name

Response: Get the git branch name of the current HEAD in path.


Instruction:
Can you write a function in Python 3 where it
gets the GIT version of the working copy.

Response:
def get_git_version(path):
    """Get the GIT version."""
    branch_name = get_git_cleaned_branch_name(path)
    # Determine whether working copy is dirty (i.e. contains modified files)
    mods = run_cmd(path, 'git', 'status', '--porcelain', '--untracked-files=no')
    dirty = '.dirty' if mods else ''
    # Get a list of all commits on branch, with corresponding branch/tag refs
    # Each line looks something like: "d3e4d42 (HEAD, master, tag: v0.1)"
    git_output = run_cmd(path, 'git', 'log', '--pretty="%h%d"')
    commits = git_output.strip().replace('"', '').split('\n')
    num_commits_since_branch = len(commits)
    # Short hash of the latest commit
    short_commit_name = commits[0].partition(' ')[0]
    # A valid version is sequence of dotted numbers optionally prefixed by 'v'
    valid_version = re.compile(r'^v?([\.\d]+)$')

    def tagged_version(commit):
        """First tag on commit that is valid version, as a list of numbers."""
        refs = commit.partition(' ')[2]
        for ref in refs.lstrip('(').rstrip(')').split(', '):
            if ref.startswith('tag: '):
                tag = ref[5:].lower()
                found = valid_version.match(tag)
                if found:
                    return [int(v) for v in found.group(1).split('.') if v]
        return []
    # Walk back along branch and find first valid tagged version (or use 0.0)
    for commit in commits:
        version_numbers = tagged_version(commit)
        if version_numbers:
            break
    else:
        version_numbers = [0, 0]
    # It is a release if current commit has a version tag (and dir is clean)
    release = (commit == commits[0]) and not dirty
    if not release:
        # We are working towards the next (minor) release according to PEP 440
        version_numbers[-1] += 1
    version = '.'.join([str(v) for v in version_numbers])
    if not release:
        # Development version contains extra embellishments
        version = ("%s.dev%d+%s.%s%s" % (version, num_commits_since_branch,
                                         branch_name, short_commit_name, dirty))
    return version


Instruction:
Can you create a Python 3 function that
gets the current version string of this package using SCM tool.

Response:
def get_version_from_scm(path=None):
    """Get the current version string of this package using SCM tool.

    Parameters
    ----------
    path : None or string, optional
        The SCM checkout path (default is current directory)

    Returns
    -------
    version : string
        The version string for this package

    """
    if is_git(path):
        return 'git', get_git_version(path)
    elif is_svn(path):
        return 'svn', get_svn_version(path)
    return None, None


Instruction:
Explain what the following Python 3 code does
def get_version_from_module(module):
    if module is not None:
        # Setup.py will not pass in a module, but creating __version__ from
        # __init__ will.
        module = str(module).split('.', 1)[0]
        try:
            package = pkg_resources.get_distribution(module)
            return package.version
        except pkg_resources.DistributionNotFound:
            # So there you have it the module is not installed.
            pass

Response: Use pkg_resources to get version of installed module by name.


Instruction:
Write a Python 3 function for
copying from pkginfo 1. 4. 1 _compat module.

Response:
def _must_decode(value):
    """Copied from pkginfo 1.4.1, _compat module."""
    if type(value) is bytes:
        try:
            return value.decode('utf-8')
        except UnicodeDecodeError:
            return value.decode('latin1')
    return value


Instruction:
Here you have a function in Python 3, explain what it does
def get_version_from_unpacked_sdist(path):
    # This is a condensed version of the relevant code in pkginfo 1.4.1
    try:
        with open(os.path.join(path, 'PKG-INFO')) as f:
            data = f.read()
    except IOError:
        # Could not load path as an unpacked sdist as it had no PKG-INFO file
        return
    fp = StringIO(_must_decode(data))
    msg = Parser().parse(fp)
    value = msg.get('Version')
    if value != 'UNKNOWN':
        return value

Response: Assume path points to unpacked source distribution and get version.