Instruction:
Write a Python 3 script to
launch an EC2 instance with the specified parameters intended to create a CONS3RT template.

Response:
def launch_instance(self, ami_id, key_name, subnet_id, security_group_id=None, security_group_list=None,
                        user_data_script_path=None, instance_type='t2.small', root_device_name='/dev/xvda'):
        """Launches an EC2 instance with the specified parameters, intended to launch
        an instance for creation of a CONS3RT template.

        :param ami_id: (str) ID of the AMI to launch from
        :param key_name: (str) Name of the key-pair to use
        :param subnet_id: (str) IF of the VPC subnet to attach the instance to
        :param security_group_id: (str) ID of the security group, of not provided the default will be applied
                appended to security_group_list if provided
        :param security_group_id_list: (list) of IDs of the security group, if not provided the default will be applied
        :param user_data_script_path: (str) Path to the user-data script to run
        :param instance_type: (str) Instance Type (e.g. t2.micro)
        :param root_device_name: (str) The device name for the root volume
        :return:
        """
        log = logging.getLogger(self.cls_logger + '.launch_instance')
        log.info('Launching with AMI ID: {a}'.format(a=ami_id))
        log.info('Launching with Key Pair: {k}'.format(k=key_name))

        if security_group_list:
            if not isinstance(security_group_list, list):
                raise EC2UtilError('security_group_list must be a list')

        if security_group_id and security_group_list:
            security_group_list.append(security_group_id)
        elif security_group_id and not security_group_list:
            security_group_list = [security_group_id]
            log.info('Launching with security group list: {s}'.format(s=security_group_list))
        user_data = None
        if user_data_script_path is not None:
            if os.path.isfile(user_data_script_path):
                with open(user_data_script_path, 'r') as f:
                    user_data = f.read()
        monitoring = {'Enabled': False}
        block_device_mappings = [
            {
                'DeviceName': root_device_name,
                'Ebs': {
                    'VolumeSize': 100,
                    'DeleteOnTermination': True
                }
            }
        ]
        log.info('Attempting to launch the EC2 instance now...')
        try:
            response = self.client.run_instances(
                DryRun=False,
                ImageId=ami_id,
                MinCount=1,
                MaxCount=1,
                KeyName=key_name,
                SecurityGroupIds=security_group_list,
                UserData=user_data,
                InstanceType=instance_type,
                Monitoring=monitoring,
                SubnetId=subnet_id,
                InstanceInitiatedShutdownBehavior='stop',
                BlockDeviceMappings=block_device_mappings
            )
        except ClientError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem launching the EC2 instance\n{e}'.format(n=ex.__class__.__name__, e=str(ex))
            raise EC2UtilError, msg, trace
        instance_id = response['Instances'][0]['InstanceId']
        output = {
            'InstanceId': instance_id,
            'InstanceInfo': response['Instances'][0]
        }
        return output


Instruction:
Given the following Python 3 function, write the documentation
def get_ec2_instances(self):
        log = logging.getLogger(self.cls_logger + '.get_ec2_instances')
        log.info('Describing EC2 instances...')
        try:
            response = self.client.describe_instances()
        except ClientError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem describing EC2 instances\n{e}'.format(n=ex.__class__.__name__, e=str(ex))
            raise EC2UtilError, msg, trace
        return response

Response: Describes the EC2 instances and returns a dict containing the EC2 instance data


Instruction:
Given the following Python 3 function, write the documentation
def docs_cli(ctx, recreate, gen_index, run_doctests):
    # type: (click.Context, bool, bool, bool) -> None
    """ Build project documentation.

    This command will run sphinx-refdoc first to generate the reference
    documentation for the code base. Then it will run sphinx to generate the
    final docs. You can configure the directory that stores the docs source
    (index.rst, conf.py, etc.) using the DOC_SRC_PATH conf variable. In case you
    need it, the sphinx build directory is located in ``BUILD_DIR/docs``.

    The reference documentation will be generated for all directories listed
    under 'REFDOC_PATHS conf variable. By default it is empty so no reference
    docs are generated.

    Sample Config::

        \b
        build_dir: '.build'

        docs:
          path: 'docs'
          reference:
            - 'src/mypkg'

    Examples::

        \b
        $ peltak docs                           # Generate docs for the project
        $ peltak docs --no-index                # Skip main reference index
        $ peltak docs --recreate --no-index     # Build docs from clean slate

    """
    if ctx.invoked_subcommand:
        return

    from peltak.logic import docs
    docs.docs(recreate, gen_index, run_doctests)

Response: Build the documentation for the current project.


Instruction:
Can you generate the documentation for the following Python 3 function
def as_string(value):
    if six.PY2:
        buffer_types = buffer, memoryview  # noqa: F821
    else:
        buffer_types = memoryview

    if value is None:
        return u''
    elif isinstance(value, buffer_types):
        return bytes(value).decode('utf8', 'ignore')
    elif isinstance(value, bytes):
        return value.decode('utf8', 'ignore')
    else:
        return six.text_type(value)

Response: Convert a value to a Unicode string for matching with a query.


Instruction:
Here you have a function in Python 3, explain what it does
def displayable_path(path, separator=u'; '):
    if isinstance(path, (list, tuple)):
        return separator.join(displayable_path(p) for p in path)
    elif isinstance(path, six.text_type):
        return path
    elif not isinstance(path, bytes):
        # A non-string object: just get its unicode representation.
        return six.text_type(path)

    try:
        return path.decode(_fsencoding(), 'ignore')
    except (UnicodeError, LookupError):
        return path.decode('utf8', 'ignore')

Response:
Given a bytestring path to a unicode object for the
    purpose of displaying it to the user.


Instruction:
Given the following Python 3 function, write the documentation
def syspath(path, prefix=True):
    # Don't do anything if we're not on windows
    if os.path.__name__ != 'ntpath':
        return path

    if not isinstance(path, six.text_type):
        # Beets currently represents Windows paths internally with UTF-8
        # arbitrarily. But earlier versions used MBCS because it is
        # reported as the FS encoding by Windows. Try both.
        try:
            path = path.decode('utf8')
        except UnicodeError:
            # The encoding should always be MBCS, Windows' broken
            # Unicode representation.
            encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
            path = path.decode(encoding, 'replace')

    # Add the magic prefix if it isn't already there.
    # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx
    if prefix and not path.startswith(WINDOWS_MAGIC_PREFIX):
        if path.startswith(u'\\\\'):
            # UNC path. Final path should look like \\?\UNC\...
            path = u'UNC' + path[1:]
        path = WINDOWS_MAGIC_PREFIX + path

    return path

Response: Convert a path to a Unicode string for use by the operating system.


Instruction:
Given the following Python 3 function, write the documentation
def on_new(self, button):
        '''
        Copy selected notebook template to notebook directory.

        ## Notes ##

         - An exception is raised if the parent of the selected file is the
           notebook directory.
         - If notebook with same name already exists in notebook directory,
           offer is made to overwrite (the new copy of the file is renamed with
           a count if overwrite is not selected).
        '''
        buttons = (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                   Gtk.STOCK_OPEN, Gtk.ResponseType.OK)
        dialog = Gtk.FileChooserDialog("Select notebook template", self.parent,
                                       Gtk.FileChooserAction.OPEN, buttons)
        add_filters(dialog, [{'name': 'IPython notebook (*.ipynb)',
                              'pattern': '*.ipynb'}])
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            selected_path = path(dialog.get_filename())
            output_path = self.notebook_dir.joinpath(selected_path.name)

            overwrite = False
            if output_path.isfile():
                response = yesno('%s already exists. Overwrite?' % output_path.name,
                                 'Overwrite?')
                if response == Gtk.ResponseType.YES:
                    overwrite = True
                else:
                    counter = 1
                    renamed_path = output_path
                    while renamed_path.isfile():
                        new_name = '%s (%d)%s' % (output_path.namebase, counter,
                                                  output_path.ext)
                        renamed_path = output_path.parent.joinpath(new_name)
                        counter += 1
                    output_path = renamed_path
            self.notebook_manager.launch_from_template(selected_path,
                                                       overwrite=overwrite,
                                                       output_name=output_path.name,
                                                       notebook_dir=self.notebook_dir)
        dialog.destroy()

Response: This method is called when a new notebook template is selected.


Instruction:
Can you generate the documentation for the following Python 3 function
def se_iban_load_map(filename: str) -> list:
    out = []
    name_repl = {
        'BNP Paribas Fortis SA/NV, Bankfilial Sverige': 'BNP Paribas Fortis SA/NV',
        'Citibank International Plc, Sweden Branch': 'Citibank International Plc',
        'Santander Consumer Bank AS (deltar endast i Dataclearingen)': 'Santander Consumer Bank AS',
        'Nordax Bank AB (deltar endast i Dataclearingen)': 'Nordax Bank AB',
        'Swedbank och fristående Sparbanker, t ex Leksands Sparbank och Roslagsbanken.': 'Swedbank',
        'Ålandsbanken Abp (Finland),svensk filial': 'Ålandsbanken Abp',
        'SBAB deltar endast i Dataclearingen': 'SBAB',
    }
    with open(filename) as fp:
        for row in csv.reader(fp):
            if len(row) == 3:
                name, series, acc_digits = row
                # pprint([name, series, acc_digits])

                # clean up name
                name = re.sub(r'\n.*', '', name)
                if name in name_repl:
                    name = name_repl[name]

                # clean up series
                ml_acc_digits = acc_digits.split('\n')
                for i, ser in enumerate(series.split('\n')):
                    begin, end = None, None
                    res = re.match(r'^(\d+)-(\d+).*$', ser)
                    if res:
                        begin, end = res.group(1), res.group(2)
                    if begin is None:
                        res = re.match(r'^(\d{4}).*$', ser)
                        if res:
                            begin = res.group(1)
                            end = begin

                    if begin and end:
                        digits = None
                        try:
                            digits = int(acc_digits)
                        except ValueError:
                            pass
                        if digits is None:
                            try:
                                digits = int(ml_acc_digits[i])
                            except ValueError:
                                digits = '?'
                            except IndexError:
                                digits = '?'

                        out.append([name, begin, end, digits])
                        # print('OK!')
    return out

Response: Loads Swedish monetary institution codes in CSV format.


Instruction:
Can you implement a function in Python 3 that
logs an entry to admin logs of model instances.

Response:
def admin_log(instances, msg: str, who: User=None, **kw):
    """
    Logs an entry to admin logs of model(s).
    :param instances: Model instance or list of instances
    :param msg: Message to log
    :param who: Who did the change
    :param kw: Optional key-value attributes to append to message
    :return: None
    """

    from django.contrib.admin.models import LogEntry, CHANGE
    from django.contrib.admin.options import get_content_type_for_model
    from django.utils.encoding import force_text

    # use system user if 'who' is missing
    if not who:
        username = settings.DJANGO_SYSTEM_USER if hasattr(settings, 'DJANGO_SYSTEM_USER') else 'system'
        who, created = User.objects.get_or_create(username=username)

    # append extra keyword attributes if any
    att_str = ''
    for k, v in kw.items():
        if hasattr(v, 'pk'):  # log only primary key for model instances, not whole str representation
            v = v.pk
        att_str += '{}={}'.format(k, v) if not att_str else ', {}={}'.format(k, v)
    if att_str:
        att_str = ' [{}]'.format(att_str)
    msg = str(msg) + att_str

    if not isinstance(instances, list) and not isinstance(instances, tuple):
        instances = [instances]
    for instance in instances:
        if instance:
            LogEntry.objects.log_action(
                user_id=who.pk,
                content_type_id=get_content_type_for_model(instance).pk,
                object_id=instance.pk,
                object_repr=force_text(instance),
                action_flag=CHANGE,
                change_message=msg,
            )


Instruction:
Make a summary of the following Python 3 code
def history_view(self, request, object_id, extra_context=None):
        from django.template.response import TemplateResponse
        from django.contrib.admin.options import get_content_type_for_model
        from django.contrib.admin.utils import unquote
        from django.core.exceptions import PermissionDenied
        from django.utils.text import capfirst
        from django.utils.encoding import force_text
        from django.utils.translation import ugettext as _

        "The 'history' admin view for this model."
        from django.contrib.admin.models import LogEntry
        # First check if the user can see this history.
        model = self.model
        obj = self.get_object(request, unquote(object_id))
        if obj is None:
            return self._get_obj_does_not_exist_redirect(request, model._meta, object_id)

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        # Then get the history for this object.
        opts = model._meta
        app_label = opts.app_label
        action_list = LogEntry.objects.filter(
            object_id=unquote(object_id),
            content_type=get_content_type_for_model(model)
        ).select_related().order_by('-action_time')[:self.max_history_length]

        context = dict(
            self.admin_site.each_context(request),
            title=_('Change history: %s') % force_text(obj),
            action_list=action_list,
            module_name=capfirst(force_text(opts.verbose_name_plural)),
            object=obj,
            opts=opts,
            preserved_filters=self.get_preserved_filters(request),
        )
        context.update(extra_context or {})

        request.current_app = self.admin_site.name

        return TemplateResponse(request, self.object_history_template or [
            "admin/%s/%s/object_history.html" % (app_label, opts.model_name),
            "admin/%s/object_history.html" % app_label,
            "admin/object_history.html"
        ], context)

Response: The history admin view for this model.


Instruction:
How would you code a function in Python 3 to
return owner object by filename.

Response:
def get_object_by_filename(self, request, filename):
        """
        Returns owner object by filename (to be downloaded).
        This can be used to implement custom permission checks.
        :param request: HttpRequest
        :param filename: File name of the downloaded object.
        :return: owner object
        """
        kw = dict()
        kw[self.file_field] = filename
        obj = self.get_queryset(request).filter(**kw).first()
        if not obj:
            raise Http404(_('File {} not found').format(filename))
        return self.get_object(request, obj.id)


Instruction:
Make a summary of the following Python 3 code
def get_download_urls(self):
        info = self.model._meta.app_label, self.model._meta.model_name
        return [
            url(r'^.+(' + self.upload_to + '/.+)/$', self.file_download_view, name='%s_%s_file_download' % info),
        ]

Response: Returns a list of file download URLs for this model.


Instruction:
How would you code a function in Python 3 to
write the given version to the VERSION_FILE.

Response:
def write(version):
    # type: (str) -> None
    """ Write the given version to the VERSION_FILE """
    if not is_valid(version):
        raise ValueError("Invalid version: ".format(version))

    storage = get_version_storage()
    storage.write(version)


Instruction:
How would you code a function in Python 3 to
bump the given version component.

Response:
def bump(component='patch', exact=None):
    # type: (str, str) -> Tuple[str, str]
    """ Bump the given version component.

    Args:
        component (str):
            What part of the version should be bumped. Can be one of:

            - major
            - minor
            - patch

        exact (str):
            The exact version that should be set instead of bumping the current
            one.

    Returns:
        tuple(str, str): A tuple of old and bumped version.
    """
    old_ver = current()

    if exact is None:
        new_ver = _bump_version(old_ver, component)
    else:
        new_ver = exact

    write(new_ver)
    return old_ver, new_ver


Instruction:
Here you have a function in Python 3, explain what it does
def _bump_version(version, component='patch'):
    # type: (str, str) -> str
    """ Bump the given version component.

    Args:
        version (str):
            The current version. The format is: MAJOR.MINOR[.PATCH].
        component (str):
            What part of the version should be bumped. Can be one of:

            - major
            - minor
            - patch

    Returns:
        str: Bumped version as a string.
    """
    if component not in ('major', 'minor', 'patch'):
        raise ValueError("Invalid version component: {}".format(component))

    m = RE_VERSION.match(version)
    if m is None:
        raise ValueError("Version must be in MAJOR.MINOR[.PATCH] format")

    major = m.group('major')
    minor = m.group('minor') or '0'
    patch = m.group('patch') or None

    if patch == '0':
        patch = None

    if component == 'major':
        major = str(int(major) + 1)
        minor = '0'
        patch = None

    elif component == 'minor':
        minor = str(int(minor) + 1)
        patch = None

    else:
        patch = patch or 0
        patch = str(int(patch) + 1)

    new_ver = '{}.{}'.format(major, minor)
    if patch is not None:
        new_ver += '.' + patch

    return new_ver

Response: Bump the given version component.


Instruction:
How would you explain what the following Python 3 function does
def get_version_storage():
    # type: () -> VersionStorage
    """ Get version storage for the given version file.

    The storage engine used depends on the extension of the *version_file*.
    """
    version_file = conf.get_path('version_file', 'VERSION')
    if version_file.endswith('.py'):
        return PyVersionStorage(version_file)
    elif version_file.endswith('package.json'):
        return NodeVersionStorage(version_file)
    else:
        return RawVersionStorage(version_file)

Response: Returns the version storage for the given version file.


Instruction:
Create a Python 3 function for
reading the project version from. py file.

Response:
def read(self):
        # type: () -> Optional[str]
        """ Read the project version from .py file.

        This will regex search in the file for a
        ``__version__ = VERSION_STRING`` and read the version string.
        """
        with open(self.version_file) as fp:
            content = fp.read()
            m = RE_PY_VERSION.search(content)
            if not m:
                return None
            else:
                return m.group('version')


Instruction:
Make a summary of the following Python 3 code
def write(self, version):
        # type: (str) -> None
        """ Write the project version to .py file.

        This will regex search in the file for a
        ``__version__ = VERSION_STRING`` and substitute the version string
        for the new version.
        """
        with open(self.version_file) as fp:
            content = fp.read()

        ver_statement = "__version__ = '{}'".format(version)
        new_content = RE_PY_VERSION.sub(ver_statement, content)
        fs.write_file(self.version_file, new_content)

Response: Writes the project version to. py file.


Instruction:
Write a Python 3 function for
reading the project version from. py file.

Response:
def read(self):
        # type: () -> Optional[str]
        """ Read the project version from .py file.

        This will regex search in the file for a
        ``__version__ = VERSION_STRING`` and read the version string.
        """
        with open(self.version_file) as fp:
            version = fp.read().strip()

            if is_valid(version):
                return version

            return None


Instruction:
Here you have a function in Python 3, explain what it does
def fromfits(infile, hdu = 0, verbose = True):

    pixelarray, hdr = ft.getdata(infile, hdu, header=True)
    pixelarray = np.asarray(pixelarray).transpose()
    #print pixelarray

    pixelarrayshape = pixelarray.shape
    if verbose :
        print "Input shape : (%i, %i)" % (pixelarrayshape[0], pixelarrayshape[1])
        print "Input file BITPIX : %s" % (hdr["BITPIX"])
    pixelarrayshape = np.asarray(pixelarrayshape)
    if verbose :
        print "Internal array type :", pixelarray.dtype.name

    return f2nimage(pixelarray, verbose = verbose)

Response: Returns a nimage object from a FITS file.


Instruction:
Explain what the following Python 3 code does
def rebin(a, newshape):

    shape = a.shape

    lenShape = len(shape)

    factor = np.asarray(shape)/np.asarray(newshape)
    #print factor

    evList = ['a.reshape('] + \
             ['newshape[%d],factor[%d],'%(i,i) for i in xrange(lenShape)] + \
             [')'] + ['.sum(%d)'%(i+1) for i in xrange(lenShape)] + \
             ['/factor[%d]'%i for i in xrange(lenShape)]

    return eval(''.join(evList))

Response: Auxiliary function to rebin ndarray data.


Instruction:
Write a Python 3 function that can
take f2nimages and writes them into one png file side by side.

Response:
def compose(f2nimages, outfile):
    """
    Takes f2nimages and writes them into one single png file, side by side.
    f2nimages is a list of horizontal lines, where each line is a list of f2nimages.
    For instance :
    [
    [image1, image2],
    [image3, image4]
    ]
    The sizes of these images have to "match", so that the final result is rectangular.

    This function is verbose if any of the images is verbose.

    """
    # We start by doing some checks, and try to print out helpfull error messages.
    verbosity = []
    colourmodes = []
    for i, line in enumerate(f2nimages):
        for j, img in enumerate(line):
            if img.verbose:
                print "Checking line %i, image %i (verbose)..." % (i+1, j+1)
            img.checkforpilimage()
            verbosity.append(img.verbose)
            colourmodes.append(img.pilimage.mode)
    verbose = np.any(np.array(verbosity)) # So we set the verbosity used in this function to true if any of the images is verbose.
    colours = list(set(colourmodes))

    # We check if the widths are compatible :
    widths = [np.sum(np.array([img.pilimage.size[0] for img in line])) for line in f2nimages]
    if len(set(widths)) != 1 :
        print "Total widths of the lines :"
        print widths
        raise RuntimeError, "The total widths of your lines are not compatible !"
    totwidth = widths[0]

    # Similar for the heights :
    for i, line in enumerate(f2nimages):
        heights = [img.pilimage.size[1] for img in line]
        if len(set(heights)) != 1 :
            print "Heights of the images in line %i :" % (i + 1)
            print heights
            raise RuntimeError, "Heights of the images in line %i are not compatible." % (i + 1)

    totheight = np.sum(np.array([line[0].pilimage.size[1] for line in f2nimages]))
    # Ok, now it should be safe to go for the composition :
    if verbose:
        print "Composition size : %i x %i" % (totwidth, totheight)

    if verbose:
        print "Colour modes of input : %s" % colours
    if len(colours) == 1 and colours[0] == "L" :
        if verbose :
            print "Builing graylevel composition"
        compoimg = im.new("L", (totwidth, totheight), 128)
    else:
        if verbose :
            print "Building RGB composition"
        compoimg = im.new("RGB", (totwidth, totheight), (255, 0, 0))

    y = 0
    for line in f2nimages:
        x = 0
        for img in line:
            box = (x, y, x+img.pilimage.size[0], y+img.pilimage.size[1])
            #print box
            compoimg.paste(img.pilimage, box)
            x += img.pilimage.size[0]
        y += img.pilimage.size[1]

    if verbose:
        print "Writing compositions to %s...\n%i x %i pixels, mode %s" % (outfile, compoimg.size[0], compoimg.size[1], compoimg.mode)
    compoimg.save(outfile, "PNG")


Instruction:
How would you explain what the following Python 3 function does
def crop(self, xa, xb, ya, yb):

        if self.pilimage != None:
            raise RuntimeError, "Cannot crop anymore, PIL image already exists !"

        if self.verbose:
            print "Cropping : [%i:%i, %i:%i]" % (xa, xb, ya, yb)
        self.numpyarray = self.numpyarray[xa:xb, ya:yb]

        self.xa += xa
        self.ya += ya
        self.xb = self.xa + (xb - xa)
        self.yb = self.ya + (yb - ya)

Response:
Crops the image. Two points :

            - We use numpy conventions
            xa = 200 and xb = 400 will give you a width of 200 pixels !

            - We crop relative to the current array (i.e. not necessarily to the original array !)
            This means you can crop several times in a row with xa = 10, it will each time remove 10 pixels in x !

        But we update the crop region specifications, so that the object remembers how it was cut.

        Please give positive integers in compatible ranges, no checks are made.


Instruction:
Given the following Python 3 function, write the documentation
def irafcrop(self, irafcropstring):
        irafcropstring = irafcropstring[1:-1] # removing the [ ]
        ranges = irafcropstring.split(",")
        xr = ranges[0].split(":")
        yr = ranges[1].split(":")
        xmin = int(xr[0])
        xmax = int(xr[1])+1
        ymin = int(yr[0])
        ymax = int(yr[1])+1
        self.crop(xmin, xmax, ymin, ymax)

Response: Crop the image with the given irafcropstring.


Instruction:
Create a Python 3 function for
making a PIL image out of the array.

Response:
def makepilimage(self, scale = "log", negative = False):
        """
        Makes a PIL image out of the array, respecting the z1 and z2 cutoffs.
        By default we use a log scaling identical to iraf's, and produce an image of mode "L", i.e. grayscale.
        But some drawings or colourscales will change the mode to "RGB" later, if you choose your own colours.
        If you choose scale = "clog" or "clin", you get hue values (aka rainbow colours).
        """

        if scale == "log" or scale == "lin":
            self.negative = negative
            numpyarrayshape = self.numpyarray.shape
            calcarray = self.numpyarray.copy()
            #calcarray.ravel() # does not change in place in fact !
            calcarray = calcarray.clip(min = self.z1, max = self.z2)

            if scale == "log":
                calcarray = np.array(map(lambda x: loggray(x, self.z1, self.z2), calcarray))
            else :
                calcarray = np.array(map(lambda x: lingray(x, self.z1, self.z2), calcarray))

            calcarray.shape = numpyarrayshape
            bwarray = np.zeros(numpyarrayshape, dtype=np.uint8)
            calcarray.round(out=bwarray)
            if negative:
                if self.verbose:
                    print "Using negative scale"
                bwarray = 255 - bwarray

            if self.verbose:
                print "PIL range : [%i, %i]" % (np.min(bwarray), np.max(bwarray))

            # We flip it so that (0, 0) is back in the bottom left corner as in ds9
            # We do this here, so that you can write on the image from left to right :-)

            self.pilimage = imop.flip(im.fromarray(bwarray.transpose()))
            if self.verbose:
                    print "PIL image made with scale : %s" % scale
            return 0

        if scale == "clog" or scale == "clin":

            """
            rainbow !
            Algorithm for HSV to RGB from http://www.cs.rit.edu/~ncs/color/t_convert.html, by Eugene Vishnevsky
            Same stuff then for f2n in C

            h is from 0 to 360 (hue)
            s from 0 to 1 (saturation)
            v from 0 to 1 (brightness)
            """

            self.negative = False
            calcarray = self.numpyarray.transpose()
            if scale == "clin":
                calcarray = (calcarray.clip(min = self.z1, max = self.z2)-self.z1)/(self.z2 - self.z1) # 0 to 1
            if scale == "clog":
                calcarray = 10.0 + 990.0 * (calcarray.clip(min = self.z1, max = self.z2)-self.z1)/(self.z2 - self.z1) # 10 to 1000
                calcarray = (np.log10(calcarray)-1.0)*0.5 # 0 to 1

            #calcarray = calcarray * 359.0 # This is now our "hue value", 0 to 360
            calcarray = (1.0-calcarray) * 300.0 # I limit this to not go into red again
            # The order of colours is Violet < Blue < Green < Yellow < Red

            # We prepare the output arrays
            rcalcarray = np.ones(calcarray.shape)
            gcalcarray = np.ones(calcarray.shape)
            bcalcarray = np.ones(calcarray.shape)

            h = calcarray/60.0 # sector 0 to 5
            i = np.floor(h).astype(np.int)

            v = 1.0 * np.ones(calcarray.shape)
            s = 1.0 * np.ones(calcarray.shape)

            f = h - i # factorial part of h, this is an array
            p = v * ( 1.0 - s )
            q = v * ( 1.0 - s * f )
            t = v * ( 1.0 - s * ( 1.0 - f ) )

            # sector 0:
            indices = (i == 0)
            rcalcarray[indices] = 255.0 * v[indices]
            gcalcarray[indices] = 255.0 * t[indices]
            bcalcarray[indices] = 255.0 * p[indices]

            # sector 1:
            indices = (i == 1)
            rcalcarray[indices] = 255.0 * q[indices]
            gcalcarray[indices] = 255.0 * v[indices]
            bcalcarray[indices] = 255.0 * p[indices]

            # sector 2:
            indices = (i == 2)
            rcalcarray[indices] = 255.0 * p[indices]
            gcalcarray[indices] = 255.0 * v[indices]
            bcalcarray[indices] = 255.0 * t[indices]

            # sector 3:
            indices = (i == 3)
            rcalcarray[indices] = 255.0 * p[indices]
            gcalcarray[indices] = 255.0 * q[indices]
            bcalcarray[indices] = 255.0 * v[indices]

            # sector 4:
            indices = (i == 4)
            rcalcarray[indices] = 255.0 * t[indices]
            gcalcarray[indices] = 255.0 * p[indices]
            bcalcarray[indices] = 255.0 * v[indices]

            # sector 5:
            indices = (i == 5)
            rcalcarray[indices] = 255.0 * v[indices]
            gcalcarray[indices] = 255.0 * p[indices]
            bcalcarray[indices] = 255.0 * q[indices]

            rarray = np.zeros(calcarray.shape, dtype=np.uint8)
            garray = np.zeros(calcarray.shape, dtype=np.uint8)
            barray = np.zeros(calcarray.shape, dtype=np.uint8)
            rcalcarray.round(out=rarray)
            gcalcarray.round(out=garray)
            bcalcarray.round(out=barray)

            carray = np.dstack((rarray,garray,barray))

            self.pilimage = imop.flip(im.fromarray(carray, "RGB"))
            if self.verbose:
                    print "PIL image made with scale : %s" % scale
            return 0

        raise RuntimeError, "I don't know your colourscale, choose lin log clin or clog !"


Instruction:
Can you generate a brief explanation for the following Python 3 code
def showcutoffs(self, redblue = False):

        highmask = self.numpyarray > self.z2
        lowmask = self.numpyarray < self.z1
        if redblue == False :
            if self.negative :
                self.drawmask(highmask, colour = 255)
                self.drawmask(lowmask, colour = 0)
            else :
                self.drawmask(highmask, colour = 0)
                self.drawmask(lowmask, colour = 255)
        else :

            self.drawmask(highmask, colour = (255, 0, 0))
            self.drawmask(lowmask, colour = (0, 0, 255))

Response: This method shows the cutoffs of the related image.


Instruction:
How would you explain what the following Python 3 function does
def makedraw(self):
        if self.draw == None:
            self.draw = imdw.Draw(self.pilimage)

Response: Auxiliary method to make a draw object.


Instruction:
How would you explain what the following Python 3 function does
def loadtitlefont(self):
        if self.titlefont == None:
#             print 'the bloody fonts dir is????', fontsdir
#             print 'pero esto que hace??', os.path.join(fontsdir, "courR18.pil")
#             /home/vital/Workspace/pyResources/Scientific_Lib/f2n_fonts/f2n_fonts/courR18.pil
#             /home/vital/Workspace/pyResources/Scientific_Lib/f2n_fonts
            self.titlefont = imft.load_path(os.path.join(fontsdir, "courR18.pil"))

Response: Loads the title font from the file system.


Instruction:
Explain what the following Python 3 code does
def loadlabelfont(self):
        if self.labelfont == None:
            self.labelfont = imft.load_path(os.path.join(fontsdir, "courR10.pil"))

Response: Auxiliary method to load label font if not yet done.


Instruction:
Explain what the following Python 3 code does
def changecolourmode(self, newcolour):
        if type(newcolour) != type(0) and self.pilimage.mode != "RGB":
            if self.verbose :
                print "Switching to RGB !"
            self.pilimage = self.pilimage.convert("RGB")
            self.draw = None # important, we have to bebuild the draw object.
            self.makedraw()

Response: Change the colour mode of the current image.


Instruction:
Can you implement a function in Python 3 that
converts the coordinates x y of the original array or FITS file to the current coordinates of the PIL image.

Response:
def pilcoords(self, (x,y)):
        """
        Converts the coordinates (x,y) of the original array or FITS file to the current coordinates of the PIL image,
        respecting cropping, rebinning, and upsampling.
        This is only used once the PIL image is available, for drawing.
        Note that we also have to take care about the different origin conventions here !
        For PIL, (0,0) is top left, so the y axis needs to be inverted.
        """

        pilx = int((x - 1 - self.xa) * float(self.upsamplefactor) / float(self.binfactor))
        pily = int((self.yb - y) * float(self.upsamplefactor) / float(self.binfactor))

        return (pilx, pily)


Instruction:
Create a Python 3 function for
converting a scale from the original array or FITS file to the current PIL coordinates.

Response:
def pilscale(self, r):
        """
        Converts a "scale" (like an aperture radius) of the original array or FITS file to the current PIL coordinates.
        """
        return r * float(self.upsamplefactor) / float(self.binfactor)


Instruction:
Write a Python 3 function that can
draw a point on the current image.

Response:
def drawpoint(self, x, y, colour = None):
        """
        Most elementary drawing, single pixel, used mainly for testing purposes.
        Coordinates are those of your initial image !
        """
        self.checkforpilimage()
        colour = self.defaultcolour(colour)
        self.changecolourmode(colour)
        self.makedraw()

        (pilx, pily) = self.pilcoords((x,y))

        self.draw.point((pilx, pily), fill = colour)


Instruction:
How would you code a function in Python 3 to
draw a circle centered on x y with radius r.

Response:
def drawcircle(self, x, y, r = 10, colour = None, label = None):
        """
        Draws a circle centered on (x, y) with radius r. All these are in the coordinates of your initial image !
        You give these x and y in the usual ds9 pixels, (0,0) is bottom left.
        I will convert this into the right PIL coordiates.
        """

        self.checkforpilimage()
        colour = self.defaultcolour(colour)
        self.changecolourmode(colour)
        self.makedraw()

        (pilx, pily) = self.pilcoords((x,y))
        pilr = self.pilscale(r)

        self.draw.ellipse([(pilx-pilr+1, pily-pilr+1), (pilx+pilr+1, pily+pilr+1)], outline = colour)

        if label != None:
            # The we write it :
            self.loadlabelfont()
            textwidth = self.draw.textsize(label, font = self.labelfont)[0]
            self.draw.text((pilx - float(textwidth)/2.0 + 2, pily + pilr + 4), label, fill = colour, font = self.labelfont)


Instruction:
Create a Python 3 function for
drawing a 1 - pixel wide frame AROUND the region you specify.

Response:
def drawrectangle(self, xa, xb, ya, yb, colour=None, label = None):
        """
        Draws a 1-pixel wide frame AROUND the region you specify. Same convention as for crop().

        """

        self.checkforpilimage()
        colour = self.defaultcolour(colour)
        self.changecolourmode(colour)
        self.makedraw()

        (pilxa, pilya) = self.pilcoords((xa,ya))
        (pilxb, pilyb) = self.pilcoords((xb,yb))

        self.draw.rectangle([(pilxa, pilyb-1), (pilxb+1, pilya)], outline = colour)

        if label != None:
            # The we write it :
            self.loadlabelfont()
            textwidth = self.draw.textsize(label, font = self.labelfont)[0]
            self.draw.text(((pilxa + pilxb)/2.0 - float(textwidth)/2.0 + 1, pilya + 2), label, fill = colour, font = self.labelfont)


Instruction:
Can you generate the documentation for the following Python 3 function
def writetitle(self, titlestring, colour = None):

        self.checkforpilimage()
        colour = self.defaultcolour(colour)
        self.changecolourmode(colour)
        self.makedraw()

        self.loadtitlefont()

        imgwidth = self.pilimage.size[0]
        imgheight = self.pilimage.size[1]
        textwidth = self.draw.textsize(titlestring, font = self.titlefont)[0]
        textxpos = imgwidth/2.0 - textwidth/2.0
        textypos = imgheight - 30

        self.draw.text((textxpos, textypos), titlestring, fill = colour, font = self.titlefont)

        if self.verbose :
            print "I've written a title on the image."

Response: Writes a title on the image.


Instruction:
Create a Python 3 function to
write some info on the image.

Response:
def writeinfo(self, linelist, colour = None):
        """
        We add a longer chunk of text on the upper left corner of the image.
        Provide linelist, a list of strings that will be written one below the other.
        """

        self.checkforpilimage()
        colour = self.defaultcolour(colour)
        self.changecolourmode(colour)
        self.makedraw()

        self.loadinfofont()

        for i, line in enumerate(linelist):
            topspacing = 5 + (12 + 5)*i
            self.draw.text((10, topspacing), line, fill = colour, font = self.infofont)

        if self.verbose :
            print "I've written some info on the image."


Instruction:
Write a Python 3 function for
calling drawcircle and writelable for an list of stars.

Response:
def drawstarslist(self, dictlist, r = 10, colour = None):
        """
        Calls drawcircle and writelable for an list of stars.
        Provide a list of dictionnaries, where each dictionnary contains "name", "x", and "y".

        """

        self.checkforpilimage()
        colour = self.defaultcolour(colour)
        self.changecolourmode(colour)
        self.makedraw()

        for star in dictlist:
            self.drawcircle(star["x"], star["y"], r = r, colour = colour, label = star["name"])
            #self.writelabel(star["x"], star["y"], star["name"], r = r, colour = colour)

        if self.verbose :
            print "I've drawn %i stars." % len(dictlist)


Instruction:
Create a Python 3 function for
writing the PIL image into a png file.

Response:
def tonet(self, outfile):
        """
        Writes the PIL image into a png.
        We do not want to flip the image at this stage, as you might have written on it !
        """

        self.checkforpilimage()
        if self.verbose :
            print "Writing image to %s...\n%i x %i pixels, mode %s" % (outfile, self.pilimage.size[0], self.pilimage.size[1], self.pilimage.mode)
        self.pilimage.save(outfile, "PNG")


Instruction:
Can you tell what is the following Python 3 function doing
def cors_setup(self, request):
        def cors_headers(request, response):
            if request.method.lower() == 'options':
                response.headers.update({
                    '-'.join([p.capitalize() for p in k.split('_')]): v
                    for k, v in self.cors_options.items()
                })
            else:
                origin = self.cors_options.get('access_control_allow_origin', '*')
                expose_headers = self.cors_options.get('access_control_expose_headers', '')
                response.headers['Access-Control-Allow-Origin'] = origin
                if expose_headers:
                    response.headers['Access-Control-Expose-Headers'] = expose_headers

        # setup the CORS supported response
        request.add_response_callback(cors_headers)

Response: Sets up the CORS headers response based on the settings used for the API.


Instruction:
Make a summary of the following Python 3 code
def factory(self, request, parent=None, name=None):
        traverse = request.matchdict['traverse']

        # show documentation at the root path
        if not traverse:
            return {}
        else:
            service = {}
            name = name or traverse[0]

            # look for direct pattern matches
            traversed = '/' + '/'.join(traverse)
            service_type = None
            service_object = None

            for route, endpoint in self.routes:
                result = route.match(traversed)
                if result is not None:
                    request.matchdict = result
                    request.endpoint = endpoint
                    break
            else:
                try:
                    service_type, service_object = self.services[name]
                except KeyError:
                    raise HTTPNotFound()

            if service_type:
                if isinstance(service_type, Endpoint):
                    service[name] = service_type
                elif service_object is None:
                    service[name] = service_type(request)
                else:
                    service[name] = service_type(request, service_object)

            request.api_service = service
            return service

Response: Returns a new service for the given request.


Instruction:
Can you create a Python 3 function that
registers a given service to this API.

Response:
def register(self, service, name=''):
        """
        Exposes a given service to this API.
        """
        # expose a sub-factory
        if isinstance(service, ApiFactory):
            self.services[name] = (service.factory, None)

        # expose a module dynamically as a service
        elif inspect.ismodule(service):
            name = name or service.__name__.split('.')[-1]

            # exclude endpoints with patterns
            for obj in vars(service).values():
                endpoint = getattr(obj, 'endpoint', None)
                if isinstance(endpoint, Endpoint) and endpoint.pattern:
                    route = Route('', endpoint.pattern)
                    self.routes.append((route, endpoint))

            self.services[name] = (ModuleService, service)

        # expose a class dynamically as a service
        elif inspect.isclass(service):
            name = name or service.__name__
            self.services[name] = (ClassService, service)

        # expose an endpoint directly
        elif isinstance(getattr(service, 'endpoint', None), Endpoint):
            if service.endpoint.pattern:
                route = Route('', service.endpoint.pattern)
                self.routes.append((route, service.endpoint))
            else:
                self.services[service.endpoint.name] = (service.endpoint, None)

        # expose a scope
        elif isinstance(service, dict):
            for srv in service.values():
                try:
                    self.register(srv)
                except RuntimeError:
                    pass

        # expose a list of services
        elif isinstance(service, list):
            for srv in service:
                try:
                    self.register(srv)
                except RuntimeError:
                    pass

        # expose a service directly
        else:
            raise RuntimeError('Invalid service provide: {0} ({1}).'.format(service, type(service)))


Instruction:
Make a summary of the following Python 3 code
def serve(self, config, path, route_name=None, permission=None, **view_options):
        route_name = route_name or path.replace('/', '.').strip('.')
        path = path.strip('/') + '*traverse'

        self.route_name = route_name
        self.base_permission = permission

        # configure the route and the path
        config.add_route(route_name, path, factory=self.factory)
        config.add_view(
            self.handle_standard_error,
            route_name=route_name,
            renderer='json2',
            context=StandardError
        ),
        config.add_view(
            self.handle_http_error,
            route_name=route_name,
            renderer='json2',
            context=HTTPException
        )
        config.add_view(
            self.process,
            route_name=route_name,
            renderer='json2',
            **view_options
        )

Response: Serves this API from the inputted root path


Instruction:
Make a summary of the following Python 3 code
def line(separator="-·-", color=None, padding=None, num=1):
    for x in range(num):
        columns = get_terminal_width()
        separator = "".join(
            separator for x in
            range(floor(columns/len(separator))))
        print(padd(colorize(separator.strip(), color), padding))

Response: Prints a line from the terminal.


Instruction:
Can you generate the documentation for the following Python 3 function
def padd(text, padding="top", size=1):
    if padding:
        padding = padding.lower()
        pad_all = padding == 'all'
        padding_top = ""
        if padding and (padding == 'top' or pad_all):
            padding_top = "".join("\n" for x in range(size))
        padding_bottom = ""
        if padding and (padding == 'bottom' or pad_all):
            padding_bottom = "".join("\n" for x in range(size))
        return "{}{}{}".format(padding_top, text, padding_bottom)
    return text

Response:
Adds extra new lines to the top bottom or all of a String
           .


Instruction:
Make a summary of the following Python 3 code
def colorize(text, color="BLUE", close=True):
    if color:
        color = getattr(colors, color.upper())
        return color + uncolorize(str(text)) + (colors.RESET if close else "")
    return text

Response: Colorizes the text for terminal outputs.


Instruction:
Can you tell what is the following Python 3 function doing
def bold(text, close=True):
    return getattr(colors, "BOLD") + str(text) + \
        (colors.RESET if close else "")

Response: Bolds text for terminal outputs


Instruction:
Create a Python 3 function to
shorten text to length appends replace_with to end of string

Response:
def cut(text, length=50, replace_with="…"):
    """ Shortens text to @length, appends @replace_with to end of string
        if the string length is > @length

        @text: #str text to shortens
        @length: #int max length of string
        @replace_with: #str to replace chars beyond @length with
        ..
            from vital.debug import cut

            cut("Hello world", 8)
            # -> 'Hello w…'

            cut("Hello world", 15)
            # -> 'Hello world'
        ..
    """
    text_len = len(uncolorize(text))
    if text_len > length:
        replace_len = len(replace_with)
        color_spans = [
            _colors.span() for _colors in _find_colors.finditer(text)]
        chars = 0
        _length = length+1 - replace_len
        for i, c in enumerate(text):
            broken = False
            for span in color_spans:
                if span[0] <= i < span[1]:
                    broken = True
                    break
            if broken:
                continue
            chars += 1
            if chars <= _length:
                cutoff = i
            else:
                break
        if color_spans:
            return text[:cutoff] + replace_with + colors.RESET
        else:
            return text[:cutoff] + replace_with
    return text


Instruction:
Write a Python 3 script for
wrapping @text in parentheses (), optionally colors and pads and prints the text. @text: #str text to (flag) @color: #str color to :func:colorize the text within @padding: #str location of padding from :func:padd @show: #bool whether or not to print the text in addition to returning it -> #str (flagged) text .. from vital.debug import flag flag("Hello world", "blue") # -> (Hello world) # '(\x1b[0;34mHello world\x1b[1;m)' flag("Hello world", "blue", show=False) # -> '(\x1b[0;34mHello world\x1b[1;m)' flag("Hello world", color="blue", padding="all") # -> # (Hello world) # # '\\n(\x1b[0;34mHello world\x1b[1;m)\\n' ..

Response:
def flag(text=None, color=None, padding=None, show=True, brackets='⸨⸩'):
    """ Wraps @text in parentheses (), optionally colors and pads and
        prints the text.

        @text: #str text to (flag)
        @color: #str color to :func:colorize the text within
        @padding: #str location of padding from :func:padd
        @show: #bool whether or not to print the text in addition to returning
            it

        -> #str (flagged) text
        ..
            from vital.debug import flag

            flag("Hello world", "blue")
            # -> (Hello world)
            #    '(\x1b[0;34mHello world\x1b[1;m)'

            flag("Hello world", "blue", show=False)
            # -> '(\x1b[0;34mHello world\x1b[1;m)'

            flag("Hello world", color="blue", padding="all")
            # ->
            #    (Hello world)
            #
            #    '\\n(\x1b[0;34mHello world\x1b[1;m)\\n'
        ..
    """
    _flag = None
    if text:
        _flag = padd(
            "{}{}{}".format(
                brackets[0],
                colorize(text, color) if color else text,
                brackets[1]
            ),
            padding
        )
        if not show:
            return _flag
        else:
            print(_flag)
    return _flag or text


Instruction:
Make a summary of the following Python 3 code
def gen_rand_str(*size, use=None, keyspace=None):
    keyspace = keyspace or (string.ascii_letters + string.digits)
    keyspace = [char for char in keyspace]
    use = use or _random
    use.seed()
    if size:
        size = size if len(size) == 2 else (size[0], size[0])
    else:
        size = (10, 12)
    return ''.join(
        use.choice(keyspace)
        for _ in range(use.randint(*size)))

Response: Generates a random string from the specified random module.


Instruction:
Implement a Python 3 function for
getting the name of the object containing the object and returns as a string

Response:
def get_parent_name(obj):
    """ Gets the name of the object containing @obj and returns as a string

        @obj: any python object

        -> #str parent object name or None
        ..
            from vital.debug import get_parent_name

            get_parent_name(get_parent_name)
            # -> 'vital.debug'

            get_parent_name(vital.debug)
            # -> 'vital'

            get_parent_name(str)
            # -> 'builtins'
        ..
    """
    parent_obj = get_parent_obj(obj)
    parent_name = get_obj_name(parent_obj) if parent_obj else None
    n = 0
    while parent_obj and n < 2500:
        parent_obj = get_parent_obj(parent_obj)
        if parent_obj:
            parent_name = "{}.{}".format(get_obj_name(parent_obj), parent_name)
            n += 1
    if not parent_name or not len(parent_name):
        parent_name = None
        objname = get_obj_name(obj)
        if objname and len(objname.split(".")) > 1:
            return ".".join(objname.split(".")[:-1])
        return None
    return parent_name


Instruction:
How would you explain what the following Python 3 function does
def get_class_that_defined_method(meth):
    if inspect.ismethod(meth):
        for cls in inspect.getmro(meth.__self__.__class__):
            if cls.__dict__.get(meth.__name__) is meth:
                return cls
        meth = meth.__func__  # fallback to __qualname__ parsing
    if inspect.isfunction(meth):
        cls = getattr(
            inspect.getmodule(meth),
            meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0])
        if isinstance(cls, type):
            return cls
    return None

Response: Gets the class object which defined a given method.


Instruction:
Here you have a function in Python 3, explain what it does
def get_parent_obj(obj):
    try:
        cls = get_class_that_defined_method(obj)
        if cls and cls != obj:
            return cls
    except AttributeError:
        pass
    if hasattr(obj, '__module__') and obj.__module__:
        try:
            module = locate(obj.__module__)
            assert module is not obj
            return module
        except Exception:
            try:
                module = module.__module__.split('.')[:-1]
                if len(module):
                    return locate(module)
            except Exception:
                pass
    elif hasattr(obj, '__objclass__') and obj.__objclass__:
        return obj.__objclass__
    try:
        assert hasattr(obj, '__qualname__') or hasattr(obj, '__name__')
        objname = obj.__qualname__ if hasattr(obj, '__qualname__') \
            else obj.__name__
        objname = objname.split(".")
        assert len(objname) > 1
        return locate(".".join(objname[:-1]))
    except Exception:
        try:
            module = importlib.import_module(".".join(objname[:-1]))
            return module
        except Exception:
            pass
    return None

Response:
Gets the name of the object containing obj and returns as a string
       ..


Instruction:
Can you write a function in Python 3 where it
formats the object name in a pretty way that contains a parent object name.

Response:
def format_obj_name(obj, delim="<>"):
    """ Formats the object name in a pretty way

        @obj: any python object
        @delim: the characters to wrap a parent object name in

        -> #str formatted name
        ..
            from vital.debug import format_obj_name

            format_obj_name(vital.debug.Timer)
            # -> 'Timer<vital.debug>'

            format_obj_name(vital.debug)
            # -> 'debug<vital>'

            format_obj_name(vital.debug.Timer.time)
            # -> 'time<vital.debug.Timer>'
        ..
    """
    pname = ""
    parent_name = get_parent_name(obj)
    if parent_name:
        pname = "{}{}{}".format(delim[0], get_parent_name(obj), delim[1])
    return "{}{}".format(get_obj_name(obj), pname)


Instruction:
Here you have a function in Python 3, explain what it does
def preprX(*attributes, address=True, full_name=False,
           pretty=False, keyless=False, **kwargs):
    """ `Creates prettier object representations`

        @*attributes: (#str) instance attributes within the object you
            wish to display. Attributes can be recursive
            e.g. |one.two.three| for access to |self.one.two.three|
        @address: (#bool) |True| to include the memory address
        @full_name: (#bool) |True| to include the full path to the
            object vs. the qualified name
        @pretty: (#bool) |True| to allow bolding and coloring
        @keyless: (#bool) |True| to display the values of @attributes
            withotu their attribute names
        ..
            class Foo(object):

                def __init__(self, bar, baz=None):
                    self.bar = bar
                    self.baz = baz

                __repr__ = prepr('bar', 'baz', address=False)

            foo = Foo('foobar')
            repr(foo)
        ..
        |<Foo:bar=`foobar`, baz=None>|
    """
    def _format(obj, attribute):
        try:
            if keyless:
                val = getattr_in(obj, attribute)
                if val is not None:
                    return repr(val)
            else:
                return '%s=%s' % (attribute,
                                  repr(getattr_in(obj, attribute)))
        except AttributeError:
            return None

    def prep(obj, address=address, full_name=full_name, pretty=pretty,
             keyless=keyless, **kwargs):
        if address:
            address = ":%s" % hex(id(obj))
        else:
            address = ""
        data = list(filter(lambda x: x is not None,
                           map(lambda a: _format(obj, a), attributes)))
        if data:
            data = ':%s' % ', '.join(data)
        else:
            data = ''
        return stdout_encode("<%s%s%s>" % (get_obj_name(obj), data, address))
    return prep

Response: Creates prettier object representations


Instruction:
Can you tell what is the following Python 3 function doing
def add_attrs(self, *args, _order=[], **kwargs):
        for arg in args:
            if isinstance(arg, (tuple, list)):
                key, color = arg
                self.attrs[key] = (None, color)
            else:
                self.attrs[arg] = (None, None)
        if not _order:
            for key, value in kwargs.items():
                self.attrs[key] = (value, None)
        else:
            for key in _order:
                self.attrs[key] = (kwargs[key], None)

Response: Adds attributes to the __repr__ string


Instruction:
Explain what the following Python 3 code does
def _format_attrs(self):
        _bold = bold
        _colorize = colorize
        if not self.pretty:
            _bold = lambda x: x
            _colorize = lambda x, c: x
        attrs = []
        add_attr = attrs.append
        if self.doc and hasattr(self.obj, "__doc__"):
            # Optionally attaches documentation
            if self.obj.__doc__:
                add_attr("`{}`".format(self.obj.__doc__.strip()))
        if self.attrs:
            # Attach request attributes
            for key, value in self.attrs.items():
                value, color = value
                try:
                    value = value or \
                        self._getattrs(getattr, self.obj, key.split("."))
                except AttributeError:
                    pass
                value = _colorize(value, color) if color else value
                v = None
                if value is not None:
                    value = "`{}`".format(value) \
                        if isinstance(value, Look.str_) else value
                    k, v = _bold(key), value
                else:
                    k, v = _bold(key), str(value)
                if v:
                    k = '{}='.format(k) if not self._no_keys else ''
                    add_attr("{}{}".format(k, v))
        if len(attrs):
            breaker = "\n    " if self.line_break and len(attrs) > 1 else ""
            return breaker + ((", "+breaker).join(attrs)) + breaker.strip(" ")
        else:
            return ""

Response: Formats the attributes of the current object.


Instruction:
How would you implement a function in Python 3 that
formats the __repr__ string containing __repr__ output

Response:
def format(self):
        """ Formats the __repr__ string
            -> #str containing __repr__ output
        """
        _bold = bold
        _break = "\n    "
        if not self.pretty:
            _bold = lambda x: x
        # Attach memory address and return
        _attrs = self._format_attrs()
        parent_name = get_parent_name(self.obj) if self.full_name else None
        self.data = "<{}{}:{}{}>{}".format(
            parent_name + "." if parent_name else "",
            get_obj_name(self.obj),
            _attrs,
            ":{}".format(hex(id(self.obj))) if self.address else "",
            _break+self.supplemental if self.supplemental else "")
        return stdout_encode(self.data)


Instruction:
Can you implement a function in Python 3 that
generates random string from the current system.

Response:
def randstr(self):
        """ -> #str result of :func:gen_rand_str """
        return gen_rand_str(
            4, 10, use=self.random, keyspace=list(string.ascii_letters))


Instruction:
Write a Python 3 script for
returning a random bytes - encoded version of the current n - z instance.

Response:
def randbytes(self):
        """ -> #bytes result of bytes-encoded :func:gen_rand_str """
        return gen_rand_str(
            10, 30, use=self.random, keyspace=list(self.keyspace)
        ).encode("utf-8")


Instruction:
Write a Python 3 function that can
return a randomized domain - like name

Response:
def randdomain(self):
        """ -> a randomized domain-like name """
        return '.'.join(
            rand_readable(3, 6, use=self.random, density=3)
            for _ in range(self.random.randint(1, 2))
        ).lower()


Instruction:
Implement a Python 3 function for
returning a random URI - like path

Response:
def randpath(self):
        """ -> a random URI-like #str path """
        return '/'.join(
            gen_rand_str(3, 10, use=self.random, keyspace=list(self.keyspace))
            for _ in range(self.random.randint(0, 3)))


Instruction:
Write a Python 3 function for
returning a random tld from the set of TLDs

Response:
def randtld(self):
        """ -> a random #str tld via :mod:tlds """
        self.tlds = tuple(tlds.tlds) if not self.tlds else self.tlds
        return self.random.choice(self.tlds)


Instruction:
Write a Python 3 function for
returning a random url - like string via Random.

Response:
def randurl(self):
        """ -> a random url-like #str via :prop:randdomain, :prop:randtld,
                and :prop:randpath
        """
        return "{}://{}.{}/{}".format(
            self.random.choice(("http", "https")),
            self.randdomain, self.randtld, self.randpath)


Instruction:
Explain what the following Python 3 code does
def randtuple(self):
        return tuple(
            self.randint
            for x in range(0, self.random.randint(3, 10)))

Response: Returns a random tuple of random integers


Instruction:
How would you explain what the following Python 3 function does
def randdeque(self):
        return deque(
            self.randint
            for x in range(0, self.random.randint(3, 10)))

Response: Returns a deque of random integers.


Instruction:
Can you write a function in Python 3 where it
returns a random dictionary of the class

Response:
def randdict(self):
        """ -> a #dict of |{random_string: random_int}| """
        return {
            self.randstr: self._map_type(int)
            for x in range(self.random.randint(3, 10))}


Instruction:
Can you tell what is the following Python 3 function doing
def randset(self):
        return {
            self._map_type(int)
            for x in range(self.random.randint(3, 10))}

Response: Returns a set of random integers


Instruction:
Explain what the following Python 3 code does
def dict(self, key_depth=1000, tree_depth=1):
        if not tree_depth:
            return self._map_type()
        return {
            self.randstr: self.dict(key_depth, tree_depth-1)
            for x in range(key_depth)}

Response: Creates a dict of random items for the current tree depth.


Instruction:
Given the following Python 3 function, write the documentation
def defaultdict(self, key_depth=1000, tree_depth=1):
        if not tree_depth:
            return self._map_type()
        _dict = defaultdict()
        _dict.update({
            self.randstr: self.defaultdict(key_depth, tree_depth-1)
            for x in range(key_depth)})
        return _dict

Response: Creates a dictionary of random values for the available node types.


Instruction:
How would you code a function in Python 3 to
create a random tuple of size and tree_depth

Response:
def tuple(self, size=1000, tree_depth=1):
        """ Creates a random #tuple

            @size: #int number of random values to include in each @tree_depth
            @tree_depth: #int dict tree dimensions size, i.e.
                1=|(value1, value2)|
                2=|((value1, value2), (value1, value2))|

            -> random #tuple
        """
        if not tree_depth:
            return self._map_type()
        return tuple(self.tuple(size, tree_depth-1) for x in range(size))


Instruction:
How would you explain what the following Python 3 function does
def generator(self, size=1000, tree_depth=1):
        if not tree_depth:
            return self._map_type()
        return (self.generator(size, tree_depth-1) for x in range(size))

Response: Creates a random generator for the size of the items in the tree_depth.


Instruction:
Write a Python 3 function for
generating random values for the sequence - like objects in the specified structure.

Response:
def sequence(self, struct, size=1000, tree_depth=1, append_callable=None):
        """ Generates random values for sequence-like objects

            @struct: the sequence-like structure you want to fill with random
                data
            @size: #int number of random values to include in each @tree_depth
            @tree_depth: #int dict tree dimensions size, i.e.
                1=|(value1, value2)|
                2=|((value1, value2), (value1, value2))|
            @append_callable: #callable method which appends/adds data to your
                sequence-like structure - e.g. :meth:list.append

            -> random @struct
            ..
                from collections import UserList
                from vital.debug import RandData

                class MySequence(UserList):
                    pass

                rd = RandData(int)

                my_seq = MySequence()
                rd.sequence(my_seq, 3, 1, my_seq.append)
                # -> [88508293836062443, 49097807561770961, 55043550817099444]
            ..
        """
        if not tree_depth:
            return self._map_type()
        _struct = struct()
        add_struct = _struct.append if not append_callable \
            else getattr(_struct, append_callable)
        for x in range(size):
            add_struct(self.sequence(
                struct, size, tree_depth-1, append_callable))
        return _struct


Instruction:
How would you code a function in Python 3 to
generate random values for the dict - like object in the tree.

Response:
def mapping(self, struct, key_depth=1000, tree_depth=1,
                update_callable=None):
        """ Generates random values for dict-like objects

            @struct: the dict-like structure you want to fill with random data
            @size: #int number of random values to include in each @tree_depth
            @tree_depth: #int dict tree dimensions size, i.e.
                1=|{key: value}|
                2=|{key: {key: value}, key2: {key2: value2}}|
            @update_callable: #callable method which updates data in your
                dict-like structure - e.g. :meth:builtins.dict.update

            -> random @struct
            ..
                from collections import UserDict
                from vital.debug import RandData

                class MyDict(UserDict):
                    pass

                rd = RandData(int)

                my_dict = MyDict()
                rd.dict(my_dict, 3, 1, my_dict.update)
                # -> {
                #   'SE0ZNy0F6O': 42078648993195761,
                #   'pbK': 70822820981335987,
                #   '0A5Aa7': 17503122029338459}
            ..
        """
        if not tree_depth:
            return self._map_type()
        _struct = struct()
        add_struct = _struct.update if not update_callable \
            else getattr(_struct, update_callable)
        for x in range(key_depth):
            add_struct({
                self.randstr: self.mapping(
                    struct, key_depth, tree_depth-1, update_callable)
            })
        return _struct


Instruction:
Can you create a Python 3 function that
returns a string that is prefixed with the key and value.

Response:
def _dict_prefix(self, key, value, i, dj=0, color=None, separator=":"):
        just = self._justify if i > 0 else dj
        key = cut(str(key), self._key_maxlen).rjust(just)
        key = colorize(key, color=color)
        pref = "{}{} {}".format(key, separator, value)
        """pref = "{}{} {}".format(colorize(str(key)[:self._key_maxlen]\
            .rjust(just), color=color), separator, value)"""
        return pref


Instruction:
How would you code a function in Python 3 to
format object names in a pretty fashion

Response:
def objname(self, obj=None):
        """ Formats object names in a pretty fashion """
        obj = obj or self.obj
        _objname = self.pretty_objname(obj, color=None)
        _objname = "'{}'".format(colorize(_objname, "blue"))
        return _objname


Instruction:
Implement a Python 3 function for
formatting the object in a pretty format.

Response:
def pretty(self, obj=None, display=True):
        """ Formats @obj or :prop:obj

            @obj: the object you'd like to prettify

            -> #str pretty object
        """
        ret = self._format_obj(obj if obj is not None else self.obj)
        if display:
            print(ret)
        else:
            return ret


Instruction:
Write a Python 3 function that can
format the object to the correct format for the

Response:
def _format_obj(self, item=None):
        """ Determines the type of the object and maps it to the correct
            formatter
        """
        # Order here matters, odd behavior with tuples
        if item is None:
            return getattr(self, 'number')(item)
        elif isinstance(item, self.str_):
            #: String
            return item + " "
        elif isinstance(item, bytes):
            #: Bytes
            return getattr(self, 'bytes')(item)
        elif isinstance(item, self.numeric_):
            #: Float, int, etc.
            return getattr(self, 'number')(item)
        elif isinstance(item, self.dict_):
            #: Dict
            return getattr(self, 'dict')(item)
        elif isinstance(item, self.list_):
            #: List
            return getattr(self, 'list')(item)
        elif isinstance(item, tuple):
            #: Tuple
            return getattr(self, 'tuple')(item)
        elif isinstance(item, types.GeneratorType):
            #: Generator
            return getattr(self, 'generator')(item)
        elif isinstance(item, self.set_):
            #: Set
            return getattr(self, 'set')(item)
        elif isinstance(item, deque):
            #: Deque
            return getattr(self, 'deque')(item)
        elif isinstance(item, Sequence):
            #: Sequence
            return getattr(self, 'sequence')(item)
        #: Any other object
        return getattr(self, 'object')(item)


Instruction:
Given the following Python 3 function, write the documentation
def set_level(self, level):
        if not level:
            return None
        self.levelmap = set()
        for char in level:
            self.levelmap = self.levelmap.union(self.levels[char])
        self.loglevel = level
        return self.loglevel

Response: Sets the loglevel to the given level.


Instruction:
Implement a function in Python 3 to
log the message with the given text using the given color.

Response:
def log(self, flag_message=None, padding=None, color=None, force=False):
        """ Log Level: :attr:LOG

            @flag_message: #str flags the message with the given text
                using :func:flag
            @padding: #str 'top', 'bottom' or 'all', adds a new line to the
                specified area with :func:padd
            @color: #str colorizes @flag_message using :func:colorize
            @force: #bool whether or not to force the message to log in spite
                of the assigned log level

            ..
                from vital.debug import Logg
                logg = Logg(loglevel="v")

                logg("World").log("Hello")
                # (Hello) World

                logg("Hello world").log()
                # Hello world
            ..
        """
        if self.should_log(self.LOG) or force:
            self._print_message(
                flag_message=flag_message, color=color or colors.bold,
                padding=padding)


Instruction:
Make a summary of the following Python 3 code
def success(self, flag_message="Success", padding=None, force=False):
        if self.should_log(self.SUCCESS) or force:
            self._print_message(
                flag_message=flag_message, color=colors.success_color,
                padding=padding)

Response: Log the message with the given text and padding.


Instruction:
Create a Python 3 function for
logging the message with the given text and flag the message with the given text using the given padding.

Response:
def complete(self, flag_message="Complete", padding=None, force=False):
        """ Log Level: :attr:COMPLETE

            @flag_message: #str flags the message with the given text
                using :func:flag
            @padding: #str 'top', 'bottom' or 'all', adds a new line to the
                specified area with :func:padd
            @color: #str colorizes @flag_message using :func:colorize
            @force: #bool whether or not to force the message to log in spite
                of the assigned log level

            ..
                from vital.debug import Logg
                logg = Logg(loglevel="v")

                logg("World").complete("Hello")
                # (Hello) World

                logg("Hello world").complete()
                # (Complete) Hello world
            ..
        """
        if self.should_log(self.COMPLETE) or force:
            self._print_message(
                flag_message=flag_message, color=colors.complete_color,
                padding=padding)


Instruction:
Write a Python 3 function for
logging a notice message to the log file.

Response:
def notice(self, flag_message="Notice", padding=None, force=False):
        """ Log Level: :attr:NOTICE

            @flag_message: #str flags the message with the given text
                using :func:flag
            @padding: #str 'top', 'bottom' or 'all', adds a new line to the
                specified area with :func:padd
            @color: #str colorizes @flag_message using :func:colorize
            @force: #bool whether or not to force the message to log in spite
                of the assigned log level

            ..
                from vital.debug import Logg
                logg = Logg(loglevel="v")

                logg("World").notice("Hello")
                # (Hello) World

                logg("Hello world").notice()
                # (Notice) Hello world
            ..
        """
        if self.should_log(self.NOTICE) or force:
            self._print_message(
                flag_message=flag_message, color=colors.notice_color,
                padding=padding)


Instruction:
Create a Python 3 function to
log a warning message to the log file.

Response:
def warning(self, flag_message="Warning", padding=None, force=False):
        """ Log Level: :attr:WARNING

            @flag_message: #str flags the message with the given text
                using :func:flag
            @padding: #str 'top', 'bottom' or 'all', adds a new line to the
                specified area with :func:padd
            @color: #str colorizes @flag_message using :func:colorize
            @force: #bool whether or not to force the message to log in spite
                of the assigned log level

            ..
                from vital.debug import Logg
                logg = Logg(loglevel="v")

                logg("World").warning("Hello")
                # (Hello) World

                logg("Hello world").warning()
                # (Warning) Hello world
            ..
        """
        if self.should_log(self.WARNING) or force:
            self._print_message(
                flag_message=flag_message, color=colors.warning_color,
                padding=padding)


Instruction:
Can you generate the documentation for the following Python 3 function
def error(self, flag_message="Error", padding=None, force=False):
        if self.should_log(self.ERROR) or force:
            self._print_message(
                flag_message=flag_message, color=colors.error_color,
                padding=padding)

Response: Log an error message for the current object.


Instruction:
Can you generate the documentation for the following Python 3 function
def timing(self, flag_message, padding=None, force=False):
        if self.should_log(self.TIMING) or force:
            self._print_message(
                flag_message=Timer.format_time(flag_message), padding=padding,
                reverse=True, color=colors.timing_color)

Response: Log a timing message to the log file.


Instruction:
Write a Python 3 function that can
count the number of available log entries in the available log files.

Response:
def count(self, flag_message, padding=None, force=False):
        """ Log Level: :attr:COUNT

            @flag_message: time-like #float
            @padding: #str 'top', 'bottom' or 'all', adds a new line to the
                specified area with :func:padd
            @force: #bool whether or not to force the message to log in spite
                of the assigned log level

            ..
                from vital.debug import Logg
                logg = Logg(loglevel="v")

                logg("Total apps").count(3)
                # Total apps (3)

                logg().count([0, 1, 2, 3])
                # (4)
            ..
        """
        if self.should_log(self.COUNT) or force:
            flag_message = flag_message \
                if isinstance(flag_message, (int, float)) else \
                str(len(flag_message))
            self._print_message(
                flag_message=flag_message, padding=padding, reverse=True,
                color=colors.timing_color)


Instruction:
Can you implement a function in Python 3 that
formats a message with a Look object

Response:
def format_message(self, message):
        """ Formats a message with :class:Look """
        look = Look(message)
        return look.pretty(display=False)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def format_messages(self, messages):
        mess = ""
        for message in self.message:
            if self.pretty:
                mess = "{}{}".format(mess, self.format_message(message))
            else:
                mess += str(message)
        if self.include_time:
            return ": {} : {}".format(
                datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), mess)
        return stdout_encode(mess)

Response: Formats several messages with the same class and encodes them with stdout_encode


Instruction:
How would you implement a function in Python 3 that
outputs the message to the terminal

Response:
def _print_message(self, flag_message=None, color=None, padding=None,
                       reverse=False):
        """ Outputs the message to the terminal """
        if flag_message:
            flag_message = stdout_encode(flag(flag_message,
                                              color=color if self.pretty else None,
                                              show=False))
            if not reverse:
                print(padd(flag_message, padding),
                      self.format_messages(self.message))
            else:
                print(self.format_messages(self.message),
                      padd(flag_message, padding))
        else:
            print(self.format_messages(self.message))
        self.message = []


Instruction:
Write a Python 3 function that can
build the progress bar

Response:
def format_bar(self):
        """ Builds the progress bar """
        pct = floor(round(self.progress/self.size, 2)*100)
        pr = floor(pct*.33)
        bar = "".join(
            ["‒" for x in range(pr)] + ["↦"] +
            [" " for o in range(self._barsize-pr-1)])
        subprogress = self.format_parent_bar() if self.parent_bar else ""
        message = "Loading{} ={}{} ({}%)".format(subprogress, bar, "☉", pct)
        return message.ljust(len(message)+5)


Instruction:
Create a Python 3 function to
print the progress bar and clears it from the terminal

Response:
def finish(self):
        """ Resets the progress bar and clears it from the terminal """
        pct = floor(round(self.progress/self.size, 2)*100)
        pr = floor(pct*.33)
        bar = "".join([" " for x in range(pr-1)] + ["↦"])
        subprogress = self.format_parent_bar() if self.parent_bar else ""
        fin = "Loading{} ={}{} ({}%)".format(subprogress, bar, "ӿ", pct)
        print(fin.ljust(len(fin)+5), end="\r")
        time.sleep(0.10)
        print("\033[K\033[1A")
        self.progress = 0


Instruction:
How would you explain what the following Python 3 function does
def update(self, progress=0):
        self.progress += (progress or 1)
        if self.visible:
            if self.progress % self._mod == 1 or\
               self.progress == self.size - 1:
                print(self.format_bar(), end="\r")
            if self.progress == (self.size):
                self.finish()

Response: Updates the progress bar with the given value.


Instruction:
How would you implement a function in Python 3 that
stops the timer and adds it as an interval to the intervals property

Response:
def stop(self, precision=0):
        """ Stops the timer, adds it as an interval to :prop:intervals
            @precision: #int number of decimal places to round to

            -> #str formatted interval time
        """
        self._stop = time.perf_counter()
        return self.add_interval(precision)


Instruction:
Given the following Python 3 function, write the documentation
def format_time(self, sec):
        # µsec
        if sec < 0.001:
            return "{}{}".format(
                colorize(round(sec*1000000, 2), "purple"), bold("µs"))
        # ms
        elif sec < 1.0:
            return "{}{}".format(
                colorize(round(sec*1000, 2), "purple"), bold("ms"))
        # s
        elif sec < 60.0:
            return "{}{}".format(
                colorize(round(sec, 2), "purple"), bold("s"))
        else:
            floored = floor(sec/60)
            return "{}{} {}{}".format(
                colorize(floored, "purple"),
                bold("m"),
                colorize(floor(sec-(floored*60)), "purple"),
                bold("s"))

Response: Pretty - formats a given time in a readable manner.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_interval(self, precision=0):
        precision = precision or self.precision
        interval = round((self._stop - self._start), precision)
        self.intervals.append(interval)
        self._intervals_len += 1
        self._start = time.perf_counter()
        return self.format_time(interval)

Response: Adds an interval to the list of intervals and returns a formatted string.


Instruction:
Here you have a function in Python 3, explain what it does
def time(self, intervals=1, *args, _show_progress=True, _print=True,
             _collect_garbage=True, _quiet=True, **kwargs):
        """ Measures the execution time of :prop:_callable for @intervals

            @intervals: #int number of intervals to measure the execution time
                of the function for
            @*args: arguments to pass to the callable being timed
            @**kwargs: arguments to pass to the callable being timed
            @_show_progress: #bool whether or not to print a progress bar
            @_print: #bool whether or not to print the results of the timing
            @_collect_garbage: #bool whether or not to garbage collect
                while timing
            @_quiet: #bool whether or not to disable the print() function's
                ability to output to terminal during the timing

            -> :class:collections.OrderedDict of stats about the timing
        """
        self.reset()
        args = list(args) + list(self._callableargs[0])
        _kwargs = self._callableargs[1]
        _kwargs.update(kwargs)
        kwargs = _kwargs
        if not _collect_garbage:
            gc.disable()  # Garbage collection setting
        gc.collect()
        self.allocated_memory = 0
        for x in self.progress(intervals):
            if _quiet:  # Quiets print()s in the tested function
                sys.stdout = NullIO()
            try:
                self.start()  # Starts the timer
                self._callable(*args, **kwargs)
                self.stop()  # Stops the timer
            except Exception as e:
                if _quiet:  # Unquiets prints()
                    sys.stdout = sys.__stdout__
                raise e
            if _quiet:  # Unquiets prints()
                sys.stdout = sys.__stdout__
        if not _collect_garbage:
            gc.enable()  # Garbage collection setting
        if _print:
            self.info()

Response: Measure the execution time of the function for the given number of intervals.


Instruction:
Here you have a function in Python 3, explain what it does
def mean(self):
        return round(np.mean(self.array), self.precision)\
            if len(self.array) else None

Response: Returns the mean value of the time intervals


Instruction:
Here you have a function in Python 3, explain what it does
def median(self):
        return round(float(np.median(self.array)), self.precision)\
            if len(self.array) else None

Response: Returns the median value of the time intervals


Instruction:
Here you have a function in Python 3, explain what it does
def max(self):
        return round(np.max(self.array), self.precision)\
            if len(self.array) else None

Response: Returns the maximum value of the resource in the array


Instruction:
Write a Python 3 function that can
return the minimum value of the resource class

Response:
def min(self):
        """ -> #float :func:numpy.min of the timing intervals """
        return round(np.min(self.array), self.precision)\
            if len(self.array) else None


Instruction:
Can you generate the documentation for the following Python 3 function
def stdev(self):
        return round(np.std(self.array), self.precision)\
            if len(self.array) else None

Response: Returns the standard deviation of the time intervals


Instruction:
Implement a Python 3 function for
returning an OrderedDict of stats about the time intervals

Response:
def stats(self):
        """ -> :class:collections.OrderedDict of stats about the time intervals
        """
        return OrderedDict([
            ("Intervals", len(self.array)),
            ("Mean", self.format_time(self.mean or 0)),
            ("Min", self.format_time(self.min or 0)),
            ("Median", self.format_time(self.median or 0)),
            ("Max", self.format_time(self.max or 0)),
            ("St. Dev.", self.format_time(self.stdev or 0)),
            ("Total", self.format_time(self.exectime or 0)),
        ])


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _pct_diff(self, best, other):
        return colorize("{}%".format(
            round(((best-other)/best)*100, 2)).rjust(10), "red")

Response: Calculates and colorizes the percent difference between the best and other cluster keys.


Instruction:
Make a summary of the following Python 3 code
def info(self, verbose=None):
        if self.name:
            flag(bold(self.name))
        flag("Results after {} intervals".format(
            bold(self.num_intervals, close=False)),
            colors.notice_color, padding="top")
        line("‒")
        verbose = verbose if verbose is not None else self.verbose
        if verbose:
            for result in self._callable_results:
                result.info()
                line()
        diffs = [
            (i, result.mean)
            for i, result in enumerate(self._callable_results)
            if result.mean]
        ranking = [
            (i, self._callable_results[i].format_time(r))
            for i, r in sorted(diffs, key=lambda x: x[1])]
        max_rlen = len(str(len(ranking)))+2
        max_rlen2 = max(len(r) for i, r in ranking)+1
        best = self._callable_results[ranking[0][0]].mean
        for idx, (i, rank) in enumerate(ranking, 1):
            _obj_name = Look(self._callables[i]).objname()
            pct = "".rjust(10) if idx == 1 else \
                self._pct_diff(best, self._callable_results[i].mean)
            print(
                ("#"+str(idx)+" ¦").rjust(max_rlen), rank.rjust(max_rlen2),
                pct, "{}".format(_obj_name))
        line("‒", padding="bottom")

Response:
Prints and formats the results of the timing
           .


Instruction:
Make a summary of the following Python 3 code
def fi_iban_load_map(filename: str) -> dict:
    out = {}
    with open(filename, 'rt') as fp:
        lines = [line.strip().split(',') for line in fp.readlines()]
        ver = lines.pop(0)
        head = lines.pop(0)
        if head != ['National ID', 'BIC Code', 'Financial Institution Name']:
            raise ValidationError('Incompatible file content in {}'.format(filename))
        for line in lines:
            if len(line) == 3 and line[0]:
                nat_id = str(line[0]).strip()
                bic_code = line[1].strip()
                name = line[2].strip()
                out[nat_id] = (bic_code, name)
    return out

Response: Loads Finnish monetary institution codes and BICs from CSV format.


Instruction:
Can you generate the documentation for the following Python 3 function
def async_lru(size=100):
    cache = collections.OrderedDict()

    def decorator(fn):
        @wraps(fn)
        @asyncio.coroutine
        def memoizer(*args, **kwargs):
            key = str((args, kwargs))
            try:
                result = cache.pop(key)
                cache[key] = result
            except KeyError:
                if len(cache) >= size:
                    cache.popitem(last=False)
                result = cache[key] = yield from fn(*args, **kwargs)
            return result
        return memoizer
    return decorator

Response: A decorator that returns an asynchronous LRU cache for Python 3. 5.


Instruction:
Can you tell what is the following Python 3 function doing
def choices_label(choices: tuple, value) -> str:
    for key, label in choices:
        if key == value:
            return label
    return ''

Response: Returns the label of the object in the choices list.


Instruction:
Given the following Python 3 function, write the documentation
def info(msg, *args, **kw):
    # type: (str, *Any, **Any) -> None
    """ Print sys message to stdout.

    System messages should inform about the flow of the script. This should
    be a major milestones during the build.
    """
    if len(args) or len(kw):
        msg = msg.format(*args, **kw)

    shell.cprint('-- <32>{}<0>'.format(msg))

Response: Print sys message to stdout.


Instruction:
Write a Python 3 script to
determine whether the string pattern is username - like .

Response:
def is_username(string, minlen=1, maxlen=15):
    """ Determines whether the @string pattern is username-like
        @string: #str being tested
        @minlen: minimum required username length
        @maxlen: maximum username length

        -> #bool
    """
    if string:
        string = string.strip()
        return username_re.match(string) and (minlen <= len(string) <= maxlen)
    return False


Instruction:
Write a Python 3 function for
converting a big integer to a string if it is a big integer.

Response:
def bigint_to_string(val):
    """ Converts @val to a string if it is a big integer (|>2**53-1|)

        @val: #int or #float

        -> #str if @val is a big integer, otherwise @val
    """
    if isinstance(val, _NUMBERS) and not abs(val) <= 2**53-1:
        return str(val)
    return val


Instruction:
Can you create a Python 3 function that
removes all blank lines in the string

Response:
def remove_blank_lines(string):
    """ Removes all blank lines in @string

        -> #str without blank lines
    """
    return "\n".join(line
                     for line in string.split("\n")
                     if len(line.strip()))


Instruction:
How would you implement a function in Python 3 that
runs django. manage. py command manually.

Response:
def _manage_cmd(cmd, settings=None):
    # type: () -> None
    """ Run django ./manage.py command manually.

    This function eliminates the need for having ``manage.py`` (reduces file
    clutter).
    """
    import sys
    from os import environ
    from peltak.core import conf
    from peltak.core import context
    from peltak.core import log

    sys.path.insert(0, conf.get('src_dir'))

    settings = settings or conf.get('django.settings', None)
    environ.setdefault("DJANGO_SETTINGS_MODULE", settings)

    args = sys.argv[0:-1] + cmd

    if context.get('pretend', False):
        log.info("Would run the following manage command:\n<90>{}", args)
    else:
        from django.core.management import execute_from_command_line
        execute_from_command_line(args)


Instruction:
Write a Python 3 script for
returning the BranchDetails for the current branch.

Response:
def current_branch():
    # type: () -> BranchDetails
    """ Return the BranchDetails for the current branch.

    Return:
        BranchDetails: The details of the current branch.
    """
    cmd = 'git symbolic-ref --short HEAD'
    branch_name = shell.run(
        cmd,
        capture=True,
        never_pretend=True
    ).stdout.strip()

    return BranchDetails.parse(branch_name)


Instruction:
Can you generate the documentation for the following Python 3 function
def commit_branches(sha1):
    # type: (str) -> List[str]
    """ Get the name of the branches that this commit belongs to. """
    cmd = 'git branch --contains {}'.format(sha1)
    return shell.run(
        cmd,
        capture=True,
        never_pretend=True
    ).stdout.strip().split()

Response: Returns the names of branches that this commit belongs to.


Instruction:
Write a Python 3 function that can
try to guess the base branch for the current branch.

Response:
def guess_base_branch():
    # type: (str) -> Optional[str, None]
    """ Try to guess the base branch for the current branch.

    Do not trust this guess. git makes it pretty much impossible to guess
    the base branch reliably so this function implements few heuristics that
    will work on most common use cases but anything a bit crazy will probably
    trip this function.

    Returns:
        Optional[str]: The name of the base branch for the current branch if
        guessable or **None** if can't guess.
    """
    my_branch = current_branch(refresh=True).name

    curr = latest_commit()
    if len(curr.branches) > 1:
        # We're possibly at the beginning of the new branch (currently both
        # on base and new branch).
        other = [x for x in curr.branches if x != my_branch]
        if len(other) == 1:
            return other[0]
        return None
    else:
        # We're on one branch
        parent = curr

        while parent and my_branch in parent.branches:
            curr = parent

            if len(curr.branches) > 1:
                other = [x for x in curr.branches if x != my_branch]
                if len(other) == 1:
                    return other[0]
                return None

            parents = [p for p in curr.parents if my_branch in p.branches]
            num_parents = len(parents)

            if num_parents > 2:
                # More than two parent, give up
                return None
            if num_parents == 2:
                # This is a merge commit.
                for p in parents:
                    if p.branches == [my_branch]:
                        parent = p
                        break
            elif num_parents == 1:
                parent = parents[0]
            elif num_parents == 0:
                parent = None

        return None


Instruction:
Make a summary of the following Python 3 code
def commit_author(sha1=''):
    # type: (str) -> Author
    """ Return the author of the given commit.

    Args:
        sha1 (str):
            The sha1 of the commit to query. If not given, it will return the
            sha1 for the current commit.
    Returns:
        Author: A named tuple ``(name, email)`` with the commit author details.
    """
    with conf.within_proj_dir():
        cmd = 'git show -s --format="%an||%ae" {}'.format(sha1)
        result = shell.run(
            cmd,
            capture=True,
            never_pretend=True
        ).stdout
        name, email = result.split('||')
        return Author(name, email)

Response: Returns the author of the given commit.