text:
import unittest
import os
import numpy as np
import pandas as pd
import pickle
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import OneHotEncoder
from PyALE._src.ALE_1D import (
    aleplot_1D_continuous,
    plot_1D_continuous_eff,
    aleplot_1D_discrete,
    aleplot_1D_categorical,
    plot_1D_discrete_eff,
)

def onehot_encode(feat):
    ohe = OneHotEncoder().fit(feat)
    col_names = ohe.categories_[0]
    feat_coded = pd.DataFrame(ohe.transform(feat).toarray())
    feat_coded.columns = col_names
    return feat_coded

def onehot_encode_custom(feat, groups=['A', 'C', 'B']):
    feat_coded = onehot_encode(feat)
    missing_feat = [x for x in groups if x not in feat_coded.columns]
    if missing_feat:
        feat_coded[missing_feat] = 0
    return feat_coded

class Test1DFunctions(unittest.TestCase):
    def setUp(self):
        path_to_fixtures = os.path.join(os.path.dirname(__file__), "fixtures")
        with open(os.path.join(path_to_fixtures, "X.pickle"), "rb") as model_pickle:
            self.X = pickle.load(model_pickle)
        with open(
            os.path.join(path_to_fixtures, "X_cleaned.pickle"), "rb"
        ) as model_pickle:
            self.X_cleaned = pickle.load(model_pickle)
        with open(os.path.join(path_to_fixtures, "y.npy"), "rb") as y_npy:
            self.y = np.load(y_npy)
        with open(os.path.join(path_to_fixtures, "model.pickle"), "rb") as model_pickle:
            self.model = pickle.load(model_pickle)

class Test1DContinuous(Test1DFunctions):
    def test_indexname(self):
        ale_eff = aleplot_1D_continuous(
            X=self.X_cleaned,
            model=self.model,
            feature="x1",
            grid_size=5,
            include_CI=False,
        )
        self.assertEqual(ale_eff.index.name, "x1")

    def test_outputshape_noCI(self):
        ale_eff = aleplot_1D_continuous(
            X=self.X_cleaned,
            model=self.model,
            feature="x1",
            grid_size=5,
            include_CI=False,
        )
        self.assertEqual(ale_eff.shape, (6, 2))
        self.assertCountEqual(ale_eff.columns, ["eff", "size"])

    def test_outputshape_withCI(self):
        ale_eff = aleplot_1D_continuous(
            X=self.X_cleaned,
            model=self.model,
            feature="x1",
            grid_size=5,
            include_CI=True,
            C=0.9,
        )
        self.assertEqual(ale_eff.shape, (6, 4))
        self.assertCountEqual(
            ale_eff.columns, ["eff", "size", "lowerCI_90%", "upperCI_90%"]
        )

    def test_bins(self):
        ale_eff = aleplot_1D_continuous(
            X=self.X_cleaned,
            model=self.model,
            feature="x1",
            grid_size=5,
            include_CI=False,
        )
        self.assertCountEqual(
            ale_eff.index,
            [
                0.0013107121819164735,
                0.21205399821897986,
                0.3905585553320686,
                0.5561380185409515,
                0.7797798975036754,
                0.9986526271693825,
            ],
        )

    def test_effvalues(self):
        ale_eff = aleplot_1D_continuous(
            X=self.X_cleaned,
            model=self.model,
            feature="x1",
            grid_size=5,
            include_CI=False,
        )
        self.assertCountEqual(
            np.round(ale_eff.loc[:, "eff"], 8),
            [-0.3302859, -0.25946135, -0.03809224, 0.03292833, 0.27153761, 0.3164612],
        )

    def test_binsizes(self):
        ale_eff = aleplot_1D_continuous(
            X=self.X_cleaned,
            model=self.model,
            feature="x1",
            grid_size=5,
            include_CI=False,
        )
        self.assertCountEqual(
            ale_eff.loc[:, "size"], [0.0, 40.0, 40.0, 40.0, 40.0, 40.0]
        )

    def test_CIvalues(self):
        ale_eff = aleplot_1D_continuous(
            X=self.X_cleaned,
            model=self.model,
            feature="x1",
            grid_size=5,
            include_CI=True,
            C=0.9,
        )
        # assert that the first bin do not have a CI
        self.assertTrue(np.isnan(ale_eff.loc[ale_eff.index[0], "lowerCI_90%"]))
        self.assertTrue(np.isnan(ale_eff.loc[ale_eff.index[0], "upperCI_90%"]))
        # check the values of the CI
        self.assertCountEqual(
            np.round(ale_eff.loc[ale_eff.index[1] :, "lowerCI_90%"], 8),
            [-0.37210104, -0.08077478, -0.00175768, 0.20772107, 0.24621853],
        )
        self.assertCountEqual(
            np.round(ale_eff.loc[ale_eff.index[1] :, "upperCI_90%"], 8),
            [-0.14682166, 0.00459031, 0.06761434, 0.33535415, 0.38670386],
        )

    def test_exceptions(self):
        # dataset should be compatible with the model
        with self.assertRaises(Exception) as mod_ex_2:
            aleplot_1D_continuous(self.X, self.model, "x1")
        mod_ex_msg = "Please check that your model is fitted, and accepts X as input."
        self.assertEqual(mod_ex_2.exception.args[0], mod_ex_msg)

class Test1Ddiscrete(Test1DFunctions):
    def test_indexname(self):
        ale_eff = aleplot_1D_discrete(
            X=self.X_cleaned, model=self.model, feature="x4", include_CI=False
        )
        self.assertEqual(ale_eff.index.name, "x4")

    def test_outputshape_noCI(self):
        ale_eff = aleplot_1D_discrete(
            X=self.X_cleaned, model=self.model, feature="x4", include_CI=False
        )
        self.assertEqual(ale_eff.shape, (10, 2))
        self.assertCountEqual(ale_eff.columns, ["eff", "size"])

    def test_outputshape_withCI(self):
        ale_eff = aleplot_1D_discrete(
            X=self.X_cleaned, model=self.model, feature="x4", include_CI=True, C=0.9
        )
        self.assertEqual(ale_eff.shape, (10, 4))
        self.assertCountEqual(
            ale_eff.columns, ["eff", "size", "lowerCI_90%", "upperCI_90%"]
        )

    def test_bins(self):
        ale_eff = aleplot_1D_discrete(
            X=self.X_cleaned, model=self.model, feature="x4", include_CI=False
        )
        self.assertCountEqual(
            ale_eff.index, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        )

    def test_effvalues(self):
        ale_eff = aleplot_1D_discrete(
            X=self.X_cleaned, model=self.model, feature="x4", include_CI=False
        )
        self.assertCountEqual(
            np.round(ale_eff.loc[:, "eff"], 8),
            [
                -1.15833245,
                -0.87518863,
                -0.17627267,
                -0.03183705,
                0.21772015,
                0.3103579,
                0.37654819,
                0.38187692,
                0.54013521,
                0.59118777,
            ],
        )

    def test_binsizes(self):
        ale_eff = aleplot_1D_discrete(
            X=self.X_cleaned, model=self.model, feature="x4", include_CI=False
        )
        self.assertCountEqual(
            ale_eff.loc[:, "size"], [27, 14, 16, 26, 20, 17, 18, 23, 21, 18]
        )

    def test_CIvalues(self):
        ale_eff = aleplot_1D_discrete(
            X=self.X_cleaned, model=self.model, feature="x4", include_CI=True, C=0.9
        )
        # assert that the first bin do not have a CI
        self.assertTrue(np.isnan(ale_eff.loc[ale_eff.index[0], "lowerCI_90%"]))
        self.assertTrue(np.isnan(ale_eff.loc[ale_eff.index[0], "upperCI_90%"]))
        # check the values of the CI
        self.assertCountEqual(
            np.round(ale_eff.loc[ale_eff.index[1] :, "lowerCI_90%"], 8),
            [
                -0.92693686,
                -0.30837293,
                -0.05872927,
                0.17298345,
                0.23835091,
                0.34097451,
                0.35996381,
                0.47381797,
                0.56927921,
            ],
        )
        self.assertCountEqual(
            np.round(ale_eff.loc[ale_eff.index[1] :, "upperCI_90%"], 8),
            [
                -0.8234404,
                -0.0441724,
                -0.00494484,
                0.26245684,
                0.38236488,
                0.41212186,
                0.40379003,
                0.60645245,
                0.61309633,
            ],
        )

    def test_exceptions(self):
        mod_not_fit = RandomForestRegressor()
        # dataset should be compatible with the model
        with self.assertRaises(Exception) as mod_ex_2:
            aleplot_1D_discrete(self.X, mod_not_fit, "x4")
        mod_ex_msg = "Please check that your model is fitted, and accepts X as input."
        self.assertEqual(mod_ex_2.exception.args[0], mod_ex_msg)

class Test1Ddiscrete(Test1DFunctions):
    def test_indexname(self):
        ale_eff = aleplot_1D_categorical(
            X=self.X,
            model=self.model,
            feature="x5",
            predictors=self.X_cleaned.columns,
            encode_fun=onehot_encode_custom,
            include_CI=False
        )
        self.assertEqual(ale_eff.index.name, "x5")

    def test_outputshape_noCI(self):
        ale_eff = aleplot_1D_categorical(
            X=self.X,
            model=self.model,
            feature="x5",
            predictors=self.X_cleaned.columns,
            encode_fun=onehot_encode_custom,
            include_CI=False
        )
        self.assertEqual(ale_eff.shape, (3, 2))
        self.assertCountEqual(ale_eff.columns, ["eff", "size"])

    def test_outputshape_withCI(self):
        ale_eff = aleplot_1D_categorical(
            X=self.X,
            model=self.model,
            feature="x5",
            predictors=self.X_cleaned.columns,
            encode_fun=onehot_encode_custom,
            include_CI=True,
            C=0.9
        )
        self.assertEqual(ale_eff.shape, (3, 4))
        self.assertCountEqual(
            ale_eff.columns, ["eff", "size", "lowerCI_90%", "upperCI_90%"]
        )

    def test_bins(self):
        ale_eff = aleplot_1D_categorical(
            X=self.X,
            model=self.model,
            feature="x5",
            predictors=self.X_cleaned.columns,
            encode_fun=onehot_encode_custom,
            include_CI=False
        )
        self.assertCountEqual(
            ale_eff.index, ['A', 'B', 'C'],
        )

    def test_effvalues(self):
        ale_eff = aleplot_1D_categorical(
            X=self.X,
            model=self.model,
            feature="x5",
            predictors=self.X_cleaned.columns,
            encode_fun=onehot_encode_custom,
            include_CI=False
        )
        self.assertCountEqual(
            np.round(ale_eff.loc[:, "eff"], 8),
            [-0.05565697,  0.02367971,  0.02044105],
        )

    def test_binsizes(self):
        ale_eff = aleplot_1D_categorical(
            X=self.X,
            model=self.model,
            feature="x5",
            predictors=self.X_cleaned.columns,
            encode_fun=onehot_encode_custom,
            include_CI=False
        )
        self.assertCountEqual(
            ale_eff.loc[:, "size"], [57, 77, 66]
        )

    def test_CIvalues(self):
        ale_eff = aleplot_1D_categorical(
            X=self.X,
            model=self.model,
            feature="x5",
            predictors=self.X_cleaned.columns,
            encode_fun=onehot_encode_custom,
            include_CI=True,
            C=0.9
        )
        # assert that the first bin do not have a CI
        self.assertTrue(np.isnan(ale_eff.loc[ale_eff.index[0], "lowerCI_90%"]))
        self.assertTrue(np.isnan(ale_eff.loc[ale_eff.index[0], "upperCI_90%"]))
        # check the values of the CI
        self.assertCountEqual(
            np.round(ale_eff.loc[ale_eff.index[1] :, "lowerCI_90%"], 8),
            [-0.00605249, -0.00523023],
        )
        self.assertCountEqual(
            np.round(ale_eff.loc[ale_eff.index[1] :, "upperCI_90%"], 8),
            [0.05341192, 0.04611233],
        )
    def test_exceptions(self):
        mod_not_fit = RandomForestRegressor()
        # dataset should be compatible with the model
        with self.assertRaises(Exception) as mod_ex_1:
            aleplot_1D_categorical(
                X=self.X,
                model=self.model.predict,
                feature="x5",
                predictors=self.X_cleaned.columns,
                encode_fun=onehot_encode_custom,
                )
        with self.assertRaises(Exception) as mod_ex_2:
            aleplot_1D_categorical(
                X=self.X,
                model=self.model,
                feature="x5",
                predictors=self.X.columns,
                encode_fun=onehot_encode_custom,
                )
        with self.assertRaises(Exception) as mod_ex_3:
            aleplot_1D_categorical(
                X=self.X,
                model=self.model,
                feature="x5",
                predictors=self.X_cleaned.columns,
                encode_fun=onehot_encode,
                )
        mod_ex_msg = (
            """There seems to be a problem when predicting with the model.
            Please check the following:
                - Your model is fitted.
                - The list of predictors contains the names of all the features"""
            """ used for training the model.
                - The encoding function takes the raw feature and returns the"""
            """ right columns encoding it, including the case of a missing category.
            """
        )
        self.assertEqual(mod_ex_1.exception.args[0], mod_ex_msg)
        self.assertEqual(mod_ex_2.exception.args[0], mod_ex_msg)
        self.assertEqual(mod_ex_3.exception.args[0], mod_ex_msg)

class TestContPlottingFun(Test1DFunctions):
    def test_1D_continuous_line_plot(self):
        ale_eff = aleplot_1D_continuous(
            X=self.X_cleaned,
            model=self.model,
            feature="x1",
            grid_size=5,
            include_CI=True,
        )
        fig, ax = plot_1D_continuous_eff(ale_eff, self.X_cleaned)
        ## effect line
        eff_plt_data = ax.lines[0].get_xydata()
        # the x values should be the bins
        self.assertCountEqual(eff_plt_data[:, 0], ale_eff.index)
        # the y values should be the effect
        self.assertCountEqual(eff_plt_data[:, 1], ale_eff.eff)

    def test_1D_continuous_rug_plot(self):
        ale_eff = aleplot_1D_continuous(
            X=self.X_cleaned,
            model=self.model,
            feature="x1",
            grid_size=5,
            include_CI=True,
        )
        fig, ax = plot_1D_continuous_eff(ale_eff, self.X_cleaned)
        ## the rug
        rug_plot_data = ax.lines[1].get_xydata()
        # a line for each data point in X
        self.assertEqual(rug_plot_data.shape[0], self.X_cleaned.shape[0])
        # y position is always at the lowest eff value (including the values
        # of the confidence interval)
        self.assertCountEqual(
            np.unique(rug_plot_data[:, 1]),
            [ale_eff.drop("size", axis=1, inplace=False).min().min()],
        )
        # x position should always be plotted within the bin it belongs to
        # (less than the upper bin limit and more than the lower bin limit)
        self.assertTrue(
            np.all(
                ale_eff.index[
                    pd.cut(
                        self.X_cleaned["x1"], ale_eff.index, include_lowest=True
                    ).cat.codes
                    + 1
                ]
                > rug_plot_data[:, 0]
            )
            and np.all(
                ale_eff.index[
                    pd.cut(
                        self.X_cleaned["x1"], ale_eff.index, include_lowest=True
                    ).cat.codes
                ]
                < rug_plot_data[:, 0]
            )
        )

    def test_1D_continuous_ci_plot(self):
        ale_eff = aleplot_1D_continuous(
            X=self.X_cleaned,
            model=self.model,
            feature="x1",
            grid_size=5,
            include_CI=True,
        )
        fig, ax = plot_1D_continuous_eff(ale_eff, self.X_cleaned)
        ci_plot_data = (
            pd.DataFrame(ax.collections[0].get_paths()[0].vertices)
            .drop_duplicates()
            .groupby(0)
            .agg(["min", "max"])
        )
        ci_plot_data.index.name = "x1"
        ci_plot_data.columns = ["lowerCI_95%", "upperCI_95%"]
        self.assertTrue(
            np.all(
                ale_eff.loc[ale_eff.index[1] :, ["lowerCI_95%", "upperCI_95%"]]
                == ci_plot_data
            )
        )

class TestDiscPlottingFun(Test1DFunctions):
    def test_1D_continuous_line_plot(self):
        ale_eff = aleplot_1D_discrete(
            X=self.X_cleaned, model=self.model, feature="x4", include_CI=True
        )
        fig, ax, ax2 = plot_1D_discrete_eff(ale_eff, self.X_cleaned)
        self.assertCountEqual(ax.lines[0].get_xydata()[:, 0], ale_eff.index)
        self.assertCountEqual(ax.lines[0].get_xydata()[:, 1], ale_eff.eff)

    def test_1D_continuous_ci_plot(self):
        ale_eff = aleplot_1D_discrete(
            X=self.X_cleaned, model=self.model, feature="x4", include_CI=True
        )
        fig, ax, ax2 = plot_1D_discrete_eff(ale_eff, self.X_cleaned)
        self.assertCountEqual(
            np.round(ax.lines[1].get_xydata()[1:, 1], 8),
            np.round(ale_eff["lowerCI_95%"][1:], 8),
        )
        self.assertCountEqual(
            np.round(ax.lines[2].get_xydata()[1:, 1], 8),
            np.round(ale_eff["upperCI_95%"][1:], 8),
        )

    def test_1D_continuous_bar_plot(self):
        ale_eff = aleplot_1D_discrete(
            X=self.X_cleaned, model=self.model, feature="x4", include_CI=True
        )
        fig, ax, ax2 = plot_1D_discrete_eff(ale_eff, self.X_cleaned)
        self.assertCountEqual(
            ale_eff["size"], [bar.get_height() for bar in ax2.patches]
        )

if __name__ == "__main__":
    unittest.main()

max_stars_repo_name: srikiran-cpn/PyALE

max_issues_repo_name: it-power-services/PyALE

max_forks_repo_name: it-power-services/PyALE


text:
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#

from __future__ import absolute_import, division, unicode_literals

import sys
import numpy as np
import logging
import torch
from collections import OrderedDict
import pickle
import os
import code

# Set PATHs
PATH_TO_ENTEVAL = '..'
PATH_TO_DATA = '../data'

ELMO_PATH="entelmo"
sys.path.insert(0, ELMO_PATH)
from elmo import Elmo, batch_to_ids
# Dump: elmo_dump.hdf5
# Options: options.json
# Code: elmo.py
options_file = os.path.join(ELMO_PATH, "options.json")
weight_file = os.path.join(ELMO_PATH, "elmo_dump.hdf5")

# import EntEval
sys.path.insert(0, PATH_TO_ENTEVAL)
import enteval

def prepare(params, samples):
    return

def batcher(params, batch):
    use_ctx = False
    use_def = False
    if batch[0][0] is not None:
        use_ctx = True
    if batch[0][3] is not None:
        use_def = True

    if use_ctx:
        max_context_len = max([len(item[0]) for item in batch])
        batch_contexts = []
        batch_context_span_mask = np.zeros((len(batch), max_context_len)).astype("float32")
    if use_def:
        batch_desc = []

    for i, (ctx, s, e, desc) in enumerate(batch):
        if use_ctx:
            batch_contexts.append([w.lower() for w in ctx] if ctx != [] else ['.'])
            batch_context_span_mask[i, s:] = 1.
            batch_context_span_mask[i, e:] = 0.
        if use_def:
            batch_desc.append([w.lower() for w in desc] if desc != [] else ['.'])

    context_embedding = None
    def_embedding = None
    with torch.no_grad():
        if use_ctx:
            char_ids = batch_to_ids(batch_contexts).cuda().contiguous()
            elmo_outputs = elmo(char_ids, if_context=True)
            embeddings = elmo_outputs["elmo_representations"][0]
            mask = torch.from_numpy(batch_context_span_mask).cuda().unsqueeze(-1)
            embeddings = torch.sum(embeddings * mask, 1) / torch.sum(mask, 1)
            context_embedding = embeddings.cpu().data.numpy()
        if use_def:
            char_ids = batch_to_ids(batch_desc).cuda().contiguous()
            elmo_outputs = elmo(char_ids, if_context=False)
            embeddings = elmo_outputs["elmo_representations"][0]
            mask = elmo_outputs["mask"].unsqueeze(-1).float()
            embeddings = torch.sum(embeddings * mask, 1) / torch.sum(mask, 1)
            def_embedding = embeddings.data.cpu().numpy()

    return context_embedding, def_embedding

# Set params for EntEval
params_enteval = {'task_path': PATH_TO_DATA, 'usepytorch': True, 'batch_size': 8}
params_enteval['classifier'] = {'nhid': 0, 'optim': 'adam', 'batch_size': 64,
                                 'tenacity': 5, 'epoch_size': 4}

# Set up logger
logging.basicConfig(format='%(asctime)s : %(message)s', level=logging.DEBUG)

if __name__ == "__main__":
    layer = sys.argv[1]
    task = int(sys.argv[2])
    mix_params = np.ones(3)
    if layer in ['0', '1', '2']:
        layer = int(layer)
        mix_params *= -1e4
        mix_params[layer] = 1e4

    elmo = Elmo(options_file, weight_file, 1, dropout=0, scalar_mix_parameters=mix_params).cuda()

    print("Using {} layer of ElMo".format(layer))

    se = enteval.engine.SE(params_enteval, batcher, prepare)
    task_groups = [
        ["CAPsame", "CAPnext", "CERP", "EFP", "KORE", "WikiSRS", "ERT"],
        ["Rare"],
        ["ET"],
        ["ConllYago"],
    ]

    results = se.eval(task_groups[task])
    for k, v in results.items():
        print(k, v)

ext: py

reason: import numpy


text:
import requests
import json
import getpass
import datetime
import hmac
import base64
import pandas as pd
import numpy as np
import configparser
import plotly.graph_objects as go

from okcoin.DataObjects import  _Candlestick
from okcoin.DataObjects import _Resp
from okcoin.DataObjects import _AccountInfo

# documentation following numpy: https://numpydoc.readthedocs.io/en/latest/example.html#example

CONTENT_TYPE = 'Content-Type'
OK_ACCESS_KEY = 'OK-ACCESS-KEY'
OK_ACCESS_SIGN = 'OK-ACCESS-SIGN'
OK_ACCESS_TIMESTAMP = 'OK-ACCESS-TIMESTAMP'
OK_ACCESS_PASSPHRASE = 'OK-ACCESS-PASSPHRASE'
APPLICATION_JSON = 'application/json'
GET = 'GET'
POST = 'POST'
REST_API_URL = "https://www.okcoin.com"

class _Signature:
    """
    The Signature class is a private class that is used to create a signature to that enables users to
    interface with the okcoin API. It takes as inputs a config file that contains your
    API_KEY, SECRET_KEY, and an optional PASS_PHRASE. If the PASS_PHRASE is not specified, you
    will be prompted for it upon instantiating the account object.

    Parameters
    ----------
    config_file : A file containing the api_key, secret_key, and pass_phrase

    pass_phrase : If a pass_phrase is not specified in the config_file, it can be entered as a separate parameter
    or you will be prompted to enter it through your Python IDE.

    Attributes
    ----------
    """

    def __init__(self,
                 config_file=r'auth.config',
                 pass_phrase=None):

        config = configparser.ConfigParser()
        config.read(config_file)

        self.api_key = config['DEFAULT']['api_key']  # api_key
        self.secret_key = config['DEFAULT']['secret_key']  # secret_key
        self.REST_API_URL = REST_API_URL
        print("GetPass")
        print(config['DEFAULT']['pass_phrase'])
        if pass_phrase == None and config['DEFAULT']['pass_phrase'] == "":
            # print("HERE1")
            p = getpass.getpass(prompt='Enter your okcoin API pass phrase:')
            self.pass_phrase = p
        else:
            # print("HERE2")
            self.pass_phrase = config['DEFAULT']['pass_phrase']  # pass_phrase
        # self.query_result = query_result()

    def __get_timestamp(self):
        timestamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + "Z"
        print(timestamp)
        return timestamp

    # signature
    def __get_signature(self, t, method, request_path, body=None):
        if str(body) == '{}' or str(body) == 'None' or body == None:
            body = ''
        message = str(t) + str.upper(method) + request_path + str(body)
        mac = hmac.new(bytes(self.secret_key, encoding='utf8'), bytes(message, encoding='utf-8'),
                       digestmod='sha256')
        d = mac.digest()
        return base64.b64encode(d)

    # set request header
    def __get_header(self, sig, t):
        header = dict()
        header[CONTENT_TYPE] = APPLICATION_JSON
        header[OK_ACCESS_KEY] = self.api_key
        header[OK_ACCESS_SIGN] = sig
        header[OK_ACCESS_TIMESTAMP] = t
        header[OK_ACCESS_PASSPHRASE] = self.pass_phrase
        return header

    def __parse_params_to_str(self, params):
        url = '?'
        for key, value in params.items():
            url = url + str(key) + '=' + str(value) + '&'

        return url[0:-1]

    def query(self, type, request_path, body=''):
        #print(request_path)
        #print(type)
        #print(body)
        if type == "POST":
            body = json.dumps(body)
            print(body)
        else:
            if body != '':
                body = self.__parse_params_to_str(body)

        timestamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + "Z"
        # self.get_timestamp()
        print(body)
        signature = self.__get_signature(timestamp, type, request_path, body)
        #signature = self.__get_signature(timestamp, type, request_path, body)
        #signature = self.__get_signature(timestamp, type, request_path, '')

        header = self.__get_header(signature, timestamp)
        # do request
        if type == 'GET':
            response = requests.get(self.REST_API_URL + request_path + body,
                                headers=header)
        else:
            print(self.REST_API_URL + request_path)
            response = requests.post(self.REST_API_URL + request_path, data=body,
                                    headers=header)

#data=body

        return response

class Account(_Signature):
    """
    The Account class is used to interface with you okcoin account. If contains functions that
    return your account value, the assets in contains, and its history. The Account class
    inherits from the Signature class, which takes as inputs a config file that contains your
    API_KEY, SECRET_KEY, and an optional PASS_PHRASE. If the PASS_PHRASE is not specified, you
    will be prompted for it upon instantiating the account object.

    Parameters
    ----------
    config_file : A file containing the api_key, secret_key, and pass_phrase

    pass_phrase : If a pass_phrase is not specified in the config_file, it can be entered as a separate parameter
    or you will be prompted to enter it through your Python IDE.

    Attributes
    ----------

    Examples
    --------
    These are written in doctest format, and should illustrate how to
    use the function.

    >>> from okcoin import Account
    >>> acc = Account(config_file='auth.conf')
    <okcoin.Account object at 0x00000291A320A288>
    """

    def get_account_type(self):
        r"""Returns a dictionary of the different acount types and the
        numerical code that corresponds to them in okcoin.

        Returns
        -------
        account_tpye : dict
            A dictionary of account types (i.e. funding, trading, spot).

        Examples
        --------
        >>> account_type = acc.get_account_type()
        >>> print(account_type)
        {'spot': 1, 'margin': 5, 'funding': 6}
        """
        # In Account API
        account_type = {
            'spot': 1,
            'margin': 5,
            'funding': 6
        }
        #return pd.DataFrame(account_type, index=[0])
        return account_type

    def get_withdrwal_status(self):
        r"""Returns a dictionary of the withdrawal status and the
        numerical code that corresponds to them in okcoin.

        Returns
        -------
        withdrawal_status : dict
            A dictionary of withdrawal status (i.e. cancelled, failed, pending, etc.).

        Examples
        --------
        >>> withdrawal_status = acc.get_withdrwal_status()
        >>> print(withdrawal_status)
        {'Pending cancel': -3, 'Cancelled': -2, 'Failed': -1, 'Pending': 0, 'Sending': 1, 'Sent': 2,
        'Awaiting email verification': 3, 'Awaiting manual verification': 4,
        'Awaiting identity verification': 5}
        """
        # In Account API
        withdrawal_status = {
            'Pending cancel': -3,
            'Cancelled': -2,
            'Failed': -1,
            'Pending': 0,
            'Sending': 1,
            'Sent': 2,
            'Awaiting email verification': 3,
            'Awaiting manual verification': 4,
            'Awaiting identity verification': 5
        }
        #return pd.DataFrame(withdrawal_status, index=[0])
        return withdrawal_status

    def get_wallet(self):
        r"""Retrieves information on the balances of all of the assets that are
        available or on hold.

        Returns
        -------
        account_info : _AccountInfo
            A custom data structure that enables you to view you wallet as a dataframe,
            json, or plotly chart.

        Examples
        --------
        >>> acc = Account('auth.conf')
        >>> wallet = acc.get_wallet()
        >>> print(wallet.r)
        <Response [200]>
        >>> print(wallet.json)
        [{'balance': '0.00071305', 'available': '0.00071305', 'currency': 'BTC', 'hold': '0.00000000'}, {'balance': '793.99043577', 'available': '793.99043577', 'currency': 'STX', 'hold': '0.00000000'}]
        >>> print(wallet.df)
                balance     available currency        hold
        0    0.00071305    0.00071305      BTC  0.00000000
        1  793.99043577  793.99043577      STX  0.00000000
        """
        request_path = '/api/account/v3/wallet'
        #body = ''

        #resp = _AccountInfo(self.query(GET, request_path, body))

        #fig = go.Figure([go.Bar(x=resp.df['currency'].tolist(), y=resp.df['balance'].tolist())])
        #fig.update_layout(
        #    title='Funding Account Assets',
        #    yaxis_title='Asset',
        #    xaxis_title='Quantity')

        return _AccountInfo(self.query(GET, request_path)) #, fig

    def get_asset_valuation(self, currency='BTC'):
        r"""Get the valuation of the total assets of the account in btc or fiat currency.

        Parameters
        ----------
        currency : 	The valuation according to a certain fiat currency.  The currency
            can only be one of the following: BTC, USD, CNY, JPY, KRW, RUB.
            The default unit is BTC.

        Returns
        -------
        account_info : _Resp
            A custom data structure that allows you to view the request status,
            the request response as json, and the request response as a dataframe.

        Examples
        --------
        >>> asset_val = acc.get_asset_valuation('USD')
        >>> print(asset_val.df)
        account_type                               0
        balance                               523.51
        valuation_currency                       USD
        timestamp           2021-05-13T02:21:30.061Z
        """
        request_path = '/api/account/v3/asset-valuation'
        body = {'valuation_currency': currency}

        return _Resp(self.query(GET, request_path, body))

    # Sub account erroring
    def get_sub_account(self, account_name=''):
        r""" Obtains the fund balance information in each sub account in the users okcoint
        account.

        Parameters
        ----------
        account_name : 	The name of the sub-account.

        Returns
        -------
        account_info : _Resp
            A custom data structure that allows you to view the request status,
            the request response as json, and the request response as a dataframe.

        Examples
        --------
        >>> sub_account = acc.get_sub_account()
        >>> print(sub_account.json)
        {
            "data": {
                "sub_account": "Test",
                "asset_valuation": 0.00003463,
                "account_type:futures": [
                    {
                        "balance": 0.00000245,
                        "max_withdraw": 0.00000245,
                        "currency": "BTC",
                        "underlying": "BTC_USD",
                        "equity": 0.00000245
                    },
                    {
                        "balance": 1.053473,
                        "max_withdraw": 1.053473,
                        "currency": "XRP",
                        "underlying": "XRP_USD",
                        "equity": 1.053473
                    }
                ],
                "account_type:spot": [
                    {
                        "balance": 0.000312544038152,
                        "max_withdraw": 0.000312544038152,
                        "available": 0.000312544038152,
                        "currency": "USDT",
                        "hold": 0
                    }
                ]
            }
        }
        """
        request_path = '/api/account/v3/sub-account'
        if account_name:
            body = {'sub-account':account_name}

        else:
            body = {'sub-account': ''}

        return _Resp(self.query(GET, request_path, body))

    def get_currency(self, token='BTC'):
        r""" Retrieves information for a single token in your account,
        including the remaining balance, and the amount available or on hold.

        Parameters
        ----------
        token : str
            The token you are querying.

        Returns
        -------
        token_info : _Resp
            A custom data structure that allows you to view the request status,
            the request response as json, and the request response as a dataframe.

        Examples
        --------
        >>> curr = acc.get_currency(token='BTC')
        >>> print(curr.df)
              balance   available currency        hold
        0  0.00076409  0.00076409      BTC  0.00000000
        """
        request_path = '/api/account/v3/wallet/' + token
        return _Resp(self.query(GET, request_path))

    ## Withdraw or Trade Permission
    def get_funds_transfer(self):
        r"""This request supports the transfer of funds among your funding account,
        trading accounts, main account, and sub accounts.

        Returns
        -------
        success : bool

        Examples
        --------
        >>>
        """
        pass

    ## Withdraw or Trade Permission
    def withdraw(self, currency, amount, destination, to_address, trade_pwd, fee):
        body = {'currency': currency,
                  'amount': amount,
                  'destination': destination,
                  'to_address': to_address,
                  'trade_pwd': trade_pwd,
                  'fee': fee}
        request_path = '/api/account/v3/withdrawal'
        return _Resp(self.query(POST, request_path, body=body))

    def get_withdrawal_history(self, currency=''):
        r""" Retrieves the 100 most recent withdrawal records.

        Parameters
        ----------
        currency : 	str
            The currency that was withdrawn.

        Returns
        -------
        withdrawal_hist : _Resp
            A custom data structure that allows you to view the request status,
            the request response as json, and the request response as a dataframe.

        Examples
        --------
        >>> withdraw_hist = acc.get_withdrawal_history()
        >>> withdraw_hist.df
        Empty DataFrame
        Columns: []
        Index: []
        """
        if currency:
            request_path = '/api/account/v3/withdrawal/history/' + currency.lower()
        else:
            request_path = '/api/account/v3/withdrawal/history'
        return _Resp(self.query(GET, request_path))

    def get_ledger(self):
        r""" Retrieves the value of your account for the past month.

        Returns
        -------
        bills : _Resp
            A custom data structure that allows you to view the request status,
            the request response as json, and the request response as a dataframe.

        Examples
        --------
        >>> ledger = acc.get_ledger()
        >>> ledger.df
                   amount       balance  ...            typename                 timestamp
        0      0.00000611    0.00076409  ...                      2021-05-16T05:41:27.000Z
        1      0.00000793    0.00075798  ...                      2021-05-15T04:41:24.000Z
        2      0.00001004    0.00075005  ...                      2021-05-14T04:41:25.000Z
        3      0.00001777    0.00074001  ...                      2021-05-13T04:41:27.000Z
        [4 rows x 7 columns]
        """
        request_path = '/api/account/v3/ledger'
        ledger_resp = _Resp(self.query(GET, request_path))
        ledger_resp.df.amount = ledger_resp.df.amount.astype('float64')
        ledger_resp.df.balance = ledger_resp.df.balance.astype('float64')
        ledger_resp.df.fee = ledger_resp.df.fee.astype('float64')
        ledger_resp.df.ledger_id = ledger_resp.df.ledger_id.astype('int64')
        ledger_resp.df.timestamp = ledger_resp.df.timestamp.astype('datetime64')
        return ledger_resp

    def get_deposit_address(self, currency='BTC'):
        r""" Retrieves the deposit addresses of currencies, including previously used addresses.

        Parameters
        ----------
        currency : 	str
            The currency deposited.

        Returns
        -------
        account_info : _Resp
            A custom data structure that allows you to view the request status,
            the request response as json, and the request response as a dataframe.

        Examples
        --------
        >>> dep_addr = acc.get_deposit_address()
        >>> dep_addr.json
        {'code': 404,
         'data': {},
         'detailMsg': '',
         'error_code': '404',
         'error_message': 'Not Found',
         'msg': 'Not Found'}
        """

        request_path = '/api/account/v3/deposit/address/' + currency.lower()
        return _Resp(self.query(GET, request_path))

    def get_total_deposit_value(self, start_date=None, end_date=None, currency='USD'):
        r""" Retrieves amount that has been deposited between two date.

        Parameters
        ----------
        start_date : 	str
            Start date of query in YYYY-MM-DD.

        end_date : str
            End date of query in YYYY-MM-DD

        currency : str
            Currency of deposit. Set to USD by default

        Returns
        -------
        value : float
            Value representing the amount deposited during that date range.

        Examples
        --------
        >>> dep_value = acc.get_total_deposit_value('2021-04-12','2021-06-12')
        >>> print(dep_value)
            400.00
        """
        if start_date == None:
            start_date = '2000-01-01'
        if end_date == None:
            end_date = datetime.datetime.today().strftime('%Y-%m-%d')

        dep = self.get_deposit_history(currency)
        df = dep.df
        df['amount'] = pd.to_numeric(df['amount'])
        df['updated_at'] = pd.to_datetime(df['updated_at'])

        mask = (df['updated_at'] > start_date) & (df['updated_at'] <= end_date)
        df = df.loc[mask]
        val = np.sum(df['amount'].to_list())

        return val

    def get_deposit_history(self, currency='USD'):
        r""" Retrieves the deposit history of all currencies,
        up to 100 recent records(Within one year).

        Parameters
        ----------
        currency : 	str
            The currency deposited.

        Returns
        -------
        account_info : _Resp
            A custom data structure that allows you to view the request status,
            the request response as json, and the request response as a dataframe.

        Examples
        --------
        >>> dep_hist = acc.get_deposit_history()
        >>> dep_hist.df
                 amount                updated_at  ...                 timestamp status
        0  200.00000000  2021-05-11T17:18:21.000Z  ...  2021-05-10T13:09:39.000Z      5
        1  100.00000000  2021-05-03T17:18:41.000Z  ...  2021-04-30T17:06:11.000Z      5
        2  100.00000000  2021-04-24T03:13:52.000Z  ...  2021-04-23T13:34:20.000Z      5
        3  100.00000000  2021-04-12T15:40:51.000Z  ...  2021-04-09T12:22:16.000Z      5
        [4 rows x 9 columns]
        """
        request_path = '/api/account/v3/deposit/history/'+currency.lower()

        return _Resp(self.query(GET, request_path))

    def get_currencies(self):
        r""" This retrieves a list of all currencies.

        Returns
        -------
        currency_info : _Resp
            An object containing the currencies currently supported by okcoin.

        Examples
        --------
        >>> currencies = acc.get_currencies()
        >>> print(currencies.df)
        can_internal                     name  ... can_deposit min_withdrawal
        0             0                US Dollar  ...           1
        1             0                     Euro  ...           1
        """
        request_path = '/api/account/v3/currencies'
        return _Resp(self.query(GET, request_path))

    # This is buggy. You need to specify a currency to get anything back
    def get_withdrawal_fees(self, currency='BTC'):
        r"""

        Parameters
        ----------
        account_name : 	str
            The name of the sub-account.

        Returns
        -------
        fee : _Resp
            An object contianing the min and max fees for the withdrawal of the
            specified currency.

        Examples
        --------
        >>> withdraw_fee = acc.get_withdrawal_fees('STX')
        >>> print(withdraw_fee.df)
        min_fee     currency     max_fee
        0  1.00000000      STX  2.00000000
        """
        request_path = '/api/account/v3/withdrawal/fee'
        if currency:
            body = {'currency':currency.lower()}
        else:
            body=''
        #body = json.dumps(p)
        #print(body)
        return _Resp(self.query(GET, request_path, body=body))

    def get_balance_from_ledger(self, df, currency='BTC'):
        r""" Returns a dataframe and Plotly chart that show the balance
        of the funding account.

        Parameters
        ----------
        df : 	dataframe
            The dataframe generated by the

        currency : str
            The currency that you are querying.

        Returns
        -------
        balance : _Resp
            A n object that...

        fig : Plotly chart
            A plotly chart of the balance of the funding account.

        Examples
        --------
        >>> ledger = account.get_ledger()
        >>> btc_balance = account.get_balance_from_ledger(ledger.df,'BTC')
        >>> print(btc_balance[0])
        >>> btc_balance[1].write_html('test.html', auto_open=True)
        """
        cur = df[df['currency']==currency]
        cur_balance = cur.groupby('timestamp')['balance'].max()
        balance = cur_balance.to_frame()
        balance.reset_index(inplace=True)

        fig = go.Figure(data=go.Scatter(
            x=balance.timestamp.tolist(),
            y=balance.balance.tolist(),
            mode='markers'
        ))

        fig.update_layout(
            title=currency,
            xaxis_title="Date",
            yaxis_title="Value in " + currency)

        return balance, fig

## Spot Trading Account Info
class Spot(_Signature):
    """
    The Spot class is used to interface with you okcoin spot trading account. If contains functions that
    return your account value and your trading history. It also contains functions that return the current
    crypto market conditions, such as trading pairs, asset prices, ad asset history. The Spot class
    inherits from the Signature class, which takes as inputs a config file that contains your
    API_KEY, SECRET_KEY, and an optional PASS_PHRASE. If the PASS_PHRASE is not specified, you
    will be prompted for it upon instantiating the account object.

    Parameters
    ----------
    config_file : A file containing the api_key, secret_key, and pass_phrase

    pass_phrase : If a pass_phrase is not specified in the config_file, it can be entered as a separate parameter
    or you will be prompted to enter it through your Python IDE.

    Attributes
    ----------

    Examples
    --------
    These are written in doctest format, and should illustrate how to
    use the function.

    >>> from okcoin import Spot
    >>> spot = Spot(config_file='auth.conf')

    """

    def get_account_chart(self, df):
        fig = go.Figure([go.Bar(x=df['currency'].tolist(), y=df['balance'].tolist())])
        fig.show()

    def get_order_status(self):
        # In Spot API
        r""" Returns the status of an order and the numeric value that corresponds to it
        in the Okcoin API.

        Returns
        -------
        order_status : A dictionary object of order status values.

        Examples
        --------
        >>> status = spot.get_order_status()
        """
        order_status = {
            'Failed': -2,
            'Canceled': -1,
            'Open': 0,
            'Partially Filled': 1,
            'Fully Filled': 2,
            'Submitting': 3,
            'Cancelling': 4,
            'Incomplete': 6,
            'Complete': 7
        }
        #return pd.DataFrame(order_status, index=[0])
        return order_status

    def get_accounts(self, currency=None):
        r""" Returns a list of assets, (with non-zero balance),
        remaining balance, and amount available in the spot trading account.

        Parameters
        ----------
        currency : 	str
            Optional parameter specifying which asset you want to return

        Returns
        -------
        resp : _Resp
            A query response object that contains the query result as a dictionary or dataframe

        fig : figure
            A Plotly figure displaying the valuation of the assets in the account

        Examples
        --------
        >>> accounts = spot.get_accounts()
        >>> accounts[1].write_html('temp.html', auto_open=True)
        """
        request_path = '/api/spot/v3/accounts'
        if currency:
            request_path += "/" + currency.lower()

        resp = _Resp(self.query(GET, request_path))

        fig = go.Figure([go.Bar(x=resp.df['currency'].tolist(), y=resp.df['balance'].tolist())])
        fig.update_layout(
            title='Spot Trading Account Assets',
            yaxis_title='Asset',
            xaxis_title='Quantity')

        return resp, fig

    def get_ledger(self, currency='BTC'):
        r""" Returns the spot account bills dating back the past 3 months.
        Pagination is supported and the response is sorted
        with most recent first in reverse chronological order.

        Parameters
        ----------
        currency : 	str
            Currency being queried

        Returns
        -------
        balance : _Resp
            A query response opbect that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> currency = spot.get_ledger('USD')
        >>> currency.df
        """
        request_path = '/api/spot/v3/accounts'
        request_path += "/" + currency.lower() + "/ledger"
        return _Resp(self.query(GET, request_path))

    def place_order(self,
                    side='buy',
                    trading_pair='STX-USD',
                    order_type='0',
                    limit_or_market='limit',
                    size='',
                    price='',
                    amount_to_spend='',
                    client_id=''):
        r""" Returns This the list of your orders from
        the most recent 3 months. This request supports paging
        and is stored according to the order time in chronological
        order from latest to earliest.

        Parameters
        ----------
        side : str
            'buy' or 'sell'

        trading_pair : str
            The trading pair that was ordered

        order_type='0',
            Specify 0: Normal order (Unfilled and 0 imply normal limit order) 1:
            Post only 2: Fill or Kill 3: Immediate Or Cancel

        limit_or_market : str
            'limit' or 'market' order

        size : float
            Quantity to be sold. Required for market sells or limit buys.

        price : float
            The price you want to purchase the asset at

        amount_to_spend : float
            Amount to spend. Required for market buys.

        client_id : str
            A user defined ID that you can give your order

        Returns
        -------
        orders : _Resp
            A query response object that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> order = spot.place_order('buy', 'MIA-USD','0','limit',1000, .04)
        >>> order.df
        """
        request_path = '/api/spot/v3/orders'#?instrument_id='+trading_pair+'&state='+str(state)
        # Using the "body" doesn't work

        if limit_or_market == 'market':
            body = {'side': side,
                 'instrument_id': trading_pair,
                 'order_type': order_type,
                 'type': 'market',
                 'size':str(size),
                 'notional': str(amount_to_spend),
                 'client_id': client_id}
        else:
            body = {'side':side,
                'instrument_id':trading_pair,
                'order_type':order_type,
                'type':'limit',
                'size':str(size),
                'price': str(price),
                'client_id':client_id}

        return _Resp(self.query(POST, request_path, body=body))

    def cancel_order(self, order_id, trading_pair):
        r""" Cancels an existing trade.

                Parameters
                ----------
                order_id : str
                    The ID for the order you would like to cancel.

                trading_pair : str
                    The trading pair that was ordered.

                Returns
                -------
                orders : _Resp
                    A query response object that contains the query result as a dictionary and as a dataframe

                Examples
                --------
                >>> order = spot.cancel_order('5468800', 'MIA-USD')
                >>> order.df
                """
        request_path = '/api/spot/v3/cancel_orders'#?instrument_id='+trading_pair+'&state='+str(state)
        body = {'instrument_id': trading_pair.lower()}

        return _Resp(self.query(POST, request_path + '/' + str(order_id), body=body))

    def get_order_list(self, trading_pair='STX-USD', state=0):
        r""" Returns This the list of your orders from
        the most recent 3 months. This request supports paging
        and is stored according to the order time in chronological
        order from latest to earliest.

        Parameters
        ----------
        trading_pair : str
            The trading pair that was ordered

        state : int
            The state of the order, represented as an integer.

        Returns
        -------
        orders : _Resp
            A query response object that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> orders = spot.get_order_list('STX-USD')
        >>> orders.df
        """
        request_path = '/api/spot/v3/orders'#?instrument_id='+trading_pair+'&state='+str(state)
        body = {'instrument_id': trading_pair,
                'state': str(state)}
        return _Resp(self.query(GET, request_path, body=body))

    def get_orders_pending(self, trading_pair='BTC-USD'):
        r""" Returns the list of your current open orders.
        Pagination is supported and the response
        is sorted with most recent first in reverse chronological order.

        Parameters
        ----------
        trading_pair : str
            The trading pair that was ordered.

        Returns
        -------
        orders : _Resp
            A query response opbect that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> pending = spot.get_orders_pending('STX-USD')
        >>> pending.df
        """
        request_path = '/api/spot/v3/orders_pending'
        body = {'instrument_id':trading_pair.lower()}
        return _Resp(self.query(GET, request_path, body=body))

    def get_order_details(self, order_id, trading_pair='BTC-USDT'):
        r""" Returns order details by order ID.Can get order information for nearly 3 months。
        Unfilled orders will be kept in record for only
        two hours after it is canceled.

        Parameters
        ----------
        order_id : int
            The specific order ID that you want to query

        trading_pair : str
            The trading pair that was ordered

        Returns
        -------
        orders : _Resp
            A query response opbect that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> details = spot.get_order_details(order_id, 'BTC-USD')
        >>> details.df
        """
        request_path = '/api/spot/v3/orders/' + str(order_id)
        body = {'instrument_id': trading_pair.lower()}
        return _Resp(self.query(GET, request_path, body=body))

    def get_trade_fee(self):
        r""" Returns the transaction fee rate corresponding to
        your current account transaction level. The sub-account
        rate under the parent account
        is the same as the parent account.
        Update every day at 0am

        Returns
        -------
        fee : _Resp
            A query response opbect that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> fees = spot.get_trade_fee()
        >>> fees.json
        {'category': '1', 'maker': '0.001', 'taker': '0.002', 'timestamp': '2021-06-11T02:41:44.149Z'}
        """
        request_path = '/api/spot/v3/trade_fee'
        return _Resp(self.query(GET, request_path))

    def get_filled_orders(self, trading_pair='BTC-USDT'):
        r""" Returns recently filled transaction details.
        This request supports paging and is stored according
        to the transaction time in chronological order from
        latest to earliest.
        Data for up to 3 months can be retrieved.

        Parameters
        ----------
        trading_pair : 	str
            The trading pair that was ordered

        Returns
        -------
        orders : _Resp
            A query response opbect that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> filled = spot.get_filled_orders('STX-USD')
        >>> filled.df
                  created_at        currency  ...                 timestamp trade_id
        0   2021-04-02T15:20:37.000Z      USD  ...  2021-04-02T15:20:37.000Z   103932
        1   2021-04-02T15:20:37.000Z      BTC  ...  2021-04-02T15:20:37.000Z   103932
        """
        request_path = '/api/spot/v3/fills'
        body = {'instrument_id': trading_pair.lower()}
        return _Resp(self.query(GET, request_path, body=body))

class Earn(_Signature):
    """
    The Earn class is used to learn about yeild bearing offers on Okcoin and place orders.

        Parameters
        ----------
        config_file : A file containing the api_key, secret_key, and pass_phrase

        pass_phrase : If a pass_phrase is not specified in the config_file, it can be entered as a separate parameter
        or you will be prompted to enter it through your Python IDE.

        Attributes
        ----------

        Examples
        --------
        These are written in doctest format, and should illustrate how to
        use the function.

        >>> from okcoin import Earn
        >>> earn = Earn(config_file='auth.conf')

        """
    def get_offers(self, investment_currency="MIA", protocol_name="MiamiCoin"):
        r""" Returns the listing of offerings on Okcoin Earn.

        Parameters
        ----------
        investment_currency : 	str
            The currency you want to stake

        protocol_name : str
            The protocal listed for the currency

        Returns
        -------
        orders : _Resp
            A query response opbect that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> offers = earn.get_offers("STX", "stacks")
        >>> offers.df
        max_invest_amount min_invest_amount  ... annual_interest_rate protocol_name
        0                         50.00000000  ...               0.1000        stacks
        [1 rows x 10 columns]
        """
        request_path = '/api/earning/v3/offers'
        body = {'investment_currency': investment_currency.upper(),
                'protocol_name': protocol_name}
        return _Resp(self.query(GET, request_path, body=body))

    def deposit(self, investment_currency="MIA", protocol_name="MiamiCoin", amount=50, cycles=1):
        r""" Returns the listing of offerings on Okcoin Earn.

        Parameters
        ----------
        investment_currency : 	str
            The currency you want to stake

        protocol_name : str
            The protocal listed for the currency

        amount : float
            The amount you want to deposit

        cycles : int
            The number of staking cycles, usually 1 or 12

        Returns
        -------
        orders : _Resp
            A query response opbect that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> deposit = earn.get_offers("STX", "stacks", 100, 12)
        >>> deposit.df
        """
        request_path = '/api/earning/v3/purchase'
        body = {'investment_currency': investment_currency.upper(),
                'protocol_name': protocol_name.lower(),
                'amount':str(amount),
                'cycles':str(cycles)}
        return _Resp(self.query(POST, request_path, body=body))

    def cancel(self, order_id):
        r""" Cancel a deposit order that has been placed on Earn.

        Parameters
        ----------
        order_id : 	str
            The ID of the order to cancel.

        Returns
        -------
        orders : _Resp
            A query response opbect that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> order = earn.cancel("1234")
        >>> order.df
        """
        request_path = '/api/earning/v3/cancel'
        body = {'order_id': str(order_id)}
        return _Resp(self.query(POST, request_path, body=body))

    def get_positions(self, investment_currency="MIA", protocol_name="MiamiCoin"):
        r""" Returns the the list of your assets currently earning yeild.

        Parameters
        ----------
        investment_currency : 	str
            The currency you want to stake

        protocol_name : str
            The protocal listed for the currency

        Returns
        -------
        orders : _Resp
            A query response opbect that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> positions = earn.get_positions("STX", "stacks")
        >>> positions.df
        """
        request_path = '/api/earning/v3/positions'
        body = {'investment_currency': investment_currency.upper(),
                'protocol_name': protocol_name}
        return _Resp(self.query(GET, request_path, body=body))

    def get_order_details(self, investment_currency=None, protocol_name=None, status=None):
        r""" Returns the last 100 orders placed into Earn.

        Parameters
        ----------
        investment_currency : 	str
            The currency you want to stake

        protocol_name : str
            The protocal listed for the currency

        status : int
            An integer representing the status. This can be retrieved from the
            earn.status dictionary object.

        Returns
        -------
        orders : _Resp
            A query response opbect that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> orders = earn.get_positions("STX", "stacks")
        >>> orders.df
        """
        request_path = '/api/earning/v3/orders'
        if investment_currency:
            body = {'investment_currency': investment_currency.upper()}
        elif investment_currency and protocol_name:
            body = {'investment_currency': investment_currency.upper(),
                    'protocol_name': protocol_name}
        elif status and investment_currency and protocol_name:
            body = {'investment_currency': investment_currency.upper(),
                'protocol_name': protocol_name,
                'status':status}
        else:
            body = ""

        resp = _Resp(self.query(GET, request_path, body=body))
        resp.df.replace({"status": self.order_status()},inplace=True)
        return resp
        #return _Resp(self.query(GET, request_path, body=body))

    def redeem_order(self, order_id, early_redemption_permit=False):
        r""" Redeeming flexible or fixed orders from Earn. This function only takes one order at a time.
        This will be updated to take a list of orders.

        Parameters
        ----------
        order_id : 	str or list
            The order(s) to redeem. If it is a single order, the order_id should be a string, for example, '1234'.
            If it is multiple orders, the order_id should be a list of string, for example, ['1234', '2345', '3456']

        early_redemption_permit : bool
            Permission for early redemption. Set to false by default. If submitting multiple orders, the single
            value will be applied to all orders.

        Returns
        -------
        orders : _Resp
            A query response opbect that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>> redeem = earn.redeem_order("oid1234",True)
        >>> redeem.df
        """
        request_path = '/api/earning/v3/redeem'

        if type(order_id) == str:
            body = [{'order_id': order_id,
                    'early_redemption_permit':str(early_redemption_permit)}]
        elif type(order_id) == list:
            body = []
            for oid in order_ids:
                body.append({'order_id': str(oid),
                            'early_redemption_permit': str(early_redemption_permit).lower()})
        else:
            print('ERROR: order_id is not a list or a string.')

        return _Resp(self.query(POST, request_path, body=body))

    def order_status(self):
        return {'8': 'Pending',
            '13': 'Cancelling',
            '17': 'Cancelled',
            '9': 'Onchain',
            '1': 'Earning',
            '4': 'Redeem Pending',
            '2': 'Redeeming',
            '3': 'Redeemed'}

class Fiat(_Signature):
    """
    The Fiat class is used to withdraw and deposit money into your okcoin account. It enables you to
    understand your deposit and withdrawal history. It also enables you to withdraw and deposit currency
    if you have created an API key that enables trading. The Fiat class
    inherits from the Signature class, which takes as inputs a config file that contains your
    API_KEY, SECRET_KEY, and an optional PASS_PHRASE. If the PASS_PHRASE is not specified, you
    will be prompted for it upon instantiating the account object.

    Parameters
    ----------
    config_file : A file containing the api_key, secret_key, and pass_phrase

    pass_phrase : If a pass_phrase is not specified in the config_file, it can be entered as a separate parameter
    or you will be prompted to enter it through your Python IDE.

    Attributes
    ----------

    Examples
    --------
    These are written in doctest format, and should illustrate how to
    use the function.

    >>> from okcoin import Fiat
    >>> fiat = Fiat(config_file='auth.conf')

    """

    def get_deposit_history(self):
        r""" Returns the details of a deposit given the
        deposit ID.

        Parameters
        ----------
        deposit_id : str
            The dataframe generated by the

        Returns
        -------
        deposit_hist : _Resp
            A query response object that contains the query result as a dictionary and as a dataframe

        Examples
        --------
        >>>
        """
        request_path = '/api/account/v3/fiat/deposit/details'
        return _Resp(self.query(GET, request_path))

    def get_channel_info(self):
        r""" Returns the status of an order and the numeric value that corresponds to it
        in the Okcoin API.

        Parameters
        ----------
        df : 	dataframe
            The dataframe generated by the

        Returns
        -------
        balance : _Resp
            A n object that...

        Examples
        --------
        >>>
        """
        request_path = '/api/account/v3/fiat/channel'
        return _Resp(self.query(GET, request_path))

    def get_withdrawal_history(self):
        r""" Returns the status of an order and the numeric value that corresponds to it
        in the Okcoin API.

        Parameters
        ----------
        df : 	dataframe
            The dataframe generated by the

        Returns
        -------
        balance : _Resp
            A n object that...

        Examples
        --------
        >>>
        """
        request_path = '/api/account/v3/fiat/withdraw/details'
        return _Resp(self.query(GET, request_path))

max_stars_repo_name: gbrunner/python-api-for-okcoin

max_issues_repo_name: gbrunner/python-api-for-okcoin

max_forks_repo_name: gbrunner/python-api-for-okcoin


text:
import numpy as np

from causal_bald.library import utils

def complete_propensity(x, u, lambda_, beta=0.75):
    nominal = nominal_propensity(x, beta=beta)
    alpha = utils.alpha_fn(nominal, lambda_)
    beta = utils.beta_fn(nominal, lambda_)
    return (u / alpha) + ((1 - u) / beta)

def nominal_propensity(x, beta=0.75):
    logit = beta * x + 0.5
    return (1 + np.exp(-logit)) ** -1

def f_mu(x, t, u, gamma=4.0):
    mu = (
        (2 * t - 1) * x
        + (2.0 * t - 1)
        - 2 * np.sin((4 * t - 2) * x)
        - (gamma * u - 2) * (1 + 0.5 * x)
    )
    return mu

def linear_normalization(x, new_min, new_max):
    return (x - x.min()) * (new_max - new_min) / (x.max() - x.min()) + new_min

max_stars_repo_name: BlackHC/causal-bald

max_issues_repo_name: BlackHC/causal-bald

max_forks_repo_name: BlackHC/causal-bald


text:
#!/usr/bin/env python
# [Description] A script to extract exact number of frames from a sequence video (including data augmentation)
# [Author] chaonan99
# [Date] 2016/07/17/
# [Last Modified] 2018/02/15 by Luowei Zhou
# [Email] luozhou@umich.edu

import subprocess as sp
import re
import optparse
import os
import math
import numpy as np
from PIL import Image
# import Image
import sys

parser = optparse.OptionParser()
parser.add_option('-i', '--input', dest='infile', help='input video file name')
parser.add_option('-o', '--output_folder', dest='outfolder', help='output folder name')
parser.add_option('-n', '--number', dest='fnum', help='number of frames', default=500, type=int)
parser.add_option('-r', '--repeat', dest='repeat', help='number of frame batches or temporal data augmentation (default=1; all=-1)', default=1, type=int)

(opts, args) = parser.parse_args()

def getInfo(filename):
    result = sp.Popen(["ffmpeg", "-i", filename],
        stdout = sp.PIPE, stderr = sp.STDOUT)
    return [x for x in result.stdout.readlines() if "Duration" in x or "yuv" in x]

def decode(filename):
    sp.call(["ffmpeg", "-i", filename, "temp.yuv"],stdout = sp.PIPE, stderr = sp.STDOUT)

def yuv_import(filename,dim):
    data = np.fromfile(filename,dtype=np.uint8).reshape((-1,6,dim[0]*dim[1]/4))
    y = data[:,0:4,:].reshape(-1,dim[1],dim[0])
    u = data[:,4,:].reshape(-1,dim[1]/2,dim[0]/2)
    v = data[:,5,:].reshape(-1,dim[1]/2,dim[0]/2)
    return y,u,v

def touch(indir):
    if not os.path.isdir(indir):
        os.mkdir(indir)

infoStr = getInfo(opts.infile)
durarr = re.findall(r'Duration:\s\d{2}:\d{2}:\d+.\d+',infoStr[0])
findstr = np.asarray(re.findall(r'(\d+)x(\d+) (?=\[)', infoStr[1]))
if len(findstr) == 0:
    findstr = np.asarray(re.findall(r'yuv420p.*? (\d+)x(\d+)', infoStr[1]))
if len(findstr) == 0:
    print("[ERROR] Size not found: "+ opts.infile)

else:
    decode(opts.infile)
    touch(opts.outfolder)
    dim = findstr[0].astype(np.int32)
    o = np.ones((2,2)).astype(np.uint8)

    # temp.yuv might be huge, sometimes you need to mannally delete it
    y,u,v = yuv_import(r"temp.yuv",dim)

    total_frames = y.shape[0]
    # jump = int(math.floor(total_frames/opts.fnum))+1
    jump = int(math.ceil(total_frames/opts.fnum))

    if opts.repeat < 0:
        opts.repeat = jump

    print("[INFO] " + opts.infile + " " + str(durarr[0]) + " " + "Frame size: %dx%d Total frames: %d"%(dim[0],dim[1],total_frames))
    if jump < opts.repeat:
        print("[Warning] Total frames is less than batch_size * number of batches. Output numver of batches may be less than %d"
            %(opts.repeat))
        opts.repeat = jump

    skip = int(math.floor(jump/opts.repeat))
    for i in range(opts.repeat):
        batch_folder = opts.outfolder + "/%04d/"%(i+1)
        touch(batch_folder)
        for j in range(opts.fnum):
            ind = min(j*jump + i*skip, total_frames - 1)
            im = Image.fromarray(np.dstack((y[ind,:,:], np.kron(u[ind,:,:],o), np.kron(v[ind,:,:],o))),mode="YCbCr")
            im.thumbnail([400,225], Image.ANTIALIAS)
            im.save(batch_folder + "%04d"%(j+1) + ".jpg")

    os.remove("temp.yuv")


text:
import random

import numpy

from pyquaternion import Quaternion

from ltron.geometry.utils import squared_distance
from ltron.gym.components.ltron_gym_component import LtronGymComponent

class RandomFloatingBricks(LtronGymComponent):
    def __init__(self,
            scene_component,
            bricks,
            colors,
            bricks_per_scene = (10,20),
            min_brick_distance = 50,
            brick_placement_distance = (40, 60),#(50, 100),
            rotation_mode = 'identity'):

        self.scene_component = scene_component
        self.bricks = bricks
        self.colors = colors
        self.bricks_per_scene = bricks_per_scene
        self.min_brick_distance = min_brick_distance
        self.brick_placement_distance = brick_placement_distance
        self.rotation_mode = rotation_mode

    def reset(self):
        try:
            len(self.bricks_per_scene)
            bricks_per_scene = self.bricks_per_scene
        except TypeError:
            bricks_per_scene = (self.bricks_per_scene, self.bricks_per_scene)
        num_new_bricks = random.randint(*bricks_per_scene)

        try:
            len(self.brick_placement_distance)
            brick_placement_distance = self.brick_placement_distance
        except TypeError:
            brick_placement_distance = (
                    self.brick_placement_distance,
                    self.brick_placement_distance)

        brick_scene = self.scene_component.brick_scene

        for brick in range(num_new_bricks):

            all_brick_transforms = [instance.transform
                    for instance in brick_scene.instances.values()]
            all_brick_positions = [numpy.dot(transform, [0,0,0,1])[:3]
                    for transform in all_brick_transforms]

            if len(all_brick_positions):
                while True:
                    distance = random.uniform(*brick_placement_distance)
                    offset = [1,1,1]
                    while squared_distance(offset, (0,0,0)) > 1.:
                        offset = [random.random() * 2 - 1. for _ in range(3)]
                    norm = squared_distance(offset, (0,0,0))**0.5
                    offset = [o*distance/norm for o in offset]

                    seed_id = random.randint(0, len(all_brick_transforms)-1)
                    seed_transform = all_brick_transforms[seed_id]

                    offset_position = numpy.dot(
                            seed_transform, offset + [1])[:3]

                    far_enough = [
                            squared_distance(position, offset_position) >
                                self.min_brick_distance**2
                            for position in all_brick_positions]
                    if all(far_enough):
                        new_brick_transform = numpy.dot(seed_transform,
                                numpy.array([
                                    [1, 0, 0, offset[0]],
                                    [0, 1, 0, offset[1]],
                                    [0, 0, 1, offset[2]],
                                    [0, 0, 0, 1]]))
                        if self.rotation_mode == 'identity':
                            r = numpy.eye(3)
                            r[1,1] = -1
                            r[2,2] = -1
                            new_brick_transform[:3,:3] = r
                        elif self.rotation_mode == 'uniform':
                            q = Quaternion.random()
                            new_brick_transform[:3,:3] = q.rotation_matrix
                        break

            else:
                if (self.rotation_mode == 'identity' or
                        self.rotation_mode == 'local_identity'):
                    new_brick_transform = numpy.array([
                            [1, 0, 0, 0],
                            [0,-1, 0, 0],
                            [0, 0,-1, 0],
                            [0, 0, 0, 1]])
                elif self.rotation_mode == 'uniform':
                    q = Quaternion.random()
                    new_brick_transform = q.transformation_matrix

            brick_shape = random.choice(self.bricks)
            if brick_shape not in brick_scene.shape_library:
                brick_scene.add_brick_shape(brick_shape)
            brick_color = random.choice(self.colors)
            if brick_color not in brick_scene.color_library:
                brick_scene.load_colors([brick_color])
            brick_scene.add_instance(
                    brick_shape, brick_color, new_brick_transform)

        return None

max_stars_repo_name: aaronwalsman/ltron

max_issues_repo_name: aaronwalsman/ltron

max_forks_repo_name: aaronwalsman/ltron


text:
import unittest
from pyalink.alink import *
import numpy as np
import pandas as pd
class TestBucketizer(unittest.TestCase):
    def test_bucketizer(self):

        df = pd.DataFrame([
            [1.1, True, "2", "A"],
            [1.1, False, "2", "B"],
            [1.1, True, "1", "B"],
            [2.2, True, "1", "A"]
        ])

        inOp = BatchOperator.fromDataframe(df, schemaStr='double double, bool boolean, number int, str string')
        bucketizer = Bucketizer().setSelectedCols(["double"]).setCutsArray([[2.0]])
        bucketizer.transform(inOp).print()
        pass


text:
############################################################
# -*- coding: utf-8 -*-
#
#       #   #  #   #   #    #
#      ##  ##  #  ##  #    #
#     # # # #  # # # #    #  #
#    #  ##  #  ##  ##    ######
#   #   #   #  #   #       #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 for python
#
# written in python3, (c) 2019-2021 by mworion
#
# Licence APL2.0
#
###########################################################
# standard libraries
import unittest.mock as mock
import pytest
import platform
import os
import math

# external packages
from PyQt5.QtWidgets import QMessageBox, QFileDialog, QWidget, QStyle
from PyQt5.QtWidgets import QPushButton, QComboBox, QTableWidgetItem
from PyQt5.QtCore import pyqtSignal, QObject, QEvent
from skyfield.api import Angle
import numpy as np

# local import
from gui.utilities.toolsQtWidget import MWidget
from gui.utilities.toolsQtWidget import FileSortProxyModel
from gui.utilities.toolsQtWidget import QMultiWait, QCustomTableWidgetItem

@pytest.fixture(autouse=True, scope='module')
def module(qapp):
    yield

@pytest.fixture(autouse=True, scope='function')
def function(module):

    window = MWidget()
    yield window

def test_FileSortProxyModel_1():
    f = FileSortProxyModel()
    f.sort()

def test_QMultiWait_1():
    class Test(QObject):
        a = pyqtSignal()
    w = QMultiWait()
    A = Test()
    w.addWaitableSignal(A.a)

def test_QMultiWait_2():
    class Test(QObject):
        a = pyqtSignal()
    w = QMultiWait()
    A = Test()
    w.addWaitableSignal(A.a)
    w.checkSignal()

def test_QMultiWait_3():
    w = QMultiWait()
    w.resetSignals()

def test_QMultiWait_4():
    class Test(QObject):
        a = pyqtSignal()
    w = QMultiWait()
    A = Test()
    w.addWaitableSignal(A.a)
    w.clear()

def test_QCustomTableWidgetItem_1():
    i1 = QCustomTableWidgetItem('')
    i2 = QCustomTableWidgetItem('')
    assert not (i1 < i2)

def test_QCustomTableWidgetItem_2():
    i1 = QCustomTableWidgetItem('-2.0')
    i2 = QCustomTableWidgetItem('')
    assert i1 < i2

def test_QCustomTableWidgetItem_3():
    i1 = QCustomTableWidgetItem('-2.0')
    i2 = QCustomTableWidgetItem('5')
    assert i1 < i2

def test_QCustomTableWidgetItem_4():
    i1 = QCustomTableWidgetItem('-2.0')
    i2 = QTableWidgetItem('5')
    assert i1 < i2

def test_FileSortProxyModel_1():
    w = QWidget()
    dialog = QFileDialog()
    dialog.setProxyModel(FileSortProxyModel(w))

def test_findIndexValue_0(function):
    ui = QComboBox()
    ui.addItem('')
    val = function.findIndexValue(ui=ui,
                                  searchString='dome')
    assert val == 0

def test_findIndexValue_1(function):
    ui = QComboBox()
    ui.addItem('dome')
    ui.addItem('test')
    val = function.findIndexValue(ui=ui,
                                  searchString='dome')
    assert val == 0

def test_findIndexValue_2(function):
    ui = QComboBox()
    ui.addItem('dome')
    ui.addItem('indi')
    val = function.findIndexValue(ui=ui,
                                  searchString='indi')
    assert val == 1

def test_findIndexValue_3(function):
    ui = QComboBox()
    ui.addItem('dome')
    ui.addItem('test')
    ui.addItem('indi - test')
    val = function.findIndexValue(ui=ui,
                                  searchString='indi')
    assert val == 2

def test_findIndexValue_4(function):
    ui = QComboBox()
    ui.addItem('dome')
    ui.addItem('test')
    ui.addItem('indi - test')
    val = function.findIndexValue(ui=ui,
                                  searchString='indi',
                                  relaxed=True)
    assert val == 2

def test_findIndexValue_5(function):
    ui = QComboBox()
    val = function.findIndexValue(ui=ui,
                                  searchString='indi')
    assert val == 0

def test_wIcon_1(function):
    suc = function.wIcon()
    assert not suc

def test_wIcon_2(function):
    icon = QStyle.SP_DialogApplyButton
    suc = function.wIcon()
    assert not suc

def test_wIcon_3(function):
    ui = QPushButton()
    suc = function.wIcon(gui=ui)
    assert not suc

def test_wIcon_4(function):
    icon = QStyle.SP_DialogApplyButton
    ui = QPushButton()
    suc = function.wIcon(gui=ui, name='load')
    assert suc

def test_getStyle_1(function):
    with mock.patch.object(platform,
                           'system',
                           return_value='Darwin'):
        ret = function.getStyle()
        assert ret == function.MAC_STYLE + function.BASIC_STYLE

def test_getStyle_2(function):
    with mock.patch.object(platform,
                           'system',
                           return_value='Windows'):
        ret = function.getStyle()
        assert ret == function.NON_MAC_STYLE + function.BASIC_STYLE

def test_initUI_1(function):
    suc = function.initUI()
    assert suc

def test_changeStyleDynamic_1(function):
    suc = function.changeStyleDynamic()
    assert not suc

def test_changeStyleDynamic_2(function):
    ui = QPushButton()
    suc = function.changeStyleDynamic(ui)
    assert not suc

def test_changeStyleDynamic_3(function):
    ui = QPushButton()
    suc = function.changeStyleDynamic(ui, 'color')
    assert not suc

def test_changeStyleDynamic_4(function):
    ui = QPushButton()
    suc = function.changeStyleDynamic(ui, 'color', 'red')
    assert suc

def test_changeStyleDynamic_5(function):
    ui = QPushButton()
    ui.setProperty('color', 'red')
    suc = function.changeStyleDynamic(ui, 'color', 'red')
    assert suc

def test_extractNames_0(function):
    name = ''
    name, short, ext = function.extractNames(name)
    assert name == ''
    assert short == ''
    assert ext == ''

def test_extractNames_1(function):
    name = 1
    name, short, ext = function.extractNames(name)
    assert name == ''
    assert short == ''
    assert ext == ''

def test_extractNames_2(function):
    name = ['test']
    name, short, ext = function.extractNames(name)
    assert name == os.path.abspath(os.getcwd() + '/test')
    assert short == 'test'
    assert ext == ''

def test_extractNames_3(function):
    name = ['c:/test']
    name, short, ext = function.extractNames(name)
    assert name == os.path.abspath('c:/test')
    assert short == 'test'
    assert ext == ''

def test_extractNames_4(function):
    name = ['c:/test.cfg']
    name, short, ext = function.extractNames(name)
    assert name == os.path.abspath('c:/test.cfg')
    assert short == 'test'
    assert ext == '.cfg'

def test_extractNames_5(function):
    name = ['c:/test.cfg', 'c:/test.cfg']
    name, short, ext = function.extractNames(name)
    assert name == [os.path.abspath('c:/test.cfg'),
                    os.path.abspath('c:/test.cfg')]
    assert short == ['test', 'test']
    assert ext == ['.cfg', '.cfg']

def test_extractNames_6(function):
    name = ['', 'c:/test.cfg']
    name, short, ext = function.extractNames(name)
    assert name == [os.path.abspath(''),
                    os.path.abspath('c:/test.cfg')]
    assert short == ['', 'test']
    assert ext == ['', '.cfg']

def test_prepareFileDialog_1(function):
    suc = function.prepareFileDialog()
    assert not suc

def test_prepareFileDialog_2(function):
    window = QWidget()
    suc = function.prepareFileDialog(window=window)
    assert suc

def test_prepareFileDialog_3(function):
    window = QWidget()
    suc = function.prepareFileDialog(window=window, enableDir=True, reverseOrder=True)
    assert suc

def test_runDialog_1(function):
    dialog = QFileDialog()
    with mock.patch.object(QFileDialog,
                           'exec_',
                           return_value=0):
        val = function.runDialog(dialog)
        assert val == 0

def test_messageDialog_1(function):
    widget = QWidget()
    with mock.patch.object(QMessageBox,
                           'question',
                           return_value=QMessageBox.No):
        with mock.patch.object(QMessageBox,
                               'show'):
            with mock.patch.object(function,
                                   'runDialog',
                                   return_value=QMessageBox.No):
                suc = function.messageDialog(widget, 'test', 'test')
                assert not suc

def test_messageDialog_2(function):
    widget = QWidget()
    with mock.patch.object(QMessageBox,
                           'question',
                           return_value=QMessageBox.Yes):
        with mock.patch.object(QMessageBox,
                               'show'):
            with mock.patch.object(function,
                                   'runDialog',
                                   return_value=QMessageBox.Yes):
                suc = function.messageDialog(widget, 'test', 'test')
                assert suc

def test_openFile_1(function):
    full, short, ext = function.openFile()
    assert full == ''
    assert short == ''
    assert ext == ''

def test_openFile_2(function):
    window = QWidget()
    full, short, ext = function.openFile(window=window)
    assert full == ''
    assert short == ''
    assert ext == ''

def test_openFile_3(function):
    window = QWidget()
    full, short, ext = function.openFile(window=window,
                                         title='title')
    assert full == ''
    assert short == ''
    assert ext == ''

def test_openFile_4(function):
    window = QWidget()
    full, short, ext = function.openFile(window=window,
                                         title='title',
                                         folder='.')
    assert full == ''
    assert short == ''
    assert ext == ''

def test_openFile_5(function):
    window = QWidget()
    with mock.patch.object(function,
                           'runDialog',
                           return_value=0):
        full, short, ext = function.openFile(window=window,
                                             title='title',
                                             folder='.',
                                             filterSet='*.*')
        assert full == ''
        assert short == ''
        assert ext == ''

def test_openFile_6(function):
    window = QWidget()
    with mock.patch.object(function,
                           'runDialog',
                           return_value=1):
        with mock.patch.object(QFileDialog,
                               'selectedFiles',
                               return_value=('test1', 'test2')):
            full, short, ext = function.openFile(window=window,
                                                 title='title',
                                                 folder='.',
                                                 filterSet='*.*',
                                                 multiple=True)
            assert full == ''
            assert short == ''
            assert ext == ''

def test_saveFile_1(function):
    full, short, ext = function.saveFile()
    assert full == ''
    assert short == ''
    assert ext == ''

def test_saveFile_2(function):
    window = QWidget()
    full, short, ext = function.saveFile(window=window)
    assert full == ''
    assert short == ''
    assert ext == ''

def test_saveFile_3(function):
    window = QWidget()
    full, short, ext = function.saveFile(window=window,
                                         title='title')
    assert full == ''
    assert short == ''
    assert ext == ''

def test_saveFile_4(function):
    window = QWidget()
    full, short, ext = function.saveFile(window=window,
                                         title='title',
                                         folder='.')
    assert full == ''
    assert short == ''
    assert ext == ''

def test_saveFile_5(function):
    window = QWidget()
    with mock.patch.object(function,
                           'runDialog',
                           return_value=0):
        full, short, ext = function.saveFile(window=window,
                                             title='title',
                                             folder='.',
                                             filterSet='*.*')
        assert full == ''
        assert short == ''
        assert ext == ''

def test_saveFile_6(function):
    window = QWidget()
    with mock.patch.object(function,
                           'runDialog',
                           return_value=1):
        with mock.patch.object(QFileDialog,
                               'selectedFiles',
                               return_value=(['tests/test.txt'])):
            full, short, ext = function.saveFile(window=window,
                                                 title='title',
                                                 folder='.',
                                                 filterSet='*.*')
        assert short == 'test'
        assert ext == '.txt'

def test_openDir_1(function):
    full, short, ext = function.openDir()
    assert full == ''
    assert short == ''
    assert ext == ''

def test_openDir_2(function):
    window = QWidget()
    full, short, ext = function.openDir(window=window)
    assert full == ''
    assert short == ''
    assert ext == ''

def test_openDir_3(function):
    window = QWidget()
    full, short, ext = function.openDir(window=window,
                                        title='title')
    assert full == ''
    assert short == ''
    assert ext == ''

def test_openDir_4(function):
    window = QWidget()
    with mock.patch.object(function,
                           'runDialog',
                           return_value=1):
        full, short, ext = function.openDir(window=window,
                                            title='title',
                                            folder='.')
        assert full == os.getcwd()

def test_openDir_5(function):
    window = QWidget()
    with mock.patch.object(function,
                           'runDialog',
                           return_value=None):
        full, short, ext = function.openDir(window=window,
                                            title='title',
                                            folder='.')
        assert full == ''
        assert short == ''
        assert ext == ''

def test_clickable_1(function):
    suc = function.clickable()
    assert not suc

def test_clickable_2(function):
    event = QEvent(QEvent.MouseButtonRelease)
    widget = QPushButton()
    suc = function.clickable(widget=widget)
    assert suc
    suc = widget.eventFilter(widget, event)
    assert not suc

def test_guiSetText_1(function):
    suc = function.guiSetText(None, None)
    assert not suc

def test_guiSetText_2(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, None)
    assert not suc

def test_guiSetText_3(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, '3.5f')
    assert suc
    assert pb.text() == '-'

def test_guiSetText_3b(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, '3.5f', [])
    assert suc

def test_guiSetText_3c(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, '3.5f', np.array([]))
    assert suc

def test_guiSetText_4(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, '3.0f', 100)
    assert suc
    assert pb.text() == '100'

def test_guiSetText_5(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, 'HSTR', Angle(hours=10))
    assert suc
    assert pb.text() == '10 00 00'

def test_guiSetText_6(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, 'DSTR', Angle(degrees=90))
    assert suc
    assert pb.text() == '+90 00 00'

def test_guiSetText_7(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, 'H2.2f', Angle(hours=12))
    assert suc
    assert pb.text() == '12.00'

def test_guiSetText_8(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, 'D+2.2f', Angle(degrees=90))
    assert suc
    assert pb.text() == '+90.00'

def test_guiSetText_9(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, 's', 'E')
    assert suc
    assert pb.text() == 'EAST'

def test_guiSetText_10(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, 's', 'W')
    assert suc
    assert pb.text() == 'WEST'

def test_guiSetText_11(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, 's', True)
    assert suc
    assert pb.text() == 'ON'

def test_guiSetText_12(function):
    pb = QPushButton()
    suc = function.guiSetText(pb, 's', False)
    assert suc
    assert pb.text() == 'OFF'

def test_guiSetStyle_1(function):
    pb = QPushButton()
    suc = function.guiSetStyle(pb)
    assert not suc

def test_guiSetStyle_2(function):
    pb = QPushButton()
    suc = function.guiSetStyle(pb, pStyle='color', value=None)
    assert suc

def test_guiSetStyle_3(function):
    pb = QPushButton()
    suc = function.guiSetStyle(pb, pStyle='color', value=True)
    assert suc

def test_guiSetStyle_4(function):
    pb = QPushButton()
    suc = function.guiSetStyle(pb, pStyle='color', value=False)
    assert suc

def test_returnDriver_1(function):
    sender = QWidget()
    searchDict = {}
    driver = function.returnDriver(sender, searchDict)
    assert driver == ''

def test_returnDriver_2(function):
    sender = QWidget()
    searchDict = {}
    driver = function.returnDriver(sender, searchDict, addKey='test')
    assert driver == ''


text:
import channel as Channel
import math
import numpy as np
class Player:
    def __init__(self, song, frame_rate_period):
        self.song = song
        self.frame_rate_period = frame_rate_period
        self.channels = []
        self.sequence = 0
        self.channels.append(Channel.channel(song.samples,frame_rate_period))
        self.channels.append(Channel.channel(song.samples,frame_rate_period))
        self.channels.append(Channel.channel(song.samples,frame_rate_period))
        self.channels.append(Channel.channel(song.samples,frame_rate_period))
        self.sequence = 0
        self.pattern_row = 0
        self.last_note_counter = 0
        self.finished = False

    def get_frames(self, duration):
        requested_frames = math.floor(duration / self.frame_rate_period)
        buffer = [0.0] * requested_frames

    def get_frames_row(self):
        self.play_notes(self.song.sequences[self.sequence],self.pattern_row)
        self.pattern_row += 1
        if self.pattern_row > 63:
            self.sequence += 1
            self.pattern_row = 0
            print(f"squence {self.sequence} pattern {self.song.sequences[self.sequence]}")
            if self.sequence >= self.song.length:
                self.finished = True
                print("Finished!")

        notes = [x.get_frames(self.song.note_period) for x in self.channels ]
        mix = np.add.reduce(np.single(notes)) * 0.25
        return mix

    def play_notes(self, pattern, row):
        for i, channel in enumerate(self.channels):
            note = self.song.patterns[pattern][row][i]
            print(f"{note.sample_number:03}", end=" ")
            channel.play_note(note.sample_number,note.period,note.effect)
        print("")

max_stars_repo_name: MatthewRobertDunn/PyAmigamModule

max_issues_repo_name: MatthewRobertDunn/PyAmigamModule

max_forks_repo_name: MatthewRobertDunn/PyAmigamModule


text:
from __future__ import print_function
from cif2system import initialize_system, duplicate_system, replication_determination, write_cif_from_system
import atomic_data
import sys
import os
import numpy as np
import math
import datetime

from UFF4MOF_construction import UFF4MOF
import UFF4MOF_constants

from UFF_construction import UFF
import UFF_constants

from Dreiding_construction import Dreiding
import Dreiding_constants

UFF4MOF_atom_parameters = UFF4MOF_constants.UFF4MOF_atom_parameters
UFF4MOF_bond_orders_0 = UFF4MOF_constants.UFF4MOF_bond_orders_0

UFF_atom_parameters = UFF_constants.UFF_atom_parameters
UFF_bond_orders_0 = UFF_constants.UFF_bond_orders_0

Dreiding_atom_parameters = Dreiding_constants.Dreiding_atom_parameters
Dreiding_bond_orders_0 = Dreiding_constants.Dreiding_bond_orders_0

mass_key = atomic_data.mass_key

# add more force field classes here as they are made

# this is a placeholder script for conversion to GULP, currently it is just used
# for validating LAMMPS UFF4MOF calculations, it will be exanpded for more
# general GULP usage

def isfloat(value):
    """
        determines if a value is a float
    """
    try:
        float(value)
        return True
    except ValueError:
        return False

mass_key = atomic_data.mass_key

def GULP_inputs(args):

    gulp_bond_types = {0.25:'quarter', 0.5:'half', 1.0:'', 1.5:'resonant', 2.0:'', 3.0:''}

    cifname, force_field, outdir, charges, replication, noautobond = args
    FF_args = {'FF_parameters':UFF4MOF_atom_parameters, 'bond_orders':UFF4MOF_bond_orders_0}
    cutoff = 12.5

    system = initialize_system(cifname, charges=charges)
    system, replication = replication_determination(system, replication, cutoff)
    FF = force_field(system, cutoff, FF_args)
    FF.compile_force_field(charges=charges)

    SG = FF.system['graph']
    a,b,c,alpha,beta,gamma = system['box']
    lx = np.round(a, 8)
    xy = np.round(b * np.cos(math.radians(gamma)), 8)
    xz = np.round(c * np.cos(math.radians(beta)), 8)
    ly = np.round(np.sqrt(b**2 - xy**2), 8)
    yz = np.round((b * c*np.cos(math.radians(alpha)) - xy*xz)/ly, 8)
    lz = np.round(np.sqrt(c**2 - xz**2 - yz**2), 8)

    preffix = cifname.split('/')[-1].split('.')[0]
    name = preffix + '.gin'

    with open(outdir + os.sep + name, 'w') as gin:

        if noautobond:
            gin.write('opti conp free zsisa noautobond cartesian\n')
        else:
            gin.write('opti conp free zsisa cartesian\n')
        gin.write('vectors\n')
        gin.write(str(lx) + ' 0.0 0.0' '\n')
        gin.write('0.0 ' + str(ly) + ' 0.0'+ '\n')
        gin.write('0.0 0.0 ' + str(lz) + '\n')
        gin.write('cartesian\n')

        for a in SG.nodes(data=True):
            atom_data = a[1]
            index = atom_data['index']
            force_field_type = atom_data['force_field_type']
            gulp_type = FF.atom_types[force_field_type]
            elem = FF.atom_element_symbols[force_field_type]
            pos = [np.round(v,8) for v in atom_data['cartesian_position']]
            line = [elem + str(gulp_type), 'core', pos[0], pos[1], pos[2]]
            gin.write('{:5} {:<6} {:12.5f} {:12.5f} {:12.5f}'.format(*line))
            gin.write('\n')
        gin.write('\n')

        bonds = [(b,ty) for ty in FF.bond_data['all_bonds'] for b in FF.bond_data['all_bonds'][ty]]
        bonds.sort(key = lambda x:x[0][0])

        if noautobond:
            for bond in bonds:
                b, ty = bond
                comments = FF.bond_data['comments'][ty]
                bond_order = float(comments[-1].split('=')[-1])
                gulp_bond = gulp_bond_types[bond_order]
                line = ['connect', b[0], b[1], gulp_bond]
                gin.write('{:10} {:5} {:5} {:>10}'.format(*line))
                gin.write('\n')
            gin.write('\n')
        else:
            pass

        gin.write('species\n')
        for fft in FF.atom_types:

            elem = FF.atom_element_symbols[fft]
            gulp_type = FF.atom_types[fft]

            write_type = fft
            if fft == 'O_2_M':
                write_type = 'O_2'
            if fft == 'O_3_M':
                write_type = 'O_3'

            line = [elem + str(gulp_type), write_type]
            gin.write('{:4} {:7}'.format(*line))
            gin.write('\n')
        gin.write('\n')

        gin.write('library uff4mof.lib\n')
        gin.write('uff_bondorder custom 0.001\n')
        gin.write('output cif ' + 'OPT_' + preffix + '.cif' + '\n')
        gin.write('rspeed 0.1000\n')
        gin.write('temperature 300\n')

#GULP_inputs(['unopt_cifs/pcu_v1-6c_Zn_1_Ch_1B_2thiophene_Ch.cif', UFF4MOF, 'GULP_inputs', False, '1x1x1'])