Instruction:
Write a Python 3 script to
compile the user dictionary.

Response:
def compile_dictionary(self, lang, wordlists, encoding, output):
        """Compile user dictionary."""

        cmd = [
            self.binary,
            '--lang', lang,
            '--encoding', codecs.lookup(filters.PYTHON_ENCODING_NAMES.get(encoding, encoding).lower()).name,
            'create',
            'master', output
        ]

        wordlist = ''

        try:
            output_location = os.path.dirname(output)
            if not os.path.exists(output_location):
                os.makedirs(output_location)
            if os.path.exists(output):
                os.remove(output)

            self.log("Compiling Dictionary...", 1)
            # Read word lists and create a unique set of words
            words = set()
            for wordlist in wordlists:
                with open(wordlist, 'rb') as src:
                    for word in src.read().split(b'\n'):
                        words.add(word.replace(b'\r', b''))

            # Compile wordlist against language
            util.call(
                [
                    self.binary,
                    '--lang', lang,
                    '--encoding=utf-8',
                    'create',
                    'master', output
                ],
                input_text=b'\n'.join(sorted(words)) + b'\n'
            )
        except Exception:
            self.log(cmd, 0)
            self.log("Current wordlist: '%s'" % wordlist, 0)
            self.log("Problem compiling dictionary. Check the binary path and options.", 0)
            raise


Instruction:
Write a Python 3 script to
spell check without the pipeline.

Response:
def spell_check_no_pipeline(self, sources, options, personal_dict):
        """Spell check without the pipeline."""

        for source in sources:
            if source._has_error():  # pragma: no cover
                yield Results([], source.context, source.category, source.error)

            cmd = self.setup_command(source.encoding, options, personal_dict, source.context)
            self.log('', 3)
            self.log("Command: " + str(cmd), 4)
            try:
                wordlist = util.call_spellchecker(cmd, input_text=None, encoding=source.encoding)
                yield Results(
                    [w for w in sorted(set(wordlist.replace('\r', '').split('\n'))) if w],
                    source.context,
                    source.category
                )
            except Exception as e:  # pragma: no cover
                err = self.get_error(e)
                yield Results([], source.context, source.category, err)


Instruction:
Here you have a function in Python 3, explain what it does
def fusion_append(fields, error_field, etl_func):
    return compose(read_fields(fields),
                   etl_func, dict_enforcer, write_error_field(error_field))

Response: appends a new element to a list of nacvables


Instruction:
Create a Python 3 function to
match the category with the pattern.

Response:
def match(self, category, pattern):
        """Match the category."""

        return fnmatch.fnmatch(category, pattern, flags=self.FNMATCH_FLAGS)


Instruction:
Write a Python 3 function for
adjusting the flow of source control objects.

Response:
def adjust_flow(self, category):
        """Adjust the flow of source control objects."""

        status = flow_control.SKIP
        for allow in self.allow:
            if self.match(category, allow):
                status = flow_control.ALLOW
                for skip in self.skip:
                    if self.match(category, skip):
                        status = flow_control.SKIP
                for halt in self.halt:
                    if self.match(category, halt):
                        status = flow_control.HALT
                if status != flow_control.ALLOW:
                    break
        return status


Instruction:
Can you generate a brief explanation for the following Python 3 code
def plot_tcoords(array, coords, scantypes=None, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()

    if scantypes is None:
        ax.plot(array[coords[0]], array[coords[1]], label='ALL', **kwargs)
    else:
        for scantype in scantypes:
            ax.plot(array[coords[0]][array.scantype == scantype],
                    array[coords[1]][array.scantype == scantype], label=scantype, **kwargs)
    ax.set_xlabel(coords[0])
    ax.set_ylabel(coords[1])
    ax.set_title('{} vs {}'.format(coords[1], coords[0]))
    ax.legend()

    logger.info('{} vs {} has been plotted.'.format(coords[1], coords[0]))

Response: Plot the coordinates related to the time axis.


Instruction:
Given the following Python 3 function, write the documentation
def plot_timestream(array, kidid, xtick='time', scantypes=None, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()

    index = np.where(array.kidid == kidid)[0]
    if len(index) == 0:
        raise KeyError('Such a kidid does not exist.')
    index = int(index)

    if scantypes is None:
        if xtick == 'time':
            ax.plot(array.time, array[:, index], label='ALL', **kwargs)
        elif xtick == 'index':
            ax.plot(np.ogrid[:len(array.time)], array[:, index], label='ALL', **kwargs)
    else:
        for scantype in scantypes:
            if xtick == 'time':
                ax.plot(array.time[array.scantype == scantype],
                        array[:, index][array.scantype == scantype], label=scantype, **kwargs)
            elif xtick == 'index':
                ax.plot(np.ogrid[:len(array.time[array.scantype == scantype])],
                        array[:, index][array.scantype == scantype], label=scantype, **kwargs)
    ax.set_xlabel('{}'.format(xtick))
    ax.set_ylabel(str(array.datatype.values))
    ax.legend()

    kidtpdict = {0: 'wideband', 1: 'filter', 2: 'blind'}
    try:
        kidtp = kidtpdict[int(array.kidtp[index])]
    except KeyError:
        kidtp = 'filter'
    ax.set_title('ch #{} ({})'.format(kidid, kidtp))

    logger.info('timestream data (ch={}) has been plotted.'.format(kidid))

Response:
Plot timestream data.

    Args:
        array (xarray.DataArray): Array which the timestream data are included.
        kidid (int): Kidid.
        xtick (str): Type of x axis.
            'time': Time.
            'index': Time index.
        scantypes (list): Scantypes. If None, all scantypes are used.
        ax (matplotlib.axes): Axis you want to plot on.
        kwargs (optional): Plot options passed to ax.plot().


Instruction:
How would you code a function in Python 3 to
plot a spectrum on the specified axis.

Response:
def plot_spectrum(cube, xtick, ytick, aperture, ax=None, **kwargs):
    """Plot a spectrum.

    Args:
        cube (xarray.DataArray): Cube which the spectrum information is included.
        xtick (str): Type of x axis.
            'freq': Frequency [GHz].
            'id': Kid id.
        ytick (str): Type of y axis.
            'max': Maximum.
            'sum': Summation.
            'mean': Mean.
        aperture (str): The shape of aperture.
            'box': Box.
            'circle': Circle.
        ax (matplotlib.axes): Axis you want to plot on.
        kwargs (optional):
            When 'box' is specified as shape,
                xc: Center of x.
                yc: Center of y.
                width: Width.
                height: Height.
                xmin: Minimum of x.
                xmax: Maximum of x.
                ymin: Minimum of y.
                ymax: Maximum of y.
            When 'circle' is specified as shape,
                xc: Center of x.
                yc: Center of y.
                radius: Radius.
            Remaining kwargs are passed to ax.step().

    Notes:
        All kwargs should be specified as pixel coordinates.
    """
    if ax is None:
        ax = plt.gca()

    ### pick up kwargs
    xc     = kwargs.pop('xc', None)
    yc     = kwargs.pop('yc', None)
    width  = kwargs.pop('width', None)
    height = kwargs.pop('height', None)
    xmin   = kwargs.pop('xmin', None)
    xmax   = kwargs.pop('xmax', None)
    ymin   = kwargs.pop('ymin', None)
    ymax   = kwargs.pop('ymax', None)
    radius = kwargs.pop('radius', None)
    exchs  = kwargs.pop('exchs', None)

    ### labels
    xlabeldict = {'freq': 'frequency [GHz]', 'id': 'kidid'}

    cube     = cube.copy()
    datatype = cube.datatype
    if aperture == 'box':
        if None not in [xc, yc, width, height]:
            xmin, xmax = int(xc - width / 2), int(xc + width / 2)
            ymin, ymax = int(yc - width / 2), int(yc + width / 2)
        elif None not in [xmin, xmax, ymin, ymax]:
            pass
        else:
            raise KeyError('Invalid arguments.')
        value = getattr(cube[xmin:xmax, ymin:ymax, :], ytick)(dim=('x', 'y'))
    elif aperture == 'circle':
        if None not in [xc, yc, radius]:
            pass
        else:
            raise KeyError('Invalid arguments.')
        x, y   = np.ogrid[0:len(cube.x), 0:len(cube.y)]
        mask   = ((x - xc)**2 + (y - yc)**2 < radius**2)
        mask   = np.broadcast_to(mask[:, :, np.newaxis], cube.shape)
        masked = np.ma.array(cube.values, mask=~mask)
        value  = getattr(np, 'nan'+ytick)(masked, axis=(0, 1))
    else:
        raise KeyError(aperture)

    if xtick == 'freq':
        kidfq     = cube.kidfq.values
        freqrange = ~np.isnan(kidfq)
        if exchs is not None:
            freqrange[exchs] = False
        x = kidfq[freqrange]
        y = value[freqrange]
        ax.step(x[np.argsort(x)], y[np.argsort(x)], where='mid', **kwargs)
    elif xtick == 'id':
        ax.step(cube.kidid.values, value, where='mid', **kwargs)
    else:
        raise KeyError(xtick)
    ax.set_xlabel('{}'.format(xlabeldict[xtick]))
    ax.set_ylabel('{} ({})'.format(datatype.values, ytick))
    ax.set_title('spectrum')


Instruction:
Can you implement a function in Python 3 that
plots an intensity map.

Response:
def plot_chmap(cube, kidid, ax=None, **kwargs):
    """Plot an intensity map.

    Args:
        cube (xarray.DataArray): Cube which the spectrum information is included.
        kidid (int): Kidid.
        ax (matplotlib.axes): Axis the figure is plotted on.
        kwargs (optional): Plot options passed to ax.imshow().
    """
    if ax is None:
        ax = plt.gca()

    index = np.where(cube.kidid == kidid)[0]
    if len(index) == 0:
        raise KeyError('Such a kidid does not exist.')
    index = int(index)

    im = ax.pcolormesh(cube.x, cube.y, cube[:, :, index].T, **kwargs)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_title('intensity map ch #{}'.format(kidid))
    return im


Instruction:
Explain what the following Python 3 code does
def plotpsd(data, dt, ndivide=1, window=hanning, overlap_half=False, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()
    vk, psddata = psd(data, dt, ndivide, window, overlap_half)
    ax.loglog(vk, psddata, **kwargs)
    ax.set_xlabel('Frequency [Hz]')
    ax.set_ylabel('PSD')
    ax.legend()

Response: Plot a power - spectrum density.


Instruction:
How would you code a function in Python 3 to
plot Allan variance. Args: data (np.ndarray): Input data. dt (float): Time between each data. tmax (float): Maximum time. ax (matplotlib.axes): Axis the figure is plotted on. kwargs (optional): Plot options passed to ax.plot().

Response:
def plotallanvar(data, dt, tmax=10, ax=None, **kwargs):
    """Plot Allan variance.

    Args:
        data (np.ndarray): Input data.
        dt (float): Time between each data.
        tmax (float): Maximum time.
        ax (matplotlib.axes): Axis the figure is plotted on.
        kwargs (optional): Plot options passed to ax.plot().
    """
    if ax is None:
        ax = plt.gca()
    tk, allanvar = allan_variance(data, dt, tmax)
    ax.loglog(tk, allanvar, **kwargs)
    ax.set_xlabel('Time [s]')
    ax.set_ylabel('Allan Variance')
    ax.legend()


Instruction:
Implement a function in Python 3 to
function to create a cancellation request for the order ID from the open orders on the order book. Execution of this function is as follows:: create_cancellation(order_id=order['id'], private_key=kp) The expected return result for this function is as follows:: { 'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74', 'transaction': { 'hash': '50d99ebd7e57dbdceb7edc2014da5f446c8f44cc0a0b6d9c762a29e8a74bb051', 'sha256': '509edb9888fa675988fa71a27600b2655e63fe979424f13f5c958897b2e99ed8', 'type': 209, 'version': 1, 'attributes': [ { 'usage': 32, 'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe' } ], 'inputs': [ { 'prevHash': '9eaca1adcbbc0669a936576cb9ad03c11c99c356347aae3037ce1f0e4d330d85', 'prevIndex': 0 }, { 'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d', 'prevIndex': 37 } ], 'outputs': [ { 'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7', 'scriptHash': 'e707714512577b42f9a011f8b870625429f93573', 'value': 1e-08 } ], 'scripts': [], 'script': '....', 'gas': 0 }, 'script_params': { 'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'operation': 'cancelOffer', 'args': [ '923ebd865a6c5db39bd67403c1677f29d3949d9d8d9a2eb36a56dabd2dd83068' ] } } :param order_id: The order ID of the open transaction on the order book that you want to cancel. :type order_id: str :param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain. :type private_key: KeyPair :return: Dictionary that contains the cancellation request along with blockchain transaction information.

Response:
def create_cancellation(self, order_id, private_key):
        """
        Function to create a cancellation request for the order ID from the open orders on the order book.
        Execution of this function is as follows::

            create_cancellation(order_id=order['id'], private_key=kp)

        The expected return result for this function is as follows::

            {
                'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74',
                'transaction': {
                    'hash': '50d99ebd7e57dbdceb7edc2014da5f446c8f44cc0a0b6d9c762a29e8a74bb051',
                    'sha256': '509edb9888fa675988fa71a27600b2655e63fe979424f13f5c958897b2e99ed8',
                    'type': 209,
                    'version': 1,
                    'attributes': [
                        {
                            'usage': 32,
                            'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe'
                        }
                    ],
                    'inputs': [
                        {
                            'prevHash': '9eaca1adcbbc0669a936576cb9ad03c11c99c356347aae3037ce1f0e4d330d85',
                            'prevIndex': 0
                        }, {
                            'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d',
                            'prevIndex': 37
                        }
                    ],
                    'outputs': [
                        {
                            'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7',
                            'scriptHash': 'e707714512577b42f9a011f8b870625429f93573',
                            'value': 1e-08
                        }
                    ],
                    'scripts': [],
                    'script': '....',
                    'gas': 0
                },
                'script_params': {
                    'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
                    'operation': 'cancelOffer',
                    'args': [
                        '923ebd865a6c5db39bd67403c1677f29d3949d9d8d9a2eb36a56dabd2dd83068'
                    ]
                }
            }

        :param order_id: The order ID of the open transaction on the order book that you want to cancel.
        :type order_id: str
        :param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain.
        :type private_key: KeyPair
        :return: Dictionary that contains the cancellation request along with blockchain transaction information.
        """
        cancellation_params = {
            "order_id": order_id,
            "timestamp": get_epoch_milliseconds()
        }
        api_params = self.sign_create_cancellation_function[self.blockchain](cancellation_params, private_key)
        return self.request.post(path='/cancellations', json_data=api_params)


Instruction:
Make a summary of the following Python 3 code
def create_deposit(self, asset, amount, private_key):
        signable_params = {
            'blockchain': self.blockchain,
            'asset_id': asset,
            'amount': str(self.blockchain_amount[self.blockchain](amount)),
            'timestamp': get_epoch_milliseconds(),
            'contract_hash': self.contract_hash
        }
        api_params = self.sign_create_deposit_function[self.blockchain](signable_params, private_key)
        return self.request.post(path='/deposits', json_data=api_params)

Response: This function generates a deposit request for a specific asset.


Instruction:
Explain what the following Python 3 code does
def execute_deposit(self, deposit_params, private_key):
        deposit_id = deposit_params['id']
        api_params = self.sign_execute_deposit_function[self.blockchain](deposit_params, private_key)
        return self.request.post(path='/deposits/{}/broadcast'.format(deposit_id), json_data=api_params)

Response: Execute the deposit request by signing the transaction generated by the create deposit function.


Instruction:
Write a Python 3 function that can
function to create an order for the trade pair and details requested. Execution of this function is as follows:: create_order(pair="SWTH_NEO", side="buy", price=0.0002, quantity=100, private_key=kp, use_native_token=True, order_type="limit") The expected return result for this function is as follows:: { 'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67', 'blockchain': 'neo', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'side': 'buy', 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'offer_amount': '2000000', 'want_amount': '10000000000', 'transfer_amount': '0', 'priority_gas_amount': '0', 'use_native_token': True, 'native_fee_transfer_amount': 0, 'deposit_txn': None, 'created_at': '2018-08-05T10:38:37.714Z', 'status': 'pending', 'fills': [], 'makes': [ { 'id': 'e30a7fdf-779c-4623-8f92-8a961450d843', 'offer_hash': None, 'available_amount': None, 'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', 'offer_amount': '2000000', 'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'want_amount': '10000000000', 'filled_amount': None, 'txn': { 'offerHash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968', 'hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f', 'sha256': 'f0b70640627947584a2976edeb055a124ae85594db76453532b893c05618e6ca', 'invoke': { 'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'operation': 'makeOffer', 'args': [ '592c8a46a0d06c600f06c994d1f25e7283b8a2fe', '9b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc5', 2000000, '32e125258b7db0a0dffde5bd03b2b859253538ab', 10000000000, '65333061376664662d373739632d343632332d386639322d386139363134353064383433' ] }, 'type': 209, 'version': 1, 'attributes': [ { 'usage': 32, 'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe' } ], 'inputs': [ { 'prevHash': '0fcfd792a9d20a7795255d1d3d3927f5968b9953e80d16ffd222656edf8fedbc', 'prevIndex': 0 }, { 'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d', 'prevIndex': 35 } ], 'outputs': [ { 'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7', 'scriptHash': 'e707714512577b42f9a011f8b870625429f93573', 'value': 1e-08 } ], 'scripts': [], 'script': '....', 'gas': 0 }, 'cancel_txn': None, 'price': '0.0002', 'status': 'pending', 'created_at': '2018-08-05T10:38:37.731Z', 'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f', 'trades': [] } ] } :param pair: The trading pair this order is being submitted for. :type pair: str :param side: The side of the trade being submitted i.e. buy or sell :type side: str :param price: The price target for this trade. :type price: float :param quantity: The amount of the asset being exchanged in the trade. :type quantity: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :param use_native_token: Flag to indicate whether or not to pay fees with the Switcheo native token. :type use_native_token: bool :param order_type: The type of order being submitted, currently this can only be a limit order. :type order_type: str :param otc_address: The address to trade with for Over the Counter exchanges. :type otc_address: str :return: Dictionary of order details to specify which parts of the trade will be filled (taker) or open (maker)

Response:
def create_order(self, pair, side, price, quantity, private_key, use_native_token=True, order_type="limit",
                     otc_address=None):
        """
        Function to create an order for the trade pair and details requested.
        Execution of this function is as follows::

            create_order(pair="SWTH_NEO", side="buy", price=0.0002, quantity=100, private_key=kp,
                         use_native_token=True, order_type="limit")

        The expected return result for this function is as follows::

            {
                'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67',
                'blockchain': 'neo',
                'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
                'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
                'side': 'buy',
                'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
                'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
                'offer_amount': '2000000',
                'want_amount': '10000000000',
                'transfer_amount': '0',
                'priority_gas_amount': '0',
                'use_native_token': True,
                'native_fee_transfer_amount': 0,
                'deposit_txn': None,
                'created_at': '2018-08-05T10:38:37.714Z',
                'status': 'pending',
                'fills': [],
                'makes': [
                    {
                        'id': 'e30a7fdf-779c-4623-8f92-8a961450d843',
                        'offer_hash': None,
                        'available_amount': None,
                        'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
                        'offer_amount': '2000000',
                        'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
                        'want_amount': '10000000000',
                        'filled_amount': None,
                        'txn': {
                            'offerHash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968',
                            'hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f',
                            'sha256': 'f0b70640627947584a2976edeb055a124ae85594db76453532b893c05618e6ca',
                            'invoke': {
                                'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
                                'operation': 'makeOffer',
                                'args': [
                                    '592c8a46a0d06c600f06c994d1f25e7283b8a2fe',
                                    '9b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc5',
                                    2000000,
                                    '32e125258b7db0a0dffde5bd03b2b859253538ab',
                                    10000000000,
                                    '65333061376664662d373739632d343632332d386639322d386139363134353064383433'
                                ]
                            },
                            'type': 209,
                            'version': 1,
                            'attributes': [
                                {
                                    'usage': 32,
                                    'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe'
                                }
                            ],
                            'inputs': [
                                {
                                    'prevHash': '0fcfd792a9d20a7795255d1d3d3927f5968b9953e80d16ffd222656edf8fedbc',
                                    'prevIndex': 0
                                }, {
                                    'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d',
                                    'prevIndex': 35
                                }
                            ],
                            'outputs': [
                                {
                                    'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7',
                                    'scriptHash': 'e707714512577b42f9a011f8b870625429f93573',
                                    'value': 1e-08
                                }
                            ],
                            'scripts': [],
                            'script': '....',
                            'gas': 0
                        },
                        'cancel_txn': None,
                        'price': '0.0002',
                        'status': 'pending',
                        'created_at': '2018-08-05T10:38:37.731Z',
                        'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f',
                        'trades': []
                    }
                ]
            }

        :param pair: The trading pair this order is being submitted for.
        :type pair: str
        :param side: The side of the trade being submitted i.e. buy or sell
        :type side: str
        :param price: The price target for this trade.
        :type price: float
        :param quantity: The amount of the asset being exchanged in the trade.
        :type quantity: float
        :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
        :type private_key: KeyPair or str
        :param use_native_token: Flag to indicate whether or not to pay fees with the Switcheo native token.
        :type use_native_token: bool
        :param order_type: The type of order being submitted, currently this can only be a limit order.
        :type order_type: str
        :param otc_address: The address to trade with for Over the Counter exchanges.
        :type otc_address: str
        :return: Dictionary of order details to specify which parts of the trade will be filled (taker) or open (maker)
        """
        if side.lower() not in ["buy", "sell"]:
            raise ValueError("Allowed trade types are buy or sell, you entered {}".format(side.lower()))
        if order_type.lower() not in ["limit", "market", "otc"]:
            raise ValueError("Allowed order type is limit, you entered {}".format(order_type.lower()))
        if order_type.lower() == "otc" and otc_address is None:
            raise ValueError("OTC Address is required when trade type is otc (over the counter).")
        order_params = {
            "blockchain": self.blockchain,
            "pair": pair,
            "side": side,
            "price": '{:.8f}'.format(price) if order_type.lower() != "market" else None,
            "quantity": str(self.blockchain_amount[self.blockchain](quantity)),
            "use_native_tokens": use_native_token,
            "order_type": order_type,
            "timestamp": get_epoch_milliseconds(),
            "contract_hash": self.contract_hash
        }
        api_params = self.sign_create_order_function[self.blockchain](order_params, private_key)
        return self.request.post(path='/orders', json_data=api_params)


Instruction:
Can you create a Python 3 function that
executes the order and returns the order record.

Response:
def execute_order(self, order_params, private_key):
        """
        This function executes the order created before it and signs the transaction to be submitted to the blockchain.
        Execution of this function is as follows::

            execute_order(order_params=create_order, private_key=kp)

        The expected return result for this function is the same as the execute_order function::

            {
                'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67',
                'blockchain': 'neo',
                'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
                'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
                'side': 'buy',
                'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
                'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
                'offer_amount': '2000000',
                'want_amount': '10000000000',
                'transfer_amount': '0',
                'priority_gas_amount': '0',
                'use_native_token': True,
                'native_fee_transfer_amount': 0,
                'deposit_txn': None,
                'created_at': '2018-08-05T10:38:37.714Z',
                'status': 'processed',
                'fills': [],
                'makes': [
                    {
                        'id': 'e30a7fdf-779c-4623-8f92-8a961450d843',
                        'offer_hash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968',
                        'available_amount': '2000000',
                        'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
                        'offer_amount': '2000000',
                        'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
                        'want_amount': '10000000000',
                        'filled_amount': '0.0',
                        'txn': None,
                        'cancel_txn': None,
                        'price': '0.0002',
                        'status': 'confirming',
                        'created_at': '2018-08-05T10:38:37.731Z',
                        'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f',
                        'trades': []
                    }
                ]
            }

        :param order_params: Dictionary generated from the create order function.
        :type order_params: dict
        :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
        :type private_key: KeyPair or str
        :return: Dictionary of the transaction on the order book.
        """
        order_id = order_params['id']
        api_params = self.sign_execute_order_function[self.blockchain](order_params, private_key)
        return self.request.post(path='/orders/{}/broadcast'.format(order_id), json_data=api_params)


Instruction:
Given the following Python 3 function, write the documentation
def withdrawal(self, asset, amount, private_key):
        create_withdrawal = self.create_withdrawal(asset=asset, amount=amount, private_key=private_key)
        return self.execute_withdrawal(withdrawal_params=create_withdrawal, private_key=private_key)

Response: This function creates a new withdrawal request for the asset and amount of coins and tokens.


Instruction:
Implement a Python 3 function for
functioning to create a withdrawal request by generating a withdrawal ID request from the Switcheo API. Execution of this function is as follows:: create_withdrawal(asset="SWTH", amount=1.1, private_key=kp) The expected return result for this function is as follows:: { 'id': 'a5a4d396-fa9f-4191-bf50-39a3d06d5e0d' } :param asset: Script Hash of asset ID from the available products. :type asset: str :param amount: The amount of coins/tokens to be withdrawn. :type amount: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary with the withdrawal ID generated by the Switcheo API.

Response:
def create_withdrawal(self, asset, amount, private_key):
        """
        Function to create a withdrawal request by generating a withdrawal ID request from the Switcheo API.
        Execution of this function is as follows::

            create_withdrawal(asset="SWTH", amount=1.1, private_key=kp)

        The expected return result for this function is as follows::

            {
                'id': 'a5a4d396-fa9f-4191-bf50-39a3d06d5e0d'
            }

        :param asset:  Script Hash of asset ID from the available products.
        :type asset: str
        :param amount: The amount of coins/tokens to be withdrawn.
        :type amount: float
        :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
        :type private_key: KeyPair or str
        :return: Dictionary with the withdrawal ID generated by the Switcheo API.
        """
        signable_params = {
            'blockchain': self.blockchain,
            'asset_id': asset,
            'amount': str(self.blockchain_amount[self.blockchain](amount)),
            'timestamp': get_epoch_milliseconds(),
            'contract_hash': self.contract_hash
        }
        api_params = self.sign_create_withdrawal_function[self.blockchain](signable_params, private_key)
        return self.request.post(path='/withdrawals', json_data=api_params)


Instruction:
How would you code a function in Python 3 to
return an adaptive rejection sampling of the given logpdf and target distribution.

Response:
def adaptive_rejection_sampling(logpdf: callable,
                                a: float, b: float,
                                domain: Tuple[float, float],
                                n_samples: int,
                                random_stream=None):
    """
    Adaptive rejection sampling samples exactly (all samples are i.i.d) and efficiently from any univariate log-concave distribution. The basic idea is to successively determine an envelope of straight-line segments to construct an increasingly accurate approximation of the logarithm.
    It does not require any normalization of the target distribution.

    Parameters
    ----------
    logpdf: callable
        Univariate function that computes :math:`log(f(u))`
        for a given :math:`u`, where :math:`f(u)` is proportional
        to the target density to sample from.

    a: float
        Lower starting point used to initialize the hulls.
        Must lie in the domain of the logpdf and it
        must hold: :math:`a < b`.

    b: float
        Upper starting point used to initialize the hulls.
        Must lie in the domain of the logpdf and it
        must hold: :math:`a < b`.

    domain : Tuple[float, float]
        Domain of `logpdf`.
        May be unbounded on either or both sides,
        in which case `(float("-inf"), float("inf"))`
        would be passed.
        If this domain is unbounded to the left,
        the derivative of the logpdf
        for x<= a must be positive.
        If this domain is unbounded to the right the derivative of the logpdf for x>=b
        must be negative.

    n_samples: int
        Number of samples to draw.

    random_stream : RandomState, optional
        Seeded random number generator object with same interface as a NumPy
        RandomState object. Defaults to `None` in which case a NumPy
        RandomState seeded from `/dev/urandom` if available or the clock if not
        will be used.

    Returns
    ----------
    samples : list
        A list of samples drawn from the
        target distribution :math:`f`
        with the given `logpdf`.

    Examples
    ----------
    Sampling from a simple gaussian, adaptive rejection sampling style.
    We use the logpdf of a standard gaussian and this small code snippet
    demonstrates that our sample approximation accurately approximates the mean:

    >>> from math import isclose
    >>> from numpy import log, exp, mean
    >>> gaussian_logpdf = lambda x, sigma=1: log(exp(-x ** 2 / sigma))
    >>> a, b = -2, 2  # a < b must hold
    >>> domain = (float("-inf"), float("inf"))
    >>> n_samples = 10000
    >>> samples = adaptive_rejection_sampling(logpdf=gaussian_logpdf, a=a, b=b, domain=domain, n_samples=n_samples)
    >>> isclose(mean(samples), 0.0, abs_tol=1e-02)
    True

    """
    assert(hasattr(logpdf, "__call__"))
    assert(len(domain) == 2), "Domain must be two-element iterable."
    assert(domain[1] >= domain[0]), "Invalid domain, it must hold: domain[1] >= domain[0]."
    assert(n_samples >= 0), "Number of samples must be >= 0."

    if random_stream is None:
        random_stream = RandomState()

    if a >= b or isinf(a) or isinf(b) or a < domain[0] or b > domain[1]:
        raise ValueError("invalid a and b")

    n_derivative_steps = 1e-3 * (b - a)

    S = (a, a + n_derivative_steps, b - n_derivative_steps, b)

    if domain[0] == float("-inf"):
        # ensure positive derivative at 'a'
        derivative_sign = sign(logpdf(a + n_derivative_steps) - logpdf(a))
        positive_derivative = derivative_sign > 0

        assert(positive_derivative), "derivative at 'a' must be positive, since the domain is unbounded to the left"

    if domain[1] == float("inf"):
        # ensure negative derivative at 'b'
        derivative_sign = sign(logpdf(b) - logpdf(b - n_derivative_steps))
        negative_derivative = derivative_sign < 0

        assert(negative_derivative), "derivative at 'b' must be negative, since the domain is unbounded to the right"

    # initialize a mesh on which to create upper & lower hulls
    n_initial_mesh_points = 3

    S = unique(
        (S[0], *(linspace(S[1], S[2], num=n_initial_mesh_points + 2)), S[3])
    )

    fS = tuple(logpdf(s) for s in S)

    lower_hull, upper_hull = compute_hulls(S=S, fS=fS, domain=domain)

    samples = []

    while len(samples) < n_samples:

        mesh_changed = False

        x = sample_upper_hull(upper_hull, random_stream=random_stream)

        lh_val, uh_val = evaluate_hulls(x, lower_hull, upper_hull)

        U = random_stream.rand()

        if log(U) <= lh_val - uh_val:
            # accept u is below lower bound
            samples.append(x)

        elif log(U) <= logpdf(x) - uh_val:
            # accept, u is between lower bound and f
            samples.append(x)

            mesh_changed = True
        else:
            # reject, u is between f and upper_bound
            mesh_changed = True

        if mesh_changed:
            S = sorted([*S, x])
            fS = tuple(logpdf(s) for s in S)
            lower_hull, upper_hull = compute_hulls(S=S, fS=fS, domain=domain)
    return samples


Instruction:
Here you have a function in Python 3, explain what it does
def sign_create_cancellation(cancellation_params, key_pair):
    encoded_message = encode_message(cancellation_params)
    create_params = cancellation_params.copy()
    create_params['address'] = neo_get_scripthash_from_private_key(private_key=key_pair.PrivateKey).ToString()
    create_params['signature'] = sign_message(encoded_message=encoded_message,
                                              private_key_hex=private_key_to_hex(key_pair=key_pair))
    return create_params

Response: This function is used to sign the parameters required to create a cancellation request from Switcheo Exchange.


Instruction:
Implement a Python 3 function for
functioning to sign the parameters required to execute a cancellation request on the Switcheo Exchange. Execution of this function is as follows:: sign_execute_cancellation(cancellation_params=signable_params, key_pair=key_pair) The expected return result for this function is as follows:: { 'signature': '6a40d6c011b7517f8fd3f2d0de32dd486adfd1d424d06d56c80eb....' } :param cancellation_params: Parameters the Switcheo Exchange returns from the create cancellation. :type cancellation_params: dict :param key_pair: The KeyPair for the wallet being used to sign deposit message. :type key_pair: KeyPair :return: Dictionary of signed message to send to the Switcheo API.

Response:
def sign_execute_cancellation(cancellation_params, key_pair):
    """
    Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange.
    Execution of this function is as follows::

        sign_execute_cancellation(cancellation_params=signable_params, key_pair=key_pair)

    The expected return result for this function is as follows::

        {
            'signature': '6a40d6c011b7517f8fd3f2d0de32dd486adfd1d424d06d56c80eb....'
        }

    :param cancellation_params: Parameters the Switcheo Exchange returns from the create cancellation.
    :type cancellation_params: dict
    :param key_pair: The KeyPair for the wallet being used to sign deposit message.
    :type key_pair: KeyPair
    :return: Dictionary of signed message to send to the Switcheo API.
    """
    signature = sign_transaction(transaction=cancellation_params['transaction'],
                                 private_key_hex=private_key_to_hex(key_pair=key_pair))
    return {'signature': signature}


Instruction:
How would you explain what the following Python 3 function does
def sign_create_deposit(deposit_params, key_pair):
    encoded_message = encode_message(deposit_params)
    create_params = deposit_params.copy()
    create_params['address'] = neo_get_scripthash_from_private_key(private_key=key_pair.PrivateKey).ToString()
    create_params['signature'] = sign_message(encoded_message=encoded_message,
                                              private_key_hex=private_key_to_hex(key_pair=key_pair))
    return create_params

Response: This function generates a transaction request from the Switcheo API and signs it.


Instruction:
Explain what the following Python 3 code does
def sign_execute_deposit(deposit_params, key_pair):
    signature = sign_transaction(transaction=deposit_params['transaction'],
                                 private_key_hex=private_key_to_hex(key_pair=key_pair))
    return {'signature': signature}

Response: This function is used to execute the deposit request by signing the transaction generated by the create deposit function.


Instruction:
How would you explain what the following Python 3 function does
def sign_create_order(order_params, key_pair):
    encoded_message = encode_message(order_params)
    create_params = order_params.copy()
    create_params['address'] = neo_get_scripthash_from_private_key(private_key=key_pair.PrivateKey).ToString()
    create_params['signature'] = sign_message(encoded_message=encoded_message,
                                              private_key_hex=private_key_to_hex(key_pair=key_pair))
    return create_params

Response: This function is used to sign the create order parameters and send to Switcheo API.


Instruction:
Make a summary of the following Python 3 code
def sign_execute_order(order_params, key_pair):
    execute_params = {
        'signatures': {
            'fill_groups': {},
            'fills': sign_txn_array(messages=order_params['fills'],
                                    private_key_hex=private_key_to_hex(key_pair=key_pair)),
            'makes': sign_txn_array(messages=order_params['makes'],
                                    private_key_hex=private_key_to_hex(key_pair=key_pair))
        }
    }
    return execute_params

Response: This function is used to sign the order request by signing the transaction generated by the create order function.


Instruction:
Create a Python 3 function to
function to create the withdrawal request by signing the parameters necessary for withdrawal. Execution of this function is as follows:: sign_create_withdrawal(withdrawal_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follows:: { 'blockchain': 'neo', 'asset_id': 'SWTH', 'amount': '100', 'timestamp': 1542090737236, 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82', 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'signature': 'f66d604c0a80940bf70ce9e13c0fd47bc79de....' } :param withdrawal_params: Dictionary specifications for withdrawal from the Switcheo Smart Contract. :type withdrawal_params: dict :param key_pair: The NEO key pair to be used to sign messages for the NEO Blockchain. :type key_pair: KeyPair :return: Dictionary of parameters to be sent to the Switcheo API

Response:
def sign_create_withdrawal(withdrawal_params, key_pair):
    """
    Function to create the withdrawal request by signing the parameters necessary for withdrawal.
    Execution of this function is as follows::

        sign_create_withdrawal(withdrawal_params=signable_params, private_key=eth_private_key)

    The expected return result for this function is as follows::

        {
            'blockchain': 'neo',
            'asset_id': 'SWTH',
            'amount': '100',
            'timestamp': 1542090737236,
            'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
            'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
            'signature': 'f66d604c0a80940bf70ce9e13c0fd47bc79de....'
        }

    :param withdrawal_params: Dictionary specifications for withdrawal from the Switcheo Smart Contract.
    :type withdrawal_params: dict
    :param key_pair: The NEO key pair to be used to sign messages for the NEO Blockchain.
    :type key_pair: KeyPair
    :return: Dictionary of parameters to be sent to the Switcheo API
    """
    encoded_message = encode_message(withdrawal_params)
    create_params = withdrawal_params.copy()
    create_params['address'] = neo_get_scripthash_from_private_key(private_key=key_pair.PrivateKey).ToString()
    create_params['signature'] = sign_message(encoded_message=encoded_message,
                                              private_key_hex=private_key_to_hex(key_pair=key_pair))
    return create_params


Instruction:
Can you generate the documentation for the following Python 3 function
def sign_execute_withdrawal(withdrawal_params, key_pair):
    withdrawal_id = withdrawal_params['id']
    signable_params = {
        'id': withdrawal_id,
        'timestamp': get_epoch_milliseconds()
    }
    encoded_message = encode_message(signable_params)
    execute_params = signable_params.copy()
    execute_params['signature'] = sign_message(encoded_message=encoded_message,
                                               private_key_hex=private_key_to_hex(key_pair=key_pair))
    return execute_params

Response: This function is used to sign the withdrawal request for the NEO Blockchain.


Instruction:
Explain what the following Python 3 code does
def register(cls, range_mixin):

        def decorator(range_set_mixin):
            cls.add(range_mixin, range_set_mixin)
            return range_set_mixin
        return decorator

Response: A decorator for registering range set mixins for global use. This works with the same as the meta - range - set. add decorator. This works with the meta - range - set. add decorator. This works with the meta - range - set. add decorator.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def pca(onarray, offarray, n=10, exchs=None, pc=False, mode='mean'):
    logger = getLogger('decode.models.pca')
    logger.info('n_components exchs mode')
    if exchs is None:
        exchs = [16, 44, 46]
    logger.info('{} {} {}'.format(n, exchs, mode))

    offid = np.unique(offarray.scanid)
    onid  = np.unique(onarray.scanid)

    onarray   = onarray.copy() # Xarray
    onarray[:, exchs] = 0
    onvalues  = onarray.values
    onscanid  = onarray.scanid.values
    offarray  = offarray.copy() # Xarray
    offarray[:, exchs] = 0
    offvalues = offarray.values
    offscanid = offarray.scanid.values

    Ps, Cs     = [], []
    Xatm       = dc.full_like(onarray, onarray)
    Xatmvalues = Xatm.values
    model = TruncatedSVD(n_components=n)
    for i in onid:
        leftid  = np.searchsorted(offid, i) - 1
        rightid = np.searchsorted(offid, i)

        Xon = onvalues[onscanid == i]
        if leftid == -1:
            Xoff   = offvalues[offscanid == offid[rightid]]
            Xoff_m = getattr(np, 'nan'+mode)(Xoff, axis=0) if mode is not None else 0
            Xon_m  = Xoff_m
            model.fit(Xoff - Xoff_m)
        elif rightid == len(offid):
            Xoff   = offvalues[offscanid == offid[leftid]]
            Xoff_m = getattr(np, 'nan'+mode)(Xoff, axis=0) if mode is not None else 0
            Xon_m  = Xoff_m
            model.fit(Xoff - Xoff_m)
        else:
            Xoff_l  = offvalues[offscanid == offid[leftid]]
            Xoff_lm = getattr(np, 'nan'+mode)(Xoff_l, axis=0) if mode is not None else 0
            Xoff_r  = offvalues[offscanid == offid[rightid]]
            Xoff_rm = getattr(np, 'nan'+mode)(Xoff_r, axis=0) if mode is not None else 0
            Xon_m   = getattr(np, 'nan'+mode)(np.vstack([Xoff_l, Xoff_r]), axis=0) if mode is not None else 0
            model.fit(np.vstack([Xoff_l - Xoff_lm, Xoff_r - Xoff_rm]))
        P = model.components_
        C = model.transform(Xon - Xon_m)

        Xatmvalues[onscanid == i] = C @ P + Xon_m
        # Xatms.append(dc.full_like(Xon, C @ P + Xon_m.values))
        Ps.append(P)
        Cs.append(C)

    if pc:
        return Xatm, Ps, Cs
    else:
        return Xatm

Response: This function calculates the pricipal components at each time.


Instruction:
Can you tell what is the following Python 3 function doing
def r_division(onarray, offarray, rarray, mode='mean'):
    logger = getLogger('decode.models.r_division')
    logger.info('mode')
    logger.info('{}'.format(mode))

    offid = np.unique(offarray.scanid)
    onid  = np.unique(onarray.scanid)
    rid   = np.unique(rarray.scanid)

    onarray   = onarray.copy() # Xarray
    onvalues  = onarray.values
    onscanid  = onarray.scanid.values
    offarray  = offarray.copy() # Xarray
    offvalues = offarray.values
    offscanid = offarray.scanid.values
    rarray    = rarray.copy() # Xarray
    rvalues   = rarray.values
    rscanid   = rarray.scanid.values
    for i in onid:
        rleftid  = np.searchsorted(rid, i) - 1
        rrightid = np.searchsorted(rid, i)

        if rleftid == -1:
            Xr   = rvalues[rscanid == rid[rrightid]]
            Xr_m = getattr(np, 'nan'+mode)(Xr, axis=0)
        elif rrightid == len(rid):
            Xr   = rvalues[rscanid == rid[rleftid]]
            Xr_m = getattr(np, 'nan'+mode)(Xr, axis=0)
        else:
            Xr_l  = rvalues[rscanid == rid[rleftid]]
            Xr_r  = rvalues[rscanid == rid[rrightid]]
            Xr_m  = getattr(np, 'nan'+mode)(np.vstack([Xr_l, Xr_r]), axis=0)
        onvalues[onscanid == i] /= Xr_m

    for j in offid:
        rleftid  = np.searchsorted(rid, j) - 1
        rrightid = np.searchsorted(rid, j)

        Xoff_m = getattr(np, 'nan'+mode)(offvalues[offscanid == j], axis=0)
        if rleftid == -1:
            Xr   = rvalues[rscanid == rid[rrightid]]
            Xr_m = getattr(np, 'nan'+mode)(Xr, axis=0)
        elif rrightid == len(rid):
            Xr   = rvalues[rscanid == rid[rleftid]]
            Xr_m = getattr(np, 'nan'+mode)(Xr, axis=0)
        else:
            Xr_l  = rvalues[rscanid == rid[rleftid]]
            Xr_r  = rvalues[rscanid == rid[rrightid]]
            Xr_m  = getattr(np, 'nan'+mode)(np.vstack([Xr_l, Xr_r]), axis=0)
        offvalues[offscanid == j] /= Xr_m

    Xon_rdiv    = dc.full_like(onarray, onarray)
    Xoff_rdiv   = dc.full_like(offarray, offarray)
    Xonoff_rdiv = dc.concat([Xon_rdiv, Xoff_rdiv], dim='t')
    Xonoff_rdiv_sorted = Xonoff_rdiv[np.argsort(Xonoff_rdiv.time.values)]

    scantype    = Xonoff_rdiv_sorted.scantype.values
    newscanid   = np.cumsum(np.hstack([False, scantype[1:] != scantype[:-1]]))
    onmask      = np.in1d(Xonoff_rdiv_sorted.scanid, onid)
    offmask     = np.in1d(Xonoff_rdiv_sorted.scanid, offid)
    Xon_rdiv    = Xonoff_rdiv_sorted[onmask]
    Xoff_rdiv   = Xonoff_rdiv_sorted[offmask]
    Xon_rdiv.coords.update({'scanid': ('t', newscanid[onmask])})
    Xoff_rdiv.coords.update({'scanid': ('t', newscanid[offmask])})

    return Xon_rdiv, Xoff_rdiv

Response: Apply R division to the on - point and off - point observations.


Instruction:
Explain what the following Python 3 code does
def gauss_fit(map_data, chs=None, mode='deg', amplitude=1, x_mean=0, y_mean=0, x_stddev=None, y_stddev=None, theta=None, cov_matrix=None, noise=0, **kwargs):

    if chs is None:
        chs = np.ogrid[0:63] # the number of channels would be changed

    if len(chs) > 1:
        for n,ch in enumerate(chs):
            subdata = np.transpose(np.full_like(map_data[:, :, ch], map_data.values[:, :, ch]))
            subdata[np.isnan(subdata)] = 0

            if mode == 'deg':
                mX, mY = np.meshgrid(map_data.x, map_data.y)

            elif mode == 'pix':
                mX, mY = np.mgrid[0:len(map_data.y), 0:len(map_data.x)]

            g_init = models.Gaussian2D(amplitude=np.nanmax(subdata),
                                       x_mean=x_mean, y_mean=y_mean,
                                       x_stddev=x_stddev, y_stddev=y_stddev, theta=theta,
                                       cov_matrix=cov_matrix, **kwargs) + models.Const2D(noise)
            fit_g  = fitting.LevMarLSQFitter()
            g      = fit_g(g_init, mX, mY, subdata)

            g_init2 = models.Gaussian2D(amplitude=np.nanmax(subdata-g.amplitude_1),
                                        x_mean=x_mean, y_mean=y_mean,
                                        x_stddev=x_stddev, y_stddev=y_stddev, theta=theta,
                                        cov_matrix=cov_matrix, **kwargs)
            fit_g2  = fitting.LevMarLSQFitter()
            g2      = fit_g2(g_init2, mX, mY, subdata)

            if n == 0:
                results   = np.array([g2(mX,mY)])
                peaks     = np.array([g2.amplitude.value])
                x_means   = np.array([g2.x_mean.value])
                y_means   = np.array([g2.y_mean.value])
                x_stddevs = np.array([g2.x_stddev.value])
                y_stddevs = np.array([g2.y_stddev.value])
                thetas    = np.array([g2.theta.value])
                if fit_g2.fit_info['param_cov'] is None:
                    unserts = nop.array([0])
                else:
                    error   = np.diag(fit_g2.fit_info['param_cov'])**0.5
                    uncerts = np.array([error[0]])

            else:
                results   = np.append(results, [g2(mX,mY)], axis=0)
                peaks     = np.append(peaks, [g2.amplitude.value], axis=0)
                x_means   = np.append(x_means, [g2.x_mean.value], axis=0)
                y_means   = np.append(y_means, [g2.y_mean.value], axis=0)
                x_stddevs = np.append(x_stddevs, [g2.x_stddev.value], axis=0)
                y_stddevs = np.append(y_stddevs, [g2.y_stddev.value], axis=0)
                thetas    = np.append(thetas, [g2.theta.value], axis=0)

                if fit_g2.fit_info['param_cov'] is None:
                    uncerts = np.append(uncerts, [0], axis=0)
                else:
                    error   = np.diag(fit_g2.fit_info['param_cov'])**0.5
                    uncerts = np.append(uncerts, [error[0]], axis=0)

        result = map_data.copy()
        result.values = np.transpose(results)
        result.attrs.update({'peak': peaks, 'x_mean': x_means, 'y_mean': y_means,
                             'x_stddev': x_stddevs, 'y_stddev': y_stddevs,
                             'theta': thetas, 'uncert': uncerts})

    else:
        subdata = np.transpose(np.full_like(map_data[:, :, 0], map_data.values[:, :, 0]))
        subdata[np.isnan(subdata)] = 0

        if mode == 'deg':
            mX, mY = np.meshgrid(map_data.x, map_data.y)

        elif mode == 'pix':
            mX, mY = np.mgrid[0:len(map_data.y), 0:len(map_data.x)]

        g_init = models.Gaussian2D(amplitude=np.nanmax(subdata),
                                   x_mean=x_mean, y_mean=y_mean,
                                   x_stddev=x_stddev, y_stddev=y_stddev, theta=theta,
                                   cov_matrix=cov_matrix, **kwargs) + models.Const2D(noise)
        fit_g  = fitting.LevMarLSQFitter()
        g      = fit_g(g_init, mX, mY, subdata)

        g_init2 = models.Gaussian2D(amplitude=np.nanmax(subdata-g.amplitude_1),
                                    x_mean=x_mean, y_mean=y_mean,
                                    x_stddev=x_stddev, y_stddev=y_stddev, theta=theta,
                                    cov_matrix=cov_matrix, **kwargs)
        fit_g2  = fitting.LevMarLSQFitter()
        g2      = fit_g2(g_init2, mX, mY, subdata)

        results   = np.array([g2(mX, mY)])
        peaks     = np.array([g2.amplitude.value])
        x_means   = np.array([g2.x_mean.value])
        y_means   = np.array([g2.y_mean.value])
        x_stddevs = np.array([g2.x_stddev.value])
        y_stddevs = np.array([g2.y_stddev.value])
        thetas    = np.array([g2.theta.value])
        error     = np.diag(fit_g2.fit_info['param_cov'])**0.5
        uncerts   = np.array(error[0])

        result = map_data.copy()
        result.values = np.transpose(results)
        result.attrs.update({'peak': peaks, 'x_mean': x_means, 'y_mean': y_means,
                             'x_stddev': x_stddevs, 'y_stddev': y_stddevs,
                             'theta': thetas, 'uncert': uncerts})

    return result

Response: make a 2D Gaussian model and fit the observed data with the model.


Instruction:
Given the following Python 3 function, write the documentation
def _filter(self, text):

        if self.urls:
            text = RE_LINK.sub('', text)
        if self.emails:
            text = RE_MAIL.sub('', text)
        return text

Response: Filter out the URL and email addresses.


Instruction:
Create a Python 3 function to
return parent directory of mac. app

Response:
def get_mac_dot_app_dir(directory):
    """Returns parent directory of mac .app

    Args:

       directory (str): Current directory

    Returns:

       (str): Parent directory of mac .app
    """
    return os.path.dirname(os.path.dirname(os.path.dirname(directory)))


Instruction:
Given the following Python 3 function, write the documentation
def copy_function(func, name=None):
    code = func.__code__
    newname = name or func.__name__
    newcode = CodeType(
        code.co_argcount,
        code.co_kwonlyargcount,
        code.co_nlocals,
        code.co_stacksize,
        code.co_flags,
        code.co_code,
        code.co_consts,
        code.co_names,
        code.co_varnames,
        code.co_filename,
        newname,
        code.co_firstlineno,
        code.co_lnotab,
        code.co_freevars,
        code.co_cellvars,
    )
    newfunc = FunctionType(
        newcode,
        func.__globals__,
        newname,
        func.__defaults__,
        func.__closure__,
    )
    newfunc.__dict__.update(func.__dict__)
    return newfunc

Response: Copy a function object with different name.


Instruction:
How would you code a function in Python 3 to
return a context manager where only one thread is allocated to a process.

Response:
def one_thread_per_process():
    """Return a context manager where only one thread is allocated to a process.

    This function is intended to be used as a with statement like::

        >>> with process_per_thread():
        ...     do_something() # one thread per process

    Notes:
        This function only works when MKL (Intel Math Kernel Library)
        is installed and used in, for example, NumPy and SciPy.
        Otherwise this function does nothing.

    """
    try:
        import mkl
        is_mkl = True
    except ImportError:
        is_mkl = False

    if is_mkl:
        n_threads = mkl.get_max_threads()
        mkl.set_num_threads(1)
        try:
            # block nested in the with statement
            yield
        finally:
            # revert to the original value
            mkl.set_num_threads(n_threads)
    else:
        yield


Instruction:
Can you generate the documentation for the following Python 3 function
def compute_hulls(S, fS, domain):
    assert(len(S) == len(fS))
    assert(len(domain) == 2)

    lower_hull = []

    for li in range(len(S) - 1):
        m = (fS[li + 1] - fS[li]) / (S[li + 1] - S[li])
        b = fS[li] - m * S[li]
        left = S[li]
        right = S[li + 1]
        lower_hull.append(HullNode(m=m, b=b, left=left, right=right))

    # compute upper piecewise-linear hull

    # expected final length of upper hull after full computation
    n_upper_segments = 2 * (len(S) - 2) + isinf(domain[0]) + isinf(domain[1])

    upper_hull = []

    if isinf(domain[0]):
        # first line (from -infinity)

        m = (fS[1] - fS[0]) / (S[1] - S[0])
        b = fS[0] - m * S[0]
        pr = compute_segment_log_prob(float("-inf"), S[0], m, b)

        upper_hull.append(
            HullNode(m=m, b=b, pr=pr, left=float("-inf"), right=S[0])
        )

    # second line
    m = (fS[2] - fS[1]) / (S[2] - S[1])
    b = fS[1] - m * S[1]
    pr = compute_segment_log_prob(S[0], S[1], m, b)

    upper_hull.append(HullNode(m=m, b=b, pr=pr, left=S[0], right=S[1]))

    # interior lines
    # there are two lines between each abscissa
    for li in range(1, len(S) - 2):

        m1 = (fS[li] - fS[li - 1]) / (S[li] - S[li - 1])
        b1 = fS[li] - m1 * S[li]

        m2 = (fS[li + 2] - fS[li + 1]) / (S[li + 2] - S[li + 1])
        b2 = fS[li + 1] - m2 * S[li + 1]

        if isinf(m1) and isinf(m2):
            raise ValueError("both hull slopes are infinite")

        dx1 = S[li] - S[li - 1]
        df1 = fS[li] - fS[li - 1]
        dx2 = S[li + 2] - S[li + 1]
        df2 = fS[li + 2] - fS[li + 1]

        f1 = fS[li]
        f2 = fS[li + 1]
        x1 = S[li]
        x2 = S[li + 1]

        # more numerically stable than above
        ix = ((f1 * dx1 - df1 * x1) * dx2 - (f2 * dx2 - df2 * x2) * dx1) / (df2 * dx1 - df1 * dx2)

        if isinf(m1) or abs(m1 - m2) < 10.0 ** 8 * eps(m1):
            ix = S[li]
            pr1 = float("-inf")
            pr2 = compute_segment_log_prob(ix, S[li + 1], m2, b2)
        elif isinf(m2):
            ix = S[li + 1]
            pr1 = compute_segment_log_prob(S[li], ix, m1, b1)
            pr2 = float("-inf")
        else:
            if isinf(ix):
                raise ValueError("Non finite intersection")

            if abs(ix - S[li]) < 10.0 ** 12 * eps(S[li]):
                ix = S[li]
            elif abs(ix - S[li + 1]) < 10.0**12 * eps(S[li + 1]):
                ix = S[li + 1]

            if ix < S[li] or ix > S[li + 1]:
                raise ValueError("Intersection out of bounds -- logpdf is not concave")

            pr1 = compute_segment_log_prob(S[li], ix, m1, b1)
            pr2 = compute_segment_log_prob(ix, S[li + 1], m2, b2)

            upper_hull.append(HullNode(m=m1, b=b1, pr=pr1, left=S[li], right=ix))
            upper_hull.append(HullNode(m=m2, b=b2, pr=pr2, left=ix, right=S[li + 1]))

    # second last line
    m = (fS[-2] - fS[-3]) / float(S[-2] - S[-3])
    b = fS[-2] - m * S[-2]
    pr = compute_segment_log_prob(S[-2], S[-1], m, b)

    upper_hull.append(HullNode(m=m, b=b, pr=pr, left=S[-2], right=S[-1]))

    if isinf(domain[1]):
        # last line (to infinity)
        m = (fS[-1] - fS[-2]) / (S[-1] - S[-2])
        b = fS[-1] - m * S[-1]
        pr = compute_segment_log_prob(S[-1], float("inf"), m, b)

        upper_hull.append(
            HullNode(m=m, b=b, pr=pr, left=S[-1], right=float("inf"))
        )

    # normalize probabilities
    normalized_probabilities = exp_normalize(
        asarray([node.pr for node in upper_hull])
    )

    for node, probability in zip(upper_hull, normalized_probabilities):
        node.pr = probability

    assert(len(lower_hull) == len(S) - 1)
    assert(len(upper_hull) == n_upper_segments)

    return lower_hull, upper_hull

Response: Compute the upper and lower hulls given the segment points S with function values fS and the domain of the logpdf.


Instruction:
Given the following Python 3 function, write the documentation
def sample_upper_hull(upper_hull, random_stream):
    cdf = cumsum([node.pr for node in upper_hull])

    # randomly choose a line segment
    U = random_stream.rand()

    node = next(
        (node for node, cdf_value in zip(upper_hull, cdf) if U < cdf_value),
        upper_hull[-1]  # default is last line segment
    )

    # sample along that line segment
    U = random_stream.rand()

    m, left, right = node.m, node.left, node.right

    M = max(m * right, m * left)
    x = (log(U * (exp(m * right - M) - exp(m * left - M)) + exp(m * left - M)) + M) / m

    assert(x >= left and x <= right)

    if isinf(x) or isnan(x):
        raise ValueError("sampled an infinite or 'nan' x")

    return x

Response: Return a single value randomly sampled from the given upper_hull.


Instruction:
Make a summary of the following Python 3 code
def check_for_required_columns(problems, table, df):
    r = cs.PROTOFEED_REF
    req_columns = r.loc[(r['table'] == table) & r['column_required'],
      'column'].values
    for col in req_columns:
        if col not in df.columns:
            problems.append(['error', 'Missing column {!s}'.format(col),
              table, []])

    return problems

Response: Checks that the given ProtoFeed table has the required columns.


Instruction:
Explain what the following Python 3 code does
def check_for_invalid_columns(problems, table, df):
    r = cs.PROTOFEED_REF
    valid_columns = r.loc[r['table'] == table, 'column'].values
    for col in df.columns:
        if col not in valid_columns:
            problems.append(['warning',
              'Unrecognized column {!s}'.format(col),
              table, []])

    return problems

Response: Checks if the given ProtoFeed DataFrame contains invalid columns.


Instruction:
How would you explain what the following Python 3 function does
def check_frequencies(pfeed, *, as_df=False, include_warnings=False):
    table = 'frequencies'
    problems = []

    # Preliminary checks
    if pfeed.frequencies is None:
        problems.append(['error', 'Missing table', table, []])
    else:
        f = pfeed.frequencies.copy()
        problems = check_for_required_columns(problems, table, f)
    if problems:
        return gt.format_problems(problems, as_df=as_df)

    if include_warnings:
        problems = check_for_invalid_columns(problems, table, f)

    # Check route_short_name and route_long_name
    for column in ['route_short_name', 'route_long_name']:
        problems = gt.check_column(problems, table, f, column, gt.valid_str,
          column_required=False)

    cond = ~(f['route_short_name'].notnull() | f['route_long_name'].notnull())
    problems = gt.check_table(problems, table, f, cond,
      'route_short_name and route_long_name both empty')

    # Check route_type
    v = lambda x: x in range(8)
    problems = gt.check_column(problems, table, f, 'route_type', v)

    # Check service window ID
    problems = gt.check_column_linked_id(problems, table, f,
      'service_window_id', pfeed.service_windows)

    # Check direction
    v = lambda x: x in range(3)
    problems = gt.check_column(problems, table, f, 'direction', v)

    # Check frequency
    v = lambda x: isinstance(x, int)
    problems = gt.check_column(problems, table, f, 'frequency', v)

    # Check speed
    problems = gt.check_column(problems, table, f, 'speed', valid_speed,
      column_required=False)

    # Check shape ID
    problems = gt.check_column_linked_id(problems, table, f, 'shape_id',
      pfeed.shapes)

    return gt.format_problems(problems, as_df=as_df)

Response: Check that the frequency of the current feed is well - formed.


Instruction:
Write a Python 3 script for
checking the meta data for the current feed.

Response:
def check_meta(pfeed, *, as_df=False, include_warnings=False):
    """
    Analog of :func:`check_frequencies` for ``pfeed.meta``
    """
    table = 'meta'
    problems = []

    # Preliminary checks
    if pfeed.meta is None:
        problems.append(['error', 'Missing table', table, []])
    else:
        f = pfeed.meta.copy()
        problems = check_for_required_columns(problems, table, f)
    if problems:
        return gt.format_problems(problems, as_df=as_df)

    if include_warnings:
        problems = check_for_invalid_columns(problems, table, f)

    if f.shape[0] > 1:
        problems.append(['error', 'Meta must have only one row',
          table, list(range(1, f.shape[0]))])

    # Check agency_name
    problems = gt.check_column(problems, table, f, 'agency_name', gt.valid_str)

    # Check agency_url
    problems = gt.check_column(problems, table, f, 'agency_url', gt.valid_url)

    # Check agency_timezone
    problems = gt.check_column(problems, table, f, 'agency_timezone',
      gt.valid_timezone)

    # Check start_date and end_date
    for col in ['start_date', 'end_date']:
        problems = gt.check_column(problems, table, f, col, gt.valid_date)

    # Check default_route_speed
    problems = gt.check_column(problems, table, f, 'default_route_speed',
      valid_speed)

    return gt.format_problems(problems, as_df=as_df)


Instruction:
Can you tell what is the following Python 3 function doing
def check_service_windows(pfeed, *, as_df=False, include_warnings=False):
    table = 'service_windows'
    problems = []

    # Preliminary checks
    if pfeed.service_windows is None:
        problems.append(['error', 'Missing table', table, []])
    else:
        f = pfeed.service_windows.copy()
        problems = check_for_required_columns(problems, table, f)
    if problems:
        return gt.format_problems(problems, as_df=as_df)

    if include_warnings:
        problems = check_for_invalid_columns(problems, table, f)

    # Check service window ID
    problems = gt.check_column_id(problems, table, f,
      'service_window_id')

    # Check start_time and end_time
    for column in ['start_time', 'end_time']:
        problems = gt.check_column(problems, table, f, column, gt.valid_time)

    # Check weekday columns
    v = lambda x: x in range(2)
    for col in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday',
      'saturday', 'sunday']:
        problems = gt.check_column(problems, table, f, col, v)

    return gt.format_problems(problems, as_df=as_df)

Response: Checks that the service windows are valid and returns a list of problems.


Instruction:
Implement a function in Python 3 to
check that all required columns are present in the feed.

Response:
def check_shapes(pfeed, *, as_df=False, include_warnings=False):
    """
    Analog of :func:`check_frequencies` for ``pfeed.shapes``
    """
    table = 'shapes'
    problems = []

    # Preliminary checks
    if pfeed.shapes is None:
        return problems

    f = pfeed.shapes.copy()
    problems = check_for_required_columns(problems, table, f)
    if problems:
        return gt.format_problems(problems, as_df=as_df)

    if include_warnings:
        problems = check_for_invalid_columns(problems, table, f)

    # Check shape_id
    problems = gt.check_column(problems, table, f, 'shape_id', gt.valid_str)

    # Check geometry
    v = lambda x: isinstance(x, sg.LineString) and not x.is_empty
    problems = gt.check_column(problems, table, f, 'geometry', v)

    return gt.format_problems(problems, as_df=as_df)


Instruction:
Write a Python 3 function for
checking that all stops in a given feed are in a given distribution.

Response:
def check_stops(pfeed, *, as_df=False, include_warnings=False):
    """
    Analog of :func:`check_frequencies` for ``pfeed.stops``
    """
    # Use gtfstk's stop validator
    if pfeed.stops is not None:
        stop_times = pd.DataFrame(columns=['stop_id'])
        feed = gt.Feed(stops=pfeed.stops, stop_times=stop_times,
          dist_units='km')
        return gt.check_stops(feed, as_df=as_df, include_warnings=False)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def validate(pfeed, *, as_df=True, include_warnings=True):
    problems = []

    # Check for invalid columns and check the required tables
    checkers = [
      'check_frequencies',
      'check_meta',
      'check_service_windows',
      'check_shapes',
      'check_stops',
    ]
    for checker in checkers:
        problems.extend(globals()[checker](pfeed,
          include_warnings=include_warnings))

    return gt.format_problems(problems, as_df=as_df)

Response: Validate a ProtoFeed object.


Instruction:
Make a summary of the following Python 3 code
def youtube(keyword=None):
    if keyword is None:
        web.open('https://www.youtube.com/watch?v=L_mBVT2jBFw')
    else:
        web.open(quote('https://www.youtube.com/results?search_query={}'.format(keyword), RESERVED))

Response:
Open youtube.

    Args:
        keyword (optional): Search word.


Instruction:
Explain what the following Python 3 code does
def replace_escapes(self, m):

        groups = m.groupdict()
        esc = m.group(0)
        if groups.get('special'):
            value = BACK_SLASH_TRANSLATION[esc]
        elif groups.get('char'):
            try:
                if esc.endswith('}'):
                    value = chr(int(esc[3:-1], 16))
                else:
                    value = chr(int(esc[2:], 16))
            except Exception:
                value = esc
        elif groups.get('oct'):
            # JavaScript only supports hex range.
            # So \400 would be \40 + '0'
            value = int(esc[1:], 8)
            overflow = ''
            if value > 255:
                value = esc[1:-1]
                overflow + esc[-1]
            value = chr(value) + overflow
        elif('other'):
            value = esc[1:]
        return value.replace('\x00', '\n')

Response: Replace escapes in a message.


Instruction:
Create a Python 3 function for
replacing surrogates in a string.

Response:
def replace_surrogates(self, m):
        """Replace surrogates."""

        high, low = ord(m.group(1)), ord(m.group(2))
        return chr((high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000)


Instruction:
Given the following Python 3 function, write the documentation
def find_content(self, text, index=0, backtick=False):

        curly_count = 0
        last = '\n'
        self.lines_num = 1
        length = len(text)
        while index < length:
            start_index = index
            c = text[index]
            if c == '{' and backtick:
                curly_count += 1
            elif c == '}' and backtick:
                if curly_count:
                    curly_count -= 1
                else:
                    index += 1
                    return index
            elif c == '`':
                done = False
                first = True
                backtick_content = []
                start_index = index
                while not done:
                    m = (RE_TEMPLATE_START if first else RE_TEMPLATE_MIDDLE_END).match(text, index)
                    first = False
                    if m:
                        self.line_num += m.group(0).count('\n')
                        content = self.evaluate_strings(m.group(1), True)
                        if content:
                            backtick_content.append(content)
                        index = m.end(0)
                        if m.group(2) == '${':
                            index = self.find_content(text, index, True)
                        else:
                            done = True
                    else:
                        done = True
                if backtick_content:
                    self.quoted_strings.append([' '.join(backtick_content), self.line_num, 'utf-8'])
            elif c in ('\'', '"'):
                m = RE_STRING.match(text, index)
                if m:
                    self.evaluate_strings(m.group(0)[1:-1])
                    self.line_num += m.group(0).count('\n')
                    index = m.end(0)
            elif c == '\n':
                self.line_num += 1
            elif last == '\n' or c == '/':
                m = RE_COMMENT.match(text, index)
                if m:
                    g = m.groupdict()
                    if g['start'] is None:
                        self.evaluate_inline_tail(g)
                    else:
                        self.evaluate_inline(g)
                    index = m.end(0)
                elif c == '/':
                    m = RE_BLOCK_COMMENT.match(text, index)
                    if m:
                        self.evaluate_block(m.group(0))
                        self.line_num += m.group(0).count('\n')
                        index = m.end(0)

            if index == start_index:
                index += 1
            last = text[index - 1]

Response: Find content in text.


Instruction:
Can you tell what is the following Python 3 function doing
def override_config(self, options):

        for k, v in options.items():
            # Reject names not in the default configuration
            if k not in self.config:
                raise KeyError("'{}' is not a valid option for '{}'".format(k, self.__class__.__name__))
            self.validate_options(k, v)
            self.config[k] = v

Response: Override the default configuration.


Instruction:
Can you create a Python 3 function that
returns the duration of the time period between the first and second time string in the given units.

Response:
def get_duration(timestr1, timestr2, units='s'):
    """
    Return the duration of the time period between the first and second
    time string in the given units.
    Allowable units are 's' (seconds), 'min' (minutes), 'h' (hours).
    Assume ``timestr1 < timestr2``.
    """
    valid_units = ['s', 'min', 'h']
    assert units in valid_units,\
      "Units must be one of {!s}".format(valid_units)

    duration = (
        gt.timestr_to_seconds(timestr2) - gt.timestr_to_seconds(timestr1)
    )

    if units == 's':
        return duration
    elif units == 'min':
        return duration/60
    else:
        return duration/3600


Instruction:
Write a Python 3 script to
build a list of stop IDs based on the given shape ID.

Response:
def build_stop_ids(shape_id):
    """
    Create a pair of stop IDs based on the given shape ID.
    """
    return [cs.SEP.join(['stp', shape_id, str(i)]) for i in range(2)]


Instruction:
Write a Python 3 script to
give a ProtoFeed return a DataFrame representing agency. txt

Response:
def build_agency(pfeed):
    """
    Given a ProtoFeed, return a DataFrame representing ``agency.txt``
    """
    return pd.DataFrame({
      'agency_name': pfeed.meta['agency_name'].iat[0],
      'agency_url': pfeed.meta['agency_url'].iat[0],
      'agency_timezone': pfeed.meta['agency_timezone'].iat[0],
    }, index=[0])


Instruction:
Implement a Python 3 function for
giving a ProtoFeed return a DataFrame representing a calendar. txt and a dictionary of the form <service window ID > -> <service ID > where each dictionary contains the service IDs and each service window ID is a unique identifier for each service window.

Response:
def build_calendar_etc(pfeed):
    """
    Given a ProtoFeed, return a DataFrame representing ``calendar.txt``
    and a dictionary of the form <service window ID> -> <service ID>,
    respectively.
    """
    windows = pfeed.service_windows.copy()

    # Create a service ID for each distinct days_active field and map the
    # service windows to those service IDs
    def get_sid(bitlist):
        return 'srv' + ''.join([str(b) for b in bitlist])

    weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday',
      'saturday', 'sunday']
    bitlists = set()

    # Create a dictionary <service window ID> -> <service ID>
    d = dict()
    for index, window in windows.iterrows():
        bitlist = window[weekdays].tolist()
        d[window['service_window_id']] = get_sid(bitlist)
        bitlists.add(tuple(bitlist))
    service_by_window = d

    # Create calendar
    start_date = pfeed.meta['start_date'].iat[0]
    end_date = pfeed.meta['end_date'].iat[0]
    F = []
    for bitlist in bitlists:
        F.append([get_sid(bitlist)] + list(bitlist) +
          [start_date, end_date])
    calendar = pd.DataFrame(F, columns=(
      ['service_id'] + weekdays + ['start_date', 'end_date']))

    return calendar, service_by_window


Instruction:
Can you tell what is the following Python 3 function doing
def build_routes(pfeed):
    f = pfeed.frequencies[['route_short_name', 'route_long_name',
      'route_type', 'shape_id']].drop_duplicates().copy()

    # Create route IDs
    f['route_id'] = 'r' + f['route_short_name'].map(str)

    del f['shape_id']

    return f

Response: Given a ProtoFeed return a DataFrame representing routes. txt.


Instruction:
Implement a Python 3 function for
giving a ProtoFeed return a DataFrame representing the shapes. txt.

Response:
def build_shapes(pfeed):
    """
    Given a ProtoFeed, return DataFrame representing ``shapes.txt``.
    Only use shape IDs that occur in both ``pfeed.shapes`` and
    ``pfeed.frequencies``.
    Create reversed shapes where routes traverse shapes in both
    directions.
    """
    rows = []
    for shape, geom in pfeed.shapes[['shape_id',
      'geometry']].itertuples(index=False):
        if shape not in pfeed.shapes_extra:
            continue
        if pfeed.shapes_extra[shape] == 2:
            # Add shape and its reverse
            shid = shape + '-1'
            new_rows = [[shid, i, lon, lat]
              for i, (lon, lat) in enumerate(geom.coords)]
            rows.extend(new_rows)
            shid = shape + '-0'
            new_rows = [[shid, i, lon, lat]
              for i, (lon, lat) in enumerate(reversed(geom.coords))]
            rows.extend(new_rows)
        else:
            # Add shape
            shid = '{}{}{}'.format(shape, cs.SEP, pfeed.shapes_extra[shape])
            new_rows = [[shid, i, lon, lat]
              for i, (lon, lat) in enumerate(geom.coords)]
            rows.extend(new_rows)

    return pd.DataFrame(rows, columns=['shape_id', 'shape_pt_sequence',
      'shape_pt_lon', 'shape_pt_lat'])


Instruction:
Here you have a function in Python 3, explain what it does
def build_stops(pfeed, shapes=None):
    if pfeed.stops is not None:
        stops = pfeed.stops.copy()
    else:
        if shapes is None:
            raise ValueError('Must input shapes built by build_shapes()')

        geo_shapes = gt.geometrize_shapes(shapes)
        rows = []
        for shape, geom in geo_shapes[['shape_id',
          'geometry']].itertuples(index=False):
            stop_ids = build_stop_ids(shape)
            stop_names = build_stop_names(shape)
            for i in range(2):
                stop_id = stop_ids[i]
                stop_name = stop_names[i]
                stop_lon, stop_lat = geom.interpolate(i,
                  normalized=True).coords[0]
                rows.append([stop_id, stop_name, stop_lon, stop_lat])

        stops = (
            pd.DataFrame(rows, columns=['stop_id', 'stop_name',
              'stop_lon', 'stop_lat'])
            .drop_duplicates(subset=['stop_lon', 'stop_lat'])
        )

    return stops

Response: Given a ProtoFeed return a DataFrame representing the stops. txt.


Instruction:
Explain what the following Python 3 code does
def build_trips(pfeed, routes, service_by_window):
    # Put together the route and service data
    routes = pd.merge(routes[['route_id', 'route_short_name']],
      pfeed.frequencies)
    routes = pd.merge(routes, pfeed.service_windows)

    # For each row in routes, add trips at the specified frequency in
    # the specified direction
    rows = []
    for index, row in routes.iterrows():
        shape = row['shape_id']
        route = row['route_id']
        window = row['service_window_id']
        start, end = row[['start_time', 'end_time']].values
        duration = get_duration(start, end, 'h')
        frequency = row['frequency']
        if not frequency:
            # No trips during this service window
            continue
        # Rounding down occurs here if the duration isn't integral
        # (bad input)
        num_trips_per_direction = int(frequency*duration)
        service = service_by_window[window]
        direction = row['direction']
        if direction == 2:
            directions = [0, 1]
        else:
            directions = [direction]
        for direction in directions:
            # Warning: this shape-ID-making logic needs to match that
            # in ``build_shapes``
            shid = '{}{}{}'.format(shape, cs.SEP, direction)
            rows.extend([[
              route,
              cs.SEP.join(['t', route, window, start,
              str(direction), str(i)]),
              direction,
              shid,
              service
            ] for i in range(num_trips_per_direction)])

    return pd.DataFrame(rows, columns=['route_id', 'trip_id', 'direction_id',
      'shape_id', 'service_id'])

Response: Given a ProtoFeed and its corresponding routes and service - by - window return a DataFrame representing the trips. txt.


Instruction:
How would you code a function in Python 3 to
give a Shapely LineString a side of the LineString and a buffer size in the distance units of the LineString return the resulting Shapely polygon.

Response:
def buffer_side(linestring, side, buffer):
    """
    Given a Shapely LineString, a side of the LineString
    (string; 'left' = left hand side of LineString,
    'right' = right hand side of LineString, or
    'both' = both sides), and a buffer size in the distance units of
    the LineString, buffer the LineString on the given side by
    the buffer size and return the resulting Shapely polygon.
    """
    b = linestring.buffer(buffer, cap_style=2)
    if side in ['left', 'right'] and buffer > 0:
        # Make a tiny buffer to split the normal-size buffer
        # in half across the linestring
        eps = min(buffer/2, 0.001)
        b0 = linestring.buffer(eps, cap_style=3)
        diff = b.difference(b0)
        polys = so.polygonize(diff)
        # Buffer sides slightly to include original linestring
        if side == 'left':
            b = list(polys)[0].buffer(1.1*eps)
        else:
            b = list(polys)[-1].buffer(1.1*eps)

    return b


Instruction:
Implement a Python 3 function for
giving a GeoDataFrame of stops a Shapely LineString and a side of the LineString return a GeoDataFrame of all the stops that lie within a buffer.

Response:
def get_nearby_stops(geo_stops, linestring, side, buffer=cs.BUFFER):
    """
    Given a GeoDataFrame of stops, a Shapely LineString in the
    same coordinate system, a side of the LineString
    (string; 'left' = left hand side of LineString,
    'right' = right hand side of LineString, or
    'both' = both sides), and a buffer in the distance units of that
    coordinate system, do the following.
    Return a GeoDataFrame of all the stops that lie within
    ``buffer`` distance units to the ``side`` of the LineString.
    """
    b = buffer_side(linestring, side, buffer)

    # Collect stops
    return geo_stops.loc[geo_stops.intersects(b)].copy()


Instruction:
Make a summary of the following Python 3 code
def build_stop_times(pfeed, routes, shapes, stops, trips, buffer=cs.BUFFER):
    # Get the table of trips and add frequency and service window details
    routes = (
        routes
        .filter(['route_id', 'route_short_name'])
        .merge(pfeed.frequencies.drop(['shape_id'], axis=1))
    )
    trips = (
        trips
        .assign(service_window_id=lambda x: x.trip_id.map(
          lambda y: y.split(cs.SEP)[2]))
        .merge(routes)
    )

    # Get the geometries of ``shapes`` and not ``pfeed.shapes``
    geometry_by_shape = dict(
        gt.geometrize_shapes(shapes, use_utm=True)
        .filter(['shape_id', 'geometry'])
        .values
    )

    # Save on distance computations by memoizing
    dist_by_stop_by_shape = {shape: {} for shape in geometry_by_shape}

    def compute_stops_dists_times(geo_stops, linestring, shape,
      start_time, end_time):
        """
        Given a GeoDataFrame of stops on one side of a given Shapely
        LineString with given shape ID, compute distances and departure
        times of a trip traversing the LineString from start to end
        at the given start and end times (in seconds past midnight)
        and stopping at the stops encountered along the way.
        Do not assume that the stops are ordered by trip encounter.
        Return three lists of the same length: the stop IDs in order
        that the trip encounters them, the shape distances traveled
        along distances at the stops, and the times the stops are
        encountered, respectively.
        """
        g = geo_stops.copy()
        dists_and_stops = []
        for i, stop in enumerate(g['stop_id'].values):
            if stop in dist_by_stop_by_shape[shape]:
                d = dist_by_stop_by_shape[shape][stop]
            else:
                d = gt.get_segment_length(linestring,
                  g.geometry.iat[i])/1000  # km
                dist_by_stop_by_shape[shape][stop] = d
            dists_and_stops.append((d, stop))
        dists, stops = zip(*sorted(dists_and_stops))
        D = linestring.length/1000
        dists_are_reasonable = all([d < D + 100 for d in dists])
        if not dists_are_reasonable:
            # Assume equal distances between stops :-(
            n = len(stops)
            delta = D/(n - 1)
            dists = [i*delta for i in range(n)]

        # Compute times using distances, start and end stop times,
        # and linear interpolation
        t0, t1 = start_time, end_time
        d0, d1 = dists[0], dists[-1]
        # Interpolate
        times = np.interp(dists, [d0, d1], [t0, t1])
        return stops, dists, times

    # Iterate through trips and set stop times based on stop ID
    # and service window frequency.
    # Remember that every trip has a valid shape ID.
    # Gather stops geographically from ``stops``.
    rows = []
    geo_stops = gt.geometrize_stops(stops, use_utm=True)
    # Look on the side of the traffic side of street for this timezone
    side = cs.traffic_by_timezone[pfeed.meta.agency_timezone.iat[0]]
    for index, row in trips.iterrows():
        shape = row['shape_id']
        geom = geometry_by_shape[shape]
        stops = get_nearby_stops(geo_stops, geom, side, buffer=buffer)
        # Don't make stop times for trips without nearby stops
        if stops.empty:
            continue
        length = geom.length/1000  # km
        speed = row['speed']  # km/h
        duration = int((length/speed)*3600)  # seconds
        frequency = row['frequency']
        if not frequency:
            # No stop times for this trip/frequency combo
            continue
        headway = 3600/frequency  # seconds
        trip = row['trip_id']
        __, route, window, base_timestr, direction, i = (
          trip.split(cs.SEP))
        direction = int(direction)
        base_time = gt.timestr_to_seconds(base_timestr)
        start_time = base_time + headway*int(i)
        end_time = start_time + duration
        stops, dists, times = compute_stops_dists_times(stops, geom, shape,
          start_time, end_time)
        new_rows = [[trip, stop, j, time, time, dist]
          for j, (stop, time, dist) in enumerate(zip(stops, times, dists))]
        rows.extend(new_rows)

    g = pd.DataFrame(rows, columns=['trip_id', 'stop_id', 'stop_sequence',
      'arrival_time', 'departure_time', 'shape_dist_traveled'])

    # Convert seconds back to time strings
    g[['arrival_time', 'departure_time']] =\
      g[['arrival_time', 'departure_time']].applymap(
      lambda x: gt.timestr_to_seconds(x, inverse=True))

    return g

Response: Builds a DataFrame representing stop times for a given ProtoFeed.


Instruction:
Given the following Python 3 function, write the documentation
def _generate_content(self):
        # concat into a dict
        dic = self.config
        dic['mode'] = self.language
        if self.theme:
            dic['theme'] = self.theme
        # dumps with json
        return json.dumps(dic, indent=8, separators=(',', ': '))

Response: Dumps content using JSON to send to CodeMirror


Instruction:
Can you tell what is the following Python 3 function doing
def get_token_details(self, show_listing_details=False, show_inactive=False):
        api_params = {
            "show_listing_details": show_listing_details,
            "show_inactive": show_inactive
        }
        return self.request.get(path='/exchange/tokens', params=api_params)

Response: This method returns the available tokens for the Switcheo exchange.


Instruction:
How would you implement a function in Python 3 that
functions to fetch trading metrics from the past 24 hours for all trading pairs offered on the exchange. Execution of this function is as follows:: get_candlesticks(pair="SWTH_NEO", start_time=round(time.time()) - 350000, end_time=round(time.time()), interval=360)) The expected return result for this function is as follows:: [{ 'time': '1533168000', 'open': '0.00046835', 'close': '0.00046835', 'high': '0.00046835', 'low': '0.00046835', 'volume': '240315335.0', 'quote_volume': '513110569018.0' },{ 'time': '1533081600', 'open': '0.00046835', 'close': '0.00046835', 'high': '0.00046835', 'low': '0.00046835', 'volume': '1170875.0', 'quote_volume': '2500000000.0' }, ... ] :param pair: The trading pair used to request candle statistics. :type pair: str :param start_time: The start time (in epoch seconds) range for collecting candle statistics. :type start_time: int :param end_time: The end time (in epoch seconds) range for collecting candle statistics. :type end_time: int :param interval: The time interval (in minutes) for candle statistics. Allowed values: 1, 5, 30, 60, 360, 1440 :type interval: int :return: List of dictionaries containing the candles statistics based on the parameter filters.

Response:
def get_candlesticks(self, pair, start_time, end_time, interval):
        """
        Function to fetch trading metrics from the past 24 hours for all trading pairs offered on the exchange.
        Execution of this function is as follows::

            get_candlesticks(pair="SWTH_NEO",
                             start_time=round(time.time()) - 350000,
                             end_time=round(time.time()),
                             interval=360))

        The expected return result for this function is as follows::

            [{
                'time': '1533168000',
                'open': '0.00046835',
                'close': '0.00046835',
                'high': '0.00046835',
                'low': '0.00046835',
                'volume': '240315335.0',
                'quote_volume': '513110569018.0'
            },{
                'time': '1533081600',
                'open': '0.00046835',
                'close': '0.00046835',
                'high': '0.00046835',
                'low': '0.00046835',
                'volume': '1170875.0',
                'quote_volume': '2500000000.0'
            },
            ...
            ]

        :param pair: The trading pair used to request candle statistics.
        :type pair: str
        :param start_time: The start time (in epoch seconds) range for collecting candle statistics.
        :type start_time: int
        :param end_time: The end time (in epoch seconds) range for collecting candle statistics.
        :type end_time: int
        :param interval: The time interval (in minutes) for candle statistics.  Allowed values: 1, 5, 30, 60, 360, 1440
        :type interval: int
        :return: List of dictionaries containing the candles statistics based on the parameter filters.
        """
        api_params = {
            "pair": pair,
            "interval": interval,
            "start_time": start_time,
            "end_time": end_time,
            "contract_hash": self.contract_hash
        }
        return self.request.get(path='/tickers/candlesticks', params=api_params)


Instruction:
Here you have a function in Python 3, explain what it does
def get_last_price(self, symbols=None, bases=None):
        api_params = {}
        if symbols is not None:
            api_params['symbols'] = symbols
        if bases is not None:
            api_params['bases'] = bases
        return self.request.get(path='/tickers/last_price', params=api_params)

Response: This function returns the last price of the most recently executed trade on the order book for each trading pair.


Instruction:
Write a Python 3 function that can
function to fetch the open orders on the order book for the trade pair requested. Execution of this function is as follows:: get_offers(pair="SWTH_NEO") The expected return result for this function is as follows:: [{ 'id': '2716c0ca-59bb-4c86-8ee4-6b9528d0e5d2', 'offer_asset': 'GAS', 'want_asset': 'NEO', 'available_amount': 9509259, 'offer_amount': 30000000, 'want_amount': 300000000, 'address': '7f345d1a031c4099540dbbbc220d4e5640ab2b6f' }, { .... }] :param pair: The trading pair that will be used to request open offers on the order book. :type pair: str :return: List of dictionaries consisting of the open offers for the requested trading pair.

Response:
def get_offers(self, pair="SWTH_NEO"):
        """
        Function to fetch the open orders on the order book for the trade pair requested.
        Execution of this function is as follows::

            get_offers(pair="SWTH_NEO")

        The expected return result for this function is as follows::

            [{
                'id': '2716c0ca-59bb-4c86-8ee4-6b9528d0e5d2',
                'offer_asset': 'GAS',
                'want_asset': 'NEO',
                'available_amount': 9509259,
                'offer_amount': 30000000,
                'want_amount': 300000000,
                'address': '7f345d1a031c4099540dbbbc220d4e5640ab2b6f'
            }, {
                ....
            }]

        :param pair: The trading pair that will be used to request open offers on the order book.
        :type pair: str
        :return: List of dictionaries consisting of the open offers for the requested trading pair.
        """
        api_params = {
            "pair": pair,
            "contract_hash": self.contract_hash
        }
        return self.request.get(path='/offers', params=api_params)