Beispiel #1
0
    def on_click(self):
        """
        'Load csv file' button's on_click call-back listener. It will do a couple of things:
        1. Get the filename of the csv file
        2. Load csv file, and convert the data into the grid data for the Sudoku solver class
        3. Open up a pygame graph to show the simulation of solving the puzzle
        """
        init_dir = './Data'
        name = 'Choose your file'
        filetype = (("csv files","*.csv"))

        self.get_filename(init_dir, name, filetype)
        self.grid = utility.load_csv(self.filename)

        while len(self.grid) != 81 or len(set(self.grid).difference(set('1234567890'))) != 0:
            """
            This part checks if the csv file is in correct format: 9 * 9 grid with only '1234567890' digits
            """
            self.pop_up("Wrong content in csv file. Make sure it is a 9 * 9 grid with only '1234567890' digits")
            self.get_filename(init_dir, name, filetype)
            self.grid = utility.load_csv(self.filename)

        # Solve the puzzle here
        self.sudoku = Solver(self.grid)
        t, final_values = self.sudoku.solve()
        if final_values == False:
            self.pop_up('There is no solution for this puzzle. Try another one!')
            return
        else:
            # If puzzle is successfully solved, write to csv file and open pygame to demo the result
            output = self.filename[:-4] + '_sol.csv'
            utility.write_csv(output, self.sudoku.final_values)
            self.open_pygame()
def withdrawDelegateReward(address, offline, config, style):
    """
    this is delegate submodule withdrawDelegateReward command.
    """
    wallet_dir = g_dict_dir_config["wallet_dir"]
    wallet_file_path, private_key, hrp, _ = verify_password(address, wallet_dir)

    ppos = get_eth_obj(config, 'ppos')
    _params = {'pri_key': private_key[2:], 'transaction_cfg': None}
    try:
        if offline:
            data = rlp.encode([rlp.encode(int(5000))])
            _params['to_type'] = 'delegateReward'
            transaction_dict = un_sign_data(data, _params, ppos, _params['pri_key'])
            unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"]
            check_dir_exits(unsigned_tx_dir)
            unsigned_file_csv_name = "unsigned_delegate_withdrawDelegateReward_{}.csv".format(get_time_stamp())
            unsigned_file_path = os.path.join(unsigned_tx_dir, unsigned_file_csv_name)
            if style == '':
                write_csv(unsigned_file_path, [transaction_dict])
            else:
                unsigned_file_path = unsigned_file_path.replace('csv', 'jpg')
                write_QRCode(transaction_dict, unsigned_file_path)
        else:
            tx_hash = ppos.withdrawDelegateReward(*_params.values())
            cust_print('delegate withdrawDelegateReward send transfer transaction successful, tx hash:{}.'.format(tx_hash),fg='g')
    except ValueError as e:
        cust_print('delegate withdrawDelegateReward send transfer transaction fail,error info:{}'.format(e), fg='r')
        sys.exit(1)
def reportDoubleSign(param, address, offline, config, style):
    """
    this is government submodule reportDoubleSign command.
    """
    if not os.path.isfile(param):
        cust_print('file {} not exits! please check!'.format(param), fg='r')
        sys.exit(1)
    params = read_json_file(param)
    wallet_dir = g_dict_dir_config["wallet_dir"]
    _, private_key, _, _ = verify_password(address, wallet_dir)
    ppos = get_eth_obj(config, 'ppos')
    try:
        _params = {'typ': params['type'], 'data': params['data']}
    except KeyError as e:
        cust_print(
            'reportDoubleSign need params {},but it does not exist,please check!'
            .format(e),
            fg='r')
        sys.exit(1)
    try:
        if offline:
            data = rlp.encode([
                rlp.encode(int(3000)),
                rlp.encode(params['type']),
                rlp.encode(params['data'])
            ])
            _params['transaction_cfg'] = params.get('transaction_cfg', None)
            _params['to_type'] = 'penalty'
            transaction_dict = un_sign_data(data, _params, ppos,
                                            private_key[2:])
            unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"]
            check_dir_exits(unsigned_tx_dir)
            unsigned_file_csv_name = "unsigned_government_reportDoubleSign_{}.csv".format(
                get_time_stamp())
            unsigned_file_path = os.path.join(unsigned_tx_dir,
                                              unsigned_file_csv_name)
            if style == '':
                write_csv(unsigned_file_path, [transaction_dict])
            else:
                unsigned_file_path = unsigned_file_path.replace('csv', 'jpg')
                write_QRCode(transaction_dict, unsigned_file_path)
            cust_print('unsigned_file save to:{}'.format(unsigned_file_path),
                       fg='g')
        else:
            _params['pri_key'] = private_key[2:]
            _params['transaction_cfg'] = params.get('transaction_cfg', None)
            txhash = ppos.reportDuplicateSign(*_params.values())
            cust_print(
                'send raw transfer transaction successful, tx hash:{}.'.format(
                    txhash),
                fg='g')
    except Exception as e:
        cust_print(
            'government send transfer transaction fail,error info:{}'.format(
                e),
            fg='r')
        sys.exit(1)
Beispiel #4
0
def vote(param, address, offline, config, style):
    """
    this is government submodule vote command.
    """
    if not os.path.isfile(param):
        cust_print('file {} not exits! please check!'.format(param), fg='r')
        sys.exit(1)
    params = read_json_file(param)
    try:
        _params = {'verifier': params['verifier'], 'proposalId': params['proposalId'], 'option': int(params['option'])}
    except KeyError as e:
        cust_print('vote need params {},but it does not exist,please check!'.format(e), fg='r')
        sys.exit(1)
    wallet_dir = g_dict_dir_config["wallet_dir"]
    _, private_key, _, _ = verify_password(address, wallet_dir)
    ppos = get_eth_obj(config, 'ppos')
    pip = get_eth_obj(config, 'pip')
    msg = ppos.admin.getProgramVersion()
    program_version = msg['Version']
    version_sign = msg['Sign']
    try:
        if offline:
            data = rlp.encode(
                [rlp.encode(int(2003)), rlp.encode(bytes.fromhex(params['verifier'])),
                 rlp.encode(bytes.fromhex(params['proposalId'])),
                 rlp.encode(params['option']), rlp.encode(int(program_version)),
                 rlp.encode(bytes.fromhex(version_sign))])
            _params['transaction_cfg'] = params.get('transaction_cfg', None)
            _params['to_type'] = 'pip'
            transaction_dict = un_sign_data(data, _params, pip, private_key[2:])
            unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"]
            check_dir_exits(unsigned_tx_dir)
            unsigned_file_csv_name = "unsigned_government_vote_{}.csv".format(get_time_stamp())
            unsigned_file_path = os.path.join(unsigned_tx_dir, unsigned_file_csv_name)
            if style == '':
                write_csv(unsigned_file_path, [transaction_dict])
            else:
                unsigned_file_path = unsigned_file_path.replace('csv', 'jpg')
                write_QRCode(transaction_dict, unsigned_file_path)
            cust_print('unsigned_file save to:{}'.format(unsigned_file_path), fg='g')
        else:
            _params['program_version'] = program_version
            _params['version_sign'] = version_sign
            _params['pri_key'] = private_key[2:]
            _params['transaction_cfg'] = params.get('transaction_cfg', None)
            txhash = pip.vote(*_params.values())
            cust_print('send raw transfer transaction successful, tx hash:{}.'.format(txhash), fg='g')
    except Exception as e:
        cust_print('vote send transfer transaction fail,error info:{}'.format(e), fg='r')
        sys.exit(1)
Beispiel #5
0
def unStaking(address, file, config, offline, style):
    """
    this is staking submodule unStaking command.
    """
    params = read_json_file(file)
    node_id = params['node_id']
    transaction_cfg = params['transaction_cfg']

    check_node_id(node_id)
    wallet_dir = g_dict_dir_config["wallet_dir"]
    _, private_key, _, _ = verify_password(address, wallet_dir)
    private_key = private_key[2:]

    ppos = get_eth_obj(config, 'ppos')
    try:
        if offline:
            unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"]
            check_dir_exits(unsigned_tx_dir)
            unsigned_file_csv_name = "unsigned_staking_unStaking_{}.csv".format(
                get_time_stamp())
            unsigned_file_path = os.path.join(unsigned_tx_dir,
                                              unsigned_file_csv_name)
            data = rlp.encode(
                [rlp.encode(int(1003)),
                 rlp.encode(bytes.fromhex(node_id))])
            params['to_type'] = 'staking'
            transaction_dict = un_sign_data(data, params, ppos, private_key)
            if style == '':
                write_csv(unsigned_file_path, [transaction_dict])
            else:
                unsigned_file_path = unsigned_file_path.replace('csv', 'jpg')
                write_QRCode(transaction_dict, unsigned_file_path)
            cust_print('unsigned_file save to:{}'.format(unsigned_file_path),
                       fg='g')
        else:
            tx_hash = ppos.withdrewStaking(node_id, private_key,
                                           transaction_cfg)
            cust_print(
                'withdrewStaking send transfer transaction successful, tx hash:{}.'
                .format(tx_hash),
                fg='g')
    except ValueError as e:
        cust_print(
            'unStaking send transfer transaction fail,error info:{}'.format(e),
            fg='r')
        sys.exit(1)
Beispiel #6
0
def create(file, address, template, config, offline, style):
    """
    this is staking submodule create command.
    """
    if template:
        show_params()
        return

    if not os.path.isfile(file):
        cust_print('file {} not exits! please check!'.format(file), fg='r')
        sys.exit(1)
    params = read_json_file(file)
    wallet_dir = g_dict_dir_config["wallet_dir"]
    wallet_file_path, private_key, hrp, _ = verify_password(address, wallet_dir)

    ppos = get_eth_obj(config, 'ppos')
    msg = ppos.admin.getProgramVersion()

    bls_pubkey = ppos.admin.nodeInfo.blsPubKey
    bls_proof = ppos.admin.getSchnorrNIZKProve()
    program_version = msg['Version']
    program_version_sign = msg['Sign']
    _params = {}
    try:
        _params['typ'] = params['typ']
        _params['benifit_address'] = params['benifit_address']
        _params['node_id'] = params['node_id'] or ppos.admin.nodeInfo.id

        _params['external_id'] = params['external_id']
        _params['node_name'] = params['node_name']
        _params['website'] = params['website']
        _params['details'] = params['details']

        _params['amount'] = ppos.w3.toWei(str(params['amount']), "ether")
        _params['program_version'] = params['program_version'] or program_version
        _params['program_version_sign'] = params['program_version_sign'] or program_version_sign
        _params['bls_pubkey'] = params['bls_pubkey'] or bls_pubkey
        _params['bls_proof'] = params['bls_proof'] or bls_proof
        _params['pri_key'] = private_key[2:]
        _params['reward_per'] = params['reward_per']
        if isinstance(params['transaction_cfg'], dict):
            _params['transaction_cfg'] = params['transaction_cfg']
    except KeyError as e:
        cust_print('Key {} does not exist in file {},please check!'.format(e, file), fg='r')
        sys.exit(1)
    try:
        if offline:
            data = rlp_params(tuple(_params.values()), hrp)
            params['to_type'] = 'staking'
            transaction_dict = un_sign_data(data, params, ppos, _params['pri_key'])
            unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"]
            check_dir_exits(unsigned_tx_dir)
            unsigned_file_csv_name = "unsigned_staking_create_{}.csv".format(get_time_stamp())
            unsigned_file_path = os.path.join(unsigned_tx_dir, unsigned_file_csv_name)
            if style == '':
                write_csv(unsigned_file_path, [transaction_dict])
            else:
                unsigned_file_path = unsigned_file_path.replace('csv', 'jpg')
                write_QRCode(transaction_dict, unsigned_file_path)
            cust_print('unsigned_file save to:{}'.format(unsigned_file_path), fg='g')
        else:
            tx_hash = ppos.createStaking(*_params.values())
            cust_print('createStaking send transfer transaction successful, tx hash:{}.'.format(tx_hash), fg='g')
    except ValueError as e:
        cust_print('createStaking send transfer transaction fail,error info:{}'.format(e))
        sys.exit(1)
Beispiel #7
0
def increase(file, address, template, config, offline, style):
    """
    this is staking submodule increase command.
    """
    if template:
        show_params()
        return
    if not os.path.isfile(file):
        cust_print('file {} not exits! please check!'.format(file), fg='r')
        sys.exit(1)
    params = read_json_file(file)
    wallet_dir = g_dict_dir_config["wallet_dir"]
    wallet_file_path, private_key, hrp, _ = verify_password(
        address, wallet_dir)

    ppos = get_eth_obj(config, 'ppos')
    _params = {}
    try:
        _params['typ'] = params['typ']
        _params['node_id'] = params['node_id'] or ppos.admin.nodeInfo.id
        _params['amount'] = ppos.w3.toWei(str(params['amount']), "ether")
        _params['pri_key'] = private_key[2:]
        if isinstance(params['transaction_cfg'], dict):
            _params['transaction_cfg'] = params['transaction_cfg']
    except KeyError as e:
        cust_print('Key {} does not exist in file {},please check!'.format(
            e, file),
                   fg='r')
        sys.exit(1)
    try:
        if offline:
            data = HexBytes(
                rlp.encode([
                    rlp.encode(int(1002)),
                    rlp.encode(bytes.fromhex(_params['node_id'])),
                    rlp.encode(_params['typ']),
                    rlp.encode(_params['amount'])
                ])).hex()
            params['to_type'] = 'staking'
            transaction_dict = un_sign_data(data, params, ppos,
                                            _params['pri_key'])
            unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"]
            check_dir_exits(unsigned_tx_dir)
            unsigned_file_csv_name = "unsigned_staking_increase_{}.csv".format(
                get_time_stamp())
            unsigned_file_path = os.path.join(unsigned_tx_dir,
                                              unsigned_file_csv_name)
            if style == '':
                write_csv(unsigned_file_path, [transaction_dict])
            else:
                unsigned_file_path = unsigned_file_path.replace('csv', 'jpg')
                write_QRCode(transaction_dict, unsigned_file_path)
            cust_print('unsigned_file save to:{}'.format(unsigned_file_path),
                       fg='g')
        else:
            tx_hash = ppos.increaseStaking(*_params.values())
            cust_print(
                'increase staking send transfer transaction successful, tx hash:{}.'
                .format(tx_hash),
                fg='g')
    except ValueError as e:
        cust_print(
            'increase staking send transfer transaction fail,error info:{}'.
            format(e),
            fg='r')
        sys.exit(1)
def createRestrictingPlan(param, address, offline, config, style):
    """
    this is government submodule vote command.
    """
    if not os.path.isfile(param):
        cust_print('file {} not exits! please check!'.format(param), fg='r')
        sys.exit(1)
    params = read_json_file(param)
    ppos = get_eth_obj(config, 'ppos')
    try:
        params['plans'] = [{
            'epoch':
            plan['epoch'],
            'amount':
            ppos.web3.toWei(str(plan['amount']), "ether")
        } for plan in params['plans']]
        _params = {'account': params['account'], 'plans': params['plans']}
    except KeyError as e:
        cust_print(
            'createRestrictingPlan need params {},but it does not exist,please check!'
            .format(e),
            fg='r')
        sys.exit(1)
    wallet_dir = g_dict_dir_config["wallet_dir"]
    _, private_key, hrp, _ = verify_password(address, wallet_dir)
    try:
        if offline:
            account = bech32_address_bytes(hrp)(params['account'])
            plan_list = [[plan[k] for k in plan] for plan in params['plans']]
            data = rlp.encode([
                rlp.encode(int(4000)),
                rlp.encode(account),
                rlp.encode(plan_list)
            ])
            _params['transaction_cfg'] = params.get('transaction_cfg', None)
            _params['to_type'] = 'restricting'
            transaction_dict = un_sign_data(data, _params, ppos,
                                            private_key[2:])
            unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"]
            check_dir_exits(unsigned_tx_dir)
            unsigned_file_csv_name = "unsigned_hedge_createRestrictingPlan_{}.csv".format(
                get_time_stamp())
            unsigned_file_path = os.path.join(unsigned_tx_dir,
                                              unsigned_file_csv_name)
            if style == '':
                write_csv(unsigned_file_path, [transaction_dict])
            else:
                unsigned_file_path = unsigned_file_path.replace('csv', 'jpg')
                write_QRCode(transaction_dict, unsigned_file_path)
            cust_print('unsigned_file save to:{}'.format(unsigned_file_path),
                       fg='g')
        else:
            _params['pri_key'] = private_key[2:]
            _params['transaction_cfg'] = params.get('transaction_cfg', None)
            txhash = ppos.createRestrictingPlan(*_params.values())
            cust_print(
                'send raw transfer transaction successful, tx hash:{}.'.format(
                    txhash),
                fg='g')
    except Exception as e:
        cust_print(
            'createRestrictingPlan send transfer transaction fail,error info:{}'
            .format(e),
            fg='r')
        sys.exit(1)
Beispiel #9
0
kfolds = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)

np.random.seed(1)

pipeline_svm = make_pipeline(
    vectorizer, SVC(probability=True, kernel="linear",
                    class_weight="balanced"))

model = GridSearchCV(pipeline_svm,
                     param_grid={'svc__C': [0.01, 0.1, 1]},
                     cv=kfolds,
                     scoring="roc_auc",
                     verbose=1,
                     n_jobs=1)
model.fit(X_train, y_train)
model.score(X_test, y_test)


def classify(sent_list):
    label_list = []
    for sent in sent_list:
        label_list.append(model.predict([sent[1]])[0])

    return label_list


if __name__ == '__main__':
    sent_list = utility.read_csv(testData)
    label_list = classify(sent_list)
    utility.write_csv(sent_list, label_list, out_path2)
Beispiel #10
0
                     healers):
    try:
        with open(damage_file_path, 'r') as dps_f:
            string_dps = dps_f.read()
        with open(healing_file_path, 'r') as healing_f:
            string_healing = healing_f.read()
    except IOError:
        print("wcl files are not exits")
        return -1

    epgp_list = utility.read_in_csv(epgp_file_path)
    for member in epgp_list:
        if member[0] in healers:
            wcl = string_healing
        else:
            wcl = string_dps
        score = utility.look_up_wcl_score(member[0], wcl)
        member.append(score)
    return epgp_list


if __name__ == "__main__":
    file_epgp = r"../ala_new_epgp.txt"
    file_damage = r"../test_data/wcl_damage.txt"
    file_heal = r"../test_data/wcl_heal.txt"
    healers = ('Gokuclose', 'Tombradyy', 'Grumpybride', 'Xiaoyan',
               'Toxictotem', 'Niubility', 'Sleepywayge', 'Babiefat',
               'Yiyibaby', 'Pigecha', 'Toxiccow', 'Cblue')
    current_list = append_wcl_score(file_epgp, file_damage, file_heal, healers)
    utility.write_csv(current_list, "../wishlist.cvs")
Beispiel #11
0
def main():
    '''
    Assemble a large corpus made up of texts written by an arbitrary
    number of authors; let’s say that number of authors is x.
    '''
    test = 'cases' # only have to change this one line
    authors = ['cases', 'laws', 'marriage', 'other', 'penance', 'second']
    authors.remove(test)
    corpus = []
    for author in authors:
        corpus += u.tokenize('./corpus/' + author + '.txt')
    '''
    Find the n most frequent words in the corpus to use as features.
    '''
    mfws = list(u.frequencies(corpus).keys())[:30]
    '''
    For each of these n features, calculate the share of each of
    the x authors’ subcorpora represented by this feature, as a
    percentage of the total number of words.
    '''
    corp_f_dict = {}
    empty = dict.fromkeys(mfws, 0)
    for author in authors:
        corp_f_dict[author] = empty.copy()
        subcorpus = u.tokenize('./corpus/' + author + '.txt')
        subcorpus_frequencies = u.frequencies(subcorpus)
        for word in mfws:
            corp_f_dict[author][word] = (subcorpus_frequencies.get(word, 0) / len(subcorpus)) * 1000
        u.write_csv(corp_f_dict, './subcorpus_frequencies.csv')
    '''
    Then, calculate the mean and the standard deviation of these x
    values and use them as the offical mean and standard deviation
    for this feature over the whole corpus. In other words, we will
    be using a mean of means instead of calculating a single value
    representing the share of the entire corpus represented by each
    word.
    '''
    means = empty.copy()
    stdevs = empty.copy()
    for word in mfws:
        corp_f_list = []
        for author in authors:
            corp_f_list.append(corp_f_dict[author][word])
        means[word] = statistics.mean(corp_f_list)
        stdevs[word] = statistics.stdev(corp_f_list)
    '''
    For each of the n features and x subcorpora, calculate a z-score
    describing how far away from the corpus norm the usage of this
    particular feature in this particular subcorpus happens to be.
    To do this, subtract the "mean of means" for the feature from
    the feature’s frequency in the subcorpus and divide the result
    by the feature’s standard deviation.
    '''
    corp_z_dict = {}
    for author in authors:
        corp_z_dict[author] = empty.copy()
        for word in mfws:
            corp_z_dict[author][word] = (corp_f_dict[author][word] - means[word]) / stdevs[word]
    '''
    Then, calculate the same z-scores for each feature in the text
    for which we want to determine authorship.
    '''
    test_tokens = []
    test_tokens = u.tokenize('./corpus/' + test + '.txt')
    test_frequencies = u.frequencies(test_tokens)
    test_f_dict = test_z_dict = empty.copy()
    for word in mfws:
       test_f_dict[word] = (test_frequencies.get(word, 0) / len(test_tokens)) * 1000
       # can collapse this into one loop
       test_z_dict[word] = (test_f_dict[word] - means[word]) / stdevs[word]
    print(test_z_dict)
    '''
    Finally, calculate a delta score comparing the anonymous paper
    with each candidate’s subcorpus. To do this, take the average
    of the absolute values of the differences between the z-scores
    for each feature between the anonymous paper and the candidate’s
    subcorpus. (Read that twice!) This gives equal weight to each
    feature, no matter how often the words occur in the texts;
    otherwise, the top 3 or 4 features would overwhelm everything
    else.
    '''
    for author in authors:
        sum = 0
        for word in mfws:
            sum += math.fabs(corp_z_dict[author][word] - test_z_dict[word])
        delta = sum / len(mfws)
        print(test + "-" + author + " delta: " + str(delta))
Beispiel #12
0
def transfer(param, address, offline, template, config, style):
    """
    this is tx submodule transfer command.
    """
    if template:
        show_params()
        return

    if param.endswith(".json"):
        try:
            with open(param, 'r') as f:
                dict_param = json.load(f)
        except:
            cust_print(
                "Params json file not exists or json file saved data is not json data,Please check {}"
                .format(param),
                fg='r')
            sys.exit(1)
    else:
        param = param.replace("\'", "\"")
        # 交易参数
        dict_param = json.loads(param)
    if "to" not in dict_param or "value" not in dict_param or 42 != len(
            dict_param["to"]):
        cust_print(
            "The transaction parameter is wrong, please check: {}.".format(
                param),
            fg='r')
        sys.exit(1)

    # 节点配置文件
    if "" == config:
        config = os.path.join(g_dict_dir_config["conf_dir"],
                              "node_config.json")
    if not os.path.exists(config):
        cust_print(
            "The node profile exists:{}, please check it.".format(config),
            fg='r')
        sys.exit(1)

    with open(config, 'r') as load_f:
        node_conf_info = json.load(load_f)
        hrp = node_conf_info["hrp"]
        chainId = node_conf_info["chainId"]
        rpcAddress = node_conf_info["rpcAddress"]

    if 'lat' == hrp or 'lax' == hrp:
        from precompile_lib import Web3, HTTPProvider, Eth
    else:
        from precompile_lib import Alaya_Web3 as Web3, Alaya_HTTPProvider as HTTPProvider, Alaya_Eth as Eth

    w3 = Web3(HTTPProvider(rpcAddress))
    platon = connect_node(w3, Eth)

    if dict_param["to"][:3] != hrp:
        cust_print(
            "To address is not in the right format:{}. What you want is {}.".
            format(dict_param["to"], hrp),
            fg='r')
        sys.exit(1)

    # 检查to地址是否合法
    if not decode(hrp, dict_param["to"]):
        cust_print("The to address is a non-BECh32 format address {}.".format(
            dict_param["to"]),
                   fg='r')
        sys.exit(1)

    # 检查from地址是否合法
    wallet_dir = g_dict_dir_config["wallet_dir"]
    wallet_file_path = ""
    net_type = "mainnet"
    if 'lax' == hrp or 'atx' == hrp:
        net_type = "testnet"
    if address.endswith(".json"):
        from_address, wallet_file_path = get_address_by_file_name(
            wallet_dir, address, net_type)
    elif 42 != len(address):
        cust_print("Wrong address parameter: --address {}".format(address),
                   fg='r')
        sys.exit(1)
    else:
        # 在线直接发送交易,需要钱包文件
        if not offline:
            find, wallet_file_path, fileName = get_wallet_file_by_address(
                wallet_dir, address, net_type)
            if not find:
                cust_print(
                    'hrp:{}, The wallet file of address:{} could not be found on {}'
                    .format(hrp, address, wallet_dir),
                    fg='r')
                sys.exit(1)
        from_address = address

    # 检查from地址是否合法
    if not decode(hrp, from_address):
        cust_print(
            "The from address is a non-BECh32 format address {}.".format(
                from_address),
            fg='r')
        sys.exit(1)

    # w3 = Web3(HTTPProvider(rpcAddress))
    # platon = Eth(w3)

    # 查询余额
    free = platon.getBalance(from_address)
    if float(free) <= float(dict_param["value"]):
        free_amount = w3.fromWei(free, "ether")
        cust_print(
            "The balance is insufficient for the transfer, balance: {} {}.".
            format(free_amount, hrp),
            fg='r')
        sys.exit(1)

    nonce = platon.getTransactionCount(from_address)
    value = w3.toWei(str(dict_param["value"]), "ether")
    gas = 4700000
    gasPrice = 1000000000
    if "gas" in dict_param:
        gas = int(dict_param["gas"])
    if "gasPrice" in dict_param:
        gasPrice = int(dict_param["gasPrice"])

    dict_transfer_tx = transfer_unsign(from_address, dict_param["to"],
                                       gasPrice, gas, value, nonce, chainId)

    # 离线方式
    if offline:
        try:
            unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"]
            if not os.path.exists(unsigned_tx_dir):
                os.mkdir(unsigned_tx_dir)
            unsigned_file_csv_name = "unsigned_tx_transfer_{}.csv".format(
                get_time_stamp())
            unsigned_file_path = os.path.join(unsigned_tx_dir,
                                              unsigned_file_csv_name)
            all_transaction = [dict_transfer_tx]
            # 生成待签名文件
            if style == '':
                write_csv(unsigned_file_path, all_transaction)
            else:
                unsigned_file_path = unsigned_file_path.replace('csv', 'jpg')
                write_QRCode(all_transaction, unsigned_file_path)
            cust_print('unsigned_file save to:{}'.format(unsigned_file_path),
                       fg='g')
        except Exception as e:
            print('{} {}'.format('exception: ', e))
            cust_print(
                'generate unsigned transfer transaction file failure:{}!!!'.
                format(e),
                fg='r')
            sys.exit(1)

        else:
            cust_print(
                'generate unsigned transfer transaction file successful:{}'.
                format(unsigned_file_path),
                fg='g')
    else:
        try:
            # 输入钱包密码,解锁私钥
            prompt_message = "Enter password:"
            if 'windows' == g_system:
                passwd = b''.join(
                    input_passwd_for_win(prompt_message)).decode()
            else:
                passwd = input_passwd_for_linux(prompt_message)

            if 'lat' == hrp or 'lax' == hrp:
                from precompile_lib import Account, keys
            else:
                from precompile_lib import Alaya_Account as Account, Alaya_keys as keys
            # 获取私钥
            privateKey = get_private_key_from_wallet_file(
                Account, keys, wallet_file_path, passwd)
            # 签名交易
            rawTransaction, _ = sign_one_transaction_by_prikey(
                Account, None, dict_transfer_tx, hrp, privateKey)
            # print(rawTransaction)
            # 发送交易
            txhash, _ = send_transaction(platon, rawTransaction)

        except Exception as e:
            cust_print(
                'send transfer transaction failure, chainid:{}, error message:{}!!!'
                .format(chainId, e),
                fg='r')
            sys.exit(1)
        else:
            cust_print(
                'send transfer transaction successful, tx hash:{}.'.format(
                    txhash),
                fg='g')
def submitProposal(param, address, offline, module, config, style):
    """
    this is government submodule submitProposal command.
    """
    if not os.path.isfile(param):
        cust_print('file {} not exits! please check!'.format(param), fg='r')
        sys.exit(1)
    params = read_json_file(param)
    check_params(params)

    _params = {'verifier': params['verifier'], 'pip_id': params['pIDID']}
    _module, func = method_module[module]
    try:
        if _module == 'submitVersion':
            _params['new_version'] = params['newVersion']
            _params['end_voting_rounds'] = params['endVotingRound']
        if _module == 'submitCancel':
            _params['end_voting_rounds'] = params['endVotingRound']
            _params['tobe_canceled_proposal_id'] = params['canceledProposalID']
        if _module == 'submitParam':
            _params['module'] = params['module']
            _params['name'] = params['name']
            _params['new_value'] = params['newValue']
    except KeyError as e:
        cust_print(
            '{} need params {},but it does not exist,please check!'.format(
                module, e),
            fg='r')
        sys.exit(1)

    wallet_dir = g_dict_dir_config["wallet_dir"]
    _, private_key, _, _ = verify_password(address, wallet_dir)
    pip = get_eth_obj(config, 'pip')
    module, func = method_module[module]
    try:
        if offline:
            data = rlp_params(func, *_params.values())
            _params['transaction_cfg'] = params.get('transaction_cfg', None)
            _params['to_type'] = 'pip'
            transaction_dict = un_sign_data(data, _params, pip,
                                            private_key[2:])
            unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"]
            check_dir_exits(unsigned_tx_dir)
            unsigned_file_csv_name = "unsigned_submitProposal_{}_{}.csv".format(
                module, get_time_stamp())
            unsigned_file_path = os.path.join(unsigned_tx_dir,
                                              unsigned_file_csv_name)
            if style == '':
                write_csv(unsigned_file_path, [transaction_dict])
            else:
                unsigned_file_path = unsigned_file_path.replace('csv', 'jpg')
                write_QRCode(transaction_dict, unsigned_file_path)
            cust_print('unsigned_file save to:{}'.format(unsigned_file_path),
                       fg='g')
        else:
            _params['pri_key'] = private_key[2:]
            _params['transaction_cfg'] = params.get('transaction_cfg', None)
            txhash = getattr(pip, module)(*_params.values())
            cust_print(
                'send raw transfer transaction successful, tx hash:{}.'.format(
                    txhash),
                fg='g')
    except Exception as e:
        cust_print(
            'submitProposal {} send transfer transaction fail,error info:{}'.
            format(module, e),
            fg='r')
        sys.exit(1)