Instruction:
Can you tell what is the following Python 3 function doing
def pause(self, signum, seconds=0, callback_function=None):
        if callback_function is None:
            callback_function = self.default_handler
        if seconds > 0:
            self.log.info("Signal handler pausing for {0} seconds or until it receives SIGALRM or SIGCONT".format(seconds))
            signal.signal(signal.SIGALRM, callback_function)
            signal.alarm(seconds)
        else:
            self.log.info('Signal handler pausing until it receives SIGALRM or SIGCONT')
        signal.signal(signal.SIGCONT, callback_function)
        signal.pause()
        self.log.info('Signal handler resuming from pause')
        if signum == signal.SIGALRM:
            return True
        else:
            return False

Response: Pause execution will pause for the specified number of seconds or until the signal handler receives SIGALRM or SIGCONT.


Instruction:
Can you write a function in Python 3 where it
runs all abort tasks then exit with error return status

Response:
def abort(self, signum):
        """ Run all abort tasks, then all exit tasks, then exit with error
        return status"""
        self.log.info('Signal handler received abort request')
        self._abort(signum)
        self._exit(signum)
        os._exit(1)


Instruction:
Write a Python 3 function for
calling when the status signal is received from the status queue.

Response:
def status(self, signum):
        """ Run all status tasks, then run all tasks in the resume queue"""
        self.log.debug('Signal handler got status signal')
        new_status_callbacks = []
        for status_call in self.status_callbacks:
            # If callback is non persistent we remove it
            try:
                self.log.debug("Calling {0}({1},{2})".format(status_call['function'].__name__, status_call['args'], status_call['kwargs']))
            except AttributeError:
                self.log.debug("Calling unbound function/method {0}".format(str(status_call)))

            apply(status_call['function'], status_call['args'], status_call['kwargs'])
            if status_call['persistent']:
                new_status_callbacks.append(status_call)
        self.status_callbacks = new_status_callbacks
        self._resume(signum)


Instruction:
Create a Python 3 function for
removing an event from the event list

Response:
def _unreg_event(self, event_list, event):
        """ Tries to remove a registered event without triggering it """
        try:
            self.log.debug("Removing event {0}({1},{2})".format(event['function'].__name__, event['args'], event['kwargs']))
        except AttributeError:
            self.log.debug("Removing event {0}".format(str(event)))

        try:
            event_list.remove(event)
        except ValueError:
            try:
                self.log.warn("Unable to remove event {0}({1},{2}) , not found in list: {3}".format(event['function'].__name__, event['args'], event['kwargs'], event_list))
            except AttributeError:
                self.log.debug("Unable to remove event {0}".format(str(event)))
            raise KeyError('Unable to unregister the specified event from the signals specified')


Instruction:
Create a Python 3 function for
registering a function or method to be called on program exit

Response:
def reg_on_exit(self, callable_object, *args, **kwargs):
        """ Register a function/method to be called on program exit,
        will get executed regardless of successs/failure of the program running """
        persistent = kwargs.pop('persistent', False)
        event = self._create_event(callable_object, 'exit', persistent, *args, **kwargs)
        self.exit_callbacks.append(event)
        return event


Instruction:
Can you tell what is the following Python 3 function doing
def reg_on_abort(self, callable_object, *args, **kwargs):
        persistent = kwargs.pop('persistent', False)
        event = self._create_event(callable_object, 'abort', persistent, *args, **kwargs)
        self.abort_callbacks.append(event)
        return event

Response: Register a function or method to be called when execution is aborted


Instruction:
Make a summary of the following Python 3 code
def reg_on_status(self, callable_object, *args, **kwargs):
        persistent = kwargs.pop('persistent', False)
        event = self._create_event(callable_object, 'status', persistent, *args, **kwargs)
        self.status_callbacks.append(event)
        return event

Response:
Register a function to be called when a user or another
        program asks for an update


Instruction:
How would you implement a function in Python 3 that
registers a function or method to be called when the system needs to have to resumed or paused execution.

Response:
def reg_on_resume(self, callable_object, *args, **kwargs):
        """ Register a function/method to be called if the system needs to
        resume a previously halted or paused execution, including status
        requests."""
        persistent = kwargs.pop('persistent', False)
        event = self._create_event(callable_object, 'resume', persistent, *args, **kwargs)
        self.resume_callbacks.append(event)
        return event


Instruction:
How would you explain what the following Python 3 function does
def fetch_metric(self, metric, start, end, tags={}, aggregator="sum",
        downsample=None, ms_resolution=True):
        """Fetch time series data from OpenTSDB

        Parameters:
            metric:
                A string representing a valid OpenTSDB metric.

            tags:
                A dict mapping tag names to tag values. Tag names and values are
                always strings.

                { 'user_id': '44' }

            start:
                A datetime.datetime-like object representing the start of the
                range to query over.

            end:
                A datetime.datetime-like object representing the end of the
                range to query over.

            aggregator:
                The function for merging multiple time series together. For
                example, if the "user_id" tag is not specified, this aggregator
                function is used to combine all heart rate time series into one
                time series. (Yes, this isn't very useful.)

                For queries that return only one time series, this parameter is
                not relevant.

                Valid values: "sum", "min", "max", "avg", "dev"

                See: http://opentsdb.net/docs/build/html/user_guide/query/aggregators.html

            downsampling:
                A relative time interval to "downsample". This isn't true
                downsampling; rather, if you specify a downsampling of "5m"
                (five minutes), OpenTSDB will split data into five minute
                intervals, and return one data point in the middle of each
                interval whose value is the average of all data points within
                that interval.

                Valid relative time values are strings of the following format:

                    "<amount><time_unit>"

                Valid time units: "ms", "s", "m", "h", "d", "w", "n", "y"

                Date and time format: http://opentsdb.net/docs/build/html/user_guide/query/dates.html

            ms_resolution:
                Whether or not to output data point timestamps in milliseconds
                or seconds. If this flag is false and there are multiple
                data points within a second, those data points will be down
                sampled using the query's aggregation function.

        Returns:
            A dict mapping timestamps to data points
        """
        query = "{aggregator}:{downsample}{metric}{{{tags}}}".format(
            aggregator=aggregator,
            downsample=downsample + "-avg:" if downsample else "",
            metric=metric,
            tags=','.join("%s=%s" % (k, v) for k, v in tags.items())
        )
        params = {
            'ms': ms_resolution,
            'start': '{0:.3f}'.format(start.timestamp()),
            'end': '{0:.3f}'.format(end.timestamp()),
            'm': query
        }
        response = self.__request("/query", params)

        if response.status_code == 200:
            try:
                return response.json()[0]['dps']
            except IndexError:
                # empty data set
                return {}

        raise QueryError(response.json())

Response: Fetch time series data from OpenTSDB.


Instruction:
Write a Python 3 script to
fetch and sort time series data from OpenTSDB Takes the same parameters as fetch_metric but returns a list of tuples sorted by timestamp.

Response:
def fetch_sorted_metric(self, *args, **kwargs):
        """Fetch and sort time series data from OpenTSDB

        Takes the same parameters as `fetch_metric`, but returns a list of
        (timestamp, value) tuples sorted by timestamp.
        """
        return sorted(self.fetch_metric(*args, **kwargs).items(),
            key=lambda x: float(x[0]))


Instruction:
Can you tell what is the following Python 3 function doing
def pfreduce(func, iterable, initial=None):

    iterator = iter(iterable)
    try:
        first_item = next(iterator)
        if initial:
            value = func(initial, first_item)
        else:
            value = first_item
    except StopIteration:
        return initial

    for item in iterator:
        value = func(value, item)
    return value

Response:
A pointfree reduce function that applies a function of two arguments cumulatively to the items supplied by the given iterable so
    as to reduce the iterable to a single value.


Instruction:
Create a Python 3 function for
collecting and returns a list of values from the given iterable. If n is not specified returns all values from the given iterable.

Response:
def pfcollect(iterable, n=None):
    """Collects and returns a list of values from the given iterable.  If
    the n parameter is not specified, collects all values from the
    iterable.

    :param iterable: An iterable yielding values for the list
    :param n: An optional maximum number of items to collect
    :rtype: List of values from the iterable

    Example::

        >>> @pointfree
        ... def fibonaccis():
        ...     a, b = 0, 1
        ...     while True:
        ...         a, b = b, a+b
        ...         yield a

        >>> (pfcollect(n=10) * fibonaccis)()
        [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

    """

    if n:
        return list(itertools.islice(iterable, n))
    else:
        return list(iterable)


Instruction:
Create a Python 3 function to
print an item to stdout.

Response:
def pfprint(item, end='\n', file=None):
    """Prints an item.

    :param item: The item to print
    :param end: String to append to the end of printed output
    :param file: File to which output is printed
    :rtype: None

    Example::

        >>> from operator import add

        >>> fn = pfreduce(add, initial=0) >> pfprint
        >>> fn([1, 2, 3, 4])
        10

    """

    # Can't just make sys.stdout the file argument's default value, because
    # then we would be capturing the stdout file descriptor, and then
    # doctest -- which works by redefining sys.stdout -- would fail:
    if file is None:
        file = sys.stdout

    print(item, end=end, file=file)


Instruction:
Implement a Python 3 function for
printing each item from an iterable yielding values to a file.

Response:
def pfprint_all(iterable, end='\n', file=None):
    """Prints each item from an iterable.

    :param iterable: An iterable yielding values to print
    :param end: String to append to the end of printed output
    :param file: File to which output is printed
    :rtype: None

    Example::

        >>> @pointfree
        ... def prefix_all(prefix, iterable):
        ...     for item in iterable:
        ...         yield "%s%s" % (prefix, item)

        >>> fn = prefix_all("An item: ") >> pfprint_all

        >>> fn(["foo", "bar", "baz"])
        An item: foo
        An item: bar
        An item: baz

    """

    for item in iterable:
        pfprint(item, end=end, file=file)


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

        if isinstance(func, types.MethodType):
            # A bound instance or class method.
            argspec = getfullargspec(func.__func__)
            self.pargl = argspec[0][1:]
        else:
            # A regular function, an unbound instance method, or a
            # bound static method.
            argspec = getfullargspec(func)
            self.pargl = argspec[0][:]

        if argspec[3] is not None:
            def_offset = len(self.pargl) - len(argspec[3])
            self.def_argv = dict((self.pargl[def_offset+i],argspec[3][i]) \
                                     for i in range(len(argspec[3])))
        else:
            self.def_argv = {}

        self.var_pargs = argspec[1] is not None
        self.var_kargs = argspec[2] is not None
        self.kargl     = argspec[4]

        # We need keyword-only arguments' default values too.
        if argspec[5] is not None:
            self.def_argv.update(argspec[5])

Response:
Extract function signature default arguments keyword - only
        arguments and whether or not variable positional or keyword - only
        arguments are allowed.


Instruction:
Implement a Python 3 function for
extracting function signature from an existing partial instance.

Response:
def __sig_from_partial(self, inst):
        """Extract function signature from an existing partial instance."""

        self.pargl     = list(inst.pargl)
        self.kargl     = list(inst.kargl)
        self.def_argv  = inst.def_argv.copy()
        self.var_pargs = inst.var_pargs
        self.var_kargs = inst.var_kargs


Instruction:
Create a Python 3 function to
make a new instance of the partial application wrapper based on an existing instance optionally overriding the original s wrapped function and optionally overriding the original s saved arguments.

Response:
def make_copy(klass, inst, func=None, argv=None, extra_argv=None, copy_sig=True):
        """Makes a new instance of the partial application wrapper based on
        an existing instance, optionally overriding the original's wrapped
        function and/or saved arguments.

        :param inst: The partial instance we're copying
        :param func: Override the original's wrapped function
        :param argv: Override saved argument values
        :param extra_argv: Override saved extra positional arguments
        :param copy_sig: Copy original's signature?
        :rtype: New partial wrapper instance

        """

        dest            = klass(func or inst.func)
        dest.argv       = (argv or inst.argv).copy()
        dest.extra_argv = list(extra_argv if extra_argv else inst.extra_argv)

        if copy_sig:
            dest.__sig_from_partial(inst)

        return dest


Instruction:
Given the following Python 3 function, write the documentation
def __new_argv(self, *new_pargs, **new_kargs):

        new_argv = self.argv.copy()
        new_extra_argv = list(self.extra_argv)

        for v in new_pargs:
            arg_name = None
            for name in self.pargl:
                if not name in new_argv:
                    arg_name = name
                    break

            if arg_name:
                new_argv[arg_name] = v
            elif self.var_pargs:
                new_extra_argv.append(v)
            else:
                num_prev_pargs = len([name for name in self.pargl if name in self.argv])
                raise TypeError("%s() takes exactly %d positional arguments (%d given)" \
                                    % (self.__name__,
                                       len(self.pargl),
                                       num_prev_pargs + len(new_pargs)))

        for k,v in new_kargs.items():
            if not (self.var_kargs or (k in self.pargl) or (k in self.kargl)):
                raise TypeError("%s() got an unexpected keyword argument '%s'" \
                                    % (self.__name__, k))
            new_argv[k] = v

        return (new_argv, new_extra_argv)

Response:
Calculate new argv and extra_argv values resulting from adding
        the specified positional and keyword arguments.


Instruction:
Explain what the following Python 3 code does
def ignore_certain_metainf_files(filename):
    ignore = ("META-INF/manifest.mf",
              "META-INF/*.sf",
              "META-INF/*.rsa",
              "META-INF/*.dsa",
              "META-INF/ids.json")

    for glob in ignore:
        # Explicitly match against all upper case to prevent the kind of
        # runtime errors that lead to https://bugzil.la/1169574
        if fnmatch.fnmatchcase(filename.upper(), glob.upper()):
            return True
    return False

Response: This function is used to prevent multiple signatures in XPI signing on a given JAR file.


Instruction:
Given the following Python 3 function, write the documentation
def file_key(filename):
    '''Sort keys for xpi files

    The filenames in a manifest are ordered so that files not in a
    directory come before files in any directory, ordered
    alphabetically but ignoring case, with a few exceptions
    (install.rdf, chrome.manifest, icon.png and icon64.png come at the
    beginning; licenses come at the end).

    This order does not appear to affect anything in any way, but it
    looks nicer.
    '''
    prio = 4
    if filename == 'install.rdf':
        prio = 1
    elif filename in ["chrome.manifest", "icon.png", "icon64.png"]:
        prio = 2
    elif filename in ["MPL", "GPL", "LGPL", "COPYING",
                      "LICENSE", "license.txt"]:
        prio = 5
    return (prio, os.path.split(filename.lower()))

Response: Sort keys for xpi files in a


Instruction:
Here you have a function in Python 3, explain what it does
def vlq2int(data):
    # The VLQ is little-endian.
    byte = ord(data.read(1))
    value = byte & 0x7F
    shift = 1
    while byte & 0x80 != 0:
        byte = ord(data.read(1))
        value = ((byte & 0x7F) << shift * 7) | value
        shift += 1
    return value

Response: Read one VLQ - encoded integer value from an input data stream.


Instruction:
Can you generate the documentation for the following Python 3 function
def read_table(data, fields):
    def read_field(field_name):
        data.read(2)
        table[field_name] = vlq2int(data) / 2
        # Discard unknown fields.
        if field_name == 'unknown':
            del table[field_name]

    table = {}
    for field in fields:
        read_field(field)
    return table

Response: Read a table structure from data.


Instruction:
Can you create a Python 3 function that
parses the user data header portion of the replay.

Response:
def _parse_header(self):
        """Parse the user data header portion of the replay."""
        header = OrderedDict()
        user_data_header = self.archive.header['user_data_header']['content']
        if re.search(r'StarCraft II replay', user_data_header):
            user_data_header = StringIO.StringIO(user_data_header)
            user_data_header.seek(30) # Just skip the beginning.
            header.update(read_table(user_data_header, ['release_flag',
                                                        'major_version',
                                                        'minor_version',
                                                        'maintenance_version',
                                                        'build_number',
                                                        'unknown',
                                                        'unknown',
                                                        'duration']))

            # Some post processing is required.
            header['version'] = '%s.%s.%s.%s' % (header['major_version'],
                                                 header['minor_version'],
                                                 header['maintenance_version'],
                                                 header['build_number'])
            if not header['release_flag']:
                header['version'] += ' (dev)'

            # Duration is actually stored as 1/16th of a seconds. Go figure.
            header['duration'] /= 16
        else:
            raise ValueError("The given file is not a StarCraft II replay.")
        return header


Instruction:
Can you create a Python 3 function that
transforms duration into a human - readable form.

Response:
def get_duration(self, seconds):
        """Transform duration into a human-readable form."""
        duration = ""
        minutes, seconds = divmod(seconds, 60)
        if minutes >= 60:
            hours, minutes = divmod(minutes, 60)
            duration = "%sh " % hours
        duration += "%sm %ss" % (minutes, seconds)
        return duration


Instruction:
Implement a Python 3 function for
printing a summary of the game details.

Response:
def print_details(self):
        """Print a summary of the game details."""
        print 'Map      ', self.map
        print 'Duration ', self.duration
        print 'Version  ', self.version
        print 'Team  Player       Race       Color'
        print '-----------------------------------'
        for player in self.players:
            print '{team:<5} {name:12} {race:10} {color}'.format(**player)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def data_processing(self):
        the_file_name = str(self.result_file)
        the_file = open(the_file_name, 'r')

        lines = the_file.readlines()

        # We put all lines in an array and we put each cell of the line in a column.
        lines_array = []
        for line in lines:
            line = line.split(',')  # Each time there is a tabulation, there is a new cell
            lines_array.append(line)

        labels_line = lines_array[0]
        cell_labels_line = 0  # Iterator on each cell of the line labels_line.
        flag = True  # Become FALSE when we find the word which separate data from wavelength values.

        try:
            while flag:  # While it is TRUE, so if the word doesn't match, it's an infinite loop,
                if "wave length (nm)" in labels_line[cell_labels_line]:
                    index = labels_line.index(labels_line[cell_labels_line])  # Find the index of the string searched.
                    flag = False
                else:
                    cell_labels_line += 1
        except IndexError:  # In case of an infinite loop.
            raise sys.exit("Warning : There is no value named 'wavelength' in the file used to plot curves. "
                           "So, I can't separate data to plot curves and data about tests linking with these curves.")

        self.information = []  # This array will contain the data displayed under the curves.
        data_wavelength = []  # This array will contain the data to plot curves.
        self.num_line = 0  # Iterator on each line of lines_array,
        # The array containing data about information and wavelength.
        for line in lines_array:
            cell_line = 0  # Iterator on each cell of the line.
            self.information.append([])
            data_wavelength.append([])
            while cell_line < len(line):
                if cell_line < index:
                    self.information[self.num_line].append(line[cell_line])
                elif cell_line > index:
                    data_wavelength[self.num_line].append(line[cell_line])
                cell_line += 1
            self.num_line += 1

        # We transform wavelengths from strings to floats.
        line_wavelength = 0  # Iterator on each line of data_wavelength
        for row_data_wavelength in data_wavelength:
            row_data_wavelength = [float(item.strip('\n').strip('\"')) for item in row_data_wavelength]
            data_wavelength[line_wavelength] = row_data_wavelength
            line_wavelength += 1

        self.wavelength = data_wavelength[0]  # The first line contains wavelength
        self.data_wanted = data_wavelength[1:]  # The others contain data useful to plot curves.

        the_file.close()

Response: This function handles the data processing of the result file and stores the data in the good arrays.


Instruction:
Write a Python 3 function that can
display the information of the current CPU CPU.

Response:
def display_the_graphic_connection(self):
        """
        The following permits to attribute the function "display_the_graphic" to the slider.
        Because, to make a connection, we can not have parameters for the function, but "display_the_graphic" has some.
        """
        self.display_the_graphic(self.num_line, self.wavelength, self.data_wanted, self.information)


Instruction:
Can you tell what is the following Python 3 function doing
def hide_error_message(self):
        self.ui.error_label.setScaledContents(False)  # Warning image hiden.
        self.ui.error_text_label.hide()

Response: This function hides the error message when all values are correct.


Instruction:
Write a Python 3 function for
quitting the current instance of the class.

Response:
def quit(self):
        """
        This function quits PlanarRad, checking if PlanarRad is running before.
        """

        """
        Nothing programmed for displaying a message box when the user clicks on the window cross in order to quit.
        """

        if self.is_running == True:
            warning_planarrad_running = QtGui.QMessageBox.warning(self.ui.quit, 'Warning !',
                                                                  "PlanarRad is running. Stop it before quit !",
                                                                  QtGui.QMessageBox.Ok)

        else:
            quit = QtGui.QMessageBox.question(self.ui.quit, 'Quit PlanarRad', "Are you sure to quit ?",
                                              QtGui.QMessageBox.Yes,
                                              QtGui.QMessageBox.No)
            if quit == QtGui.QMessageBox.Yes:
                QtGui.qApp.quit()


Instruction:
Make a summary of the following Python 3 code
def open_log_file(self):
        """
        TO DO.
        """
        # webbrowser.open('https://marrabld.github.io/planarradpy/')
        f = open(os.path.expanduser('~/.planarradpy/log/libplanarradpy.log'))
        # self.uiLog.textEdit.setText(str(f.readlines()))
        self.uiLog.textEdit.setPlainText(str(f.read()))
        self.log_window.show()

Response: Open the log file of PlanarRad.


Instruction:
Write a Python 3 script for
opening the documentation file.

Response:
def open_documentation(self):
        """
        The following opens the documentation file.
        """
        """
        TO DO.
        """
        # webbrowser.open('https://marrabld.github.io/planarradpy/')

        window = Window()
        html = QtCore.QUrl.fromLocalFile(os.path.join(os.getcwd(), './docs/_build/html/index.html')) #open('./docs/_build/html/index.html').read()
        #window.show()
        window.view.load(html)
        window.show()
        window.exec_()


Instruction:
Given the following Python 3 function, write the documentation
def click(self, event):
        if event.button == 3:
            if self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE:
                self.pos = QtGui.QCursor().pos()
                self.graphic_context_menu(self.pos)

Response: This function intercepts the mouse s right click and its position.


Instruction:
Explain what the following Python 3 code does
def mouse_move(self, event):
        if (self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE):
            self.posX = event.xdata
            self.posY = event.ydata

            self.graphic_target(self.posX, self.posY)

Response: Handles mouse move events.


Instruction:
Here you have a function in Python 3, explain what it does
def graphic_target(self, x, y):

        if self.authorized_display == True:
            try:
                self.display_the_graphic(self.num_line, self.wavelength, self.data_wanted, self.information)
                self.ui.mouse_coordinate.setText("(%0.3f, %0.3f)" % (x, y))
            except:
                pass

Response: Update the mouse coordinates.


Instruction:
How would you explain what the following Python 3 function does
def genesis_signing_lockset(genesis, privkey):
    v = VoteBlock(0, 0, genesis.hash)
    v.sign(privkey)
    ls = LockSet(num_eligible_votes=1)
    ls.add(v)
    assert ls.has_quorum
    return ls

Response: This function creates a lockset that is a genesis_signing_lockset with one vote by any validator.


Instruction:
Given the following Python 3 function, write the documentation
def sign(self, privkey):
        if self.v:
            raise InvalidSignature("already signed")

        if privkey in (0, '', '\x00' * 32):
            raise InvalidSignature("Zero privkey cannot sign")
        rawhash = sha3(rlp.encode(self, self.__class__.exclude(['v', 'r', 's'])))

        if len(privkey) == 64:
            privkey = encode_privkey(privkey, 'bin')

        pk = PrivateKey(privkey, raw=True)
        signature = pk.ecdsa_recoverable_serialize(pk.ecdsa_sign_recoverable(rawhash, raw=True))

        signature = signature[0] + chr(signature[1])

        self.v = ord(signature[64]) + 27
        self.r = big_endian_to_int(signature[0:32])
        self.s = big_endian_to_int(signature[32:64])

        self._sender = None
        return self

Response: Sign this object with a private key


Instruction:
Explain what the following Python 3 code does
def hr(self):
        assert len(self), 'no votes, can not determine height'
        h = set([(v.height, v.round) for v in self.votes])
        assert len(h) == 1, len(h)
        return h.pop()

Response: compute the height of the last entry in the set


Instruction:
Given the following Python 3 function, write the documentation
def has_quorum(self):
        assert self.is_valid
        bhs = self.blockhashes()
        if bhs and bhs[0][1] > 2 / 3. * self.num_eligible_votes:
            return bhs[0][0]

Response: Returns True if there is a quorum for a given entry.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def has_noquorum(self):
        assert self.is_valid
        bhs = self.blockhashes()
        if not bhs or bhs[0][1] <= 1 / 3. * self.num_eligible_votes:
            assert not self.has_quorum_possible
            return True

Response: Returns True if there are no possible no - quorum possible cluster entries for the given cluster entry.


Instruction:
Can you write a function in Python 3 where it
converts the transient block to a Block object.

Response:
def to_block(self, env, parent=None):
        """Convert the transient block to a :class:`ethereum.blocks.Block`"""
        return Block(self.header, self.transaction_list, self.uncles, env=env, parent=parent)


Instruction:
Here you have a function in Python 3, explain what it does
def validate_votes(self, validators_H, validators_prevH):
        "set of validators may change between heights"
        assert self.sender

        def check(lockset, validators):
            if not lockset.num_eligible_votes == len(validators):
                raise InvalidProposalError('lockset num_eligible_votes mismatch')
            for v in lockset:
                if v.sender not in validators:
                    raise InvalidProposalError('invalid signer')
        if self.round_lockset:
            check(self.round_lockset, validators_H)
        check(self.signing_lockset, validators_prevH)

        return True

Response: set of validators may change between heights


Instruction:
Can you tell what is the following Python 3 function doing
def validate_votes(self, validators_H):
        "set of validators may change between heights"
        assert self.sender
        if not self.round_lockset.num_eligible_votes == len(validators_H):
            raise InvalidProposalError('round_lockset num_eligible_votes mismatch')
        for v in self.round_lockset:
            if v.sender not in validators_H:
                raise InvalidProposalError('invalid signer')

Response: set of validators may change between heights


Instruction:
Make a summary of the following Python 3 code
def transfer(ctx, _to='address', _value='uint256', returns=STATUS):
        log.DEV('In Fungible.transfer')
        if ctx.accounts[ctx.msg_sender] >= _value:
            ctx.accounts[ctx.msg_sender] -= _value
            ctx.accounts[_to] += _value
            ctx.Transfer(ctx.msg_sender, _to, _value)
            return OK
        else:
            return INSUFFICIENTFUNDS

Response: Standardized Contract API for Transfer


Instruction:
Explain what the following Python 3 code does
def transferFrom(ctx, _from='address', _to='address', _value='uint256', returns=STATUS):
        auth = ctx.allowances[_from][ctx.msg_sender]
        if ctx.accounts[_from] >= _value and auth >= _value:
            ctx.allowances[_from][ctx.msg_sender] -= _value
            ctx.accounts[_from] -= _value
            ctx.accounts[_to] += _value
            ctx.Transfer(_from, _to, _value)
            return OK
        else:
            return INSUFFICIENTFUNDS

Response: Standardized Contract API for transferFrom


Instruction:
Explain what the following Python 3 code does
def approve(ctx, _spender='address', _value='uint256', returns=STATUS):
        ctx.allowances[ctx.msg_sender][_spender] += _value
        ctx.Approval(ctx.msg_sender, _spender, _value)
        return OK

Response: Standardized Contract API approve


Instruction:
Explain what the following Python 3 code does
def issue_funds(ctx, amount='uint256', rtgs_hash='bytes32', returns=STATUS):
        "In the IOU fungible the supply is set by Issuer, who issue funds."
        # allocate new issue as result of a new cash entry
        ctx.accounts[ctx.msg_sender] += amount
        ctx.issued_amounts[ctx.msg_sender] += amount
        # Store hash(rtgs)
        ctx.Issuance(ctx.msg_sender, rtgs_hash, amount)
        return OK

Response: In the IOU fungible the supply is set by Issuer who issue funds.


Instruction:
Explain what the following Python 3 code does
def last_lock(self):
        "highest lock on height"
        rs = list(self.rounds)
        assert len(rs) < 2 or rs[0] > rs[1]  # FIXME REMOVE
        for r in self.rounds:  # is sorted highest to lowest
            if self.rounds[r].lock is not None:
                return self.rounds[r].lock

Response: highest lock on height


Instruction:
Can you tell what is the following Python 3 function doing
def last_valid_lockset(self):
        "highest valid lockset on height"
        for r in self.rounds:
            ls = self.rounds[r].lockset
            if ls.is_valid:
                return ls
        return None

Response: highest valid lockset on height


Instruction:
How would you explain what the following Python 3 function does
def request(self):
        missing = self.missing
        self.cm.log('sync.request', missing=len(missing), requested=len(self.requested),
                    received=len(self.received))
        if self.requested:
            self.cm.log('waiting for requested')
            return
        if len(self.received) + self.max_getproposals_count >= self.max_queued:
            self.cm.log('queue is full')
            return
        if not missing:
            self.cm.log('insync')
            return
        if self.last_active_protocol is None:  # FIXME, check if it is active
            self.cm.log('no active protocol', last_active_protocol=self.last_active_protocol)
            return
        self.cm.log('collecting')
        blocknumbers = []
        for h in missing:
            if h not in self.received and h not in self.requested:
                blocknumbers.append(h)
                self.requested.add(h)
                if len(blocknumbers) == self.max_getproposals_count:
                    break
        self.cm.log('collected', num=len(blocknumbers))
        if not blocknumbers:
            return
        self.cm.log('requesting', num=len(blocknumbers),
                    requesting_range=(blocknumbers[0], blocknumbers[-1]))
        self.last_active_protocol.send_getblockproposals(*blocknumbers)
        # setup alarm
        self.cm.chainservice.setup_alarm(self.timeout, self.on_alarm, blocknumbers)

Response: request the next set of locksets


Instruction:
Can you generate the documentation for the following Python 3 function
def on_proposal(self, proposal, proto):
        "called to inform about synced peers"
        assert isinstance(proto, HDCProtocol)
        assert isinstance(proposal, Proposal)
        if proposal.height >= self.cm.height:
            assert proposal.lockset.is_valid
            self.last_active_protocol = proto

Response: called to inform about synced peers


Instruction:
How would you implement a function in Python 3 that
creates a wait_next_block function that will wait for a new block to appear.

Response:
def wait_next_block_factory(app, timeout=None):
    """Creates a `wait_next_block` function, that
    will wait `timeout` seconds (`None` = indefinitely)
    for a new block to appear.

    :param app: the app-instance the function should work for
    :param timeout: timeout in seconds
    """

    chain = app.services.chain

    # setup new block callbacks and events
    new_block_evt = gevent.event.Event()

    def _on_new_block(app):
        log.DEV('new block mined')
        new_block_evt.set()
    chain.on_new_head_cbs.append(_on_new_block)

    def wait_next_block():
        bn = chain.chain.head.number
        chain.consensus_manager.log('waiting for new block', block=bn)
        new_block_evt.wait(timeout)
        new_block_evt.clear()
        if chain.chain.head.number > bn:
            chain.consensus_manager.log('new block event', block=chain.chain.head.number)
        elif chain.chain.head.number == bn:
            chain.consensus_manager.log('wait_next_block timed out', block=bn)

    return wait_next_block


Instruction:
Can you generate a brief explanation for the following Python 3 code
def mk_privkeys(num):
    "make privkeys that support coloring, see utils.cstr"
    privkeys = []
    assert num <= num_colors
    for i in range(num):
        j = 0
        while True:
            k = sha3(str(j))
            a = privtoaddr(k)
            an = big_endian_to_int(a)
            if an % num_colors == i:
                break
            j += 1
        privkeys.append(k)
    return privkeys

Response: make privkeys that support coloring see utils. cstr


Instruction:
How would you explain what the following Python 3 function does
def delay(self, sender, receiver, packet, add_delay=0):
        bw = min(sender.ul_bandwidth, receiver.dl_bandwidth)
        delay = sender.base_latency + receiver.base_latency
        delay += len(packet) / bw
        delay += add_delay
        return delay

Response: Calculate the delay between two packets.


Instruction:
Write a Python 3 function for
delivering on edge of timeout_window

Response:
def deliver(self, sender, receiver, packet):
        "deliver on edge of timeout_window"
        to = ConsensusManager.round_timeout
        assert to > 0
        print "in slow transport deliver"
        super(SlowTransport, self).deliver(sender, receiver, packet, add_delay=to)


Instruction:
Implement a function in Python 3 to
encode args for method method_id | data

Response:
def abi_encode_args(method, args):
    "encode args for method: method_id|data"
    assert issubclass(method.im_class, NativeABIContract), method.im_class
    m_abi = method.im_class._get_method_abi(method)
    return zpad(encode_int(m_abi['id']), 4) + abi.encode_abi(m_abi['arg_types'], args)


Instruction:
Write a Python 3 function for
creating an object which acts as a proxy for the contract on the chain

Response:
def chain_nac_proxy(chain, sender, contract_address, value=0):
    "create an object which acts as a proxy for the contract on the chain"
    klass = registry[contract_address].im_self
    assert issubclass(klass, NativeABIContract)

    def mk_method(method):
        def m(s, *args):
            data = abi_encode_args(method, args)
            block = chain.head_candidate
            output = test_call(block, sender, contract_address, data)
            if output is not None:
                return abi_decode_return_vals(method, output)
        return m

    class cproxy(object):
        pass
    for m in klass._abi_methods():
        setattr(cproxy, m.__func__.func_name, mk_method(m))

    return cproxy()


Instruction:
Create a Python 3 function for
returning class _on_msg_unsafe use x. im_self to get class

Response:
def address_to_native_contract_class(self, address):
        "returns class._on_msg_unsafe, use x.im_self to get class"
        assert isinstance(address, bytes) and len(address) == 20
        assert self.is_instance_address(address)
        nca = self.native_contract_address_prefix + address[-4:]
        return self.native_contracts[nca]


Instruction:
Can you generate the documentation for the following Python 3 function
def validators_from_config(validators):
    result = []
    for validator in validators:
        if len(validator) == 40:
            validator = validator.decode('hex')
        result.append(validator)
    return result

Response:
Consolidate ( potentially hex - encoded ) list of validators
    into list of binary address representations.


Instruction:
Here you have a function in Python 3, explain what it does
def update(self, data):
        "returns True if unknown"
        if data not in self.filter:
            self.filter.append(data)
            if len(self.filter) > self.max_items:
                self.filter.pop(0)
            return True
        else:
            self.filter.append(self.filter.pop(0))
            return False

Response: returns True if unknown


Instruction:
Make a summary of the following Python 3 code
def add_transaction(self, tx, origin=None, force_broadcast=False):
        self.consensus_manager.log(
            'add_transaction', blk=self.chain.head_candidate, lock=self.proposal_lock)
        log.debug('add_transaction', lock=self.proposal_lock)
        block = self.proposal_lock.block
        self.proposal_lock.acquire()
        self.consensus_manager.log('add_transaction acquired lock', lock=self.proposal_lock)
        assert not hasattr(self.chain.head_candidate, 'should_be_locked')
        success = super(ChainService, self).add_transaction(tx, origin, force_broadcast)
        if self.proposal_lock.is_locked():  # can be unlock if we are at a new block
            self.proposal_lock.release(if_block=block)
        log.debug('added transaction', num_txs=self.chain.head_candidate.num_transactions())
        return success

Response: Add a transaction to the chain.


Instruction:
Can you generate the documentation for the following Python 3 function
def on_receive_transactions(self, proto, transactions):
        "receives rlp.decoded serialized"
        log.debug('----------------------------------')
        log.debug('remote_transactions_received', count=len(transactions), remote_id=proto)

        def _add_txs():
            for tx in transactions:
                self.add_transaction(tx, origin=proto)
        gevent.spawn(_add_txs)

Response: receives rlp. decoded serialized


Instruction:
Here you have a function in Python 3, explain what it does
def img_from_vgg(x):
    '''Decondition an image from the VGG16 model.'''
    x = x.transpose((1, 2, 0))
    x[:, :, 0] += 103.939
    x[:, :, 1] += 116.779
    x[:, :, 2] += 123.68
    x = x[:,:,::-1]  # to RGB
    return x

Response: Decondition an image from the VGG16 model.


Instruction:
Can you tell what is the following Python 3 function doing
def img_to_vgg(x):
    '''Condition an image for use with the VGG16 model.'''
    x = x[:,:,::-1]  # to BGR
    x[:, :, 0] -= 103.939
    x[:, :, 1] -= 116.779
    x[:, :, 2] -= 123.68
    x = x.transpose((2, 0, 1))
    return x

Response: Condition an image for use with the VGG16 model.


Instruction:
Write a Python 3 script for
creating a function for the response of a layer.

Response:
def get_f_layer(self, layer_name):
        '''Create a function for the response of a layer.'''
        inputs = [self.net_input]
        if self.learning_phase is not None:
            inputs.append(K.learning_phase())
        return K.function(inputs, [self.get_layer_output(layer_name)])


Instruction:
Create a Python 3 function for
getting symbolic output of a layer.

Response:
def get_layer_output(self, name):
        '''Get symbolic output of a layer.'''
        if not name in self._f_layer_outputs:
            layer = self.net.get_layer(name)
            self._f_layer_outputs[name] = layer.output
        return self._f_layer_outputs[name]


Instruction:
How would you explain what the following Python 3 function does
def get_features(self, x, layers):
        '''Evaluate layer outputs for `x`'''
        if not layers:
            return None
        inputs = [self.net.input]
        if self.learning_phase is not None:
            inputs.append(self.learning_phase)
        f = K.function(inputs, [self.get_layer_output(layer_name) for layer_name in layers])
        feature_outputs = f([x])
        features = dict(zip(layers, feature_outputs))
        return features

Response: Evaluate layer outputs for x


Instruction:
Make a summary of the following Python 3 code
def create_key_file(path):
    iv = "{}{}".format(os.urandom(32), time.time())
    new_key = generate_key(ensure_bytes(iv))
    with open(path, "wb") as f:
        f.write(base64.b64encode(new_key))
    os.chmod(path, 0o400)

Response: Creates a new encryption key in the path provided and sets the filePermissions to 0o400.


Instruction:
Here you have a function in Python 3, explain what it does
def cleanup(self):
        threads = []
        for i, table in enumerate(filter(lambda x: self.mload.exists(x), self.tables)):
            log.info("BulkLoad", "Dropping table '{}'...".format(table))
            t = threading.Thread(target=self.mload.drop_table, args=(table,))
            threads.append(t)
            t.start()
        for t in threads:
            t.join()

Response: Drops any existing work tables as returned by the mload. tables method.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def finish(self):
        if self.finished:
            return self.exit_code
        checkpoint_status = self.checkpoint()
        self.exit_code = self._exit_code()
        if self.exit_code != 0:
            raise TeradataPTError("BulkLoad job finished with return code '{}'".format(self.exit_code))
        # TODO(chris): should this happen every time?
        if self.applied_count > 0:
            self._end_acquisition()
            self._apply_rows()
        self.exit_code = self._exit_code()
        if self.exit_code != 0:
            raise TeradataPTError("BulkLoad job finished with return code '{}'".format(self.exit_code))
        self.finished = True
        return self.exit_code

Response: Finishes the load job. Called automatically when the connection closes.


Instruction:
Make a summary of the following Python 3 code
def from_file(self, filename, table=None, delimiter='|', null='NULL',
            panic=True, quotechar='"', parse_dates=False):
        """
        Load from a file into the target table, handling each step of the
        load process.

        Can load from text files, and properly formatted giraffez archive
        files. In both cases, if Gzip compression is detected the file will be
        decompressed while reading and handled appropriately. The encoding is
        determined automatically by the contents of the file.

        It is not necessary to set the columns in use prior to loading from a file.
        In the case of a text file, the header is used to determine column names
        and their order. Valid delimiters include '|', ',', and '\\t' (tab). When
        loading an archive file, the column information is decoded alongside the data.

        :param str filename: The location of the file to be loaded
        :param str table: The name of the target table, if it was not specified
            to the constructor for the isntance
        :param str null: The string that indicates a null value in the rows being
            inserted from a file. Defaults to 'NULL'
        :param str delimiter: When loading a file, indicates that fields are
            separated by this delimiter. Defaults to :code:`None`, which causes the
            delimiter to be determined from the header of the file. In most
            cases, this behavior is sufficient
        :param str quotechar: The character used to quote fields containing special characters,
            like the delimiter.
        :param bool panic: If :code:`True`, when an error is encountered it will be
            raised. Otherwise, the error will be logged and :code:`self.error_count`
            is incremented.
        :return: The output of the call to
            :meth:`~giraffez.load.TeradataBulkLoad.finish`
        :raises `giraffez.errors.GiraffeError`: if table was not set and :code:`table`
            is :code:`None`, or if a Teradata error ocurred while retrieving table info.
        :raises `giraffez.errors.GiraffeEncodeError`: if :code:`panic` is :code:`True` and there
            are format errors in the row values.
        """
        if not self.table:
            if not table:
                raise GiraffeError("Table must be set or specified to load a file.")
            self.table = table
        if not isinstance(null, basestring):
            raise GiraffeError("Expected 'null' to be str, received {}".format(type(null)))
        with Reader(filename, delimiter=delimiter, quotechar=quotechar) as f:
            if not isinstance(f.delimiter, basestring):
                raise GiraffeError("Expected 'delimiter' to be str, received {}".format(type(delimiter)))
            self.columns = f.header
            if isinstance(f, ArchiveFileReader):
                self.mload.set_encoding(ROW_ENCODING_RAW)
                self.preprocessor = lambda s: s
            if parse_dates:
                self.preprocessor = DateHandler(self.columns)
            self._initiate()
            self.mload.set_null(null)
            self.mload.set_delimiter(delimiter)
            i = 0
            for i, line in enumerate(f, 1):
                self.put(line, panic=panic)
                if i % self.checkpoint_interval == 1:
                    log.info("\rBulkLoad", "Processed {} rows".format(i), console=True)
                    checkpoint_status = self.checkpoint()
                    self.exit_code = self._exit_code()
                    if self.exit_code != 0:
                        return self.exit_code
            log.info("\rBulkLoad", "Processed {} rows".format(i))
            return self.finish()

Response: Load a new entry from a file into the target table.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def put(self, items, panic=True):
        if not self.initiated:
            self._initiate()
        try:
            row_status = self.mload.put_row(self.preprocessor(items))
            self.applied_count += 1
        except (TeradataPTError, EncoderError) as error:
            self.error_count += 1
            if panic:
                raise error
            log.info("BulkLoad", error)

Response: Load a single row into the target table.


Instruction:
Explain what the following Python 3 code does
def release(self):
        if self.table is None:
            raise GiraffeError("Cannot release. Target table has not been set.")
        log.info("BulkLoad", "Attempting release for table {}".format(self.table))
        self.mload.release(self.table)

Response: Release the current object s mload table.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def tables(self):
        if self.table is None:
            raise GiraffeError("Target table has not been set.")
        return [
            "{}_wt".format(self.table),
            "{}_log".format(self.table),
            "{}_e1".format(self.table),
            "{}_e2".format(self.table),
        ]

Response: Returns a list of four tables each the name of the target table containing the added suffixes _wt _log _e1 and _e2.


Instruction:
Here you have a function in Python 3, explain what it does
def fix_compile(remove_flags):
    import distutils.ccompiler

    def _fix_compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0,
            extra_preargs=None, extra_postargs=None, depends=None):
        for flag in remove_flags:
            if flag in self.compiler_so:
                self.compiler_so.remove(flag)
        macros, objects, extra_postargs, pp_opts, build = self._setup_compile(output_dir, macros,
                include_dirs, sources, depends, extra_postargs)
        cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
        for obj in objects:
            try:
                src, ext = build[obj]
            except KeyError:
                continue
            self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
        return objects

    distutils.ccompiler.CCompiler.compile = _fix_compile

Response: Monkey - patch compiler to allow for removal of default compiler flags.


Instruction:
Explain what the following Python 3 code does
def find_teradata_home():
    if platform.system() == 'Windows':
        # The default installation path for Windows is split between the
        # Windows directories for 32-bit/64-bit applications.  It is
        # worth noting that Teradata archiecture installed should match
        # the architecture of the Python architecture being used (i.e.
        # TTU 32-bit is required /w Python 32-bit and TTU 64-bit is
        # required for Python 64-bit).
        if is_64bit():
            return latest_teradata_version("C:/Program Files/Teradata/Client")
        else:
            return latest_teradata_version("C:/Program Files (x86)/Teradata/Client")
    elif platform.system() == 'Linux':
        return latest_teradata_version("/opt/teradata/client")
    elif platform.system() == 'Darwin':
        return latest_teradata_version("/Library/Application Support/teradata/client")
    else:
        # In the case nothing is found, the default for Linux is
        # attempted as a last effort to find the correct install
        # directory.
        return latest_teradata_version("/opt/teradata/client")

Response: Finds the Teradata installation directory with the default set for the current platform.


Instruction:
Write a Python 3 script to
retrieve the decrypted value of a key in a giraffez configuration file.

Response:
def get(self, key):
        """
        Retrieve the decrypted value of a key in a giraffez
        configuration file.

        :param str key: The key used to lookup the encrypted value
        """
        if not key.startswith("secure.") and not key.startswith("connections."):
            key = "secure.{0}".format(key)
        value = self.config.get_value(key)
        if not isinstance(value, basestring):
            value = None
        return value


Instruction:
Write a Python 3 script for
setting a decrypted value by key in a giraffez configuration file.

Response:
def set(self, key, value):
        """
        Set a decrypted value by key in a giraffez configuration file.

        :param str key: The key used to lookup the encrypted value
        :param value: Value to set at the given key, can be any value that is
            YAML serializeable.
        """
        if not key.startswith("secure."):
            key = "secure.{0}".format(key)
        self.config.set_value(key, value)
        self.config.write()


Instruction:
Can you write a function in Python 3 where it
displays results in table format

Response:
def do_table(self, line):
        """Display results in table format"""
        if len(line) > 0:
            if line.strip().lower() == "on":
                log.write("Table ON")
                self.table_output = True
                return
            elif line.strip().lower() == "off":
                log.write("Table OFF")
                self.table_output = False
                return
        log.write("Table output: {}".format("ON" if self.table_output else "OFF"))


Instruction:
Create a Python 3 function to
return the current encoder output as a dictionary.

Response:
def to_dict(self):
        """
        Sets the current encoder output to Python `dict` and returns
        the cursor.  This makes it possible to set the output encoding
        and iterate over the results:

        .. code-block:: python

            with giraffez.Cmd() as cmd:
                for row in cmd.execute(query).to_dict():
                    print(row)

        Or can be passed as a parameter to an object that consumes an iterator:

        .. code-block:: python

            result = cmd.execute(query)
            list(result.to_dict())
        """
        self.conn.set_encoding(ROW_ENCODING_DICT)
        self.processor = lambda x, y: y
        return self


Instruction:
How would you code a function in Python 3 to
set the current encoder output to list format and return the cursor.

Response:
def to_list(self):
        """
        Set the current encoder output to :class:`giraffez.Row` objects
        and returns the cursor.  This is the default value so it is not
        necessary to select this unless the encoder settings have been
        changed already.
        """
        self.conn.set_encoding(ROW_ENCODING_LIST)
        self.processor = lambda x, y: Row(x, y)
        return self


Instruction:
Explain what the following Python 3 code does
def execute(self, command, coerce_floats=True, parse_dates=False, header=False, sanitize=True,
            silent=False, panic=None,  multi_statement=False, prepare_only=False):
        """
        Execute commands using CLIv2.

        :param str command: The SQL command to be executed
        :param bool coerce_floats: Coerce Teradata decimal types into Python floats
        :param bool parse_dates: Parses Teradata datetime types into Python datetimes
        :param bool header: Include row header
        :param bool sanitize: Whether or not to call :func:`~giraffez.sql.prepare_statement`
            on the command
        :param bool silent: Silence console logging (within this function only)
        :param bool panic: If :code:`True`, when an error is encountered it will be
            raised.
        :param bool multi_statement: Execute in multi-statement mode
        :param bool prepare_only: Only prepare the command (no results)
        :return: a cursor over the results of each statement in the command
        :rtype: :class:`~giraffez.cmd.Cursor`
        :raises `giraffez.TeradataError`: if the query is invalid
        :raises `giraffez.errors.GiraffeError`: if the return data could not be decoded
        """
        if panic is None:
            panic = self.panic
        self.options("panic", panic)
        self.options("multi-statement mode", multi_statement, 3)
        if isfile(command):
            self.options("file", command, 2)
            with open(command, 'r') as f:
                command = f.read()
        else:
            if log.level >= VERBOSE:
                self.options("query", command, 2)
            else:
                self.options("query", truncate(command), 2)
        if not silent and not self.silent:
            log.info("Command", "Executing ...")
            log.info(self.options)
        if sanitize:
            command = prepare_statement(command) # accounts for comments and newlines
            log.debug("Debug[2]", "Command (sanitized): {!r}".format(command))
        self.cmd.set_encoding(ENCODER_SETTINGS_DEFAULT)
        return Cursor(self.cmd, command, multi_statement=multi_statement, header=header,
            prepare_only=prepare_only, coerce_floats=coerce_floats, parse_dates=parse_dates,
            panic=panic)

Response: Executes a command and returns a cursor over the results of each statement.


Instruction:
Write a Python 3 script for
checking if the object with the given name exists in the database.

Response:
def exists(self, object_name, silent=False):
        """
        Check that object (table or view) :code:`object_name` exists, by executing a :code:`show table object_name` query,
        followed by a :code:`show view object_name` query if :code:`object_name` is not a table.

        :param str object_name: The name of the object to check for existence.
        :param bool silent: Silence console logging (within this function only)
        :return: :code:`True` if the object exists, :code:`False` otherwise.
        :rtype: bool
        """
        try:
            self.execute("show table {}".format(object_name), silent=silent)
            return True
        except TeradataError as error:
            if error.code != TD_ERROR_OBJECT_NOT_TABLE:
                return False
        try:
            self.execute("show view {}".format(object_name), silent=silent)
            return True
        except TeradataError as error:
            if error.code not in [TD_ERROR_OBJECT_NOT_VIEW, TD_ERROR_OBJECT_NOT_EXIST]:
                    return True
        return False


Instruction:
Here you have a function in Python 3, explain what it does
def fetch_columns(self, table_name, silent=False):
        return self.execute("select top 1 * from {}".format(table_name), silent=silent, prepare_only=True).columns

Response: Fetch the columns of the table_name by executing a select top 1 * from table_name query.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def insert(self, table_name, rows, fields=None, delimiter=None, null='NULL', parse_dates=False, quotechar='"'):
        if not isfile(rows):
            return self._insert(table_name, rows, fields, parse_dates)
        with Reader(rows, delimiter=delimiter, quotechar=quotechar) as f:
            preprocessor = null_handler(null)
            rows = (preprocessor(l) for l in f)
            if isinstance(f, CSVReader):
                self.options("delimiter", unescape_string(f.reader.dialect.delimiter), 1)
                self.options("quote char", f.reader.dialect.quotechar, 2)
            elif isinstance(f, JSONReader):
                self.options("encoding", "json", 1)
            return self._insert(table_name, rows, f.header, parse_dates)

Response: Load a text file into the specified table or Insert a list of rows into the specified table.


Instruction:
Here you have a function in Python 3, explain what it does
def connections(self):
        if "connections" not in self.settings:
            raise ConfigurationError("Could not retrieve connections from config file '{}'.".format(self._config_file))
        return self.settings.get("connections")

Response: Returns a dictionary of connections from the configuration settings.


Instruction:
Given the following Python 3 function, write the documentation
def get_connection(self, dsn=None):
        if dsn is None:
            dsn = self.connections.get("default", None)
            if dsn is None:
                raise ConfigurationError("No default DSN set")
        connection = self.connections.get(dsn, None)
        if connection is None:
            raise ConfigurationError("DSN '{}' does not exist".format(dsn))
        connection = self.decrypt(connection.copy())
        if connection.get('lock', 0) > 1:
            raise ConnectionLock(dsn)
        connection['name'] = dsn
        return connection

Response: Retrieve a connection by the given DSN or the default connection.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_value(self, key, default={}, nested=True, decrypt=True):
        key = key.lstrip()
        if key.endswith("."):
            key = key[:-1]
        if nested:
            path = key.split(".")
            curr = self.settings
            for p in path[:-1]:
                curr = curr.get(p, {})
            try:
                value = curr[path[-1]]
            except KeyError:
                return default
            value = self.decrypt(value, path)
            return value
        else:
            return self.settings.get(key, default)

Response: Retrieves a value from the configuration based on its key.


Instruction:
Given the following Python 3 function, write the documentation
def list_value(self, decrypt=False):
        if decrypt:
            settings = self.decrypt(self.settings)
        else:
            settings = self.settings
        return yaml.dump(settings, default_flow_style=False)

Response: Return the contents of the configuration file as a dict.


Instruction:
Can you tell what is the following Python 3 function doing
def lock_connection(cls, conf, dsn, key=None):
        with Config(conf, "w", key) as c:
            connection = c.get_connection(dsn)
            if not connection:
                raise ConfigurationError("Unable to lock connection")
            if dsn is None:
                dsn = c.settings["connections"]["default"]
            value = "connections.{}.lock".format(dsn)
            lock = c.get_value("connections.{}.lock".format(dsn), default=0)
            if lock >= 2:
                raise ConnectionLock(dsn)
            lock += 1
            c.set_value("connections.{}.lock".format(dsn), lock)
            c.write()

Response: A class method to lock a connection in the specified configuration file.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_value(self, key, value):
        if key.endswith("."):
            key = key[:-1]
        path = key.split(".")
        curr = self.settings
        for p in path[:-1]:
            if p not in curr:
                curr[p] = {}
            curr = curr[p]
        if not isinstance(curr, dict):
            raise ConfigurationError("Cannot set nested key '{}' in configuration value '{}' (destination is not a dictionary).".format(path[-1], key))
        value = self.encrypt(value, path)
        if value in {'true', 'True'}:
            value = True
        if value in {'false', 'False'}:
            value = False
        curr[path[-1]] = value

Response: Set a value within the configuration based on its key.


Instruction:
Implement a Python 3 function for
removing a value at the given key and any nested values in the configuration.

Response:
def unset_value(self, key):
        """
        Remove a value at the given key -- and any nested values --
        from the configuration.
        *Note*: In order to write changes to the file, ensure that
        :meth:`~giraffez.config.Config.write` is called prior to exit.

        :param str key: A path to the value destination, with nested levels joined by '.'
        :raises `giraffez.errors.ConfigurationError`: if the key specifies an invalid path, or does not exist
        """
        if key.endswith("."):
            key = key[:-1]
        path = key.split(".")
        curr = self.settings
        for p in path[:-1]:
            if p not in curr:
                raise ConfigurationError("Cannot unset '{}', nested key '{}' does not exist.".format(key, p))
            curr = curr[p]
        if not isinstance(curr, dict):
            raise ConfigurationError("Cannot unset nested key '{}' in configuration value '{}'.".format(path[-1], key))
        if path[-1] not in curr:
            raise ConfigurationError("Cannot unset '{}', nested key '{}' does not exist.".format(key, path[-1]))
        del curr[path[-1]]


Instruction:
Here you have a function in Python 3, explain what it does
def write(self, settings=None):
        if "r" in self.mode:
            raise ConfigReadOnly("Cannot write Config while in 'r' mode")
        try:
            if settings:
                self.settings = settings
            with open(self._config_file, "w") as f:
                f.write(repr(self))
                return repr(self)
        except OSError:
            return None

Response: Writes the current configuration to the file.


Instruction:
Given the following Python 3 function, write the documentation
def write_default(self, conf=None):
        if conf is None:
            conf = home_file(".girafferc")
        contents = yaml.dump(default_config, default_flow_style=False)
        with open(conf, "w") as f:
            f.write(contents)
        os.chmod(conf, 0o600)
        return contents

Response: A class method to write a default configuration file structure to a file.


Instruction:
Make a summary of the following Python 3 code
def get(self, column_name):
        column_name = column_name.lower()
        for c in self.columns:
            if c.name == column_name:
                return c
        return None

Response: Retrieves a column from the list with name value column_name


Instruction:
How would you explain what the following Python 3 function does
def set_filter(self, names=None):
        _names = []
        if names:
            for name in names:
                _safe_name = safe_name(name)
                if _safe_name not in self._column_map:
                    raise GiraffeTypeError("Column '{}' does not exist".format(name))
                if _safe_name in _names:
                    continue
                _names.append(_safe_name)
        self._filtered_columns = _names

Response: Sets the names of columns to be used when iterating through the list of names for the current page.


Instruction:
Explain what the following Python 3 code does
def serialize(self):
        data = b""
        for column in self:
            row = struct.pack("5H", column.type, column.length, column.precision, column.scale,
                len(column.name))
            row += ensure_bytes(column.name)
            data += row
        return struct.pack("H", len(data)) + data

Response: Serializes the columns into the giraffez archive header and header.


Instruction:
Explain what the following Python 3 code does
def deserialize(cls, data):
        column_list = cls()
        while data:
            tup, data = data[:10], data[10:]
            column_type, length, prec, scale, title_len = struct.unpack("5H", tup)
            title, data = data[:title_len], data[title_len:]
            try:
                column_list.append((title, column_type, length, prec, scale))
            except GiraffeTypeError as error:
                raise GiraffeEncodeError(error)
        return column_list

Response: Deserializes giraffez archive header. See GiraffeEncodeError for more information.


Instruction:
Make a summary of the following Python 3 code
def items(self):
        return {k.name: v for k, v in zip(self.columns, self)}

Response: Returns the contents of the row as a dict with the columnnames as keys and the row s fields as values.


Instruction:
Create a Python 3 function to
execute a query and initiate the connection with Teradata.

Response:
def query(self, query):
        """
        Set the query to be run and initiate the connection with Teradata.
        Only necessary if the query/table name was not specified as an argument
        to the constructor of the instance.

        :param str query: Valid SQL query to be executed
        """
        if query is None:
            return
        if log.level >= VERBOSE:
            self.options("query", query, 6)
        else:
            self.options("query", truncate(query), 6)
        statements = parse_statement(remove_curly_quotes(query))
        if not statements:
            raise GiraffeError("Unable to parse SQL statement")
        if len(statements) > 1:
            show_warning(("MORE THAN ONE STATEMENT RECEIVED, EXPORT OPERATIONS ALLOW ONE "
                "STATEMENT - ONLY THE FIRST STATEMENT WILL BE USED."), RuntimeWarning)
        statement = statements[0]
        log.debug("Debug[2]", "Statement (sanitized): {!r}".format(statement))
        if not (statement.startswith("select ") or statement.startswith("sel ")):
            statement = "select * from {}".format(statement)
        if statement == self.query:
            return
        else:
            self._query = statement
        self.initiated = False
        # Since CLIv2 is used in set_query (instead of relying on the
        # colums from the TPT Export driver) and set_query will always
        # happen before calls to initiate, set_query will always fail
        # with InvalidCredentialsError before initiate despite initiate
        # presumably failing after this point as well.
        try:
            self.export.set_query(statement)
        except InvalidCredentialsError as error:
            if self.protect:
                Config.lock_connection(self.config, self.dsn, self.key_file)
            raise error


Instruction:
How would you explain what the following Python 3 function does
def to_archive(self, writer):
        if 'b' not in writer.mode:
            raise GiraffeError("Archive writer must be in binary mode")
        writer.write(GIRAFFE_MAGIC)
        writer.write(self.columns.serialize())
        i = 0
        for n, chunk in enumerate(self._fetchall(ROW_ENCODING_RAW), 1):
            writer.write(chunk)
            yield TeradataEncoder.count(chunk)

Response: Writes the table name to the Giraffez archive format.


Instruction:
Can you tell what is the following Python 3 function doing
def to_str(self, delimiter='|', null='NULL'):
        self.export.set_null(null)
        self.export.set_delimiter(delimiter)
        self.options("delimiter", escape_string(delimiter), 2)
        self.options("null", null, 3)
        return self._fetchall(ENCODER_SETTINGS_STRING, coerce_floats=False)

Response: Returns an iterator over the current encoder output as a string.


Instruction:
Here you have a function in Python 3, explain what it does
def float_with_multiplier(string):
    match = re_float_with_multiplier.search(string)
    if not match or not match.group('num'):
        raise ValueError('String "{}" is not numeric!'.format(string))

    num = float(match.group('num'))
    multi = match.group('multi')
    if multi:
        try:
            num *= multipliers[multi]
        except KeyError:
            raise ValueError('Unknown multiplier: {}'.format(multi))
    return num

Response: Convert string with optional k M G T multiplier to float


Instruction:
Here you have a function in Python 3, explain what it does
def specific_gains(string):
    if not string:
        return {}

    gains = {}
    for gain in string.split(','):
        amp_name, value = gain.split('=')
        gains[amp_name.strip()] = float(value.strip())
    return gains

Response: Convert string with gains of individual amplification elements to dict


Instruction:
Here you have a function in Python 3, explain what it does
def device_settings(string):
    if not string:
        return {}

    settings = {}
    for setting in string.split(','):
        setting_name, value = setting.split('=')
        settings[setting_name.strip()] = value.strip()
    return settings

Response: Convert string with SoapySDR device settings to dict


Instruction:
How would you implement a function in Python 3 that
wraps text to terminal width with default indentation

Response:
def wrap(text, indent='    '):
    """Wrap text to terminal width with default indentation"""
    wrapper = textwrap.TextWrapper(
        width=int(os.environ.get('COLUMNS', 80)),
        initial_indent=indent,
        subsequent_indent=indent
    )
    return '\n'.join(wrapper.wrap(text))


Instruction:
Make a summary of the following Python 3 code
def detect_devices(soapy_args=''):
    devices = simplesoapy.detect_devices(soapy_args, as_string=True)
    text = []
    text.append('Detected SoapySDR devices:')
    if devices:
        for i, d in enumerate(devices):
            text.append('  {}'.format(d))
    else:
        text.append('  No devices found!')
    return (devices, '\n'.join(text))

Response: Returns detected SoapySDR devices


Instruction:
Create a Python 3 function for
returning info about the selected SoapySDR device

Response:
def device_info(soapy_args=''):
    """Returns info about selected SoapySDR device"""
    text = []
    try:
        device = simplesoapy.SoapyDevice(soapy_args)
        text.append('Selected device: {}'.format(device.hardware))
        text.append('  Available RX channels:')
        text.append('    {}'.format(', '.join(str(x) for x in device.list_channels())))
        text.append('  Available antennas:')
        text.append('    {}'.format(', '.join(device.list_antennas())))
        text.append('  Available tunable elements:')
        text.append('    {}'.format(', '.join(device.list_frequencies())))
        text.append('  Available amplification elements:')
        text.append('    {}'.format(', '.join(device.list_gains())))
        text.append('  Available device settings:')
        for key, s in device.list_settings().items():
            text.append(wrap('{} ... {} - {} (default: {})'.format(key, s['name'], s['description'], s['value'])))
        text.append('  Available stream arguments:')
        for key, s in device.list_stream_args().items():
            text.append(wrap('{} ... {} - {} (default: {})'.format(key, s['name'], s['description'], s['value'])))
        text.append('  Allowed gain range [dB]:')
        text.append('    {:.2f} - {:.2f}'.format(*device.get_gain_range()))
        text.append('  Allowed frequency range [MHz]:')
        text.append('    {:.2f} - {:.2f}'.format(*[x / 1e6 for x in device.get_frequency_range()]))
        text.append('  Allowed sample rates [MHz]:')
        rates = []
        for r in device.list_sample_rates():
            if r[0] == r[1]:
                rates.append('{:.2f}'.format(r[0] / 1e6))
            else:
                rates.append('{:.2f} - {:.2f}'.format(r[0] / 1e6, r[1] / 1e6))
        text.append(wrap(', '.join(rates)))
        text.append('  Allowed bandwidths [MHz]:')
        bandwidths = []
        for b in device.list_bandwidths():
            if b[0] == b[1]:
                bandwidths.append('{:.2f}'.format(b[0] / 1e6))
            else:
                bandwidths.append('{:.2f} - {:.2f}'.format(b[0] / 1e6, b[1] / 1e6))
        if bandwidths:
            text.append(wrap(', '.join(bandwidths)))
        else:
            text.append('    N/A')
    except RuntimeError:
        device = None
        text.append('No devices found!')
    return (device, '\n'.join(text))


Instruction:
How would you explain what the following Python 3 function does
def setup_argument_parser():
    # Fix help formatter width
    if 'COLUMNS' not in os.environ:
        os.environ['COLUMNS'] = str(shutil.get_terminal_size().columns)

    parser = argparse.ArgumentParser(
        prog='soapy_power',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description='Obtain a power spectrum from SoapySDR devices',
        add_help=False
    )

    # Fix recognition of optional argements of type float_with_multiplier
    parser._negative_number_matcher = re_float_with_multiplier_negative

    main_title = parser.add_argument_group('Main options')
    main_title.add_argument('-h', '--help', action='help',
                            help='show this help message and exit')
    main_title.add_argument('-f', '--freq', metavar='Hz|Hz:Hz', type=freq_or_freq_range, default='1420405752',
                            help='center frequency or frequency range to scan, number '
                            'can be followed by a k, M or G multiplier (default: %(default)s)')

    output_group = main_title.add_mutually_exclusive_group()
    output_group.add_argument('-O', '--output', metavar='FILE', type=argparse.FileType('w'), default=sys.stdout,
                              help='output to file (incompatible with --output-fd, default is stdout)')
    output_group.add_argument('--output-fd', metavar='NUM', type=int, default=None,
                              help='output to existing file descriptor (incompatible with -O)')

    main_title.add_argument('-F', '--format', choices=sorted(writer.formats.keys()), default='rtl_power',
                            help='output format (default: %(default)s)')
    main_title.add_argument('-q', '--quiet', action='store_true',
                            help='limit verbosity')
    main_title.add_argument('--debug', action='store_true',
                            help='detailed debugging messages')
    main_title.add_argument('--detect', action='store_true',
                            help='detect connected SoapySDR devices and exit')
    main_title.add_argument('--info', action='store_true',
                            help='show info about selected SoapySDR device and exit')
    main_title.add_argument('--version', action='version',
                            version='%(prog)s {}'.format(__version__))

    bins_title = parser.add_argument_group('FFT bins')
    bins_group = bins_title.add_mutually_exclusive_group()
    bins_group.add_argument('-b', '--bins', type=int, default=512,
                            help='number of FFT bins (incompatible with -B, default: %(default)s)')
    bins_group.add_argument('-B', '--bin-size', metavar='Hz', type=float_with_multiplier,
                            help='bin size in Hz (incompatible with -b)')

    spectra_title = parser.add_argument_group('Averaging')
    spectra_group = spectra_title.add_mutually_exclusive_group()
    spectra_group.add_argument('-n', '--repeats', type=int, default=1600,
                               help='number of spectra to average (incompatible with -t and -T, default: %(default)s)')
    spectra_group.add_argument('-t', '--time', metavar='SECONDS', type=float,
                               help='integration time (incompatible with -T and -n)')
    spectra_group.add_argument('-T', '--total-time', metavar='SECONDS', type=float,
                               help='total integration time of all hops (incompatible with -t and -n)')

    runs_title = parser.add_argument_group('Measurements')
    runs_group = runs_title.add_mutually_exclusive_group()
    runs_group.add_argument('-c', '--continue', dest='endless', action='store_true',
                            help='repeat the measurement endlessly (incompatible with -u and -e)')
    runs_group.add_argument('-u', '--runs', type=int, default=1,
                            help='number of measurements (incompatible with -c and -e, default: %(default)s)')
    runs_group.add_argument('-e', '--elapsed', metavar='SECONDS', type=float,
                            help='scan session duration (time limit in seconds, incompatible with -c and -u)')

    device_title = parser.add_argument_group('Device settings')
    device_title.add_argument('-d', '--device', default='',
                              help='SoapySDR device to use')
    device_title.add_argument('-C', '--channel', type=int, default=0,
                              help='SoapySDR RX channel (default: %(default)s)')
    device_title.add_argument('-A', '--antenna', default='',
                              help='SoapySDR selected antenna')
    device_title.add_argument('-r', '--rate', metavar='Hz', type=float_with_multiplier, default=2e6,
                              help='sample rate (default: %(default)s)')
    device_title.add_argument('-w', '--bandwidth', metavar='Hz', type=float_with_multiplier, default=0,
                              help='filter bandwidth (default: %(default)s)')
    device_title.add_argument('-p', '--ppm', type=int, default=0,
                              help='frequency correction in ppm')

    gain_group = device_title.add_mutually_exclusive_group()
    gain_group.add_argument('-g', '--gain', metavar='dB', type=float, default=37.2,
                            help='total gain (incompatible with -G and -a, default: %(default)s)')
    gain_group.add_argument('-G', '--specific-gains', metavar='STRING', type=specific_gains, default='',
                            help='specific gains of individual amplification elements '
                                 '(incompatible with -g and -a, example: LNA=28,VGA=12,AMP=0')
    gain_group.add_argument('-a', '--agc', action='store_true',
                            help='enable Automatic Gain Control (incompatible with -g and -G)')

    device_title.add_argument('--lnb-lo', metavar='Hz', type=float_with_multiplier, default=0,
                              help='LNB LO frequency, negative for upconverters (default: %(default)s)')
    device_title.add_argument('--device-settings', metavar='STRING', type=device_settings, default='',
                              help='SoapySDR device settings (example: biastee=true)')
    device_title.add_argument('--force-rate', action='store_true',
                              help='ignore list of sample rates provided by device and allow any value')
    device_title.add_argument('--force-bandwidth', action='store_true',
                              help='ignore list of filter bandwidths provided by device and allow any value')
    device_title.add_argument('--tune-delay', metavar='SECONDS', type=float, default=0,
                              help='time to delay measurement after changing frequency (to avoid artifacts)')
    device_title.add_argument('--reset-stream', action='store_true',
                              help='reset streaming after changing frequency (to avoid artifacts)')

    crop_title = parser.add_argument_group('Crop')
    crop_group = crop_title.add_mutually_exclusive_group()
    crop_group.add_argument('-o', '--overlap', metavar='PERCENT', type=float, default=0,
                            help='percent of overlap when frequency hopping (incompatible with -k)')
    crop_group.add_argument('-k', '--crop', metavar='PERCENT', type=float, default=0,
                            help='percent of crop when frequency hopping (incompatible with -o)')

    perf_title = parser.add_argument_group('Performance options')
    perf_title.add_argument('-s', '--buffer-size', type=int, default=0,
                            help='base buffer size (number of samples, 0 = auto, default: %(default)s)')
    perf_title.add_argument('-S', '--max-buffer-size', type=int, default=0,
                            help='maximum buffer size (number of samples, -1 = unlimited, 0 = auto, default: %(default)s)')

    fft_rules_group = perf_title.add_mutually_exclusive_group()
    fft_rules_group.add_argument('--even', action='store_true',
                                 help='use only even numbers of FFT bins')
    fft_rules_group.add_argument('--pow2', action='store_true',
                                 help='use only powers of 2 as number of FFT bins')

    perf_title.add_argument('--max-threads', metavar='NUM', type=int, default=0,
                            help='maximum number of PSD threads (0 = auto, default: %(default)s)')
    perf_title.add_argument('--max-queue-size', metavar='NUM', type=int, default=0,
                            help='maximum size of PSD work queue (-1 = unlimited, 0 = auto, default: %(default)s)')
    perf_title.add_argument('--no-pyfftw', action='store_true',
                            help='don\'t use pyfftw library even if it is available (use scipy.fftpack or numpy.fft)')

    other_title = parser.add_argument_group('Other options')
    other_title.add_argument('-l', '--linear', action='store_true',
                             help='linear power values instead of logarithmic')
    other_title.add_argument('-R', '--remove-dc', action='store_true',
                             help='interpolate central point to cancel DC bias (useful only with boxcar window)')
    other_title.add_argument('-D', '--detrend', choices=['none', 'constant'], default='none',
                             help='remove mean value from data to cancel DC bias (default: %(default)s)')
    other_title.add_argument('--fft-window', choices=['boxcar', 'hann', 'hamming', 'blackman', 'bartlett', 'kaiser', 'tukey'],
                             default='hann', help='Welch\'s method window function (default: %(default)s)')
    other_title.add_argument('--fft-window-param', metavar='FLOAT', type=float, default=None,
                             help='shape parameter of window function (required for kaiser and tukey windows)')
    other_title.add_argument('--fft-overlap', metavar='PERCENT', type=float, default=50,
                             help='Welch\'s method overlap between segments (default: %(default)s)')

    return parser

Response: Setup command line parser


Instruction:
How would you implement a function in Python 3 that
sets center frequency and clear averaged PSD data

Response:
def set_center_freq(self, center_freq):
        """Set center frequency and clear averaged PSD data"""
        psd_state = {
            'repeats': 0,
            'freq_array': self._base_freq_array + self._lnb_lo + center_freq,
            'pwr_array': None,
            'update_lock': threading.Lock(),
            'futures': [],
        }
        return psd_state


Instruction:
How would you code a function in Python 3 to
return frequencies and averaged PSD for given center frequency

Response:
def result(self, psd_state):
        """Return freqs and averaged PSD for given center frequency"""
        freq_array = numpy.fft.fftshift(psd_state['freq_array'])
        pwr_array = numpy.fft.fftshift(psd_state['pwr_array'])

        if self._crop_factor:
            crop_bins_half = round((self._crop_factor * self._bins) / 2)
            freq_array = freq_array[crop_bins_half:-crop_bins_half]
            pwr_array = pwr_array[crop_bins_half:-crop_bins_half]

        if psd_state['repeats'] > 1:
            pwr_array = pwr_array / psd_state['repeats']

        if self._log_scale:
            pwr_array = 10 * numpy.log10(pwr_array)

        return (freq_array, pwr_array)


Instruction:
Write a Python 3 function for
waiting for all PSD threads to finish and return result

Response:
def wait_for_result(self, psd_state):
        """Wait for all PSD threads to finish and return result"""
        if len(psd_state['futures']) > 1:
            concurrent.futures.wait(psd_state['futures'])
        elif psd_state['futures']:
            psd_state['futures'][0].result()
        return self.result(psd_state)


Instruction:
Can you write a function in Python 3 where it
computes PSD from samples and update average for given center frequency

Response:
def update(self, psd_state, samples_array):
        """Compute PSD from samples and update average for given center frequency"""
        freq_array, pwr_array = simplespectral.welch(samples_array, self._sample_rate, nperseg=self._bins,
                                                     window=self._fft_window, noverlap=self._fft_overlap_bins,
                                                     detrend=self._detrend)

        if self._remove_dc:
            pwr_array[0] = (pwr_array[1] + pwr_array[-1]) / 2

        with psd_state['update_lock']:
            psd_state['repeats'] += 1
            if psd_state['pwr_array'] is None:
                psd_state['pwr_array'] = pwr_array
            else:
                psd_state['pwr_array'] += pwr_array


Instruction:
Here you have a function in Python 3, explain what it does
def update_async(self, psd_state, samples_array):
        future = self._executor.submit(self.update, psd_state, samples_array)
        future.add_done_callback(self._release_future_memory)
        psd_state['futures'].append(future)
        return future

Response: Compute PSD from samples and update average for given center frequency


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write_async(self, psd_data_or_future, time_start, time_stop, samples):
        return self._executor.submit(self.write, psd_data_or_future, time_start, time_stop, samples)

Response: Write PSD data asynchronously in another thread.


Instruction:
Here you have a function in Python 3, explain what it does
def read(self, f):
        magic = f.read(len(self.magic))
        if not magic:
            return None
        if magic != self.magic:
            raise ValueError('Magic bytes not found! Read data: {}'.format(magic))

        header = self.header._make(
            self.header_struct.unpack(f.read(self.header_struct.size))
        )
        pwr_array = numpy.fromstring(f.read(header.size), dtype='float32')
        return (header, pwr_array)

Response: Read data from file - like object


Instruction:
Can you generate the documentation for the following Python 3 function
def write(self, f, time_start, time_stop, start, stop, step, samples, pwr_array):
        f.write(self.magic)
        f.write(self.header_struct.pack(
            self.version, time_start, time_stop, start, stop, step, samples, pwr_array.nbytes
        ))
        #pwr_array.tofile(f)
        f.write(pwr_array.tobytes())
        f.flush()

Response: Write data to file - like object


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write(self, psd_data_or_future, time_start, time_stop, samples):
        try:
            # Wait for result of future
            f_array, pwr_array = psd_data_or_future.result()
        except AttributeError:
            f_array, pwr_array = psd_data_or_future

        try:
            step = f_array[1] - f_array[0]
            self.formatter.write(
                self.output,
                time_start.timestamp(),
                time_stop.timestamp(),
                f_array[0],
                f_array[-1] + step,
                step,
                samples,
                pwr_array
            )
        except Exception as e:
            logging.exception('Error writing to output file: {}'.format(e))

Response: Write PSD of one frequency hop to file


Instruction:
Can you implement a function in Python 3 that
writes PSD of one frequency hop to the output stream.

Response:
def write(self, psd_data_or_future, time_start, time_stop, samples):
        """Write PSD of one frequency hop"""
        try:
            # Wait for result of future
            f_array, pwr_array = psd_data_or_future.result()
        except AttributeError:
            f_array, pwr_array = psd_data_or_future

        self.output.write('# soapy_power output\n')
        self.output.write('# Acquisition start: {}\n'.format(time_start))
        self.output.write('# Acquisition end: {}\n'.format(time_stop))
        self.output.write('#\n')
        self.output.write('# frequency [Hz] power spectral density [dB/Hz]\n')

        for f, pwr in zip(f_array, pwr_array):
            self.output.write('{} {}\n'.format(f, pwr))

        self.output.write('\n')
        self.output.flush()


Instruction:
Can you generate the documentation for the following Python 3 function
def write(self, psd_data_or_future, time_start, time_stop, samples):
        try:
            # Wait for result of future
            f_array, pwr_array = psd_data_or_future.result()
        except AttributeError:
            f_array, pwr_array = psd_data_or_future

        try:
            step = f_array[1] - f_array[0]
            row = [
                time_stop.strftime('%Y-%m-%d'), time_stop.strftime('%H:%M:%S'),
                f_array[0], f_array[-1] + step, step, samples
            ]
            row += list(pwr_array)
            self.output.write('{}\n'.format(', '.join(str(x) for x in row)))
            self.output.flush()
        except Exception as e:
            logging.exception('Error writing to output file:')

Response: Write PSD of one frequency hop to file


Instruction:
Can you generate a brief explanation for the following Python 3 code
def submit(self, fn, *args, **kwargs):
        future = super().submit(fn, *args, **kwargs)
        work_queue_size = self._work_queue.qsize()
        if work_queue_size > self.max_queue_size_reached:
            self.max_queue_size_reached = work_queue_size
        return future

Response: Submits a callable to be executed with the given arguments.


Instruction:
Can you write a function in Python 3 where it
returns nearest number of FFT bins

Response:
def nearest_bins(self, bins, even=False, pow2=False):
        """Return nearest number of FFT bins (even or power of two)"""
        if pow2:
            bins_log2 = math.log(bins, 2)
            if bins_log2 % 1 != 0:
                bins = 2**math.ceil(bins_log2)
                logger.warning('number of FFT bins should be power of two, changing to {}'.format(bins))
        elif even:
            if bins % 2 != 0:
                bins = math.ceil(bins / 2) * 2
                logger.warning('number of FFT bins should be even, changing to {}'.format(bins))

        return bins


Instruction:
Explain what the following Python 3 code does
def nearest_overlap(self, overlap, bins):
        bins_overlap = overlap * bins
        if bins_overlap % 2 != 0:
            bins_overlap = math.ceil(bins_overlap / 2) * 2
            overlap = bins_overlap / bins
            logger.warning('number of overlapping FFT bins should be even, '
                           'changing overlap/crop factor to {:.5f}'.format(overlap))
        return overlap

Response: Return nearest overlap factor based on number of bins


Instruction:
Here you have a function in Python 3, explain what it does
def time_to_repeats(self, bins, integration_time):
        return math.ceil((self.device.sample_rate * integration_time) / bins)

Response: Convert integration time to number of repeats