def Func(arg_0, arg_1, arg_2):
        """
        Configure stepper motor prior to operation.

        :param steps_per_revolution: number of steps per motor revolution

        :param stepper_pins: a list of control pin numbers - either 4 or 2
        """
        arg_3 = [arg_0.STEPPER_CONFIGURE, arg_1 & 0x7f, (arg_1 >> 7) & 0x7f]
        for arg_4 in range(len(arg_2)):
            arg_3.append(arg_2[arg_4])
        arg_0._command_handler.send_sysex(arg_0._command_handler.STEPPER_DATA, arg_3)


def Func(arg_0):
        """
        Request the stepper library version from the Arduino.
        To retrieve the version after this command is called, call
        get_stepper_version
        """
        arg_1 = [arg_0.STEPPER_LIBRARY_VERSION]
        arg_0._command_handler.send_sysex(arg_0._command_handler.STEPPER_DATA, arg_1)


def Func(arg_0, arg_1):
        """
        Func the serial port using the configuration data
        returns a reference to this instance
        """
        # Func a serial port
        if arg_1:
            print('\nOpening Arduino Serial port %s ' % arg_0.port_id)

        try:

            # in case the port is already Func, let's close it and then
            # reFunc it
            arg_0.arduino.close()
            time.sleep(1)
            arg_0.arduino.Func()
            time.sleep(1)
            return arg_0.arduino

        except Exception:
            # Funced failed - will report back to caller
            raise


def Func(arg_0):
        """
        This method continually Funcs. If an incoming character is available on the serial port
        it is read and placed on the _command_deque
        @return: Never Returns
        """
        while not arg_0.is_stopped():
            # we can get an OSError: [Errno9] Bad file descriptor when shutting down
            # just ignore it
            try:
                if arg_0.arduino.inWaiting():
                    arg_1 = arg_0.arduino.read()
                    arg_0.command_deque.append(ord(arg_1))
                else:
                    time.sleep(.1)
            except OSError:
                pass
            except IOError:
                arg_0.stop()
        arg_0.close()


def Func(arg_0, arg_1):
        """
        Set the brightness level for the entire display
        @param brightness: brightness level (0 -15)
        """
        if arg_1 > 15:
            arg_1 = 15
        arg_1 |= 0xE0
        arg_0.brightness = arg_1
        arg_0.firmata.i2c_write(0x70, arg_1)


def Func(arg_0):
        """
        Write the entire buffer to the display
        """
        arg_1 = 0
        arg_2 = 0

        for arg_3 in range(0, 8):
            for arg_4 in range(0, 8):
                if arg_0.display_buffer[arg_3][arg_4] == arg_0.LED_GREEN:
                    arg_1 |= 1 << arg_4
                elif arg_0.display_buffer[arg_3][arg_4] == arg_0.LED_RED:
                    arg_2 |= 1 << arg_4
                elif arg_0.display_buffer[arg_3][arg_4] == arg_0.LED_YELLOW:
                    arg_1 |= 1 << arg_4
                    arg_2 |= 1 << arg_4
                elif arg_0.display_buffer[arg_3][arg_4] == arg_0.LED_OFF:
                    arg_1 &= ~(1 << arg_4)
                    arg_2 &= ~(1 << arg_4)

            arg_0.firmata.i2c_write(0x70, arg_3 * 2, 0, arg_1)
            arg_0.firmata.i2c_write(0x70, arg_3 * 2 + 1, 0, arg_2)


def Func(arg_0):
        """
        Set all led's to off.
        """
        for arg_1 in range(0, 8):
            arg_0.firmata.i2c_write(0x70, arg_1 * 2, 0, 0)
            arg_0.firmata.i2c_write(0x70, (arg_1 * 2) + 1, 0, 0)

            for arg_2 in range(0, 8):
                arg_0.display_buffer[arg_1][arg_2] = 0


def Func(arg_0, arg_1):
        """
        This method handles the incoming digital message.
        It stores the data values in the digital response table.
        Data is stored for all 8 bits of a  digital port

        :param data: Message data from Firmata

        :return: No return value.
        """
        arg_2 = arg_1[0]
        arg_3 = (arg_1[arg_0.MSB] << 7) + arg_1[arg_0.LSB]

        # set all the pins for this reporting port
        # get the first pin number for this report
        arg_4 = arg_2 * 8
        for arg_4 in range(arg_4, min(arg_4 + 8, arg_0.total_pins_discovered)):
            # shift through all the bit positions and set the digital response table
            with arg_0.pymata.data_lock:
                # look at the previously stored value for this pin
                arg_5 = arg_0.digital_response_table[arg_4][arg_0.RESPONSE_TABLE_PIN_DATA_VALUE]
                # get the current value
                arg_0.digital_response_table[arg_4][arg_0.RESPONSE_TABLE_PIN_DATA_VALUE] = arg_3 & 0x01
                # if the values differ and callback is enabled for the pin, then send out the callback
                if arg_5 != arg_3 & 0x01:
                    arg_8 = arg_0.digital_response_table[arg_4][arg_0.RESPONSE_TABLE_CALLBACK]
                    if arg_8:
                        arg_8([arg_0.pymata.DIGITAL, arg_4,
                                  arg_0.digital_response_table[arg_4][arg_0.RESPONSE_TABLE_PIN_DATA_VALUE]])

                # determine if the latch data table needs to be updated for each pin
                arg_9 = arg_0.digital_latch_table[arg_4]
                if arg_9[arg_0.LATCH_STATE] == arg_0.LATCH_ARMED:
                    if arg_9[arg_0.LATCHED_THRESHOLD_TYPE] == arg_0.DIGITAL_LATCH_LOW:
                        if (arg_3 & 0x01) == 0:
                            if arg_9[arg_0.DIGITAL_LATCH_CALLBACK] is not None:
                                arg_0.digital_latch_table[arg_4] = [0, 0, 0, 0, None]
                                arg_9[arg_0.DIGITAL_LATCH_CALLBACK](
                                    [arg_0.pymata.OUTPUT | arg_0.pymata.LATCH_MODE,
                                     arg_4, 0, time.time()])

                            else:
                                arg_11 = arg_9
                                arg_11[arg_0.LATCH_STATE] = arg_0.LATCH_LATCHED
                                arg_11[arg_0.DIGITAL_LATCHED_DATA] = arg_0.DIGITAL_LATCH_LOW
                                # time stamp it
                                arg_11[arg_0.DIGITAL_TIME_STAMP] = time.time()
                        else:
                            pass
                    elif arg_9[arg_0.LATCHED_THRESHOLD_TYPE] == arg_0.DIGITAL_LATCH_HIGH:
                        if arg_3 & 0x01:
                            if arg_9[arg_0.DIGITAL_LATCH_CALLBACK] is not None:
                                arg_0.digital_latch_table[arg_4] = [0, 0, 0, 0, None]
                                arg_9[arg_0.DIGITAL_LATCH_CALLBACK](
                                    [arg_0.pymata.OUTPUT | arg_0.pymata.LATCH_MODE,
                                     arg_4, 1, time.time()])
                            else:
                                arg_11 = arg_9
                                arg_11[arg_0.LATCH_STATE] = arg_0.LATCH_LATCHED
                                arg_11[arg_0.DIGITAL_LATCHED_DATA] = arg_0.DIGITAL_LATCH_HIGH
                                # time stamp it
                                arg_11[arg_0.DIGITAL_TIME_STAMP] = time.time()
                        else:
                            pass
                else:
                    pass

            # get the next data bit
            arg_3 >>= 1


def Func(arg_0, arg_1):
        """
        This method handles the incoming sonar data message and stores
        the data in the response table.

        :param data: Message data from Firmata

        :return: No return value.
        """
        arg_2 = int((arg_1[arg_0.MSB] << 7) + arg_1[arg_0.LSB])
        arg_3 = arg_1[0]
        with arg_0.pymata.data_lock:
            arg_4 = arg_0.active_sonar_map[arg_3]
            # also write it into the digital response table
            arg_0.digital_response_table[arg_1[arg_0.RESPONSE_TABLE_MODE]][arg_0.RESPONSE_TABLE_PIN_DATA_VALUE] = arg_2
            # send data through callback if there is a callback function for the pin
            if arg_4[0] is not None:
                # check if value changed since last reading
                if arg_4[1] != arg_2:
                    arg_0.active_sonar_map[arg_3][0]([arg_0.pymata.SONAR, arg_3, arg_2])
            # update the data in the table with latest value
            arg_4[1] = arg_2
            arg_0.active_sonar_map[arg_3] = arg_4


def Func(arg_0, arg_1, arg_2=None):
        """
        This method will send a Sysex command to Firmata with any accompanying data

        :param sysex_command: sysex command

        :param sysex_data: data for command

        :return : No return value.
        """
        if not arg_2:
            arg_2 = []

        # convert the message command and data to characters
        arg_3 = chr(arg_0.START_SYSEX)
        arg_3 += chr(arg_1)
        if len(arg_2):
            for arg_4 in arg_2:
                arg_3 += chr(arg_4)
        arg_3 += chr(arg_0.END_SYSEX)

        for arg_5 in arg_3:
            arg_0.pymata.transport.write(arg_5)


def Func(arg_0, arg_1):
        """
        This method is used to transmit a non-sysex command.

        :param command: Command to send to firmata includes command + data formatted by caller

        :return : No return value.
        """
        arg_2 = ""
        for arg_3 in arg_1:
            arg_2 += chr(arg_3)

        for arg_4 in arg_2:
            arg_0.pymata.transport.write(arg_4)


def Func(arg_0):
        """
        Send the reset command to the Arduino.
        It resets the response tables to their initial values

        :return: No return value
        """
        arg_1 = chr(arg_0.SYSTEM_RESET)
        arg_0.pymata.transport.write(arg_1)

        # response table re-initialization
        # for each pin set the mode to input and the last read data value to zero
        with arg_0.pymata.data_lock:
            # remove all old entries from existing tables
            for arg_2 in range(len(arg_0.digital_response_table)):
                arg_0.digital_response_table.pop()

            for arg_2 in range(len(arg_0.analog_response_table)):
                arg_0.analog_response_table.pop()

            # reinitialize tables
            for arg_3 in range(0, arg_0.total_pins_discovered):
                arg_4 = [arg_0.pymata.INPUT, 0, None]
                arg_0.digital_response_table.append(arg_4)

            for arg_3 in range(0, arg_0.number_of_analog_pins_discovered):
                arg_4 = [arg_0.pymata.INPUT, 0, None]
                arg_0.analog_response_table.append(arg_4)


def Func(arg_0, arg_1):
        """
        This method handles the incoming string data message from Firmata.
        The string is printed to the console

        :param data: Message data from Firmata

        :return: No return value.s
        """
        print("Func:")
        arg_2 = []
        for arg_3 in arg_1[::2]:
            arg_2.append(chr(arg_3))
        print("".join(arg_2))


def Func(arg_0):
        """
        Combine finder_Func and extender_Func,
        remove duplicate but keep order
        """

        arg_1 = arg_0.finder_Func[:]
        for arg_2 in arg_0.extender_Func:
            if arg_2 not in arg_1:
                arg_1.append(arg_2)

        return arg_1


def Func(arg_0,
                            arg_1,
                            arg_2=[],
                            *arg_3, **arg_4):
    """
    Find image URL in background-image

    Example:

    to
    http://distilleryimage10.ak.instagram.com/bde04558a43b11e28e5d22000a1f979a_7.jpg
    """

    arg_5 = []

    for arg_6 in arg_1.find_all(arg_8=True):
        arg_7 = arg_6['style']
        if 'background-image' in arg_7.lower():
            arg_8 = cssutils.parseStyle(arg_7)
            arg_9 = arg_8.getProperty('background-image')
            if arg_9:
                for arg_10 in arg_9.propertyValue:
                    arg_11 = str(arg_10.value)
                    if arg_11:
                        if (arg_11 not in arg_2) and \
                           (arg_11 not in arg_5):
                            arg_5.append(arg_11)

    arg_12 = {}
    arg_12['finder_image_urls'] = arg_2 + arg_5

    return arg_12


def Func(arg_0):
    '''Condition an image for use with the VGG16 model.'''
    arg_0 = arg_0[:,:,::-1]  # to BGR
    arg_0[:, :, 0] -= 103.939
    arg_0[:, :, 1] -= 116.779
    arg_0[:, :, 2] -= 123.68
    arg_0 = arg_0.transpose((2, 0, 1))
    return arg_0


def Func(arg_0, arg_1):
        '''Create a function for the response of a layer.'''
        arg_2 = [arg_0.net_input]
        if arg_0.learning_phase is not None:
            arg_2.append(K.learning_phase())
        return K.function(arg_2, [arg_0.get_layer_output(arg_1)])


def Func(arg_0, arg_1, arg_2=None, arg_3='|', arg_4='NULL',
            arg_5=True, arg_6='"', arg_7=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 arg_0.table:
            if not arg_2:
                raise GiraffeError("Table must be set or specified to load a file.")
            arg_0.table = arg_2
        if not isinstance(arg_4, basestring):
            raise GiraffeError("Expected 'null' to be str, received {}".format(type(arg_4)))
        with Reader(arg_1, arg_3=arg_3, arg_6=arg_6) as f:
            if not isinstance(f.delimiter, basestring):
                raise GiraffeError("Expected 'delimiter' to be str, received {}".format(type(arg_3)))
            arg_0.columns = f.header
            if isinstance(f, ArchiveFileReader):
                arg_0.mload.set_encoding(ROW_ENCODING_RAW)
                arg_0.preprocessor = lambda s: s
            if arg_7:
                arg_0.preprocessor = DateHandler(arg_0.columns)
            arg_0._initiate()
            arg_0.mload.set_null(arg_4)
            arg_0.mload.set_delimiter(arg_3)
            arg_10 = 0
            for arg_10, arg_11 in enumerate(f, 1):
                arg_0.put(arg_11, arg_5=arg_5)
                if arg_10 % arg_0.checkpoint_interval == 1:
                    log.info("\rBulkLoad", "Processed {} rows".format(arg_10), console=True)
                    arg_12 = arg_0.checkpoint()
                    arg_0.exit_code = arg_0._exit_code()
                    if arg_0.exit_code != 0:
                        return arg_0.exit_code
            log.info("\rBulkLoad", "Processed {} rows".format(arg_10))
            return arg_0.finish()


def Func(arg_0, arg_1, arg_2=True):
        """
        Load a single row into the target table.

        :param list items: A list of values in the row corresponding to the
            fields specified by :code:`self.columns`
        :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.
        :raises `giraffez.errors.GiraffeEncodeError`: if :code:`panic` is :code:`True` and there
            are format errors in the row values.
        :raises `giraffez.errors.GiraffeError`: if table name is not set.
        :raises `giraffez.TeradataPTError`: if there is a problem
            connecting to Teradata.
        """
        if not arg_0.initiated:
            arg_0._initiate()
        try:
            arg_3 = arg_0.mload.Func_row(arg_0.preprocessor(arg_1))
            arg_0.applied_count += 1
        except (TeradataPTError, EncoderError) as error:
            arg_0.error_count += 1
            if arg_2:
                raise error
            log.info("BulkLoad", error)


def Func(arg_0):
        """
        Attempt Func of target mload table.

        :raises `giraffez.errors.GiraffeError`: if table was not set by
            the constructor, the :code:`TeradataBulkLoad.table`, or
            :meth:`~giraffez.load.TeradataBulkLoad.from_file`.
        """
        if arg_0.table is None:
            raise GiraffeError("Cannot Func. Target table has not been set.")
        log.info("BulkLoad", "Attempting Func for table {}".format(arg_0.table))
        arg_0.mload.Func(arg_0.table)


def Func(arg_0):
        """
        The names of the work Func used for loading.

        :return: A list of four Func, each the name of the target table
            with the added suffixes, "_wt", "_log", "_e1", and "_e2"
        :raises `giraffez.errors.GiraffeError`: if table was not set by
            the constructor, the :code:`TeradataBulkLoad.table`, or
            :meth:`~giraffez.load.TeradataBulkLoad.from_file`.
        """
        if arg_0.table is None:
            raise GiraffeError("Target table has not been set.")
        return [
            "{}_wt".format(arg_0.table),
            "{}_log".format(arg_0.table),
            "{}_e1".format(arg_0.table),
            "{}_e2".format(arg_0.table),
        ]


def Func(arg_0, arg_1):
        """
        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 arg_1.startswith("secure.") and not arg_1.startswith("connections."):
            arg_1 = "secure.{0}".format(arg_1)
        arg_2 = arg_0.config.Func_value(arg_1)
        if not isinstance(arg_2, basestring):
            arg_2 = None
        return arg_2


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


def Func(arg_0, arg_1, arg_2=True, arg_3=False, arg_4=False, arg_5=True,
            arg_6=False, arg_7=None,  arg_8=False, arg_9=False):
        """
        Execute commands using CLIv2.

        :param str command: The SQL command to be Funcd
        :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 arg_7 is None:
            arg_7 = arg_0.panic
        arg_0.options("panic", arg_7)
        arg_0.options("multi-statement mode", arg_8, 3)
        if isfile(arg_1):
            arg_0.options("file", arg_1, 2)
            with open(arg_1, 'r') as f:
                arg_1 = f.read()
        else:
            if log.level >= VERBOSE:
                arg_0.options("query", arg_1, 2)
            else:
                arg_0.options("query", truncate(arg_1), 2)
        if not arg_6 and not arg_0.silent:
            log.info("Command", "Executing ...")
            log.info(arg_0.options)
        if arg_5:
            arg_1 = prepare_statement(arg_1) # accounts for comments and newlines
            log.debug("Debug[2]", "Command (sanitized): {!r}".format(arg_1))
        arg_0.cmd.set_encoding(ENCODER_SETTINGS_DEFAULT)
        return Cursor(arg_0.cmd, arg_1, arg_8=arg_8, arg_4=arg_4,
            arg_9=arg_9, arg_2=arg_2, arg_3=arg_3,
            arg_7=arg_7)


def Func(arg_0, arg_1=None):
        """
        A class method to write a default configuration file structure to a file.
        Note that the contents of the file will be overwritten if it already exists.

        :param str conf: The name of the file to write to. Defaults to :code:`None`, for ~/.girafferc
        :return: The content written to the file
        :rtype: str
        """
        if arg_1 is None:
            arg_1 = home_file(".girafferc")
        arg_2 = yaml.dump(default_config, default_flow_style=False)
        with open(arg_1, "w") as f:
            f.write(arg_2)
        os.chmod(arg_1, 0o600)
        return arg_2


def Func(arg_0, arg_1=None):
        """
        Set the names of columns to be used when iterating through the list,
        retrieving names, etc.

        :param list names: A list of names to be used, or :code:`None` for all
        """
        arg_2 = []
        if arg_1:
            for arg_3 in arg_1:
                arg_4 = safe_name(arg_3)
                if arg_4 not in arg_0._column_map:
                    raise GiraffeTypeError("Column '{}' does not exist".format(arg_3))
                if arg_4 in arg_2:
                    continue
                arg_2.append(arg_4)
        arg_0._filtered_columns = arg_2


def Func(arg_0, arg_1):
        """
        Writes export archive files in the Giraffez archive format.
        This takes a `giraffez.io.Writer` and writes archive chunks to
        file until all rows for a given statement have been exhausted.

        .. code-block:: python

            with giraffez.BulkExport("database.table_name") as export:
                with giraffez.Writer("database.table_name.tar.gz", 'wb', use_gzip=True) as out:
                    for n in export.Func(out):
                        print("Rows: {}".format(n))

        :param `giraffez.io.Writer` writer: A writer handling the archive output

        :rtype: iterator (yields ``int``)
        """
        if 'b' not in arg_1.mode:
            raise GiraffeError("Archive writer must be in binary mode")
        arg_1.write(GIRAFFE_MAGIC)
        arg_1.write(arg_0.columns.serialize())
        arg_2 = 0
        for arg_3, arg_4 in enumerate(arg_0._fetchall(ROW_ENCODING_RAW), 1):
            arg_1.write(arg_4)
            yield TeradataEncoder.count(arg_4)


def Func(arg_0, arg_1='|', arg_2='NULL'):
        """
        Sets the current encoder output to Python `str` and returns
        a row iterator.

        :param str null: The string representation of null values
        :param str delimiter: The string delimiting values in the output
            string

        :rtype: iterator (yields ``str``)
        """
        arg_0.export.set_null(arg_2)
        arg_0.export.set_delimiter(arg_1)
        arg_0.options("delimiter", escape_string(arg_1), 2)
        arg_0.options("null", arg_2, 3)
        return arg_0._fetchall(ENCODER_SETTINGS_STRING, coerce_floats=False)


def Func(arg_0):
    """Convert string with optional k, M, G, T multiplier to float"""
    arg_1 = re_Func.search(arg_0)
    if not arg_1 or not arg_1.group('num'):
        raise ValueError('String "{}" is not numeric!'.format(arg_0))

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


def Func(arg_0):
    """Convert string with gains of individual amplification elements to dict"""
    if not arg_0:
        return {}

    arg_1 = {}
    for arg_2 in arg_0.split(','):
        arg_3, arg_4 = arg_2.split('=')
        arg_1[arg_3.strip()] = float(arg_4.strip())
    return arg_1


def Func(arg_0, arg_1='    '):
    """Wrap text to terminal width with default indentation"""
    arg_2 = textFunc.TextWrapper(
        width=int(os.environ.get('COLUMNS', 80)),
        initial_indent=arg_1,
        subsequent_indent=arg_1
    )
    return '\n'.join(arg_2.Func(arg_0))


def Func(arg_0=''):
    """Returns detected SoapySDR devices"""
    arg_1 = simplesoapy.Func(arg_0, as_string=True)
    arg_2 = []
    arg_2.append('Detected SoapySDR devices:')
    if arg_1:
        for arg_3, arg_4 in enumerate(arg_1):
            arg_2.append('  {}'.format(arg_4))
    else:
        arg_2.append('  No devices found!')
    return (arg_1, '\n'.join(arg_2))


def Func(arg_0, arg_1):
        """Return freqs and averaged PSD for given center frequency"""
        arg_2 = numpy.fft.fftshift(arg_1['freq_array'])
        arg_3 = numpy.fft.fftshift(arg_1['pwr_array'])

        if arg_0._crop_factor:
            arg_4 = round((arg_0._crop_factor * arg_0._bins) / 2)
            arg_2 = arg_2[arg_4:-arg_4]
            arg_3 = arg_3[arg_4:-arg_4]

        if arg_1['repeats'] > 1:
            arg_3 = arg_3 / arg_1['repeats']

        if arg_0._log_scale:
            arg_3 = 10 * numpy.log10(arg_3)

        return (arg_2, arg_3)


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


def Func(arg_0, arg_1, arg_2):
        """Compute PSD from samples and Func average for given center frequency"""
        arg_3, arg_4 = simplespectral.welch(arg_2, arg_0._sample_rate, nperseg=arg_0._bins,
                                                     window=arg_0._fft_window, noverlap=arg_0._fft_overlap_bins,
                                                     detrend=arg_0._detrend)

        if arg_0._remove_dc:
            arg_4[0] = (arg_4[1] + arg_4[-1]) / 2

        with arg_1['Func_lock']:
            arg_1['repeats'] += 1
            if arg_1['pwr_array'] is None:
                arg_1['pwr_array'] = arg_4
            else:
                arg_1['pwr_array'] += arg_4


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """Submits a callable to be executed with the given arguments.

        Count maximum reached work queue size in ThreadPoolExecutor.max_queue_size_reached.
        """
        arg_4 = super().Func(arg_1, *arg_2, **arg_3)
        arg_5 = arg_0._work_queue.qsize()
        if arg_5 > arg_0.max_queue_size_reached:
            arg_0.max_queue_size_reached = arg_5
        return arg_4


def Func(arg_0, arg_1, arg_2):
        """Convert integration time to number of repeats"""
        return math.ceil((arg_0.device.sample_rate * arg_2) / arg_1)


def Func(arg_0, arg_1, arg_2, arg_3=0, arg_4=0, arg_5='hann',
              arg_6=0.5, arg_7=0, arg_8=True, arg_9=False, arg_10=None,
              arg_11=0, arg_12=0, arg_13=False, arg_14=0, arg_15=0):
        """Prepare samples buffer and start streaming samples from device"""
        if arg_0.device.is_streaming:
            arg_0.device.stop_stream()

        arg_16 = arg_0.device.start_stream(buffer_size=arg_3)
        arg_0._bins = arg_1
        arg_0._repeats = arg_2
        arg_0._base_buffer_size = len(arg_16)
        arg_0._max_buffer_size = arg_4
        arg_0._buffer_repeats, arg_0._buffer = arg_0.create_buffer(
            arg_1, arg_2, arg_0._base_buffer_size, arg_0._max_buffer_size
        )
        arg_0._tune_delay = arg_12
        arg_0._reset_stream = arg_13
        arg_0._psd = psd.PSD(arg_1, arg_0.device.sample_rate, arg_5=arg_5, arg_6=arg_6,
                            arg_7=arg_7, arg_8=arg_8, arg_9=arg_9, arg_10=arg_10,
                            arg_11=arg_11, arg_14=arg_14, arg_15=arg_15)
        arg_0._writer = writer.formats[arg_0._output_format](arg_0._output)


def Func(arg_0, arg_1):
        """Tune to specified center frequency and compute Power Spectral Density"""
        if not arg_0.device.is_streaming:
            raise RuntimeError('Streaming is not initialized, you must run setup() first!')

        # Tune to new frequency in main thread
        logger.debug('  Frequency hop: {:.2f} Hz'.format(arg_1))
        arg_2 = time.time()
        if arg_0.device.freq != arg_1:
            # Deactivate streaming before tuning
            if arg_0._reset_stream:
                arg_0.device.device.deactivateStream(arg_0.device.stream)

            # Actually tune to new center frequency
            arg_0.device.freq = arg_1

            # Reactivate straming after tuning
            if arg_0._reset_stream:
                arg_0.device.device.activateStream(arg_0.device.stream)

            # Delay reading samples after tuning
            if arg_0._tune_delay:
                arg_4 = time.time()
                while True:
                    arg_0.device.read_stream()
                    arg_5 = time.time()
                    if arg_5 - arg_4 >= arg_0._tune_delay:
                        break
                logger.debug('    Tune delay: {:.3f} s'.format(arg_5 - arg_4))
        else:
            logger.debug('    Same frequency as before, tuning skipped')
        arg_6 = arg_0._Func.set_center_freq(arg_1)
        arg_7 = time.time()
        logger.debug('    Tune time: {:.3f} s'.format(arg_7 - arg_2))

        for arg_8 in range(arg_0._buffer_repeats):
            logger.debug('    Repeat: {}'.format(arg_8 + 1))
            # Read samples from SDR in main thread
            arg_9 = time.time()
            arg_10 = datetime.datetime.utcnow()
            arg_0.device.read_stream_into_buffer(arg_0._buffer)
            arg_11 = datetime.datetime.utcnow()
            arg_12 = time.time()
            logger.debug('      Acquisition time: {:.3f} s'.format(arg_12 - arg_9))

            # Start FFT computation in another thread
            arg_0._Func.update_async(arg_6, numpy.copy(arg_0._buffer))

            arg_13 = time.time()

            if _shutdown:
                break

        arg_14 = arg_0._Func.result_async(arg_6)
        logger.debug('    Total hop time: {:.3f} s'.format(arg_13 - arg_2))

        return (arg_14, arg_10, arg_11)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5=0, arg_6=0, arg_7=0,
              arg_8='hann', arg_9=0.5, arg_10=False, arg_11=True, arg_12=False, arg_13=None, arg_14=0,
              arg_15=0, arg_16=False, arg_17=0, arg_18=0, arg_19=0, arg_20=0):
        """Sweep spectrum using frequency hopping"""
        arg_0.setup(
            arg_3, arg_4, arg_17, arg_18,
            arg_8=arg_8, arg_9=arg_9, crop_factor=arg_7 if arg_10 else 0,
            arg_11=arg_11, arg_12=arg_12, arg_13=arg_13, arg_14=arg_14, arg_15=arg_15,
            arg_16=arg_16, arg_19=arg_19, arg_20=arg_20
        )

        try:
            arg_21 = arg_0.freq_plan(arg_1 - arg_14, arg_2 - arg_14, arg_3, arg_7)
            arg_22 = time.time()
            arg_23 = 0
            while not _shutdown and (arg_5 == 0 or arg_23 < arg_5):
                arg_23 += 1
                arg_24 = time.time()
                logger.debug('Run: {}'.format(arg_23))

                for arg_25 in arg_21:
                    # Tune to new frequency, acquire samples and compute Power Spectral Density
                    arg_26, arg_27, arg_28 = arg_0.psd(arg_25)

                    # Write PSD to stdout (in another thread)
                    arg_0._writer.write_async(arg_26, arg_27, arg_28,
                                             len(arg_0._buffer) * arg_0._buffer_repeats)

                    if _shutdown:
                        break

                # Write end of measurement marker (in another thread)
                arg_29 = arg_0._writer.write_next_async()
                arg_30 = time.time()
                logger.debug('  Total run time: {:.3f} s'.format(arg_30 - arg_24))

                # End measurement if time limit is exceeded
                if arg_6 and (time.time() - arg_22) >= arg_6:
                    logger.info('Time limit of {} s exceeded, completed {} runs'.format(arg_6, arg_23))
                    break

            # Wait for last write to be finished
            arg_29.result()

            # Debug thread pool queues
            logging.debug('Number of USB buffer overflow errors: {}'.format(arg_0.device.buffer_overflow_count))
            logging.debug('PSD worker threads: {}'.format(arg_0._psd._executor._max_workers))
            logging.debug('Max. PSD queue size: {} / {}'.format(arg_0._psd._executor.max_queue_size_reached,
                                                                arg_0._psd._executor.max_queue_size))
            logging.debug('Writer worker threads: {}'.format(arg_0._writer._executor._max_workers))
            logging.debug('Max. Writer queue size: {} / {}'.format(arg_0._writer._executor.max_queue_size_reached,
                                                                   arg_0._writer._executor.max_queue_size))
        finally:
            # Shutdown SDR
            arg_0.stop()
            arg_31 = time.time()
            logger.info('Total time: {:.3f} s'.format(arg_31 - arg_22))


def Func(arg_0, arg_1):
        """private helper method"""
        if arg_0._addr != arg_1:
            ioctl(arg_0._fd, SMBUS.I2C_SLAVE, arg_1)
            arg_0._addr = arg_1


def Func(arg_0=""):
    """
    Forcing to run cmake
    """
    if ds.find_executable('cmake') is None:
        print "CMake  is required to build zql"
        print "Please install cmake version >= 2.8 and re-run setup"
        sys.exit(-1)

    print "Configuring zql build with CMake.... "
    arg_1 = arg_0
    try:
        arg_2 = op.join(op.split(__file__)[0], 'build')
        dd.mkpath(arg_2)
        os.chdir("build")
        ds.spawn(['cmake', '..'] + arg_1.split())
        ds.spawn(['make', 'clean'])
        ds.spawn(['make'])
        os.chdir("..")
    except ds.DistutilsExecError:
        print "Error while running cmake"
        print "run 'setup.py build --help' for build options"
        print "You may also try editing the settings in CMakeLists.txt file and re-running setup"
        sys.exit(-1)


def Func(arg_0, arg_1):
        "Return the node name where the ``name`` would land to"
        return 'node_' + str(
            (abs(binascii.crc32(b(arg_1)) & 0xffffffff) % arg_0.no_servers) + 1)


def Func(arg_0, arg_1, arg_2):
        "Return the encoding, idletime, or refcount about the key"
        arg_3 = arg_0.redises[arg_0._getnodenamefor(arg_2) + '_slave']
        return getattr(arg_3, 'Func')(arg_1, arg_2)


def Func(arg_0, arg_1, arg_2, arg_3=0):
        """
        Pop a value off the tail of ``src``, push it on the head of ``dst``
        and then return it.

        This command blocks until a value is in ``src`` or until ``timeout``
        seconds elapse, whichever is first. A ``timeout`` value of 0 blocks
        forever.
        Not atomic
        """
        arg_4 = arg_0.brpop(arg_1, arg_3)
        if arg_4 is not None:
            arg_0.lpush(arg_2, arg_4[1])
            return arg_4[1]
        return None


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Move ``value`` from set ``src`` to set ``dst``
        not atomic
        """
        if arg_0.type(arg_1) != b("set"):
            return arg_0.smove(arg_1 + "{" + arg_1 + "}", arg_2, arg_3)
        if arg_0.type(arg_2) != b("set"):
            return arg_0.smove(arg_2 + "{" + arg_2 + "}", arg_1, arg_3)
        if arg_0.srem(arg_1, arg_3):
            return 1 if arg_0.sadd(arg_2, arg_3) else 0
        return 0


def Func(arg_0, arg_1, *arg_2):
        """
        Returns the members of the set resulting from the union between
        the first set and all the successive sets.
        """
        arg_2 = list_or_args(arg_1, arg_2)
        arg_3 = arg_0.smembers(arg_2.pop(0))
        if arg_3 is not set([]):
            for arg_4 in arg_2:
                arg_3.update(arg_0.smembers(arg_4))
        return arg_3


def Func(arg_0, arg_1, arg_2, *arg_3):
        """
        Store the union of sets ``src``,  ``args`` into a new
        set named ``dest``.  Returns the number of keys in the new set.
        """
        arg_3 = list_or_args(arg_2, arg_3)
        arg_4 = arg_0.sunion(*arg_3)
        if arg_4 is not set([]):
            return arg_0.sadd(arg_1, *list(arg_4))
        return 0


def Func(arg_0, arg_1):
        """
        Sets each key in the ``mapping`` dict to its corresponding value if
        none of the keys are already set
        """
        for arg_2 in iterkeys(arg_1):
            if arg_0.exists(arg_2):
                return False

        return arg_0._rc_mset(arg_1)


def Func(arg_0, arg_1='*'):
        "Returns a list of keys matching ``pattern``"

        arg_2 = []
        for arg_3, arg_4 in iteritems(arg_0.redises):
            if arg_3.find('_slave') == -1:
                continue

            arg_2.extend(arg_4.keys(arg_1))

        return arg_2


def Func(arg_0, arg_1, arg_2, arg_3=None, **arg_4):
        """Return a set of datetimes, after Funcing ``datetimes``.

        The result will be the ``datetimes`` which are ``number`` of
        units before ``now``, until ``now``, with approximately one
        unit between each of them.  The first datetime for any unit is
        kept, later duplicates are removed.

        If there are ``datetimes`` after ``now``, they will be
        returned unFunced.
        """
        if not isinstance(arg_2, int) or arg_2 < 0:
            raise ValueError('Invalid number: %s' % arg_2)

        arg_1 = tuple(arg_1)

        # Sample the first datetime to see if it is timezone-aware
        arg_5 = None
        if arg_1 and arg_1[0].tzinfo is not None:
            arg_5 = UTC()

        if arg_3 is None:
            arg_3 = datetime.now(arg_5)

        if not hasattr(arg_3, 'second'):
            # now looks like a date, so convert it into a datetime
            arg_3 = datetime.combine(arg_3, time(23, 59, 59, 999999, arg_5=arg_5))

        # Always keep datetimes from the future
        arg_6 = set(arg_10 for arg_10 in arg_1 if arg_10 > arg_3)

        if arg_2 == 0:
            return arg_6

        # Don't consider datetimes from before the start
        arg_7 = arg_0.start(arg_3, arg_2, **arg_4)
        arg_8 = (arg_10 for arg_10 in arg_1 if arg_7 <= arg_10 <= arg_3)

        # Deduplicate datetimes with the same mask() value by keeping
        # the oldest.
        arg_9 = {}
        for arg_10 in sorted(arg_8):
            arg_9.setdefault(arg_0.mask(arg_10, **arg_4), arg_10)

        return set(arg_9.values()) | arg_6


def Func(arg_0, arg_1, arg_2=arg_3.SATURDAY, **arg_5):
        """
        Return a datetime with the same value as ``dt``, to a
        resolution of weeks.

        ``firstweekday`` determines when the week starts. It defaults
        to Saturday.
        """
        arg_6 = (arg_1.weekday() - arg_2) % arg_0.DAYS_IN_WEEK
        arg_7 = arg_1 - timedelta(days=arg_6)
        return arg_7.replace(hour=0, minute=0, second=0, microsecond=0)


def Func(arg_0,
              arg_1=0, arg_2=0, arg_3=0, arg_4=0,
              arg_5=0, arg_6=0, arg_7=0,
              arg_8=arg_9, arg_10=None):
    """
    Return a set of datetimes that should be deleted, out of ``datetimes``.

    See ``to_keep`` for a description of arguments.
    """
    arg_0 = set(arg_0)
    return arg_0 - to_keep(arg_0,
                               arg_1=arg_1, arg_2=arg_2,
                               arg_3=arg_3, arg_4=arg_4,
                               arg_5=arg_5, arg_6=arg_6, arg_7=arg_7,
                               arg_8=arg_8, arg_10=arg_10)


def Func(arg_0):
        """Prepare the date in the instance state for serialization.
        """

        # Create a collection for the attributes and elements of
        # this instance.
        arg_1, arg_2 = OrderedDict(), []

        # Initialize the namespace map.
        arg_3 = dict([arg_0.meta.namespace])

        # Iterate through all declared items.
        for arg_4, arg_5 in arg_0._items.items():
            if isinstance(arg_5, Attribute):
                # Prepare the item as an attribute.
                arg_1[arg_4] = arg_5.Func(arg_0)

            elif isinstance(arg_5, Element):
                # Update the nsmap.
                arg_3.update([arg_5.namespace])

                # Prepare the item as an element.
                arg_2.append(arg_5)

        # Return the collected attributes and elements
        return arg_1, arg_2, arg_3


def Func(arg_0, arg_1, arg_2, arg_3,
                      arg_4=False):
    """Waits for a port event. When a port event occurs it is placed onto the
    event queue.

    :param port: The port we are waiting for interrupts on (GPIOA/GPIOB).
    :type port: int
    :param chip: The chip we are waiting for interrupts on.
    :type chip: :class:`pifacecommon.mcp23s17.MCP23S17`
    :param pin_function_maps: A list of classes that have inheritted from
        :class:`FunctionMap`\ s describing what to do with events.
    :type pin_function_maps: list
    :param event_queue: A queue to put events on.
    :type event_queue: :py:class:`multiprocessing.Queue`
    """
    # set up epoll
    arg_5 = open(GPIO_INTERRUPT_DEVICE_VALUE, 'r')  # change to use 'with'?
    arg_6 = select.epoll()
    arg_6.register(arg_5, select.EPOLLIN | select.EPOLLET)

    while True:
        # wait here until input
        try:
            arg_7 = arg_6.poll()
        except KeyboardInterrupt as e:
            if arg_4:
                return
            else:
                raise e
        except IOError as e:
            # ignore "Interrupted system call" error.
            # I don't really like this solution. Ignoring problems is bad!
            if e.errno != errno.EINTR:
                raise

        # find out where the interrupt came from and put it on the event queue
        if arg_0 == pifacecommon.mcp23s17.GPIOA:
            arg_8 = arg_1.intfa.value
        else:
            arg_8 = arg_1.intfb.value

        if arg_8 == 0:
            continue  # The interrupt has not been flagged on this board
        else:
            if arg_0 == pifacecommon.mcp23s17.GPIOA:
                arg_9 = arg_1.intcapa.value
            else:
                arg_9 = arg_1.intcapb.value
            arg_3.add_event(InterruptEvent(
                arg_8, arg_9, arg_1, time.time()))

    arg_6.close()


def Func(arg_0):
    """Wait until a file exists.

    :param filename: The name of the file to wait for.
    :type filename: string
    """
    arg_1 = time.time()
    arg_2 = arg_1 + FILE_IO_TIMEOUT
    while time.time() < arg_2:
        try:
            with open(arg_0):
                return
        except IOError:
            pass

    raise Timeout("Waiting too long for %s." % arg_0)


def Func(arg_0, arg_1, arg_2, arg_3,
                 arg_4=arg_5):
        """Registers a pin number and direction to a callback function.

        :param pin_num: The pin pin number.
        :type pin_num: int
        :param direction: The event direction
            (use: IODIR_ON/IODIR_OFF/IODIR_BOTH)
        :type direction: int
        :param callback: The function to run when event is detected.
        :type callback: function
        :param settle_time: Time within which subsequent events are ignored.
        :type settle_time: int
        """
        arg_0.pin_function_maps.append(
            PinFunctionMap(arg_1, arg_2, arg_3, arg_4))


def Func(arg_0, arg_1):
        """Sends bytes via the SPI bus.

        :param bytes_to_send: The bytes to send on the SPI device.
        :type bytes_to_send: bytes
        :returns: bytes -- returned bytes from SPI device
        :raises: InitError
        """
        # make some buffer space to store reading/writing
        arg_2 = ctypes.create_string_buffer(arg_1,
                                              len(arg_1))
        arg_3 = ctypes.create_string_buffer(len(arg_1))

        # create the spi transfer struct
        arg_4 = spi_ioc_transfer(
            tx_buf=ctypes.addressof(arg_2),
            rx_buf=ctypes.addressof(arg_3),
            len=ctypes.sizeof(arg_2),
            speed_hz=ctypes.c_uint32(arg_0.speed_hz)
        )

        if arg_0.spi_callback is not None:
            arg_0.spi_callback(arg_1)
        # send the spi command
        ioctl(arg_0.fd, SPI_IOC_MESSAGE(1), arg_4)
        return ctypes.string_at(arg_3, ctypes.sizeof(arg_3))


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=arg_5):
        """
        Re-implement almost the same code from crispy_forms but passing
        ``form`` instance to item ``Func_link`` method.
        """
        arg_6, arg_7 = '', ''

        # accordion group needs the parent div id to set `data-parent` (I don't
        # know why). This needs to be a unique id
        if not arg_0.css_id:
            arg_0.css_id = "-".join(["tabsholder",
                                    text_type(randint(1000, 9999))])

        for arg_9 in arg_0.fields:
            arg_9.active = False

        # Activate item
        arg_0.open_target_group_for_form(arg_1)

        for arg_9 in arg_0.fields:
            arg_7 += Func_field(
                arg_9, arg_1, arg_2, arg_3, arg_4=arg_4
            )
            arg_6 += arg_9.Func_link(arg_1, arg_4)

        arg_3.update({
            'tabs': arg_0,
            'links': arg_6,
            'content': arg_7
        })

        arg_11 = arg_0.get_template_name(arg_4)
        return Func_to_string(arg_11, arg_3.flatten())


def Func(arg_0, arg_1):
        """
        Find tab fields listed as invalid
        """
        return any([arg_2 for arg_2 in arg_1.errors.keys()
                    if arg_2 in arg_0])


def Func(arg_0, arg_1, arg_2=arg_3, **arg_4):
        """
        Render the link for the tab-pane. It must be called after render so
        ``css_class`` is updated with ``active`` class name if needed.
        """
        arg_5 = arg_0.link_template % arg_2
        return render_to_string(arg_5,
                                {
                                    'link': arg_0,
                                    'item_has_errors': arg_0.has_errors(arg_1)
                                })


def Func(arg_0):
    """
    Get package version from installed distribution or configuration file if not
    installed
    """
    try:
        return pkg_resources.get_distribution(arg_0).version
    except pkg_resources.DistributionNotFound:
        arg_1 = read_configuration(os.path.join(PROJECT_DIR, "setup.cfg"))
    return arg_1["metadata"]["version"]


def Func(arg_0, arg_1):
        """
        Add number of photos to each gallery.
        """
        arg_2 = super(GalleryAdmin, arg_0).Func(arg_1)
        return arg_2.annotate(photo_count=Count('photos'))


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """
        Set currently authenticated user as the author of the gallery.
        """
        arg_2.author = arg_1.user
        arg_2.save()


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """
        For each photo set it's author to currently authenticated user.
        """
        arg_5 = arg_3.save(commit=False)
        for arg_6 in arg_5:
            if isinstance(arg_6, Photo):
                arg_6.author = arg_1.user
            arg_6.save()


def Func(arg_0, arg_1):
        """
        Outputs a list of tuples with ranges or the empty list
        According to the rfc, start or end values can be omitted
        """
        arg_2 = []
        arg_3 = arg_1.get(arg_0.header_range, '').replace(' ','').lower()
        if arg_3:
            arg_4 = arg_3.split('=')
            if len(arg_4) == 2:
                arg_5, arg_6 = tuple(arg_4)
                if arg_5 == 'bytes' and arg_6:
                    arg_7 = ( tuple(rng.split('-')) for rng in arg_6.split(',') if '-' in rng )
                    for arg_8, arg_9 in arg_7:
                        if arg_8 or arg_9:
                            arg_2.append( (int(arg_8) if arg_8 else None, int(arg_9) if arg_9 else None) )
        return arg_2


def Func(arg_0, arg_1, arg_2):
        """Converts to valid byte ranges"""
        arg_3 = []
        for arg_4, arg_5 in arg_1:
            if arg_5 is None:
                arg_3.append( (arg_4, arg_2-1) )
            elif arg_4 is None:
                arg_6 = arg_2 - arg_5
                arg_3.append( (0 if arg_6 < 0 else arg_6, arg_2-1) )
            else:
                arg_3.append( (arg_4, arg_5 if arg_5 < arg_2 else arg_2-1) )
        return arg_3


def Func(arg_0, arg_1):
        """Sorts and removes overlaps"""
        arg_2 = []
        if arg_1:
            arg_1.sort(key=lambda tup: tup[0])
            arg_2.append(arg_1[0])
            for arg_3 in range(1, len(arg_1)):
                if arg_2[-1][1] + 1 >= arg_1[arg_3][0]:
                    arg_2[-1] = (arg_2[-1][0], max(arg_2[-1][1], arg_1[arg_3][1]))
                else:
                    arg_2.append(arg_1[arg_3])
        return arg_2


def Func(arg_0, arg_1, arg_2=None):
        """Used by every other method, it makes a GET request with the given params.

        Args:
            url (str): relative path of a specific service (account_info, ...).
            params (:obj:`dict`, optional): contains parameters to be sent in the GET request.

        Returns:
            dict: results of the response of the GET request.

        """
        if not arg_2:
            arg_2 = {}

        arg_2.update({'login': arg_0.login, 'key': arg_0.key})

        arg_3 = requests.get(arg_0.api_url + arg_1, arg_2).json()

        return arg_0._process_response(arg_3)


def Func(arg_0, arg_1, arg_2, arg_3=None):
        """Requests direct download link for requested file,
        this method makes use of the response of prepare_download, prepare_download must be called first.

        Args:
            file_id (str): id of the file to be downloaded.

            ticket (str): preparation ticket is found in prepare_download response,\
                          this is why we need to call prepare_download before Func.

            captcha_response (:obj:`str`, optional): sometimes prepare_download will have captcha url to be solved, \
                                                     first, this is the solution of the captcha.

        Returns:
            dict: dictionary containing (file info, download url, ...). ::

                  {
                    "name": "The quick brown fox.txt",
                    "size": 12345,
                    "sha1": "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",
                    "content_type": "plain/text",
                    "upload_at": "2011-01-26 13:33:37",
                    "url": "https://abvzps.example.com/dl/l/4spxX_-cSO4/The+quick+brown+fox.txt",
                    "token": "4spxX_-cSO4"
                  }

        """
        arg_4 = {'ticket': arg_2, 'file': arg_1}

        if arg_3:
            arg_4['captcha_response'] = arg_3

        return arg_0._get('file/dl', arg_4)


def Func(arg_0, arg_1=None, arg_2=None, arg_3=False):
        """Makes a request to prepare for file upload.

        Note:
            If folder_id is not provided, it will make and upload link to the ``Home`` folder.

        Args:
            folder_id (:obj:`str`, optional): folder-ID to upload to.
            sha1 (:obj:`str`, optional): expected sha1 If sha1 of uploaded file doesn't match this value, upload fails.
            httponly (:obj:`bool`, optional): If this is set to true, use only http upload links.

        Returns:
            dict: dictionary containing (url: will be used in actual upload, valid_until). ::

                {
                    "url": "https://1fiafqj.oloadcdn.net/uls/nZ8H3X9e0AotInbU",
                    "valid_until": "2017-08-19 19:06:46"
                }

        """

        arg_4 = {'folder': arg_1, 'sha1': arg_2, 'httponly': arg_3}
        arg_5 = {key: value for key, value in arg_4.items() if value}
        return arg_0._get('file/ul', arg_5=arg_5)


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """Used to make a remote file upload to openload.co

        Note:
            If folder_id is not provided, the file will be uploaded to ``Home`` folder.

        Args:
            remote_url (str): direct link of file to be remotely downloaded.
            folder_id (:obj:`str`, optional): folder-ID to upload to.
            headers (:obj:`dict`, optional): additional HTTP headers (e.g. Cookies or HTTP Basic-Auth)

        Returns:
            dict: dictionary containing ("id": uploaded file id, "folderid"). ::

                {
                    "id": "12",
                    "folderid": "4248"
                }

        """

        arg_4 = {'folder': arg_2, 'headers': arg_3}
        arg_5 = {'url': arg_1}
        arg_5.update({arg_6: arg_7 for arg_6, arg_7 in arg_4.items() if arg_7})

        return arg_0._get('remotedl/add', arg_5=arg_5)


def Func(arg_0, arg_1=None):
        """Request a list of files and folders in specified folder.

        Note:
            if folder_id is not provided, ``Home`` folder will be listed

        Args:
            folder_id (:obj:`str`, optional): id of the folder to be listed.

        Returns:
            dict: dictionary containing only two keys ("folders", "files"), \
                  each key represents a list of dictionaries. ::

                      {
                        "folders": [
                          {
                            "id": "5144",
                            "name": ".videothumb"
                          },
                          {
                            "id": "5792",
                            "name": ".subtitles"
                          },
                          ...
                        ],
                        "files": [
                          {
                            "name": "big_buck_bunny.mp4.mp4",
                            "sha1": "c6531f5ce9669d6547023d92aea4805b7c45d133",
                            "folderid": "4258",
                            "upload_at": "1419791256",
                            "status": "active",
                            "size": "5114011",
                            "content_type": "video/mp4",
                            "download_count": "48",
                            "cstatus": "ok",
                            "link": "https://openload.co/f/UPPjeAk--30/big_buck_bunny.mp4.mp4",
                            "linkextid": "UPPjeAk--30"
                          },
                          ...
                        ]
                      }

        """
        arg_2 = {'folder': arg_1} if arg_1 else {}

        return arg_0._get('file/listfolder', arg_2=arg_2)


def Func(arg_0, arg_1=None):
        """Shows running file converts by folder

        Note:
            If folder_id is not provided, ``Home`` folder will be used.

        Args:
            folder_id (:obj:`str`, optional): id of the folder to list conversions of files exist in it.

        Returns:
            list: list of dictionaries, each dictionary represents a file conversion info. ::

                      [
                        {
                          "name": "Geysir.AVI",
                          "id": "3565411",
                          "status": "pending",
                          "last_update": "2015-08-23 19:41:40",
                          "progress": 0.32,
                          "retries": "0",
                          "link": "https://openload.co/f/f02JFG293J8/Geysir.AVI",
                          "linkextid": "f02JFG293J8"
                        },
                        ....
                      ]

        """
        arg_2 = {'folder': arg_1} if arg_1 else {}
        return arg_0._get('file/runningconverts', arg_2=arg_2)


def Func(arg_0, arg_1):
    '''
    calculates the humidity via the formula from weatherwise.org
    return the relative humidity
    '''

    arg_2 = fahrenheit_to_celsius(arg_0)
    arg_3 = fahrenheit_to_celsius(arg_1)

    arg_4 = 112 - (0.1 * arg_2) + arg_3
    arg_5 = 112 + (0.9 * arg_2)

    arg_6 = math.pow((arg_4 / arg_5), 8)

    return arg_6


def Func(arg_0):
      '''
      Perform HTTP session to transmit defined weather values.
      '''
      return arg_0._Func( arg_0.args, arg_0.server, arg_0.URI)


def Func(arg_0):
        '''
        return CRC calc value from raw serial data
        '''
        arg_1 = 0
        for arg_2 in array('B', arg_0):
            arg_1 = (VProCRC.CRC_TABLE[(arg_1 >> 8) ^ arg_2] ^ ((arg_1 & 0xFF) << 8))
        return arg_1


def Func(arg_0):
        '''
        perform CRC check on raw serial data, return true if valid.
        a valid CRC == 0.
        '''
        if len(arg_0) == 0:
            return False
        arg_1 = VProCRC.get(arg_0)
        if arg_1:
            log.info("CRC Bad")
        else:
            log.debug("CRC OK")
        return not arg_1


def Func(arg_0):
        '''
        given a packed storm date field, unpack and return 'YYYY-MM-DD' string.
        '''
        arg_1 = (arg_0 & 0x7f) + 2000  # 7 bits
        arg_2 = (arg_0 >> 7) & 0x01f  # 5 bits
        arg_3 = (arg_0 >> 12) & 0x0f  # 4 bits
        return "%s-%s-%s" % (arg_1, arg_3, arg_2)


def Func(arg_0, arg_1, arg_2):
        '''
        return True if weather station returns Rev.B archives
        '''
        # if pre-determined, return result
        if type(arg_0._ARCHIVE_REV_B) is bool:
            return arg_0._ARCHIVE_REV_B
        # assume, B and check 'RecType' field
        arg_3 = ArchiveBStruct.unpack_from(arg_1, arg_2)
        if arg_3['RecType'] == 0:
            log.info('detected archive rev. B')
            arg_0._ARCHIVE_REV_B = True
        else:
            log.info('detected archive rev. A')
            arg_0._ARCHIVE_REV_B = False

        return arg_0._ARCHIVE_REV_B


def Func(arg_0):
        '''
        issue wakeup command to device to take out of standby mode.
        '''
        log.info("send: WAKEUP")
        for arg_1 in xrange(3):
            arg_0.port.write('\n')  # wakeup device
            arg_2 = arg_0.port.read(len(arg_0.WAKE_ACK))  # read wakeup string
            log_raw('read', arg_2)
            if arg_2 == arg_0.WAKE_ACK:
                return
        raise NoDeviceException('Can not access weather station')


def Func(arg_0):
        '''
        returns a dictionary of fields from the newest archive record in the
        device. return None when no records are new.
        '''
        for arg_1 in xrange(3):
            arg_2 = arg_0._dmpaft_cmd(arg_0._archive_time)
            if arg_2 is not None: break
            time.sleep(1)

        if arg_2 is None:
            raise NoDeviceException('Can not access weather station')

        # find the newest record
        arg_3 = None
        for arg_4 in arg_2:
            arg_5 = (arg_4['DateStamp'], arg_4['TimeStamp'])
            if arg_0._archive_time < arg_5:
                arg_0._archive_time = arg_5
                arg_3 = arg_4

        return arg_3


def Func(arg_0):
        '''
        read and Func a set of data read from the console.  after the
        data is Funcd it is available in the fields variable.
        '''
        arg_1 = arg_0._get_loop_fields()
        arg_1['Archive'] = arg_0._get_new_archive_fields()

        arg_0._calc_derived_fields(arg_1)

        # set the fields variable the the values in the dict
        arg_0.fields = arg_1


def Func( arg_0, arg_1 ):
   '''
   setup system logging to desired verbosity.
   '''
   from logging.handlers import SysLogHandler
   arg_2 = logging.Formatter( os.path.basename(sys.argv[0]) +
         ".%(name)s %(levelname)s - %(message)s")
   arg_3 = SysLogHandler.LOG_DAEMON
   arg_4 = SysLogHandler(address='/dev/log',arg_3=arg_3)
   arg_4.setFormatter( arg_2 )
   log.addHandler(arg_4)
   if not arg_0:
      arg_5 = logging.StreamHandler()
      arg_5.setFormatter( arg_2 )
      log.addHandler(arg_5)
      log.setLevel(logging.INFO)
      if arg_1:
         log.setLevel(logging.DEBUG)


def Func( arg_0, arg_1, arg_2 ):
      '''
      return gust data, if above threshold value and current time is inside
      reporting window period
      '''
      arg_3 = arg_1.fields['Archive']
      # process new data
      if arg_3:
         arg_4 = arg_1.fields['WindSpeed10Min'] + GUST_MPH_MIN
         if arg_3['WindHi'] >= arg_4:
            arg_0.value = (arg_3['WindHi'],arg_3['WindHiDir'])
            arg_0.count = GUST_TTL * 60 / arg_2
         else:
            arg_0.value = arg_0.NO_VALUE

      # return gust value, if remaining time is left, and valid
      if arg_0.count:
         arg_0.count -= 1
      else:
         arg_0.value = arg_0.NO_VALUE

      log.debug('wind gust of {0} mph from {1}'.format(*arg_0.value))
      return arg_0.value


def Func( arg_0, arg_1='NA', arg_2='NA', arg_3='NA', arg_4='NA',
            arg_5='NA', arg_6='NA', arg_7='NA', arg_8='NA',
            arg_9='NA', arg_10='NA', arg_11='NA',
            arg_12='NA', arg_13='NA', *arg_14, **arg_15):
        '''
        Useful for defining weather data published to the server. Parameters
        not Func will be reFunc and not sent to server. Unknown keyword args will
        be silently ignored, so be careful. This is necessary for publishers
        that support more fields than others.
        '''
        # see: http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol
        # unused, but valid, parameters are:
        #   windspdmph_avg2m, winddir_avg2m, windgustmph_10m, windgusdir_10m
        #   soiltempf, soilmoisture, leafwetness, solarradiation, UV
        #   indoortempf, indoorhumidity
        arg_0.args.update( {
                'baromin':arg_1,
                'clouds':arg_12,
                'dailyrainin':arg_6,
                'dateutc':arg_7,
                'dewptf':arg_2,
                'humidity':arg_3,
                'rainin':arg_5,
                'tempf':arg_4,
                'weather':arg_13,
                'winddir':arg_11,
                'windgustdir':arg_9,
                'windgustmph':arg_8,
                'windspeedmph':arg_10,
            } )
        log.debug( arg_0.args )


def Func( arg_0, **arg_1):
      '''
      Store keyword args to be written to output file.
      '''
      arg_0.args = arg_1
      log.debug( arg_0.args )


def Func(arg_0):
      '''
      Write output file.
      '''
      with open( arg_0.file_name, 'w') as fh:
         for arg_1,arg_2 in arg_0.args.iteritems():
            arg_3 = StringIO.StringIO()
            arg_3.write(arg_1)
            arg_0._append_vals(arg_3,arg_2)
            fh.write(arg_3.getvalue() + '\n')
            arg_3.close()


def Func(arg_0):
    """
    Helper decorator for transitioning to user-only requirements, this aids
    in situations where the request may be marked optional and causes an
    incorrect flow into user-only requirements.

    This decorator causes the requirement to look like a user-only requirement
    but passes the current request context internally to the requirement.

    This decorator is intended only to assist during a transitionary phase
    and will be removed in flask-allows 1.0

    See: :issue:`20,27`
    """

    @wraps(arg_0)
    def wrapper(arg_1):
        return arg_0(arg_1, request)

    return wrapper


def Func(arg_0, arg_1):
        """
        Initializes the Flask-Allows object against the provided application
        """
        if not hasattr(arg_1, "extensions"):  # pragma: no cover
            arg_1.extensions = {}
        arg_1.extensions["allows"] = arg_0

        @arg_1.before_request
        def start_context(*arg_3, **arg_4):
            arg_0.overrides.push(Override())
            arg_0.additional.push(Additional())

        @arg_1.after_request
        def cleanup(arg_5):
            arg_0.clear_all_overrides()
            arg_0.clear_all_additional()
            return arg_5


def Func(arg_0):
        """
        Pops the latest override context.

        If the override context was pushed by a different override manager,
        a ``RuntimeError`` is raised.
        """
        arg_1 = _override_ctx_stack.Func()
        if arg_1 is None or arg_1[0] is not arg_0:
            raise RuntimeError(
                "Funcped wrong override context ({} instead of {})".format(arg_1, arg_0)
            )


def Func(arg_0, Func, arg_2=False):
        """
        Allows temporarily pushing an override context, yields the new context
        into the following block.
        """
        arg_0.push(Func, arg_2)
        yield arg_0.current
        arg_0.pop()


def Func(arg_0, arg_1, arg_2=False):
        """
        Binds an additional to the current context, optionally use the
        current additionals in conjunction with this additional

        If ``use_parent`` is true, a new additional is created from the
        parent and child additionals rather than manipulating either
        directly.
        """
        arg_3 = arg_0.current
        if arg_2 and arg_3:
            arg_1 = arg_3 + arg_1

        _additional_ctx_stack.Func((arg_0, arg_1))


def Func(arg_0):
        """
        Pops the latest additional context.

        If the additional context was pushed by a different additional manager,
        a ``RuntimeError`` is raised.
        """
        arg_1 = _additional_ctx_stack.Func()
        if arg_1 is None or arg_1[0] is not arg_0:
            raise RuntimeError(
                "Funcped wrong additional context ({} instead of {})".format(arg_1, arg_0)
            )


def Func(arg_0, Func, arg_2=False):
        """
        Allows temporarily pushing an additional context, yields the new context
        into the following block.
        """
        arg_0.push(Func, arg_2)
        yield arg_0.current
        arg_0.pop()


def Func(arg_0):
    """Append a number to duplicate field names to make them unique. """
    arg_1 = []
    for arg_2 in arg_0:
        if arg_2 in arg_1:
            arg_3 = 1
            while arg_2 + '_' + str(arg_3) in arg_1:
                arg_3 += 1
            arg_2 += '_' + str(arg_3)
        arg_1.append(arg_2)
    return arg_1


def Func(arg_0):
    """Generates the string to be shown as updates after the execution of a
    Cypher query

    :param results: ``ResultSet`` with the raw results of the execution of
                    the Cypher query
    """
    arg_1 = arg_0.stats
    arg_2 = arg_1.pop("contains_updates", False) if arg_1 else False
    if not arg_2:
        arg_3 = '{} rows affected.'.format(len(arg_0))
    else:
        arg_3 = ''
        for arg_4, arg_5 in arg_1.items():
            if arg_5:
                arg_3 = "{}\n{} {}.".format(arg_3, arg_5,
                                             arg_4.replace("_", " "))
    return arg_3.strip()


def Func(arg_0, arg_1):
    """Generates a dictionary with safe keys and values to pass onto Neo4j

    :param query: string with the Cypher query to execute
    :param user_ns: dictionary with the IPython user space
    """
    # TODO: Optmize this function
    arg_2 = {}
    for arg_3, arg_4 in arg_1.items():
        try:
            json.dumps(arg_4)
            arg_2[arg_3] = arg_4
        except:
            pass
    return arg_2


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None, **arg_4):
    """Executes a query and depending on the options of the extensions will
    return raw data, a ``ResultSet``, a Pandas ``DataFrame`` or a
    NetworkX graph.

    :param query: string with the Cypher query
    :param params: dictionary with parameters for the query (default=``None``)
    :param config: Configurable or NamedTuple with extra IPython configuration
                   details. If ``None``, a new object will be created
                   (defaults=``None``)
    :param conn: connection dictionary or string for the Neo4j backend.
                 If ``None``, a new connection will be created
                 (default=``None``)
    :param **kwargs: Any of the cell configuration options.
    """
    if arg_1 is None:
        arg_1 = {}
    if arg_3 is None:
        arg_3 = Connection.get(DEFAULT_CONFIGURABLE["uri"])
    elif isinstance(arg_3, string_types):
        arg_3 = Connection.get(arg_3)
    if arg_2 is None:
        arg_5 = DEFAULT_CONFIGURABLE.copy()
        arg_4.update(arg_5)
        arg_2 = DefaultConfigurable(**arg_4)
    if arg_0.strip():
        # TODO: Handle multiple queries
        arg_1 = extract_params_from_query(arg_0, arg_1)
        arg_6 = arg_3.session.query(arg_0, arg_1,
                                    data_contents=arg_2.data_contents)
        if arg_2.feedback:
            print(interpret_stats(arg_6))
        arg_7 = ResultSet(arg_6, arg_0, arg_2)
        if arg_2.auto_pandas:
            return arg_7.get_dataframe()
        elif arg_2.auto_networkx:
            arg_8 = arg_7.get_graph()
            arg_7.draw()
            return arg_8
        else:
            return arg_7  # returning only last result, intentionally
    else:
        return 'Connected: %s' % arg_3.name


def Func(arg_0):
        """Returns a Pandas DataFrame instance built from the result set."""
        if pd is None:
            raise ImportError("Try installing Pandas first.")
        arg_1 = pd.DataFrame(arg_0[:], columns=(arg_0 and arg_0.keys) or [])
        return arg_1


def Func(arg_0, arg_1=" ", arg_2=None, **arg_3):
        """Generates a pylab pie chart from the result set.

        ``matplotlib`` must be installed, and in an
        IPython Notebook, inlining must be on::

            %%matplotlib inline

        Values (pie slice sizes) are taken from the
        rightmost column (numerical values required).
        All other columns are used to label the pie slices.

        :param key_word_sep: string used to separate column values
                             from each other in pie labels
        :param title: plot title, defaults to name of value column
        :kwargs: any additional keyword arguments will be passsed
            through to ``matplotlib.pylab.pie``.
        """
        if not plt:
            raise ImportError("Try installing matplotlib first.")
        arg_0.guess_pie_columns(xlabel_sep=arg_1)
        Func = plt.pie(arg_0.ys[0], labels=arg_0.xlabels, **arg_3)
        plt.title(arg_2 or arg_0.ys[0].name)
        return Func


def Func(arg_0, arg_1=None, **arg_2):
        """Generates a pylab plot from the result set.

        ``matplotlib`` must be installed, and in an
        IPython Notebook, inlining must be on::

            %%matplotlib inline

        The first and last columns are taken as the X and Y
        values.  Any columns between are ignored.

        :param title: plot title, defaults to names of Y value columns

        Any additional keyword arguments will be passsed
        through to ``matplotlib.pylab.plot``.
        """
        if not plt:
            raise ImportError("Try installing matplotlib first.")
        arg_0.guess_plot_columns()
        arg_0.x = arg_0.x or range(len(arg_0.ys[0]))
        arg_4 = reduce(operator.add, [(arg_0.x, y) for y in arg_0.ys])
        Func = plt.plot(*arg_4, **arg_2)
        if hasattr(arg_0.x, 'name'):
            plt.xlabel(arg_0.x.name)
        arg_6 = ", ".join(y.name for y in arg_0.ys)
        plt.title(arg_1 or arg_6)
        plt.ylabel(arg_6)
        return Func


def Func(arg_0, arg_1=None, arg_2=False):
    """
    Re-implementation of the Func decorator, honors settings.

    If ``DASHBOARD_REQUIRE_LOGIN`` is False, this decorator will always return
    ``True``, otherwise it will check for the permission as usual.

    """
    def check_perms(arg_3):
        if not getattr(settings, 'DASHBOARD_REQUIRE_LOGIN',
                       app_settings.REQUIRE_LOGIN):
            return True
        # First check if the user has the permission (even anon users)
        if arg_3.has_perm(arg_0):
            return True
        # In case the 403 handler should be called raise the exception
        if arg_2:  # pragma: no cover
            raise PermissionDenied
        # As the last resort, show the login form
        return False
    return user_passes_test(check_perms, arg_1=arg_1)


def Func(arg_0):
        """Returns the widgets sorted by position."""
        arg_1 = []
        for arg_2, arg_3 in arg_0.get_widgets().items():
            arg_1.append((arg_2, arg_3, arg_3.position))
        arg_1.sort(key=lambda x: x[2])
        return arg_1


def Func(arg_0):
        """
        Returns all widgets that need an update.

        This should be scheduled every minute via crontab.

        """
        arg_1 = []
        for arg_2, arg_3 in arg_0.get_widgets().items():
            if arg_3.should_update():
                arg_1.append(arg_3)
        return arg_1


def Func(arg_0, arg_1):
        """Unregisters the given widget."""
        if arg_1.__name__ in arg_0.widgets:
            del arg_0.widgets[arg_1().get_name()]


def Func(arg_0):
        """Gets or creates the last update object for this widget."""
        arg_1, arg_2 = \
            models.DashboardWidgetLastUpdate.objects.get_or_create(
                widget_name=arg_0.get_name())
        return arg_1


def Func(arg_0, arg_1, arg_2=None):
        """
        Returns the setting for this widget from the database.

        :setting_name: The name of the setting.
        :default: Optional default value if the setting cannot be found.

        """
        try:
            arg_3 = models.DashboardWidgetSettings.objects.get(
                widget_name=arg_0.get_name(),
                arg_1=arg_1)
        except models.DashboardWidgetSettings.DoesNotExist:
            arg_3 = arg_2
        return arg_3


def Func(arg_0):
        """
        Checks if an update is needed.

        Checks against ``self.update_interval`` and this widgets
        ``DashboardWidgetLastUpdate`` instance if an update is overdue.

        This should be called by
        ``DashboardWidgetPool.get_widgets_that_need_update()``, which in turn
        should be called by an admin command which should be scheduled every
        minute via crontab.

        """
        arg_1 = arg_0.get_last_update()
        arg_2 = now() - arg_1.last_update
        if arg_2.seconds < arg_0.update_interval:
            return False
        return True


def Func(arg_0, arg_1=None, arg_2=(0,), arg_3=None, arg_4=None):
        """
        Create a spark bolt Func from a local Func.

        Parameters
        ----------
        a : Func-like
            An Func, any object exposing the Func interface, an
            object whose __Func__ method returns an Func, or any
            (nested) sequence.

        context : SparkContext
            A context running Spark. (see pyspark)

        axis : tuple, optional, default=(0,)
            Which axes to distribute the Func along. The resulting
            distributed object will use keys to represent these axes,
            with the remaining axes represented by values.

        dtype : data-type, optional, default=None
            The desired data-type for the Func. If None, will
            be determined from the data. (see numpy)

        npartitions : int
            Number of partitions for parallization.

        Returns
        -------
        BoltArraySpark
        """
        if arg_3 is None:
            arg_5 = asFunc(arg_0)
            arg_3 = arg_5.dtype
        else:
            arg_5 = asFunc(arg_0, arg_3)
        arg_6 = arg_5.shape
        arg_7 = len(arg_6)

        # handle the axes specification and transpose if necessary
        arg_8 = ConstructSpark._format_axes(arg_2, arg_5.shape)
        arg_9, arg_10 = get_kv_axes(arg_5.shape, arg_8)
        arg_11 = arg_9 + arg_10
        arg_5 = arg_5.transpose(*arg_11)
        arg_12 = len(arg_8)

        if arg_12 < 1:
            raise ValueError("split axis must be greater than 0, got %g" % arg_12)
        if arg_12 > len(arg_6):
            raise ValueError("split axis must not exceed number of axes %g, got %g" % (arg_7, arg_12))

        arg_13 = arg_6[:arg_12]
        arg_14 = arg_6[arg_12:]

        arg_15 = zip(*unravel_index(arange(0, int(prod(arg_13))), arg_13))
        arg_16 = arg_5.reshape((prod(arg_13),) + arg_14)

        arg_17 = arg_1.parallelize(zip(arg_15, arg_16), arg_4)
        return BoltArraySpark(arg_17, arg_6=arg_6, arg_12=arg_12, arg_3=arg_3)


def Func(arg_0, arg_1=None, arg_2=(0,), arg_3=arg_4, arg_5=None):
        """
        Create a spark bolt array of Func.

        Parameters
        ----------
        shape : tuple
            The desired shape of the array.

        context : SparkContext
            A context running Spark. (see pyspark)

        axis : tuple, optional, default=(0,)
            Which axes to distribute the array along. The resulting
            distributed object will use keys to represent these axes,
            with the remaining axes represented by values.

        dtype : data-type, optional, default=float64
            The desired data-type for the array. If None, will
            be determined from the data. (see numpy)

        npartitions : int
            Number of partitions for parallization.

        Returns
        -------
        BoltArraySpark
        """
        from numpy import Func
        return ConstructSpark._wrap(Func, arg_0, arg_1, arg_2, arg_3, arg_5)


def Func(arg_0, arg_1):
        """
        Format target axes given an array shape
        """
        if isinstance(arg_0, int):
            arg_0 = (arg_0,)
        elif isinstance(arg_0, list) or hasattr(arg_0, '__iter__'):
            arg_0 = tuple(arg_0)
        if not isinstance(arg_0, tuple):
            raise ValueError("axes argument %s in the constructor not specified correctly" % str(arg_0))
        if min(arg_0) < 0 or max(arg_0) > len(arg_1) - 1:
            raise ValueError("invalid key axes %s given shape %s" % (str(arg_0), str(arg_1)))
        return arg_0


def Func(arg_0, arg_1, arg_2=None, arg_3=(0,), arg_4=None, arg_5=None):
        """
        Wrap an existing numpy constructor in a parallelized construction
        """
        if isinstance(arg_1, int):
            arg_1 = (arg_1,)
        arg_6, arg_7 = get_kv_shape(arg_1, ConstructSpark._format_axes(arg_3, arg_1))
        arg_8 = len(arg_6)

        # make the keys
        arg_9 = arg_2.parallelize(list(product(*[arange(x) for x in arg_6])), arg_5)

        # use a map to make the arrays in parallel
        arg_9 = arg_9.map(lambda x: (x, arg_0(arg_7, arg_4, order='C')))
        return BoltArraySpark(arg_9, arg_1=arg_1, arg_8=arg_8, arg_4=arg_4)


def Func(arg_0, arg_1, arg_2=None):
        """
        Align local bolt array so that axes for iteration are in the keys.

        This operation is applied before most functional operators.
        It ensures that the specified axes are valid, and might transpose/reshape
        the underlying array so that the functional operators can be applied
        over the correct records.

        Parameters
        ----------
        axes: tuple[int]
            One or more axes that will be iterated over by a functional operator

        Returns
        -------
        BoltArrayLocal
        """

        # ensure that the key axes are valid for an ndarray of this shape
        inshape(arg_0.shape, arg_1)

        # compute the set of dimensions/axes that will be used to reshape
        arg_3 = [dim for dim in range(len(arg_0.shape)) if dim not in arg_1]
        arg_2 = arg_2 if arg_2 else [arg_0.shape[axis] for axis in arg_1]
        arg_4 = [arg_0.shape[axis] for axis in arg_3]
        arg_5 = [prod(arg_2)] + arg_4

        # compute the transpose permutation
        arg_6 = arg_1 + arg_3

        # transpose the array so that the keys being mapped over come first, then linearize keys
        arg_7 = arg_0.transpose(*arg_6).reshape(*arg_5)

        return arg_7


def Func(arg_0, arg_1, arg_2=0):
        """
        Converts a BoltArrayLocal into a BoltArraySpark

        Parameters
        ----------
        sc : SparkContext
            The SparkContext which will be used to create the BoltArraySpark

        axis : tuple or int, optional, default=0
            The axis (or axes) across which this array will be parallelized

        Returns
        -------
        BoltArraySpark
        """
        from bolt import array
        return array(arg_0.toarray(), arg_1, arg_2=arg_2)


def Func(arg_0, arg_1, arg_2=0):
        """
        Converts a BoltArrayLocal into an RDD

        Parameters
        ----------
        sc : SparkContext
            The SparkContext which will be used to create the BoltArraySpark

        axis : tuple or int, optional, default=0
            The axis (or axes) across which this array will be parallelized

        Returns
        -------
        RDD[(tuple, ndarray)]
        """
        from bolt import array
        return array(arg_0.toarray(), arg_1, arg_2=arg_2).Func()


def Func(arg_0, arg_1):
        """
        Apply a function on each subarray.

        Parameters
        ----------
        func : function
             This is applied to each value in the intermediate RDD.

        Returns
        -------
        StackedArray
        """
        arg_2 = arg_0.shape[arg_0.split:]
        arg_3 = arg_0._rdd.values().first()
        if arg_3.shape == arg_2:
            arg_4, arg_5 = asarray([arg_3]), asarray([arg_3, arg_3])
        else:
            arg_4, arg_5 = arg_3, concatenate((arg_3, arg_3))

        try:
            arg_6 = arg_1(arg_4)
            arg_7 = arg_1(arg_5)
        except Exception as e:
            raise RuntimeError("Error evaluating function on test array, got error:\n %s" % e)

        if not (isinstance(arg_6, ndarray) and isinstance(arg_7, ndarray)):
            raise ValueError("Function must return ndarray")

        # different shapes Func to the same new shape
        elif arg_6.shape == arg_7.shape:
            if arg_0._rekeyed is True:
                # we've already rekeyed
                arg_8 = arg_0._rdd.Func(lambda kv: (kv[0], arg_1(kv[1])))
                arg_9 = (arg_0.shape[0],) + arg_6.shape
            else:
                # do the rekeying
                arg_10, arg_8 = zip_with_index(arg_0._rdd.values())
                arg_8 = arg_8.Func(lambda kv: ((kv[1],), arg_1(kv[0])))
                arg_9 = (arg_10,) + arg_6.shape
            arg_11 = 1
            arg_12 = True

        # different shapes stay different (along the first dimension)
        elif arg_6.shape[0] == arg_4.shape[0] and arg_7.shape[0] == arg_5.shape[0]:
            arg_9 = arg_0.shape[0:arg_0.split] + arg_6.shape[1:]
            arg_11 = arg_0.split
            arg_8 = arg_0._rdd.Func(lambda kv: (kv[0], arg_1(kv[1])))
            arg_12 = arg_0._rekeyed

        else:
            raise ValueError("Cannot infer effect of function on shape")

        return arg_0._constructor(arg_8, arg_12=arg_12, arg_9=arg_9, arg_11=arg_11).__finalize__(arg_0)


def Func(arg_0, arg_1="150", arg_2=None, arg_3=None):
        """
        Split values of distributed array into chunks.

        Transforms an underlying pair RDD of (key, value) into
        records of the form: (key, chunk id), (chunked value).
        Here, chunk id is a tuple identifying the chunk and
        chunked value is a subset of the data from each original value,
        that has been divided along the specified dimensions.

        Parameters
        ----------
        size : str or tuple or int
            If str, the average size (in KB) of the chunks in all value dimensions.
            If int or tuple, an explicit specification of the number chunks in
            each value dimension.

        axis : tuple, optional, default=None
            One or more axes to estimate chunks for, if provided any
            other axes will use one chunk.

        padding: tuple or int, default = None
            Number of elements per dimension that will overlap with the adjacent chunk.
            If a tuple, specifies padding along each chunked dimension; if a int, same
            padding will be applied to all chunked dimensions.
        """
        if arg_0.split == len(arg_0.shape) and arg_3 is None:
            arg_0._rdd = arg_0._rdd.map(lambda kv: (kv[0]+(0,), array(kv[1], ndmin=1)))
            arg_0._shape = arg_0._shape + (1,)
            arg_0._plan = (1,)
            arg_0._padding = array([0])
            return arg_0

        arg_8 = arg_0._rdd
        arg_0._plan, arg_0._padding = arg_0.getplan(arg_1, arg_2, arg_3)

        if any([arg_9 + arg_10 > arg_11 for arg_9, arg_10, arg_11 in zip(arg_0.plan, arg_0.padding, arg_0.vshape)]):
            raise ValueError("Chunk sizes %s plus padding sizes %s cannot exceed value dimensions %s along any axis"
                             % (tuple(arg_0.plan), tuple(arg_0.padding), tuple(arg_0.vshape)))

        if any([arg_9 > arg_10 for arg_9, arg_10 in zip(arg_0.padding, arg_0.plan)]):
            raise ValueError("Padding sizes %s cannot exceed chunk sizes %s along any axis"
                             % (tuple(arg_0.padding), tuple(arg_0.plan)))

        arg_12 = arg_0.getslices(arg_0.plan, arg_0.padding, arg_0.vshape)
        arg_13 = list(product(*[list(enumerate(s)) for s in arg_12]))
        arg_14 = [list(zip(*s)) for s in arg_13]

        def Func(arg_15):
            arg_16, arg_17 = arg_15[0], arg_15[1]
            for (arg_18, arg_19) in arg_14:
                if type(arg_16) is int:
                    arg_16 = (arg_16,)
                yield arg_16 + arg_18, arg_17[arg_19]

        arg_8 = arg_8.flatMap(Func)
        return arg_0._constructor(arg_8, shape=arg_0.shape, split=arg_0.split,
                                 dtype=arg_0.dtype, plan=arg_0.plan, arg_3=arg_0.padding, ordered=arg_0._ordered)


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """
        Apply an array -> array function on each subarray.

        The function can change the shape of the subarray, but only along
        dimensions that are not chunked.

        Parameters
        ----------
        func : function
            Function of a single subarray to apply

        value_shape:
            Known shape of chunking plan after the Func

        dtype: numpy.dtype, optional, default=None
            Known dtype of values resulting from operation

        Returns
        -------
        ChunkedArray
        """

        if arg_2 is None or arg_3 is None:
            # try to compute the size of each Funcped element by applying func to a random array
            try:
                arg_4 = arg_1(random.randn(*arg_0.plan).astype(arg_0.dtype))
            except Exception:
                arg_5 = arg_0._rdd.first()
                if arg_5:
                    # eval func on the first element
                    arg_4 = arg_1(arg_5[1])
            if arg_2 is None:
                arg_2 = arg_4.shape
            if arg_3 is None:
                arg_3 = arg_4.dtype

        arg_6 = where(arg_0.plan != arg_0.vshape)[0]
        arg_7 = where(arg_0.plan == arg_0.vshape)[0]

        # check that no dimensions are dropped
        if len(arg_2) != len(arg_0.plan):
            raise NotImplementedError('Func on ChunkedArray cannot drop dimensions')

        # check that chunked dimensions did not change shape
        if any([arg_2[arg_8] != arg_0.plan[arg_8] for arg_8 in arg_6]):
            raise ValueError('Func cannot change the sizes of chunked dimensions')

        def check_and_apply(arg_9):
            arg_10 = arg_1(arg_9)
            if len(arg_7) > 0:
                if any([arg_10.shape[arg_8] != arg_2[arg_8] for arg_8 in arg_7]):
                    raise Exception("Map operation did not produce values of uniform shape.")
            if len(arg_6) > 0:
                if any([arg_9.shape[arg_8] != arg_10.shape[arg_8] for arg_8 in arg_6]):
                    raise Exception("Map operation changed the size of a chunked dimension")
            return arg_10

        arg_11 = arg_0._rdd.FuncValues(check_and_apply)

        arg_12 = [arg_2[arg_8] if arg_8 in arg_7 else arg_0.vshape[arg_8] for arg_8 in range(len(arg_0.vshape))]
        arg_13 = r_[arg_0.kshape, arg_12].astype(int).tolist()

        return arg_0._constructor(arg_11, shape=tuple(arg_13), arg_3=arg_3,
                                 plan=asarray(arg_2)).__finalize__(arg_0)


def Func(arg_0, arg_1="150", arg_2=None, arg_3=None):
        """
        Identify a plan for chunking values along each dimension.

        Generates an ndarray with the size (in number of elements) of chunks
        in each dimension. If provided, will estimate chunks for only a
        subset of axes, leaving all others to the full size of the axis.

        Parameters
        ----------
        size : string or tuple
             If str, the average size (in KB) of the chunks in all value dimensions.
             If int/tuple, an explicit specification of the number chunks in
             each moving value dimension.

        axes : tuple, optional, default=None
              One or more axes to estimate chunks for, if provided any
              other axes will use one chunk.

        padding : tuple or int, option, default=None
            Size over overlapping padding between chunks in each dimension.
            If tuple, specifies padding along each chunked dimension; if int,
            all dimensions use same padding; if None, no padding
        """
        from numpy import dtype as gettype

        # initialize with all elements in one chunk
        arg_4 = arg_0.vshape

        # check for subset of axes
        if arg_2 is None:
            if isinstance(arg_1, str):
                arg_2 = arange(len(arg_0.vshape))
            else:
                arg_2 = arange(len(arg_1))
        else:
            arg_2 = asarray(arg_2, 'int')

        # set padding
        arg_5 = array(len(arg_0.vshape)*[0, ])
        if arg_3 is not None:
            arg_5[arg_2] = arg_3

        # set the plan
        if isinstance(arg_1, tuple):
            arg_4[arg_2] = arg_1

        elif isinstance(arg_1, str):
            # convert from kilobytes
            arg_1 = 1000.0 * float(arg_1)

            # calculate from dtype
            arg_6 = gettype(arg_0.dtype).itemsize
            arg_7 = prod(arg_0.vshape)
            arg_8 = arg_0.vshape[arg_0.vmask(arg_2)]

            if arg_1 <= arg_6:
                arg_9 = ones(len(arg_2))

            else:
                arg_10 = 1.0 * arg_7 * arg_6
                arg_9 = []
                for (arg_11, arg_12) in enumerate(arg_8):
                    arg_13 = arg_10/arg_12
                    if arg_13 >= arg_1:
                        arg_9.append(1)
                        arg_10 = arg_13
                        continue
                    else:
                        arg_9.append(min(arg_12, floor(arg_1/arg_13)))
                        arg_9[arg_11+1:] = arg_4[arg_11+1:]
                        break

            arg_4[arg_2] = arg_9

        else:
            raise ValueError("Chunk size not understood, must be tuple or int")

        return arg_4, arg_5


def Func(arg_0, arg_1):
        """
        Obtain number of chunks for the given dimensions and chunk sizes.

        Given a plan for the number of chunks along each dimension,
        calculate the number of chunks that this will lead to.

        Parameters
        ----------
        plan: tuple or array-like
            Size of chunks (in number of elements) along each dimensions.
            Length must be equal to the number of dimensions.

        shape : tuple
             Shape of array to be chunked.
        """
        arg_2 = []
        for arg_3, arg_4 in zip(arg_0, arg_1):
            arg_2.append(int(ceil(1.0 * arg_4/arg_3)))
        return arg_2


def Func(arg_0, arg_1):
        """
        Obtain a binary mask by setting a subset of entries to true.

        Parameters
        ----------
        inds : array-like
            Which indices to set as true.

        n : int
            The length of the target mask.
        """
        arg_0 = asarray(arg_0, 'int')
        arg_2 = zeros(arg_1, dtype=bool)
        arg_2[arg_0] = True
        return arg_2


def Func(arg_0, arg_1):
        """
        Repartitions the underlying RDD

        Parameters
        ----------
        npartitions : int
            Number of partitions to repartion the underlying RDD to
        """

        arg_2 = arg_0._rdd.Func(arg_1)
        return arg_0._constructor(arg_2, ordered=False).__finalize__(arg_0)


def Func(arg_0, arg_1=None, arg_2=False):
        """
        Return the Func of the array over the given axis.

        Parameters
        ----------
        axis : tuple or int, optional, default=None
            Axis to compute statistic over, if None
            will compute over all axes

        keepdims : boolean, optional, default=False
            Keep axis remaining after operation with size 1.
        """
        return arg_0._stat(arg_1, name='Func', arg_2=arg_2)


def Func(arg_0, arg_1=None, arg_2=False):
        """
        Return the Funciance of the array over the given axis.

        Parameters
        ----------
        axis : tuple or int, optional, default=None
            Axis to compute statistic over, if None
            will compute over all axes

        keepdims : boolean, optional, default=False
            Keep axis remaining after operation with size 1.
        """
        return arg_0._stat(arg_1, name='Funciance', arg_2=arg_2)


def Func(arg_0, arg_1=None, arg_2=False):
        """
        Return the standard deviation of the array over the given axis.

        Parameters
        ----------
        axis : tuple or int, optional, default=None
            Axis to compute statistic over, if None
            will compute over all axes

        keepdims : boolean, optional, default=False
            Keep axis remaining after operation with size 1.
        """
        return arg_0._stat(arg_1, name='Funcev', arg_2=arg_2)


def Func(arg_0, arg_1=None, arg_2=False):
        """
        Return the Func of the array over the given axis.

        Parameters
        ----------
        axis : tuple or int, optional, default=None
            Axis to compute statistic over, if None
            will compute over all axes

        keepdims : boolean, optional, default=False
            Keep axis remaining after operation with size 1.
        """
        from operator import add
        return arg_0._stat(arg_1, func=add, arg_2=arg_2)


def Func(arg_0, arg_1="150", arg_2=None, arg_3=None):
        """
        Chunks records of a distributed array.

        Chunking breaks arrays into subarrays, using an specified
        size of Funcs along each value dimension. Can alternatively
        specify an average Func byte size (in kilobytes) and the size of
        Funcs (as ints) will be computed automatically.

        Parameters
        ----------
        size : tuple, int, or str, optional, default = "150"
            A string giving the size in kilobytes, or a tuple with the size
            of Funcs along each dimension.

        axis : int or tuple, optional, default = None
            One or more axis to Func array along, if None
            will use all axes,

        padding: tuple or int, default = None
            Number of elements per dimension that will overlap with the adjacent Func.
            If a tuple, specifies padding along each Funced dimension; if a int, same
            padding will be applied to all Funced dimensions.

        Returns
        -------
        ChunkedArray
        """
        if type(arg_1) is not str:
            arg_1 = tupleize((arg_1))
        arg_2 = tupleize((arg_2))
        arg_3 = tupleize((arg_3))

        from bolt.spark.Func import ChunkedArray

        arg_4 = ChunkedArray(rdd=arg_0._rdd, shape=arg_0._shape, split=arg_0._split, dtype=arg_0._dtype)
        return arg_4._Func(arg_1, arg_2, arg_3)


def Func(arg_0, arg_1, arg_2, arg_3="150"):
        """
        Swap axes from keys to values.

        This is the core operation underlying shape manipulation
        on the Spark bolt array. It exchanges an arbitrary set of axes
        between the keys and the valeus. If either is None, will only
        move axes in one direction (from keys to values, or values to keys).
        Keys moved to values will be placed immediately after the split;
        values moved to keys will be placed immediately before the split.

        Parameters
        ----------
        kaxes : tuple
            Axes from keys to move to values

        vaxes : tuple
            Axes from values to move to keys

        size : tuple or int, optional, default = "150"
            Can either provide a string giving the size in kilobytes,
            or a tuple with the number of chunks along each
            value dimension being moved

        Returns
        -------
        BoltArraySpark
        """
        arg_1 = asarray(tupleize(arg_1), 'int')
        arg_2 = asarray(tupleize(arg_2), 'int')
        if type(arg_3) is not str:
            arg_3 = tupleize(arg_3)

        if len(arg_1) == arg_0.keys.ndim and len(arg_2) == 0:
            raise ValueError('Cannot perform a Func that would '
                             'end up with all data on a single key')

        if len(arg_1) == 0 and len(arg_2) == 0:
            return arg_0

        from bolt.spark.chunk import ChunkedArray

        arg_4 = arg_0.chunk(arg_3)

        arg_5 = arg_4.keys_to_values(arg_1).values_to_keys([v+len(arg_1) for v in arg_2])
        arg_6 = arg_5.unchunk()

        return arg_6


def Func(arg_0, arg_1, arg_2):
        """
        Return the array with two axes interchanged.

        Parameters
        ----------
        axis1 : int
            The first axis to swap

        axis2 : int
            The second axis to swap
        """
        arg_3 = list(range(arg_0.ndim))
        arg_3[arg_1] = arg_2
        arg_3[arg_2] = arg_1

        return arg_0.transpose(arg_3)