Instruction:
Can you generate a brief explanation for the following Python 3 code
def random_draw(self, size=None):
        if size is None:
            size = 1
            single_val = True
        else:
            single_val = False

        out_shape = [len(self.bounds)]
        try:
            out_shape.extend(size)
        except TypeError:
            out_shape.append(size)

        out = scipy.zeros(out_shape)
        for j in xrange(0, len(self.bounds)):
            if j != 2:
                out[j, :] = numpy.random.uniform(low=self.bounds[j][0],
                                                 high=self.bounds[j][1],
                                                 size=size)
            else:
                out[j, :] = numpy.random.uniform(low=self.bounds[j][0],
                                                 high=out[j - 1, :],
                                                 size=size)
        if not single_val:
            return out
        else:
            return out.ravel()

Response: Draw random samples of the hyperparameters.


Instruction:
Here you have a function in Python 3, explain what it does
def sample_u(self, q):
        q = scipy.atleast_1d(q)
        if len(q) != len(self.univariate_priors):
            raise ValueError("length of q must equal the number of parameters!")
        if q.ndim != 1:
            raise ValueError("q must be one-dimensional!")
        if (q < 0).any() or (q > 1).any():
            raise ValueError("q must be within [0, 1]!")
        return scipy.asarray([p.ppf(v) for v, p in zip(q, self.univariate_priors)])

Response: r Returns a sample from random variates uniformly on the CDF at the given vector q.


Instruction:
How would you explain what the following Python 3 function does
def random_draw(self, size=None):
        return scipy.asarray([p.rvs(size=size) for p in self.univariate_priors])

Response: Draw random samples of the hyperparameters.


Instruction:
Can you implement a function in Python 3 that
converts a sample to random variates uniform on the CDF at a specific key.

Response:
def elementwise_cdf(self, p):
        r"""Convert a sample to random variates uniform on :math:`[0, 1]`.

        For a univariate distribution, this is simply evaluating the CDF. To
        facilitate efficient sampling, this function returns a *vector* of CDF
        values, one value for each variable. Basically, the idea is that, given
        a vector :math:`q` of `num_params` values each of which is distributed
        according to the prior, this function will return variables uniform on
        :math:`[0, 1]` corresponding to each variable. This is the inverse
        operation to :py:meth:`sample_u`.

        Parameters
        ----------
        p : array-like, (`num_params`,)
            Values to evaluate CDF at.
        """
        p = scipy.atleast_1d(p)
        if len(p) != len(self.sigma):
            raise ValueError("length of p must equal the number of parameters!")
        if p.ndim != 1:
            raise ValueError("p must be one-dimensional!")
        return scipy.asarray([scipy.stats.norm.cdf(v, loc=m, scale=s) for v, s, m in zip(p, self.sigma, self.mu)])


Instruction:
Can you implement a function in Python 3 that
draws random samples of the hyperparameters.

Response:
def random_draw(self, size=None):
        """Draw random samples of the hyperparameters.

        Parameters
        ----------
        size : None, int or array-like, optional
            The number/shape of samples to draw. If None, only one sample is
            returned. Default is None.
        """
        return scipy.asarray([scipy.stats.norm.rvs(loc=m, scale=s, size=size) for s, m in zip(self.sigma, self.mu)])


Instruction:
Make a summary of the following Python 3 code
def sample_u(self, q):
        q = scipy.atleast_1d(q)
        if len(q) != len(self.sigma):
            raise ValueError("length of q must equal the number of parameters!")
        if q.ndim != 1:
            raise ValueError("q must be one-dimensional!")
        if (q < 0).any() or (q > 1).any():
            raise ValueError("q must be within [0, 1]!")
        return scipy.asarray([scipy.stats.lognorm.ppf(v, s, loc=0, scale=em) for v, s, em in zip(q, self.sigma, self.emu)])

Response: r Returns a sample from random variates uniformly on the CDF at the given vector q.


Instruction:
Here you have a function in Python 3, explain what it does
def elementwise_cdf(self, p):
        p = scipy.atleast_1d(p)
        if len(p) != len(self.sigma):
            raise ValueError("length of p must equal the number of parameters!")
        if p.ndim != 1:
            raise ValueError("p must be one-dimensional!")
        return scipy.asarray([scipy.stats.lognorm.cdf(v, s, loc=0, scale=em) for v, s, em in zip(p, self.sigma, self.emu)])

Response: Convert a sample to random variates uniform on 0. 0 1. 0. 0.


Instruction:
Can you generate the documentation for the following Python 3 function
def random_draw(self, size=None):
        return scipy.asarray([scipy.stats.lognorm.rvs(s, loc=0, scale=em, size=size) for s, em in zip(self.sigma, self.emu)])

Response: Draw random samples of the hyperparameters.


Instruction:
How would you explain what the following Python 3 function does
def bounds(self):
        return [scipy.stats.gamma.interval(self.i, a, loc=0, scale=1.0 / b) for a, b in zip(self.a, self.b)]

Response: The bounds of the random variable.


Instruction:
Can you generate the documentation for the following Python 3 function
def random_draw(self, size=None):
        return scipy.asarray([scipy.stats.gamma.rvs(a, loc=0, scale=1.0 / b, size=size) for a, b in zip(self.a, self.b)])

Response: Draw random samples of the hyperparameters.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def random_draw(self, size=None):
        if size is None:
            size = 1
            single_val = True
        else:
            single_val = False

        out_shape = [self.num_var]
        try:
            out_shape.extend(size)
        except TypeError:
            out_shape.append(size)

        out = scipy.sort(
            numpy.random.uniform(
                low=self.lb,
                high=self.ub,
                size=out_shape
            ),
            axis=0
        )
        if not single_val:
            return out
        else:
            return out.ravel()

Response: Draw random samples of the hyperparameters.


Instruction:
Can you tell what is the following Python 3 function doing
def zapier_cancel_hook(request):
    '''
    Zapier can post something like this when tickets are cancelled
    {
        "ticket_type": "Individual (Regular)",
        "barcode": "12345678",
        "email": "demo@example.com"
    }
    '''
    if request.META.get('HTTP_X_ZAPIER_SECRET', None) != settings.WAFER_TICKETS_SECRET:
        raise PermissionDenied('Incorrect secret')

    # This is required for python 3, and in theory fine on python 2
    payload = json.loads(request.body.decode('utf8'))
    ticket = Ticket.objects.filter(barcode=payload['barcode'])
    if ticket.exists():
        # delete the ticket
        ticket.delete()
    return HttpResponse("Cancelled\n", content_type='text/plain')

Response: Cancels the current ticket in Zapier


Instruction:
Make a summary of the following Python 3 code
def fetch_token(self):
        grant_type = 'client_credentials'

        channel = yield self._tvm.ticket_full(
            self._client_id, self._client_secret, grant_type, {})
        ticket = yield channel.rx.get()

        raise gen.Return(self._make_token(ticket))

Response: Gains token from secure backend service.


Instruction:
Can you tell what is the following Python 3 function doing
def make_secure_adaptor(service, mod, client_id, client_secret, tok_update_sec=None):
        if mod == 'TVM':
            return SecureServiceAdaptor(service, TVM(client_id, client_secret), tok_update_sec)

        return SecureServiceAdaptor(service, Promiscuous(), tok_update_sec)

Response: Creates a SecureServiceAdaptor for the given service and mod.


Instruction:
Can you implement a function in Python 3 that
extracts information from an albacore summary file. Only reads which have a >0 length are returned. The fields below may or may not exist, depending on the type of sequencing performed. Fields 1-14 are for 1D sequencing. Fields 1-23 for 2D sequencing. Fields 24-27, 2-5, 22-23 for 1D^2 (1D2) sequencing Fields 28-38 for barcoded workflows 1 filename 2 read_id 3 run_id 4 channel 5 start_time 6 duration 7 num_events 8 template_start 9 num_events_template 10 template_duration 11 num_called_template 12 sequence_length_template 13 mean_qscore_template 14 strand_score_template 15 complement_start 16 num_events_complement 17 complement_duration 18 num_called_complement 19 sequence_length_complement 20 mean_qscore_complement 21 strand_score_complement 22 sequence_length_2d 23 mean_qscore_2d 24 filename1 25 filename2 26 read_id1 27 read_id2 28 barcode_arrangement 29 barcode_score 30 barcode_full_arrangement 31 front_score 32 rear_score 33 front_begin_index 34 front_foundseq_length 35 rear_end_index 36 rear_foundseq_length 37 kit 38 variant

Response:
def process_summary(summaryfile, **kwargs):
    """Extracting information from an albacore summary file.

    Only reads which have a >0 length are returned.

    The fields below may or may not exist, depending on the type of sequencing performed.
    Fields 1-14 are for 1D sequencing.
    Fields 1-23 for 2D sequencing.
    Fields 24-27, 2-5, 22-23 for 1D^2 (1D2) sequencing
    Fields 28-38 for barcoded workflows
     1  filename
     2  read_id
     3  run_id
     4  channel
     5  start_time
     6  duration
     7  num_events
     8  template_start
     9  num_events_template
    10  template_duration
    11  num_called_template
    12  sequence_length_template
    13  mean_qscore_template
    14  strand_score_template
    15  complement_start
    16    num_events_complement
    17    complement_duration
    18    num_called_complement
    19    sequence_length_complement
    20    mean_qscore_complement
    21    strand_score_complement
    22    sequence_length_2d
    23    mean_qscore_2d
    24    filename1
    25    filename2
    26    read_id1
    27    read_id2
    28    barcode_arrangement
    29    barcode_score
    30    barcode_full_arrangement
    31    front_score
    32    rear_score
    33    front_begin_index
    34    front_foundseq_length
    35    rear_end_index
    36    rear_foundseq_length
    37    kit
    38    variant
    """
    logging.info("Nanoget: Collecting metrics from summary file {} for {} sequencing".format(
        summaryfile, kwargs["readtype"]))
    ut.check_existance(summaryfile)
    if kwargs["readtype"] == "1D":
        cols = ["read_id", "run_id", "channel", "start_time", "duration",
                "sequence_length_template", "mean_qscore_template"]
    elif kwargs["readtype"] in ["2D", "1D2"]:
        cols = ["read_id", "run_id", "channel", "start_time", "duration",
                "sequence_length_2d", "mean_qscore_2d"]
    if kwargs["barcoded"]:
        cols.append("barcode_arrangement")
        logging.info("Nanoget: Extracting metrics per barcode.")
    try:
        datadf = pd.read_csv(
            filepath_or_buffer=summaryfile,
            sep="\t",
            usecols=cols,
        )
    except ValueError:
        logging.error("Nanoget: did not find expected columns in summary file {}:\n {}".format(
            summaryfile, ', '.join(cols)))
        sys.exit("ERROR: expected columns in summary file {} not found:\n {}".format(
            summaryfile, ', '.join(cols)))
    if kwargs["barcoded"]:
        datadf.columns = ["readIDs", "runIDs", "channelIDs", "time", "duration",
                          "lengths", "quals", "barcode"]
    else:
        datadf.columns = ["readIDs", "runIDs", "channelIDs", "time", "duration", "lengths", "quals"]
    logging.info("Nanoget: Finished collecting statistics from summary file {}".format(summaryfile))
    return ut.reduce_memory_usage(datadf.loc[datadf["lengths"] != 0].copy())


Instruction:
Can you generate the documentation for the following Python 3 function
def check_bam(bam, samtype="bam"):
    ut.check_existance(bam)
    samfile = pysam.AlignmentFile(bam, "rb")
    if not samfile.has_index():
        pysam.index(bam)
        samfile = pysam.AlignmentFile(bam, "rb")  # Need to reload the samfile after creating index
        logging.info("Nanoget: No index for bam file could be found, created index.")
    if not samfile.header['HD']['SO'] == 'coordinate':
        logging.error("Nanoget: Bam file {} not sorted by coordinate!.".format(bam))
        sys.exit("Please use a bam file sorted by coordinate.")
    if samtype == "bam":
        logging.info("Nanoget: Bam file {} contains {} mapped and {} unmapped reads.".format(
            bam, samfile.mapped, samfile.unmapped))
        if samfile.mapped == 0:
            logging.error("Nanoget: Bam file {} does not contain aligned reads.".format(bam))
            sys.exit("FATAL: not a single read was mapped in bam file {}".format(bam))
    return samfile

Response: Check if bam file is valid.


Instruction:
Can you tell what is the following Python 3 function doing
def process_ubam(bam, **kwargs):
    logging.info("Nanoget: Starting to collect statistics from ubam file {}.".format(bam))
    samfile = pysam.AlignmentFile(bam, "rb", check_sq=False)
    if not samfile.has_index():
        pysam.index(bam)
        # Need to reload the samfile after creating index
        samfile = pysam.AlignmentFile(bam, "rb")
        logging.info("Nanoget: No index for bam file could be found, created index.")
    datadf = pd.DataFrame(
        data=[(read.query_name, nanomath.ave_qual(read.query_qualities), read.query_length)
              for read in samfile.fetch(until_eof=True)],
        columns=["readIDs", "quals", "lengths"]) \
        .dropna(axis='columns', how='all') \
        .dropna(axis='index', how='any')
    logging.info("Nanoget: ubam {} contains {} reads.".format(
        bam, datadf["lengths"].size))
    return ut.reduce_memory_usage(datadf)

Response:
Extracting metrics from unaligned bam format
    Extracting lengths


Instruction:
Implement a Python 3 function for
combining metrics from bam after extraction.

Response:
def process_bam(bam, **kwargs):
    """Combines metrics from bam after extraction.

    Processing function: calls pool of worker functions
    to extract from a bam file the following metrics:
    -lengths
    -aligned lengths
    -qualities
    -aligned qualities
    -mapping qualities
    -edit distances to the reference genome scaled by read length
    Returned in a pandas DataFrame
    """
    logging.info("Nanoget: Starting to collect statistics from bam file {}.".format(bam))
    samfile = check_bam(bam)
    chromosomes = samfile.references
    params = zip([bam] * len(chromosomes), chromosomes)
    with cfutures.ProcessPoolExecutor() as executor:
        datadf = pd.DataFrame(
            data=[res for sublist in executor.map(extract_from_bam, params) for res in sublist],
            columns=["readIDs", "quals", "aligned_quals", "lengths",
                     "aligned_lengths", "mapQ", "percentIdentity"]) \
            .dropna(axis='columns', how='all') \
            .dropna(axis='index', how='any')
    logging.info("Nanoget: bam {} contains {} primary alignments.".format(
        bam, datadf["lengths"].size))
    return ut.reduce_memory_usage(datadf)


Instruction:
Create a Python 3 function to
extract metrics from bam. Worker function per chromosome loop over a bam file and create list with tuples containing metrics: -qualities -aligned qualities -lengths -aligned lengths -mapping qualities -edit distances to the reference genome scaled by read length

Response:
def extract_from_bam(params):
    """Extracts metrics from bam.

    Worker function per chromosome
    loop over a bam file and create list with tuples containing metrics:
    -qualities
    -aligned qualities
    -lengths
    -aligned lengths
    -mapping qualities
    -edit distances to the reference genome scaled by read length
    """
    bam, chromosome = params
    samfile = pysam.AlignmentFile(bam, "rb")
    return [
        (read.query_name,
         nanomath.ave_qual(read.query_qualities),
         nanomath.ave_qual(read.query_alignment_qualities),
         read.query_length,
         read.query_alignment_length,
         read.mapping_quality,
         get_pID(read))
        for read in samfile.fetch(reference=chromosome, multiple_iterators=True)
        if not read.is_secondary]


Instruction:
Explain what the following Python 3 code does
def get_pID(read):
    try:
        return 100 * (1 - read.get_tag("NM") / read.query_alignment_length)
    except KeyError:
        try:
            return 100 * (1 - (parse_MD(read.get_tag("MD")) + parse_CIGAR(read.cigartuples))
                          / read.query_alignment_length)
        except KeyError:
            return None
    except ZeroDivisionError:
        return None

Response: Return the percent identity of a read.


Instruction:
Implement a Python 3 function for
returning handles from compressed files according to file extension.

Response:
def handle_compressed_input(inputfq, file_type="fastq"):
    """Return handles from compressed files according to extension.

    Check for which fastq input is presented and open a handle accordingly
    Can read from compressed files (gz, bz2, bgz) or uncompressed
    Relies on file extensions to recognize compression
    """
    ut.check_existance(inputfq)
    if inputfq.endswith(('.gz', 'bgz')):
        import gzip
        logging.info("Nanoget: Decompressing gzipped {} {}".format(file_type, inputfq))
        return gzip.open(inputfq, 'rt')
    elif inputfq.endswith('.bz2'):
        import bz2
        logging.info("Nanoget: Decompressing bz2 compressed {} {}".format(file_type, inputfq))
        return bz2.open(inputfq, 'rt')
    elif inputfq.endswith(('.fastq', '.fq', 'fasta', '.fa', '.fas')):
        return open(inputfq, 'r')
    else:
        logging.error("INPUT ERROR: Unrecognized file extension {}".format(inputfq))
        sys.exit('INPUT ERROR:\nUnrecognized file extension in {}\n'
                 'Supported are gz, bz2, bgz, fastq, fq, fasta, fa and fas'.format(inputfq))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def process_fasta(fasta, **kwargs):
    logging.info("Nanoget: Starting to collect statistics from a fasta file.")
    inputfasta = handle_compressed_input(fasta, file_type="fasta")
    return ut.reduce_memory_usage(pd.DataFrame(
        data=[len(rec) for rec in SeqIO.parse(inputfasta, "fasta")],
        columns=["lengths"]
    ).dropna())

Response: Combine metrics extracted from a fasta file.


Instruction:
Make a summary of the following Python 3 code
def process_fastq_plain(fastq, **kwargs):
    logging.info("Nanoget: Starting to collect statistics from plain fastq file.")
    inputfastq = handle_compressed_input(fastq)
    return ut.reduce_memory_usage(pd.DataFrame(
        data=[res for res in extract_from_fastq(inputfastq) if res],
        columns=["quals", "lengths"]
    ).dropna())

Response: Combine metrics extracted from a plain fastq file.


Instruction:
Here you have a function in Python 3, explain what it does
def extract_from_fastq(fq):
    for rec in SeqIO.parse(fq, "fastq"):
        yield nanomath.ave_qual(rec.letter_annotations["phred_quality"]), len(rec)

Response: Extract metrics from a fastq file.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def stream_fastq_full(fastq, threads):
    logging.info("Nanoget: Starting to collect full metrics from plain fastq file.")
    inputfastq = handle_compressed_input(fastq)
    with cfutures.ProcessPoolExecutor(max_workers=threads) as executor:
        for results in executor.map(extract_all_from_fastq, SeqIO.parse(inputfastq, "fastq")):
            yield results
    logging.info("Nanoget: Finished collecting statistics from plain fastq file.")

Response: Generator for returning metrics extracted from a fastq file.


Instruction:
Explain what the following Python 3 code does
def extract_all_from_fastq(rec):
    return (rec.id,
            len(rec),
            nanomath.ave_qual(rec.letter_annotations["phred_quality"]),
            nanomath.median_qual(rec.letter_annotations["phred_quality"]))

Response:
Extract metrics from a fastq file.
            is a dict with the keys id read length average quality and median quality.


Instruction:
Make a summary of the following Python 3 code
def process_fastq_rich(fastq, **kwargs):
    logging.info("Nanoget: Starting to collect statistics from rich fastq file.")
    inputfastq = handle_compressed_input(fastq)
    res = []
    for record in SeqIO.parse(inputfastq, "fastq"):
        try:
            read_info = info_to_dict(record.description)
            res.append(
                (nanomath.ave_qual(record.letter_annotations["phred_quality"]),
                 len(record),
                 read_info["ch"],
                 read_info["start_time"],
                 read_info["runid"]))
        except KeyError:
            logging.error("Nanoget: keyerror when processing record {}".format(record.description))
            sys.exit("Unexpected fastq identifier:\n{}\n\n \
            missing one or more of expected fields 'ch', 'start_time' or 'runid'".format(
                record.description))
    df = pd.DataFrame(
        data=res,
        columns=["quals", "lengths", "channelIDs", "timestamp", "runIDs"]).dropna()
    df["channelIDs"] = df["channelIDs"].astype("int64")
    return ut.reduce_memory_usage(df)

Response: Extract metrics from a richer fastq file.


Instruction:
Make a summary of the following Python 3 code
def fq_minimal(fq):
    try:
        while True:
            time = next(fq)[1:].split(" ")[4][11:-1]
            length = len(next(fq))
            next(fq)
            next(fq)
            yield time, length
    except StopIteration:
        yield None

Response: Minimal fastq metrics extractor.


Instruction:
Make a summary of the following Python 3 code
def process_fastq_minimal(fastq, **kwargs):
    infastq = handle_compressed_input(fastq)
    try:
        df = pd.DataFrame(
            data=[rec for rec in fq_minimal(infastq) if rec],
            columns=["timestamp", "lengths"]
        )
    except IndexError:
        logging.error("Fatal: Incorrect file structure for fastq_minimal")
        sys.exit("Error: file does not match expected structure for fastq_minimal")
    return ut.reduce_memory_usage(df)

Response: Swiftly extract minimal features from a rich fastq file


Instruction:
Implement a function in Python 3 to
return the appropriate object for the given piece.

Response:
def _get_piece(string, index):
    """
    Returns Piece subclass given index of piece.

    :type: index: int
    :type: loc Location

    :raise: KeyError
    """
    piece = string[index].strip()
    piece = piece.upper()
    piece_dict = {'R': Rook,
                  'P': Pawn,
                  'B': Bishop,
                  'N': Knight,
                  'Q': Queen,
                  'K': King}
    try:
        return piece_dict[piece]
    except KeyError:
        raise ValueError("Piece {} is invalid".format(piece))


Instruction:
Given the following Python 3 function, write the documentation
def incomplete_alg(alg_str, input_color, position):
    edge_rank = 0 \
        if input_color == color.white \
        else 7

    if alg_str is None or len(alg_str) <= 1:
        raise ValueError("algebraic string {} is invalid".format(alg_str))

    # King-side castle
    if alg_str in ["00", "oo", "OO", "0-0", "o-o", "O-O"]:
        return Move(end_loc=Location(edge_rank, 6),
                    piece=King(input_color, Location(edge_rank, 4)),
                    status=notation_const.KING_SIDE_CASTLE,
                    start_loc=Location(edge_rank, 4))

    # Queen-side castle
    if alg_str in ["000", "ooo", "OOO", "0-0-0", "o-o-o", "O-O-O"]:
        return Move(end_loc=Location(edge_rank, 2),
                    piece=King(input_color, Location(edge_rank, 4)),
                    status=notation_const.QUEEN_SIDE_CASTLE,
                    start_loc=Location(edge_rank, 4))
    try:
        end_location = Location.from_string(alg_str[-2:])
    except ValueError:
        end_location = Location.from_string(alg_str[-4:-2])

    # Pawn movement
    if len(alg_str) == 2:
        possible_pawn = position.piece_at_square(end_location.shift_back(input_color))
        if type(possible_pawn) is Pawn and \
                possible_pawn.color == input_color:
            start_location = end_location.shift_back(input_color)
        else:
            start_location = end_location.shift_back(input_color, times=2)
        return Move(end_loc=end_location,
                    piece=position.piece_at_square(start_location),
                    status=notation_const.MOVEMENT,
                    start_loc=start_location)

    # Non-pawn Piece movement
    if len(alg_str) == 3:
        possible_piece, start_location = _get_piece_start_location(end_location,
                                                                   input_color,
                                                                   _get_piece(alg_str, 0),
                                                                   position)
        return Move(end_loc=end_location,
                    piece=possible_piece,
                    status=notation_const.MOVEMENT,
                    start_loc=start_location)

    # Multiple options (Capture or Piece movement with file specified)
    if len(alg_str) == 4:

        # Capture
        if alg_str[1].upper() == "X":

            # Pawn capture
            if not alg_str[0].isupper():
                pawn_location = Location(end_location.rank, ord(alg_str[0]) - 97).shift_back(input_color)
                possible_pawn = position.piece_at_square(pawn_location)
                if type(possible_pawn) is Pawn and \
                        possible_pawn.color == input_color:
                    en_passant_pawn = position.piece_at_square(end_location.shift_back(input_color))
                    if type(en_passant_pawn) is Pawn and \
                            en_passant_pawn.color != input_color and \
                            position.is_square_empty(end_location):
                        return Move(end_loc=end_location,
                                    piece=position.piece_at_square(pawn_location),
                                    status=notation_const.EN_PASSANT,
                                    start_loc=pawn_location)
                    else:
                        return Move(end_loc=end_location,
                                    piece=position.piece_at_square(pawn_location),
                                    status=notation_const.CAPTURE,
                                    start_loc=pawn_location)

            # Piece capture
            elif alg_str[0].isupper():
                possible_piece, start_location = _get_piece_start_location(end_location,
                                                                           input_color,
                                                                           _get_piece(alg_str, 0),
                                                                           position)
                return Move(end_loc=end_location,
                            piece=possible_piece,
                            status=notation_const.CAPTURE,
                            start_loc=start_location)

        # Pawn Promotion
        elif alg_str[2] == "=":
            promote_end_loc = Location.from_string(alg_str[:2])
            if promote_end_loc.rank != 0 and promote_end_loc.rank != 7:
                raise ValueError("Promotion {} must be on the last rank".format(alg_str))
            return Move(end_loc=promote_end_loc,
                        piece=Pawn(input_color, promote_end_loc),
                        status=notation_const.PROMOTE,
                        promoted_to_piece=_get_piece(alg_str, 3),
                        start_loc=promote_end_loc.shift_back(input_color))

        # Non-pawn Piece movement with file specified (aRb7)
        elif alg_str[1].isupper() and not alg_str[0].isdigit():
            possible_piece, start_location = _get_piece_start_location(end_location,
                                                                       input_color,
                                                                       _get_piece(alg_str, 1),
                                                                       position,
                                                                       start_file=alg_str[0])
            return Move(end_loc=end_location,
                        piece=possible_piece,
                        status=notation_const.MOVEMENT,
                        start_loc=start_location)

        # (alt) Non-pawn Piece movement with file specified (Rab7)
        elif alg_str[0].isupper() and not alg_str[1].isdigit():
            possible_piece, start_location = _get_piece_start_location(end_location,
                                                                       input_color,
                                                                       _get_piece(alg_str, 0),
                                                                       position,
                                                                       start_file=alg_str[1])
            return Move(end_loc=end_location,
                        piece=possible_piece,
                        status=notation_const.MOVEMENT,
                        start_loc=start_location)

        # Non-pawn Piece movement with rank specified (R1b7)
        elif alg_str[0].isupper() and alg_str[1].isdigit():
            possible_piece, start_location = _get_piece_start_location(end_location,
                                                                       input_color,
                                                                       _get_piece(alg_str, 0),
                                                                       position,
                                                                       start_rank=alg_str[1])
            return Move(end_loc=end_location,
                        piece=possible_piece,
                        status=notation_const.MOVEMENT,
                        start_loc=start_location)

    # Multiple options
    if len(alg_str) == 5:

        # Non-pawn Piece movement with rank and file specified (a2Ra1
        if not alg_str[0].isdigit() and \
                alg_str[1].isdigit() and \
                alg_str[2].isupper() and \
                not alg_str[3].isdigit() and \
                alg_str[4].isdigit:
            start_loc = Location.from_string(alg_str[:2])
            return Move(end_loc=end_location,
                        piece=_get_piece(alg_str, 2)(input_color, end_location),
                        status=notation_const.MOVEMENT,
                        start_loc=start_loc)

        # Multiple Piece capture options
        if alg_str[2].upper() == "X":

            # Piece capture with rank specified (R1xa1)
            if alg_str[1].isdigit():
                possible_piece, start_location = _get_piece_start_location(end_location,
                                                                           input_color,
                                                                           _get_piece(alg_str, 0),
                                                                           position,
                                                                           start_rank=alg_str[1])
                return Move(end_loc=end_location,
                            piece=possible_piece,
                            status=notation_const.CAPTURE,
                            start_loc=start_location)

            # Piece capture with file specified (Rdxd7)
            else:
                possible_piece, start_location = _get_piece_start_location(end_location,
                                                                           input_color,
                                                                           _get_piece(alg_str, 0),
                                                                           position,
                                                                           start_file=alg_str[1])
                return Move(end_loc=end_location,
                            piece=possible_piece,
                            status=notation_const.CAPTURE,
                            start_loc=start_location)

    # Pawn promotion with capture
    if len(alg_str) == 6 and alg_str[4] == "=":
        start_file = ord(alg_str[0]) - 97
        promote_capture_end_loc = Location.from_string(alg_str[2:4])
        return Move(end_loc=promote_capture_end_loc,
                    piece=Pawn(input_color, promote_capture_end_loc),
                    status=notation_const.CAPTURE_AND_PROMOTE,
                    promoted_to_piece=_get_piece(alg_str, 5),
                    start_loc=Location(end_location.shift_back(input_color).rank, start_file))

    raise ValueError("algebraic string {} is invalid in \n{}".format(alg_str, position))

Response: Converts a string written in short algebraic form into an incomplete move.


Instruction:
Can you implement a function in Python 3 that
converts an incomplete move into a complete move with the most likely starting point specified.

Response:
def make_legal(move, position):
    """
    Converts an incomplete move (initial ``Location`` not specified)
    and the corresponding position into the a complete move
    with the most likely starting point specified. If no moves match, ``None``
    is returned.

    :type: move: Move
    :type: position: Board
    :rtype: Move
    """
    assert isinstance(move, Move)
    for legal_move in position.all_possible_moves(move.color):

        if move.status == notation_const.LONG_ALG:
            if move.end_loc == legal_move.end_loc and \
                    move.start_loc == legal_move.start_loc:
                return legal_move

        elif move == legal_move:
            return legal_move

    raise ValueError("Move {} not legal in \n{}".format(repr(move), position))


Instruction:
How would you explain what the following Python 3 function does
def short_alg(algebraic_string, input_color, position):
    return make_legal(incomplete_alg(algebraic_string, input_color, position), position)

Response: This function converts a string written in short algebraic form into a valid move in the alphabetical order.


Instruction:
Can you create a Python 3 function that
converts a string written in long algebraic form and the corresponding position into a complete move .

Response:
def long_alg(alg_str, position):
    """
    Converts a string written in long algebraic form
    and the corresponding position into a complete move
    (initial location specified). Used primarily for
    UCI, but can be used for other purposes.

    :type: alg_str: str
    :type: position: Board
    :rtype: Move
    """
    if alg_str is None or len(alg_str) < 4 or len(alg_str) > 6:
        raise ValueError("Invalid string input {}".format(alg_str))

    end = Location.from_string(alg_str[2:])
    start = Location.from_string(alg_str[:2])
    piece = position.piece_at_square(start)

    if len(alg_str) == 4:
        return make_legal(Move(end_loc=end,
                               piece=piece,
                               status=notation_const.LONG_ALG,
                               start_loc=start), position)

    promoted_to = _get_piece(alg_str, 4)
    if promoted_to is None or \
            promoted_to is King or \
            promoted_to is Pawn:
        raise Exception("Invalid move input")

    return make_legal(Move(end_loc=end,
                           piece=piece,
                           status=notation_const.LONG_ALG,
                           start_loc=start,
                           promoted_to_piece=promoted_to), position)


Instruction:
Implement a Python 3 function for
resetting hyb and neighbors marks to atoms.

Response:
def reset_query_marks(self):
        """
        set or reset hyb and neighbors marks to atoms.
        """
        for i, atom in self.atoms():
            neighbors = 0
            hybridization = 1
            # hybridization 1- sp3; 2- sp2; 3- sp1; 4- aromatic
            for j, bond in self._adj[i].items():
                if self._node[j].element != 'H':
                    neighbors += 1

                if hybridization in (3, 4):
                    continue
                order = bond.order
                if order == 4:
                    hybridization = 4
                elif order == 3:
                    hybridization = 3
                elif order == 2:
                    if hybridization == 2:
                        hybridization = 3
                    else:
                        hybridization = 2

            atom._neighbors = neighbors
            atom._hybridization = hybridization
        self.flush_cache()


Instruction:
Implement a Python 3 function for
removing explicit hydrogen if possible :return: number of removed hydrogens

Response:
def implicify_hydrogens(self):
        """
        remove explicit hydrogen if possible

        :return: number of removed hydrogens
        """
        explicit = defaultdict(list)
        c = 0
        for n, atom in self.atoms():
            if atom.element == 'H':
                for m in self.neighbors(n):
                    if self._node[m].element != 'H':
                        explicit[m].append(n)

        for n, h in explicit.items():
            atom = self._node[n]
            len_h = len(h)
            for i in range(len_h, 0, -1):
                hi = h[:i]
                if atom.get_implicit_h([y.order for x, y in self._adj[n].items() if x not in hi]) == i:
                    for x in hi:
                        self.remove_node(x)
                        c += 1
                    break

        self.flush_cache()
        return c


Instruction:
Can you generate the documentation for the following Python 3 function
def explicify_hydrogens(self):
        tmp = []
        for n, atom in self.atoms():
            if atom.element != 'H':
                for _ in range(atom.get_implicit_h([x.order for x in self._adj[n].values()])):
                    tmp.append(n)
        for n in tmp:
            self.add_bond(n, self.add_atom(H), Bond())

        self.flush_cache()
        return len(tmp)

Response: add explicit hydrogens to atoms


Instruction:
Given the following Python 3 function, write the documentation
def substructure(self, atoms, meta=False, as_view=True):
        s = super().substructure(atoms, meta, as_view)
        if as_view:
            s.check_valence = s.explicify_hydrogens = s.implicify_hydrogens = s.reset_query_marks = frozen
            s.standardize = s.aromatize = frozen
        return s

Response: create substructure containing atoms from nbunch list


Instruction:
Can you write a function in Python 3 where it
checks valences of all atoms in the environment

Response:
def check_valence(self):
        """
        check valences of all atoms

        :return: list of invalid atoms
        """
        return [x for x, atom in self.atoms() if not atom.check_valence(self.environment(x))]


Instruction:
Implement a Python 3 function for
returning VF2 if self is a cgr - cgr container and other is a cgr - cgr container

Response:
def _matcher(self, other):
        """
        return VF2 GraphMatcher

        MoleculeContainer < MoleculeContainer
        MoleculeContainer < CGRContainer
        """
        if isinstance(other, (self._get_subclass('CGRContainer'), MoleculeContainer)):
            return GraphMatcher(other, self, lambda x, y: x == y, lambda x, y: x == y)
        raise TypeError('only cgr-cgr possible')


Instruction:
Given the following Python 3 function, write the documentation
def to_datetime(date):
    return datetime.datetime.combine(date, datetime.datetime.min.time())

Response: Turn a date into a datetime at midnight.


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

        # Find the first size change, if any
        try:
            size_changes = list(filter(lambda h: h.field == 'Story Points',
                                       itertools.chain.from_iterable([c.items for c in issue.changelog.histories])))
        except AttributeError:
            return

        # If we have no size changes and the issue has a current size then a size must have ben specified at issue creation time.
        # Return the size at creation time

        try:
            current_size = issue.fields.__dict__[self.fields['StoryPoints']]
        except:
            current_size = None

        size = (size_changes[0].fromString) if len(size_changes)  else current_size

        # Issue was created
        yield IssueSizeSnapshot(
            change=None,
            key=issue.key,
            date=dateutil.parser.parse(issue.fields.created),
            size=size
        )

        for change in issue.changelog.histories:
            change_date = dateutil.parser.parse(change.created)

            #sizes = list(filter(lambda i: i.field == 'Story Points', change.items))
            #is_resolved = (sizes[-1].to is not None) if len(sizes) > 0 else is_resolved

            for item in change.items:
                if item.field == 'Story Points':
                    # StoryPoints value was changed
                    size = item.toString
                    yield IssueSizeSnapshot(
                        change=item.field,
                        key=issue.key,
                        date=change_date,
                        size=size
                    )

Response: Yields an IssueSizeSnapshot for each time the issue size changed


Instruction:
Create a Python 3 function for
yielding an IssueSnapshot for each time the issue changed status or resolution

Response:
def iter_changes(self, issue, include_resolution_changes=True):
        """Yield an IssueSnapshot for each time the issue changed status or
        resolution
        """

        is_resolved = False

        # Find the first status change, if any
        try:
            status_changes = list(filter(
                lambda h: h.field == 'status',
                itertools.chain.from_iterable([c.items for c in issue.changelog.histories])))
        except AttributeError:
            return
        last_status = status_changes[0].fromString if len(status_changes) > 0 else issue.fields.status.name
        last_resolution = None

        # Issue was created
        yield IssueSnapshot(
            change=None,
            key=issue.key,
            date=dateutil.parser.parse(issue.fields.created),
            status=last_status,
            resolution=None,
            is_resolved=is_resolved
        )

        for change in issue.changelog.histories:
            change_date = dateutil.parser.parse(change.created)

            resolutions = list(filter(lambda i: i.field == 'resolution', change.items))
            is_resolved = (resolutions[-1].to is not None) if len(resolutions) > 0 else is_resolved

            for item in change.items:
                if item.field == 'status':
                    # Status was changed
                    last_status = item.toString
                    yield IssueSnapshot(
                        change=item.field,
                        key=issue.key,
                        date=change_date,
                        status=last_status,
                        resolution=last_resolution,
                        is_resolved=is_resolved
                    )
                elif item.field == 'resolution':
                    last_resolution = item.toString
                    if include_resolution_changes:
                        yield IssueSnapshot(
                            change=item.field,
                            key=issue.key,
                            date=change_date,
                            status=last_status,
                            resolution=last_resolution,
                            is_resolved=is_resolved
                        )


Instruction:
Can you generate the documentation for the following Python 3 function
def find_issues(self, criteria={}, jql=None, order='KEY ASC', verbose=False, changelog=True):

        query = []

        if criteria.get('project', False):
            query.append('project IN (%s)' % ', '.join(['"%s"' % p for p in criteria['project']]))

        if criteria.get('issue_types', False):
            query.append('issueType IN (%s)' % ', '.join(['"%s"' % t for t in criteria['issue_types']]))

        if criteria.get('valid_resolutions', False):
            query.append('(resolution IS EMPTY OR resolution IN (%s))' % ', '.join(['"%s"' % r for r in criteria['valid_resolutions']]))

        if criteria.get('jql_filter') is not None:
            query.append('(%s)' % criteria['jql_filter'])

        if jql is not None:
            query.append('(%s)' % jql)

        queryString = "%s ORDER BY %s" % (' AND '.join(query), order,)

        if verbose:
            print("Fetching issues with query:", queryString)

        fromRow=0
        issues = []
        while True:
            try:
                if changelog:
                    pageofissues = self.jira.search_issues(queryString, expand='changelog', maxResults=self.settings['max_results'],startAt=fromRow)
                else:
                    pageofissues = self.jira.search_issues(queryString, maxResults=self.settings['max_results'],startAt=fromRow)

                fromRow = fromRow + int(self.settings['max_results'])
                issues += pageofissues
                if verbose:
                    print("Got %s lines per jira query from result starting at line number %s " % (self.settings['max_results'],  fromRow))
                if len(pageofissues)==0:
                    break
            except JIRAError as e:
                print("Jira query error with: {}\n{}".format(queryString, e))
                return []

        if verbose:
            print("Fetched", len(issues), "issues")

        return issues

Response: Return a list of issues with changelog metadata.


Instruction:
Explain what the following Python 3 code does
def list_catalogs(self):
        _form = CatalogSelectForm(current=self.current)
        _form.set_choices_of('catalog', [(i, i) for i in fixture_bucket.get_keys()])
        self.form_out(_form)

Response: Lists existing catalogs respect to ui view template format


Instruction:
Implement a Python 3 function for
getting existing catalog and fill the form with the model data.

Response:
def get_catalog(self):
        """
        Get existing catalog and fill the form with the model data.
        If given key not found as catalog, it generates an empty catalog data form.
        """

        catalog_data = fixture_bucket.get(self.input['form']['catalog'])

        # define add or edit based on catalog data exists
        add_or_edit = "Edit" if catalog_data.exists else "Add"

        # generate form
        catalog_edit_form = CatalogEditForm(
            current=self.current,
            title='%s: %s' % (add_or_edit, self.input['form']['catalog']))

        # add model data to form
        if catalog_data.exists:
            if type(catalog_data.data) == list:
                # if catalog data is an array it means no other language of value defined, therefor the value is turkish
                for key, data in enumerate(catalog_data.data):
                    catalog_edit_form.CatalogDatas(catalog_key=key or "0", en='', tr=data)
            if type(catalog_data.data) == dict:
                for key, data in catalog_data.data.items():
                    catalog_edit_form.CatalogDatas(catalog_key=key, en=data['en'], tr=data['tr'])

        else:
            catalog_edit_form.CatalogDatas(catalog_key="0", en='', tr='')

        self.form_out(catalog_edit_form)

        # schema key for get back what key will be saved, used in save_catalog form
        self.output["object_key"] = self.input['form']['catalog']


Instruction:
Write a Python 3 script to
save the catalog data to given key Cancels if the cmd is cancel

Response:
def save_catalog(self):
        """
        Saves the catalog data to given key
        Cancels if the cmd is cancel
        Notifies user with the process.
        """
        if self.input["cmd"] == 'save_catalog':
            try:
                edited_object = dict()
                for i in self.input["form"]["CatalogDatas"]:
                    edited_object[i["catalog_key"]] = {"en": i["en"], "tr": i["tr"]}

                newobj = fixture_bucket.get(self.input["object_key"])
                newobj.data = edited_object
                newobj.store()

                # notify user by passing notify in output object
                self.output["notify"] = "catalog: %s successfully updated." % self.input[
                    "object_key"]
            except:
                raise HTTPError(500, "Form object could not be saved")
        if self.input["cmd"] == 'cancel':
            self.output["notify"] = "catalog: %s canceled." % self.input["object_key"]


Instruction:
Given the following Python 3 function, write the documentation
def date_to_solr(d):
    return "{y}-{m}-{day}T00:00:00Z".format(day=d[:2], m=d[3:5], y=d[6:]) if d else d

Response: converts a date to Solr date


Instruction:
Explain what the following Python 3 code does
def solr_to_date(d):
    return "{day}:{m}:{y}".format(y=d[:4], m=d[5:7], day=d[8:10]) if d else d

Response: converts YYYY - MM - DDT00 : 00Z to DD - MM - YYYY


Instruction:
Make a summary of the following Python 3 code
def to_safe_str(s):
    # TODO: This is insufficient as it doesn't do anything for other non-ascii chars
    return re.sub(r'[^0-9a-zA-Z]+', '_', s.strip().replace(u'ğ', 'g').replace(u'ö', 'o').replace(
        u'ç', 'c').replace(u'Ç','c').replace(u'Ö', u'O').replace(u'Ş', 's').replace(
        u'Ü', 'u').replace(u'ı', 'i').replace(u'İ','i').replace(u'Ğ', 'g').replace(
        u'ö', 'o').replace(u'ş', 's').replace(u'ü', 'u').lower(), re.UNICODE)

Response: Convert some non - ascii chars to ascii counterparts and return the result as lowercase


Instruction:
Here you have a function in Python 3, explain what it does
def merge_truthy(*dicts):
    merged = {}
    for d in dicts:
        for k, v in d.items():
            merged[k] = v or merged.get(k, v)
    return merged

Response: Merge multiple dictionaries keeping the truthy values in case of key collisions.


Instruction:
Write a Python 3 script for
performing the version upgrade on the database.

Response:
def perform(self):
        """Perform the version upgrade on the database.
        """
        db_versions = self.table.versions()

        version = self.version
        if (version.is_processed(db_versions) and
                not self.config.force_version == self.version.number):
            self.log(
                u'version {} is already installed'.format(version.number)
            )
            return

        self.start()
        try:
            self._perform_version(version)
        except Exception:
            if sys.version_info < (3, 4):
                msg = traceback.format_exc().decode('utf8', errors='ignore')
            else:
                msg = traceback.format_exc()
            error = u'\n'.join(self.logs + [u'\n', msg])
            self.table.record_log(version.number, error)
            raise
        self.finish()


Instruction:
Can you write a function in Python 3 where it
logs out view. Simply deletes the session object. For showing logout message: 'show_logout_message' field should be True in current.task_data, Message should be sent in current.task_data with 'logout_message' field. Message title should be sent in current.task_data with 'logout_title' field. current.task_data['show_logout_message'] = True current.task_data['logout_title'] = 'Message Title' current.task_data['logout_message'] = 'Message' Args: current: :attr:`~zengine.engine.WFCurrent` object.

Response:
def logout(current):
    """
    Log out view.
    Simply deletes the session object.
    For showing logout message:
        'show_logout_message' field should be True in current.task_data,
        Message should be sent in current.task_data with 'logout_message' field.
        Message title should be sent in current.task_data with 'logout_title' field.

        current.task_data['show_logout_message'] = True
        current.task_data['logout_title'] = 'Message Title'
        current.task_data['logout_message'] = 'Message'

    Args:
        current: :attr:`~zengine.engine.WFCurrent` object.
    """
    current.user.is_online(False)
    current.session.delete()
    current.output['cmd'] = 'logout'
    if current.task_data.get('show_logout_message', False):
        current.output['title'] = current.task_data.get('logout_title', None)
        current.output['msg'] = current.task_data.get('logout_message', None)


Instruction:
Can you tell what is the following Python 3 function doing
def _do_upgrade(self):
        self.current.output['cmd'] = 'upgrade'
        self.current.output['user_id'] = self.current.user_id
        self.terminate_existing_login()
        self.current.user.bind_private_channel(self.current.session.sess_id)
        user_sess = UserSessionID(self.current.user_id)
        user_sess.set(self.current.session.sess_id)
        self.current.user.is_online(True)
        # Clean up the locale from session to allow it to be re-read from the user preferences after login
        for k in translation.DEFAULT_PREFS.keys():
            self.current.session[k] = ''

Response: Open websocket connection and upgrade the user preferences


Instruction:
How would you explain what the following Python 3 function does
def do_view(self):
        self.current.output['login_process'] = True
        self.current.task_data['login_successful'] = False
        if self.current.is_auth:
            self._do_upgrade()
        else:
            try:
                auth_result = self.current.auth.authenticate(
                    self.current.input['username'],
                    self.current.input['password'])
                self.current.task_data['login_successful'] = auth_result
                if auth_result:
                    self._do_upgrade()
            except ObjectDoesNotExist:
                self.current.log.exception("Wrong username or another error occurred")
                pass
            except:
                raise
            if self.current.output.get('cmd') != 'upgrade':
                self.current.output['status_code'] = 403
            else:
                KeepAlive(self.current.user_id).reset()

Response: Authenticate user with given credentials and connect user s queue and exchange.


Instruction:
How would you code a function in Python 3 to
show the view of the login form.

Response:
def show_view(self):
        """
        Show :attr:`LoginForm` form.
        """
        self.current.output['login_process'] = True
        if self.current.is_auth:
            self._do_upgrade()
        else:
            self.current.output['forms'] = LoginForm(current=self.current).serialize()


Instruction:
How would you code a function in Python 3 to
skip all the non - duplicate entries in the sequence

Response:
def skip(mapping):
    """
    :param mapping: generator
    :return: filtered generator
    """
    found = set()
    for m in mapping:
        matched_atoms = set(m.values())
        if found.intersection(matched_atoms):
            continue
        found.update(matched_atoms)
        yield m


Instruction:
Make a summary of the following Python 3 code
def __get_mapping(self, structures):
        for c in permutations(structures, len(self.__patterns)):
            for m in product(*(x.get_substructure_mapping(y, limit=0) for x, y in zip(self.__patterns, c))):
                mapping = {}
                for i in m:
                    mapping.update(i)
                if mapping:
                    yield mapping

Response: Returns a generator of all possible mappings for each pattern to each molecule.


Instruction:
Given the following Python 3 function, write the documentation
def get(self, default=None):
        d = cache.get(self.key)
        return ((json.loads(d.decode('utf-8')) if self.serialize else d)
                if d is not None
                else default)

Response: get the cached value or default if it can t be found


Instruction:
Can you generate the documentation for the following Python 3 function
def set(self, val, lifetime=None):
        cache.set(self.key,
                  (json.dumps(val) if self.serialize else val),
                  lifetime or settings.DEFAULT_CACHE_EXPIRE_TIME)
        return val

Response:
set cache value

        :param val: any picklable object
        :param lifetime: exprition time in sec
        :return: val


Instruction:
Explain what the following Python 3 code does
def add(self, val):
        return cache.lpush(self.key, json.dumps(val) if self.serialize else val)

Response: Adds given value to the item list


Instruction:
Explain what the following Python 3 code does
def get_all(self):
        result = cache.lrange(self.key, 0, -1)
        return (json.loads(item.decode('utf-8')) for item in result if
                item) if self.serialize else result

Response: Get all list items.


Instruction:
Write a Python 3 function for
removing given item from the list.

Response:
def remove_item(self, val):
        """
        Removes given item from the list.

        Args:
            val: Item

        Returns:
            Cache backend response.
        """
        return cache.lrem(self.key, json.dumps(val))


Instruction:
Make a summary of the following Python 3 code
def flush(cls, *args):
        return _remove_keys([], [(cls._make_key(args) if args else cls.PREFIX) + '*'])

Response: Removes all keys of this namespace


Instruction:
Given the following Python 3 function, write the documentation
def update_or_expire_session(self):
        if not hasattr(self, 'key'):
            return
        now = time.time()
        timestamp = float(self.get() or 0) or now
        sess_id = self.sess_id or UserSessionID(self.user_id).get()
        if sess_id and now - timestamp > self.SESSION_EXPIRE_TIME:
            Session(sess_id).delete()
            return False
        else:
            self.set(now)
            return True

Response: Updates the keepalive request if the keepalive request expired otherwise updates the keepalive timestamp value if the keepalive request expired otherwise updates the keepalive timestamp value if the keepalive request expired otherwise returns False


Instruction:
Here you have a function in Python 3, explain what it does
def send_message_for_lane_change(sender, **kwargs):
    current = kwargs['current']
    owners = kwargs['possible_owners']
    if 'lane_change_invite' in current.task_data:
        msg_context = current.task_data.pop('lane_change_invite')
    else:
        msg_context = DEFAULT_LANE_CHANGE_INVITE_MSG

    wfi = WFCache(current).get_instance()

    # Deletion of used passive task invitation which belongs to previous lane.
    TaskInvitation.objects.filter(instance=wfi, role=current.role, wf_name=wfi.wf.name).delete()

    today = datetime.today()
    for recipient in owners:
        inv = TaskInvitation(
            instance=wfi,
            role=recipient,
            wf_name=wfi.wf.name,
            progress=30,
            start_date=today,
            finish_date=today + timedelta(15)
        )
        inv.title = current.task_data.get('INVITATION_TITLE') or wfi.wf.title
        inv.save()

        # try to send notification, if it fails go on
        try:

            recipient.send_notification(title=msg_context['title'],
                                        message="%s %s" % (wfi.wf.title, msg_context['body']),
                                        typ=1,  # info
                                        url='',
                                        sender=sender
                                        )
        except: # todo: specify which exception
            pass

Response:
Sends a message to the possible owners of the current workflows
     next lane.


Instruction:
Can you write a function in Python 3 where it
encrypts password of the user.

Response:
def set_password(sender, **kwargs):
    """
    Encrypts password of the user.
    """
    if sender.model_class.__name__ == 'User':
        usr = kwargs['object']
        if not usr.password.startswith('$pbkdf2'):
            usr.set_password(usr.password)
            usr.save()


Instruction:
Make a summary of the following Python 3 code
def channel_choice_control(self):
        self.current.task_data['control'], self.current.task_data['msg'] \
            = self.selection_error_control(self.input['form'])
        if self.current.task_data['control']:
            self.current.task_data['option'] = self.input['cmd']
            self.current.task_data['split_operation'] = False
            keys, names = self.return_selected_form_items(self.input['form']['ChannelList'])
            self.current.task_data['chosen_channels'] = keys
            self.current.task_data['chosen_channels_names'] = names

Response: It controls errors. It returns channel list screen with error message.


Instruction:
How would you code a function in Python 3 to
create a new channel

Response:
def create_new_channel(self):
        """
        Features of new channel are specified like channel's name, owner etc.
        """

        self.current.task_data['new_channel'] = True
        _form = NewChannelForm(Channel(), current=self.current)
        _form.title = _(u"Specify Features of New Channel to Create")
        _form.forward = fields.Button(_(u"Create"), flow="find_target_channel")
        self.form_out(_form)


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

        if self.current.task_data.get('msg', False):
            self.show_warning_messages()

        _form = ChannelListForm()
        _form.title = _(u"Choose a Channel Which Will Be Merged With Chosen Channels")

        for channel in Channel.objects.filter(typ=15).exclude(
                key__in=self.current.task_data['chosen_channels']):
            owner_name = channel.owner.username
            _form.ChannelList(choice=False, name=channel.name, owner=owner_name,
                              key=channel.key)

        _form.choose = fields.Button(_(u"Choose"))
        self.form_out(_form)

Response:
This method is used to choose existing channel. It is a channel choice list and chosen channels
        at previous step should not be on the screen.


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

        if self.current.task_data.get('msg', False):
            self.show_warning_messages()

        self.current.task_data['split_operation'] = True
        channel = Channel.objects.get(self.current.task_data['chosen_channels'][0])

        _form = SubscriberListForm(title=_(u'Choose Subscribers to Migrate'))

        for subscriber in Subscriber.objects.filter(channel=channel):
            subscriber_name = subscriber.user.username
            _form.SubscriberList(choice=False, name=subscriber_name, key=subscriber.key)

        _form.new_channel = fields.Button(_(u"Move to a New Channel"), cmd="create_new_channel")
        _form.existing_channel = fields.Button(_(u"Move to an Existing Channel"),
                                               cmd="choose_existing_channel")
        self.form_out(_form)

Response: A channel can be splitted to new or other existing channel. It creates subscribers list as selectable to move.


Instruction:
Create a Python 3 function to
move all the chosen channels and their subscribers to the new channel or existing channel.

Response:
def move_complete_channel(self):
        """
        Channels and theirs subscribers are moved
        completely to new channel or existing channel.
        """

        to_channel = Channel.objects.get(self.current.task_data['target_channel_key'])
        chosen_channels = self.current.task_data['chosen_channels']
        chosen_channels_names = self.current.task_data['chosen_channels_names']

        with BlockSave(Subscriber, query_dict={'channel_id': to_channel.key}):
            for s in Subscriber.objects.filter(channel_id__in=chosen_channels, typ=15):
                s.channel = to_channel
                s.save()

        with BlockDelete(Message):
            Message.objects.filter(channel_id__in=chosen_channels, typ=15).delete()

        with BlockDelete(Channel):
            Channel.objects.filter(key__in=chosen_channels).delete()

        self.current.task_data[
            'msg'] = _(u"Chosen channels(%s) have been merged to '%s' channel successfully.") % \
                     (', '.join(chosen_channels_names), to_channel.name)


Instruction:
Write a Python 3 script for
moving chosen subscribers and messages of them to new channel.

Response:
def move_chosen_subscribers(self):
        """
        After splitting operation, only chosen subscribers
        are moved to new channel or existing channel.
        """
        from_channel = Channel.objects.get(self.current.task_data['chosen_channels'][0])
        to_channel = Channel.objects.get(self.current.task_data['target_channel_key'])

        with BlockSave(Subscriber, query_dict={'channel_id': to_channel.key}):
            for subscriber in Subscriber.objects.filter(
                    key__in=self.current.task_data['chosen_subscribers']):
                subscriber.channel = to_channel
                subscriber.save()

        if self.current.task_data['new_channel']:
            self.copy_and_move_messages(from_channel, to_channel)

        self.current.task_data[
            'msg'] = _(u"Chosen subscribers and messages of them migrated from '%s' channel to "
                       u"'%s' channel successfully.") % (from_channel.name, to_channel.name)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def copy_and_move_messages(from_channel, to_channel):
        with BlockSave(Message, query_dict={'channel_id': to_channel.key}):
            for message in Message.objects.filter(channel=from_channel, typ=15):
                message.key = ''
                message.channel = to_channel
                message.save()

Response: Copy messages from one channel to another.


Instruction:
Given the following Python 3 function, write the documentation
def show_warning_messages(self, title=_(u"Incorrect Operation"), box_type='warning'):
        msg = self.current.task_data['msg']
        self.current.output['msgbox'] = {'type': box_type, "title": title, "msg": msg}
        del self.current.task_data['msg']

Response: It shows incorrect operations or successful operation messages.


Instruction:
Explain what the following Python 3 code does
def _eratosthenes():
    d = {}  # map each composite integer to its first-found prime factor
    for q in count(2):  # q gets 2, 3, 4, 5, ... ad infinitum
        p = d.pop(q, None)
        if p is None:
            # q not a key in D, so q is prime, therefore, yield it
            yield q
            # mark q squared as not-prime (with q as first-found prime factor)
            d[q * q] = q
        else:
            # let x <- smallest (N*p)+q which wasn't yet known to be composite
            # we just learned x is composite, with p first-found prime factor,
            # since p is the first-found prime factor of q -- find and mark it
            x = p + q
            while x in d:
                x += p
            d[x] = p

Response: Yields the sequence of prime numbers via the Sieve of Eratosthenes.


Instruction:
Make a summary of the following Python 3 code
def atoms_order(self):
        if not len(self):  # for empty containers
            return {}
        elif len(self) == 1:  # optimize single atom containers
            return dict.fromkeys(self, 2)

        params = {n: (int(node), tuple(sorted(int(edge) for edge in self._adj[n].values())))
                  for n, node in self.atoms()}
        newlevels = {}
        countprime = iter(primes)
        weights = {x: newlevels.get(y) or newlevels.setdefault(y, next(countprime))
                   for x, y in sorted(params.items(), key=itemgetter(1))}

        tries = len(self) * 4

        numb = len(set(weights.values()))
        stab = 0

        while tries:
            oldnumb = numb
            neweights = {}
            countprime = iter(primes)

            # weights[n] ** 2 NEED for differentiation of molecules like A-B or any other complete graphs.
            tmp = {n: reduce(mul, (weights[x] for x in m), weights[n] ** 2) for n, m in self._adj.items()}

            weights = {x: (neweights.get(y) or neweights.setdefault(y, next(countprime)))
                       for x, y in sorted(tmp.items(), key=itemgetter(1))}

            numb = len(set(weights.values()))
            if numb == len(self):  # each atom now unique
                break
            elif numb == oldnumb:
                x = Counter(weights.values())
                if x[min(x)] > 1:
                    if stab == 3:
                        break
                elif stab >= 2:
                    break

                stab += 1
            elif stab:
                stab = 0

            tries -= 1
            if not tries and numb < oldnumb:
                warning('morgan. number of attempts exceeded. uniqueness has decreased. next attempt will be made')
                tries = 1
        else:
            warning('morgan. number of attempts exceeded')

        return weights

Response:
Morgan like algorithm for graph nodes ordering
AttributeNames


Instruction:
Can you tell what is the following Python 3 function doing
def init_manual(cls, pawn_value, knight_value, bishop_value, rook_value, queen_value, king_value):
        piece_values = cls()
        piece_values.PAWN_VALUE = pawn_value
        piece_values.KNIGHT_VALUE = knight_value
        piece_values.BISHOP_VALUE = bishop_value
        piece_values.ROOK_VALUE = rook_value
        piece_values.QUEEN_VALUE = queen_value
        piece_values.KING_VALUE = king_value
        return piece_values

Response: This method is used to initialize the manual piece values for external pieces.


Instruction:
Make a summary of the following Python 3 code
def val(self, piece, ref_color):
        if piece is None:
            return 0

        if ref_color == piece.color:
            const = 1
        else:
            const = -1

        if isinstance(piece, Pawn):
            return self.PAWN_VALUE * const
        elif isinstance(piece, Queen):
            return self.QUEEN_VALUE * const
        elif isinstance(piece, Bishop):
            return self.BISHOP_VALUE * const
        elif isinstance(piece, Rook):
            return self.ROOK_VALUE * const
        elif isinstance(piece, Knight):
            return self.KNIGHT_VALUE * const
        elif isinstance(piece, King):
            return self.KING_VALUE * const
        return 0

Response: Returns the value of the key in the record.


Instruction:
How would you explain what the following Python 3 function does
def play(self):
        colors = [lambda: self.white_move(), lambda: self.black_move()]
        colors = itertools.cycle(colors)

        while True:
            color_fn = next(colors)
            if game_state.no_moves(self.position):
                if self.position.get_king(color.white).in_check(self.position):
                    return 1

                elif self.position.get_king(color.black).in_check(self.position):
                    return 0

                else:
                    return 0.5

            color_fn()

Response: Starts game and returns one of 3 results.


Instruction:
How would you explain what the following Python 3 function does
def white_move(self):
        move = self.player_white.generate_move(self.position)
        move = make_legal(move, self.position)
        self.position.update(move)

Response: Calls the white player s generate_move method and updates the board with the move returned.


Instruction:
Write a Python 3 function for
calling the black player s generate_move method and updates the board with the move returned.

Response:
def black_move(self):
        """
        Calls the black player's ``generate_move()``
        method and updates the board with the move returned.
        """
        move = self.player_black.generate_move(self.position)
        move = make_legal(move, self.position)
        self.position.update(move)


Instruction:
Given the following Python 3 function, write the documentation
def get_field_cache(self, cache_type='es'):
        if cache_type == 'kibana':
            try:
                search_results = urlopen(self.get_url).read().decode('utf-8')
            except HTTPError:  # as e:
                # self.pr_err("get_field_cache(kibana), HTTPError: %s" % e)
                return []
            index_pattern = json.loads(search_results)
            # Results look like: {"_index":".kibana","_type":"index-pattern","_id":"aaa*","_version":6,"found":true,"_source":{"title":"aaa*","fields":"<what we want>"}}  # noqa
            fields_str = index_pattern['_source']['fields']
            return json.loads(fields_str)
        elif cache_type == 'es' or cache_type.startswith('elastic'):
            search_results = urlopen(self.es_get_url).read().decode('utf-8')
            es_mappings = json.loads(search_results)
            # Results look like: {"<index_name>":{"mappings":{"<doc_type>":{"<field_name>":{"full_name":"<field_name>","mapping":{"<sub-field_name>":{"type":"date","index_name":"<sub-field_name>","boost":1.0,"index":"not_analyzed","store":false,"doc_values":false,"term_vector":"no","norms":{"enabled":false},"index_options":"docs","index_analyzer":"_date/16","search_analyzer":"_date/max","postings_format":"default","doc_values_format":"default","similarity":"default","fielddata":{},"ignore_malformed":false,"coerce":true,"precision_step":16,"format":"dateOptionalTime","null_value":null,"include_in_all":false,"numeric_resolution":"milliseconds","locale":""}}},  # noqa
            # now convert the mappings into the .kibana format
            field_cache = []
            for (index_name, val) in iteritems(es_mappings):
                if index_name != self.index:  # only get non-'.kibana' indices
                    # self.pr_dbg("index: %s" % index_name)
                    m_dict = es_mappings[index_name]['mappings']
                    # self.pr_dbg('m_dict %s' % m_dict)
                    mappings = self.get_index_mappings(m_dict)
                    # self.pr_dbg('mappings %s' % mappings)
                    field_cache.extend(mappings)
            field_cache = self.dedup_field_cache(field_cache)
            return field_cache
        self.pr_err("Unknown cache type: %s" % cache_type)
        return None

Response: Return a list of fields mappings


Instruction:
How would you explain what the following Python 3 function does
def post_field_cache(self, field_cache):
        index_pattern = self.field_cache_to_index_pattern(field_cache)
        # self.pr_dbg("request/post: %s" % index_pattern)
        resp = requests.post(self.post_url, data=index_pattern).text
        # resp = {"_index":".kibana","_type":"index-pattern","_id":"aaa*","_version":1,"created":true}  # noqa
        resp = json.loads(resp)
        return 0

Response: Post a list of fields to the index pattern.


Instruction:
Implement a Python 3 function for
returning a. kibana index - pattern doc_type

Response:
def field_cache_to_index_pattern(self, field_cache):
        """Return a .kibana index-pattern doc_type"""
        mapping_dict = {}
        mapping_dict['customFormats'] = "{}"
        mapping_dict['title'] = self.index_pattern
        # now post the data into .kibana
        mapping_dict['fields'] = json.dumps(field_cache, separators=(',', ':'))
        # in order to post, we need to create the post string
        mapping_str = json.dumps(mapping_dict, separators=(',', ':'))
        return mapping_str


Instruction:
How would you implement a function in Python 3 that
asserts minimum set of fields in cache does not validate contents

Response:
def check_mapping(self, m):
        """Assert minimum set of fields in cache, does not validate contents"""
        if 'name' not in m:
            self.pr_dbg("Missing %s" % "name")
            return False
        # self.pr_dbg("Checking %s" % m['name'])
        for x in ['analyzed', 'indexed', 'type', 'scripted', 'count']:
            if x not in m or m[x] == "":
                self.pr_dbg("Missing %s" % x)
                self.pr_dbg("Full %s" % m)
                return False
        if 'doc_values' not in m or m['doc_values'] == "":
            if not m['name'].startswith('_'):
                self.pr_dbg("Missing %s" % "doc_values")
                return False
            m['doc_values'] = False
        return True


Instruction:
Can you tell what is the following Python 3 function doing
def get_index_mappings(self, index):
        fields_arr = []
        for (key, val) in iteritems(index):
            # self.pr_dbg("\tdoc_type: %s" % key)
            doc_mapping = self.get_doc_type_mappings(index[key])
            # self.pr_dbg("\tdoc_mapping: %s" % doc_mapping)
            if doc_mapping is None:
                return None
            # keep adding to the fields array
            fields_arr.extend(doc_mapping)
        return fields_arr

Response: Converts all index s doc_types to. kibana


Instruction:
Here you have a function in Python 3, explain what it does
def get_doc_type_mappings(self, doc_type):
        doc_fields_arr = []
        found_score = False
        for (key, val) in iteritems(doc_type):
            # self.pr_dbg("\t\tfield: %s" % key)
            # self.pr_dbg("\tval: %s" % val)
            add_it = False
            retdict = {}
            # _ are system
            if not key.startswith('_'):
                if 'mapping' not in doc_type[key]:
                    self.pr_err("No mapping in doc_type[%s]" % key)
                    return None
                if key in doc_type[key]['mapping']:
                    subkey_name = key
                else:
                    subkey_name = re.sub('.*\.', '', key)
                if subkey_name not in doc_type[key]['mapping']:
                    self.pr_err(
                        "Couldn't find subkey " +
                        "doc_type[%s]['mapping'][%s]" % (key, subkey_name))
                    return None
                # self.pr_dbg("\t\tsubkey_name: %s" % subkey_name)
                retdict = self.get_field_mappings(
                    doc_type[key]['mapping'][subkey_name])
                add_it = True
            # system mappings don't list a type,
            # but kibana makes them all strings
            if key in self.sys_mappings:
                retdict['analyzed'] = False
                retdict['indexed'] = False
                if key == '_source':
                    retdict = self.get_field_mappings(
                        doc_type[key]['mapping'][key])
                    retdict['type'] = "_source"
                elif key == '_score':
                    retdict['type'] = "number"
                elif 'type' not in retdict:
                    retdict['type'] = "string"
                add_it = True
            if add_it:
                retdict['name'] = key
                retdict['count'] = 0  # always init to 0
                retdict['scripted'] = False  # I haven't observed a True yet
                if not self.check_mapping(retdict):
                    self.pr_err("Error, invalid mapping")
                    return None
                # the fields element is an escaped array of json
                # make the array here, after all collected, then escape it
                doc_fields_arr.append(retdict)
        if not found_score:
            doc_fields_arr.append(
                {"name": "_score",
                 "type": "number",
                 "count": 0,
                 "scripted": False,
                 "indexed": False,
                 "analyzed": False,
                 "doc_values": False})
        return doc_fields_arr

Response: Converts all doc_types fields to. kibana


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_field_mappings(self, field):
        retdict = {}
        retdict['indexed'] = False
        retdict['analyzed'] = False
        for (key, val) in iteritems(field):
            if key in self.mappings:
                if (key == 'type' and
                    (val == "long" or
                     val == "integer" or
                     val == "double" or
                     val == "float")):
                    val = "number"
                # self.pr_dbg("\t\t\tkey: %s" % key)
                # self.pr_dbg("\t\t\t\tval: %s" % val)
                retdict[key] = val
            if key == 'index' and val != "no":
                retdict['indexed'] = True
                # self.pr_dbg("\t\t\tkey: %s" % key)
                # self.pr_dbg("\t\t\t\tval: %s" % val)
                if val == "analyzed":
                    retdict['analyzed'] = True
        return retdict

Response: Converts ES field mappings to. kibana field mappings


Instruction:
Write a Python 3 function that can
test if k_cache is incomplete

Response:
def is_kibana_cache_incomplete(self, es_cache, k_cache):
        """Test if k_cache is incomplete

        Assume k_cache is always correct, but could be missing new
        fields that es_cache has
        """
        # convert list into dict, with each item's ['name'] as key
        k_dict = {}
        for field in k_cache:
            # self.pr_dbg("field: %s" % field)
            k_dict[field['name']] = field
            for ign_f in self.mappings_ignore:
                k_dict[field['name']][ign_f] = 0
        es_dict = {}
        for field in es_cache:
            es_dict[field['name']] = field
            for ign_f in self.mappings_ignore:
                es_dict[field['name']][ign_f] = 0
        es_set = set(es_dict.keys())
        k_set = set(k_dict.keys())
        # reasons why kibana cache could be incomplete:
        #     k_dict is missing keys that are within es_dict
        #     We don't care if k has keys that es doesn't
        # es {1,2} k {1,2,3}; intersection {1,2}; len(es-{}) 0
        # es {1,2} k {1,2};   intersection {1,2}; len(es-{}) 0
        # es {1,2} k {};      intersection {};    len(es-{}) 2
        # es {1,2} k {1};     intersection {1};   len(es-{}) 1
        # es {2,3} k {1};     intersection {};    len(es-{}) 2
        # es {2,3} k {1,2};   intersection {2};   len(es-{}) 1
        return len(es_set - k_set.intersection(es_set)) > 0


Instruction:
Implement a function in Python 3 to
convert a list into a dictionary that can be used to query easier

Response:
def list_to_compare_dict(self, list_form):
        """Convert list into a data structure we can query easier"""
        compare_dict = {}
        for field in list_form:
            if field['name'] in compare_dict:
                self.pr_dbg("List has duplicate field %s:\n%s" %
                            (field['name'], compare_dict[field['name']]))
                if compare_dict[field['name']] != field:
                    self.pr_dbg("And values are different:\n%s" % field)
                return None
            compare_dict[field['name']] = field
            for ign_f in self.mappings_ignore:
                compare_dict[field['name']][ign_f] = 0
        return compare_dict


Instruction:
Write a Python 3 script to
compare the fields in original with replica.

Response:
def compare_field_caches(self, replica, original):
        """Verify original is subset of replica"""
        if original is None:
            original = []
        if replica is None:
            replica = []
        self.pr_dbg("Comparing orig with %s fields to replica with %s fields" %
                    (len(original), len(replica)))
        # convert list into dict, with each item's ['name'] as key
        orig = self.list_to_compare_dict(original)
        if orig is None:
            self.pr_dbg("Original has duplicate fields")
            return 1
        repl = self.list_to_compare_dict(replica)
        if repl is None:
            self.pr_dbg("Replica has duplicate fields")
            return 1
        # search orig for each item in repl
        # if any items in repl not within orig or vice versa, then complain
        # make sure contents of each item match
        orig_found = {}
        for (key, field) in iteritems(repl):
            field_name = field['name']
            if field_name not in orig:
                self.pr_dbg("Replica has field not found in orig %s: %s" %
                            (field_name, field))
                return 1
            orig_found[field_name] = True
            if orig[field_name] != field:
                self.pr_dbg("Field in replica doesn't match orig:")
                self.pr_dbg("orig:%s\nrepl:%s" % (orig[field_name], field))
                return 1
        unfound = set(orig_found.keys()) - set(repl.keys())
        if len(unfound) > 0:
            self.pr_dbg("Orig contains fields that were not in replica")
            self.pr_dbg('%s' % unfound)
            return 1
        # We don't care about case when replica has more fields than orig
        # unfound = set(repl.keys()) - set(orig_found.keys())
        # if len(unfound) > 0:
        #     self.pr_dbg("Replica contains fields that were not in orig")
        #     self.pr_dbg('%s' % unfound)
        #     return 1
        self.pr_dbg("Original matches replica")
        return 0


Instruction:
Write a Python 3 function for
starting a deamon thread for a given target function and arguments.

Response:
def start_daemon_thread(target, args=()):
    """starts a deamon thread for a given target function and arguments."""
    th = Thread(target=target, args=args)
    th.daemon = True
    th.start()
    return th


Instruction:
Can you tell what is the following Python 3 function doing
def serialize_dict_keys(d, prefix=""):
    keys = []
    for k, v in d.iteritems():
        fqk = '%s%s' % (prefix, k)
        keys.append(fqk)
        if isinstance(v, dict):
            keys.extend(serialize_dict_keys(v, prefix="%s." % fqk))

    return keys

Response: returns all the keys in a dictionary.


Instruction:
Implement a Python 3 function for
writing user data to session.

Response:
def set_user(self, user):
        """
        Writes user data to session.

        Args:
            user: User object

        """
        self.session['user_id'] = user.key
        self.session['user_data'] = user.clean_value()
        role = self.get_role()
        # TODO: this should be remembered from previous login
        # self.session['role_data'] = default_role.clean_value()
        self.session['role_id'] = role.key
        self.current.role_id = role.key
        self.current.user_id = user.key
        # self.perm_cache = PermissionCache(role.key)
        self.session['permissions'] = role.get_permissions()


Instruction:
Can you generate the documentation for the following Python 3 function
def contains_opposite_color_piece(self, square, position):
        return not position.is_square_empty(square) and \
            position.piece_at_square(square).color != self.color

Response: Finds if a piece is occupied by a piece with the same color.


Instruction:
Create a Python 3 function for
returning a translated message.

Response:
def gettext(message, domain=DEFAULT_DOMAIN):
    """Mark a message as translateable, and translate it.

    All messages in the application that are translateable should be wrapped with this function.
    When importing this function, it should be renamed to '_'. For example:

    .. code-block:: python

        from zengine.lib.translation import gettext as _
        print(_('Hello, world!'))
        'Merhaba, dünya!'

    For the messages that will be formatted later on, instead of using the position-based
    formatting, key-based formatting should be used. This gives the translator an idea what
    the variables in the format are going to be, and makes it possible for the translator
    to reorder the variables. For example:

    .. code-block:: python

        name, number = 'Elizabeth', 'II'
        _('Queen %(name)s %(number)s') % {'name': name, 'number': number}
        'Kraliçe II. Elizabeth'

    The message returned by this function depends on the language of the current user.
    If this function is called before a language is installed (which is normally done
    by ZEngine when the user connects), this function will simply return the message
    without modification.

    If there are messages containing unicode characters, in Python 2 these messages must
    be marked as unicode. Otherwise, python will not be able to correctly match these
    messages with translations. For example:

    .. code-block:: python

        print(_('Café'))
        'Café'
        print(_(u'Café'))
        'Kahve'

    Args:
        message (basestring, unicode): The input message.
        domain (basestring): The domain of the message. Defaults to 'messages', which
            is the domain where all application messages should be located.

    Returns:
        unicode: The translated message.
    """

    if six.PY2:
        return InstalledLocale._active_catalogs[domain].ugettext(message)
    else:
        return InstalledLocale._active_catalogs[domain].gettext(message)


Instruction:
Explain what the following Python 3 code does
def gettext_lazy(message, domain=DEFAULT_DOMAIN):
    return LazyProxy(gettext, message, domain=domain, enable_cache=False)

Response: Returns a LazyProxy that can be used to translate a message.


Instruction:
Write a Python 3 function that can
mark a message as translateable and translate it considering plural forms.

Response:
def ngettext(singular, plural, n, domain=DEFAULT_DOMAIN):
    """Mark a message as translateable, and translate it considering plural forms.

    Some messages may need to change based on a number. For example, consider a message
    like the following:

    .. code-block:: python

        def alert_msg(msg_count): print(
        'You have %d %s' % (msg_count, 'message' if msg_count == 1 else 'messages'))

        alert_msg(1)
        'You have 1 message'
        alert_msg(5)
        'You have 5 messages'

    To translate this message, you can use ngettext to consider the plural forms:

    .. code-block:: python

        from zengine.lib.translation import ngettext
        def alert_msg(msg_count): print(ngettext('You have %(count)d message',
                                                 'You have %(count)d messages',
                                                 msg_count) % {'count': msg_count})
        alert_msg(1)
        '1 mesajınız var'

        alert_msg(5)
        '5 mesajlarınız var'

    When doing formatting, both singular and plural forms of the message should
    have the exactly same variables.

    Args:
        singular (unicode): The singular form of the message.
        plural (unicode): The plural form of the message.
        n (int): The number that is used to decide which form should be used.
        domain (basestring): The domain of the message. Defaults to 'messages', which
            is the domain where all application messages should be located.
    Returns:
        unicode: The correct pluralization, translated.

    """

    if six.PY2:
        return InstalledLocale._active_catalogs[domain].ungettext(singular, plural, n)
    else:
        return InstalledLocale._active_catalogs[domain].ngettext(singular, plural, n)


Instruction:
How would you code a function in Python 3 to
mark a message with plural forms translateable and delay the translation until the message is used.

Response:
def ngettext_lazy(singular, plural, n, domain=DEFAULT_DOMAIN):
    """Mark a message with plural forms translateable, and delay the translation
    until the message is used.

    Works the same was a `ngettext`, with a delaying functionality similiar to `gettext_lazy`.

    Args:
        singular (unicode): The singular form of the message.
        plural (unicode): The plural form of the message.
        n (int): The number that is used to decide which form should be used.
        domain (basestring): The domain of the message. Defaults to 'messages', which
                             is the domain where all application messages should be located.
    Returns:
        unicode: The correct pluralization, with the translation being
                 delayed until the message is used.
    """
    return LazyProxy(ngettext, singular, plural, n, domain=domain, enable_cache=False)


Instruction:
Can you tell what is the following Python 3 function doing
def _wrap_locale_formatter(fn, locale_type):

    def wrapped_locale_formatter(*args, **kwargs):
        """A Babel formatting function, wrapped to automatically use the
        currently installed language.

        The wrapped function will not throw any exceptions for unknown locales,
        if Babel doesn't recognise the locale, we will simply fall back to
        the default language.

        The locale used by the wrapped function can be overriden by passing it a `locale` keyword.
        To learn more about this function, check the documentation of Babel for the function of
        the same name.
        """
        # Get the current locale from the class
        kwargs_ = {'locale': getattr(InstalledLocale, locale_type)}
        # By creating a dict then updating it, we allow locale to be overridden
        kwargs_.update(kwargs)
        try:
            formatted = fn(*args, **kwargs_)
        except UnknownLocaleError:
            log.warning(
                """Can\'t do formatting for language code {locale},
                           falling back to default {default}""".format(
                    locale=kwargs_['locale'],
                    default=settings.DEFAULT_LANG)
            )
            kwargs_['locale'] = settings.DEFAULT_LANG
            formatted = fn(*args, **kwargs_)
        return formatted

    return wrapped_locale_formatter

Response: Wrap a Babel data formatting function to automatically format the currently installed language.


Instruction:
Given the following Python 3 function, write the documentation
def install_language(cls, language_code):
        # Skip if the language is already installed
        if language_code == cls.language:
            return
        try:
            cls._active_catalogs = cls._translation_catalogs[language_code]
            cls.language = language_code
            log.debug('Installed language %s', language_code)
        except KeyError:
            default = settings.DEFAULT_LANG
            log.warning('Unknown language %s, falling back to %s', language_code, default)
            cls._active_catalogs = cls._translation_catalogs[default]
            cls.language = default

Response: Install the translations for the specified language.


Instruction:
Here you have a function in Python 3, explain what it does
def install_locale(cls, locale_code, locale_type):

        # Skip if the locale is already installed
        if locale_code == getattr(cls, locale_type):
            return
        try:
            # We create a Locale instance to see if the locale code is supported
            locale = Locale(locale_code)
            log.debug('Installed locale %s', locale_code)
        except UnknownLocaleError:
            default = settings.DEFAULT_LOCALIZATION_FORMAT
            log.warning('Unknown locale %s, falling back to %s', locale_code, default)
            locale = Locale(default)
        setattr(cls, locale_type, locale.language)

Response: Install the locale specified by language_code for localizations of type locale_type.


Instruction:
Implement a function in Python 3 to
rotate x y vector over x2 y2 x1 y1 angle

Response:
def _rotate_vector(x, y, x2, y2, x1, y1):
        """
        rotate x,y vector over x2-x1, y2-y1 angle
        """
        angle = atan2(y2 - y1, x2 - x1)
        cos_rad = cos(angle)
        sin_rad = sin(angle)
        return cos_rad * x + sin_rad * y, -sin_rad * x + cos_rad * y


Instruction:
Make a summary of the following Python 3 code
def _build_static_table_mapping():
    static_table_mapping = {}
    for index, (name, value) in enumerate(CocaineHeaders.STATIC_TABLE, 1):
        header_name_search_result = static_table_mapping.setdefault(name, (index, {}))
        header_name_search_result[1][value] = index
    return static_table_mapping

Response: Build static table mapping from header name to tuple with next structure.


Instruction:
Write a Python 3 function for
returning the entry specified by index.

Response:
def get_by_index(self, index):
        """
        Returns the entry specified by index

        Note that the table is 1-based ie an index of 0 is
        invalid.  This is due to the fact that a zero value
        index signals that a completely unindexed header
        follows.

        The entry will either be from the static table or
        the dynamic table depending on the value of index.
        """
        index -= 1
        if 0 <= index < len(CocaineHeaders.STATIC_TABLE):
            return CocaineHeaders.STATIC_TABLE[index]
        index -= len(CocaineHeaders.STATIC_TABLE)
        if 0 <= index < len(self.dynamic_entries):
            return self.dynamic_entries[index]
        raise InvalidTableIndex("Invalid table index %d" % index)


Instruction:
Here you have a function in Python 3, explain what it does
def add(self, name, value):
        # We just clear the table if the entry is too big
        size = table_entry_size(name, value)
        if size > self._maxsize:
            self.dynamic_entries.clear()
            self._current_size = 0

        # Add new entry if the table actually has a size
        elif self._maxsize > 0:
            self.dynamic_entries.appendleft((name, value))
            self._current_size += size
            self._shrink()

Response: Adds a new entry to the table.