class OutputWorkbook: CONTRACT_SHEET = u"合同" INVOICE_SHEET = u"箱单发票" DETAILS_SHEET = u"出仓明细" def __init__(self,template, **kwargs): self.template = template #self.dest = dest self.wb = load_workbook(template) self.contract = Contract(self.wb.get_sheet_by_name(self.CONTRACT_SHEET)) self.invoice = Invoice(self.wb.get_sheet_by_name(self.INVOICE_SHEET)) self.details = Details(self.wb.get_sheet_by_name(self.DETAILS_SHEET)) def get_contract_sheet(self): return self.contract def get_invoice_sheet(self): return self.invoice def get_detail_sheet(self): return self.details def save(self,dest=None): if dest is None: dest = self.template self.contract.fix_borders() self.details.fix_borders() #save here self.contract.remove_empty_rows() self.invoice.remove_empty_rows() self.details.remove_empty_rows() self.wb.save(dest)
def add_contract(source, destination, provider, payload, amount, signedContract): encode_data = ( source.encode() + destination.encode() + provider.encode() + payload.encode() + amount.encode() ) # TEST # if not verify_sign(provider, encode_data, signedContract): # return None # else: ######new_contract = Contract(str(time.time()), source, destination, provider, payload, amount) new_contract = Contract(str(123), source, destination, provider, payload, amount) token_ledger[source] = str(int(token_ledger[source]) - int(new_contract.stake)) token_ledger[destination] = str( int(token_ledger[destination]) - int(new_contract.stake) ) active_contract_list.append(new_contract.serialize()) block_data = generate_data( new_contract.serialize(), None, token_ledger, active_contract_list ) node_chain_instance.add_block(block_data) """ for i in range(len(node_chain_instance.block_data)): print(str(node_chain_instance.block_data[i])) #print((json.loads(node_chain_instance.block_data[-1].data)).get('ledger')) print((json.loads(node_chain_instance.block_data[-1].data))) """ return block_data
def checkScript(): script = request.form.get('script',default="") contract = Contract(script) result = contract.check() if result["errCode"]==0: return result["result"] else: return result["errText"]
def todo_test_approve(self): # make dataclasses hashable by default by ignoring `unsafe_hash` in dataclass param in compiler) amount = 10 contract = Contract(owner=admin, tokens={}, allowances={}, total_supply=0) contract.approve(investor, amount) assert contract.allowances[AllowanceKey(admin, investor)] == amount
def newTransaction(inPrvkey, inPubkey, outPubkey, amount, utxo, script=""): if script: contract = Contract(script) result = contract.check() if result["errCode"] != 0: return result ins = [] outs = [] inAddr = Wallet.address(inPubkey) outAddr = Wallet.address(outPubkey) todo = utxo.findSpendableOutputs(inAddr, amount) #todo={"acc":3,"unspend":{"3453425125":{"index":0,"amount":"3"}, # "2543543543":{"index":0,"amount":"2"} # } # } #print("newTransaction.todo","\n",todo) amount = round(amount, 4) if todo["acc"] < amount: Transaction.logger.warning("%s not have enough money." % inAddr) return {"errCode": 1, "errText": "not enough money."} for hash in todo["unspend"]: output = todo["unspend"][hash] prevHash = hash index = output["index"] toSign = prevHash + str(index) + inAddr sign = utils.sign(message=toSign, prvkey=inPrvkey) ins.append( TXin({ "prevHash": prevHash, "index": index, "inAddr": inAddr, "pubkey": inPubkey, "sign": sign })) outs.append( TXout({ "amount": round(amount, 4), "outAddr": outAddr, "script": script })) if todo["acc"] > amount: outs.append( TXout({ "amount": round(todo["acc"] - amount, 4), "outAddr": inAddr, "script": "" })) TX = Transaction(ins=ins, outs=outs) utxoSet = copy.deepcopy(utxo.utxoSet) if not utxo.updateWithTX(TX, utxoSet): return { "errCode": 1, "errText": "double spend!!,Maybe not enough money." } utxo.utxoSet = utxoSet return TX
def __init__(self, template, **kwargs): self.template = template #self.dest = dest self.wb = load_workbook(template) self.contract = Contract(self.wb.get_sheet_by_name( self.CONTRACT_SHEET)) self.invoice = Invoice(self.wb.get_sheet_by_name(self.INVOICE_SHEET)) self.details = Details(self.wb.get_sheet_by_name(self.DETAILS_SHEET))
def __init__(self, name, properties): if type(name) is not str: raise TypeError("Expected \"name\" to be a str object") if not isinstance(properties, list): raise TypeError("Expected \"properties\" to be a list") Contract.__init__(self, name) self.properties = properties
def __init__(self, name, backing_type, cases): if type(backing_type) is not str: raise TypeError("Expected \"type\" to be a str object") if not isinstance(cases, list): raise TypeError("Expected \"properties\" to be a list") Contract.__init__(self, name) self.backing_type = backing_type self.cases = cases
def __init__(self, num, players, pins, game_header): self.num = num self.players = players self.pins = pins self.game_state = game_header # Useful string to have on hand self.scores = [0, 0] self.bags = [0, 0] self.winnings = {'A1': 0, 'B1': 0, 'A2': 0, 'B2': 0} self.contracts = [Contract(), Contract()] self.hands = {} self.spade_in_play = False # Answers: Has a spade been played yet this round? # Run the round self.run()
def __init__(self, contract_partner, endtime, premium, excess, deductible=0.0): Contract.__init__(self, contract_partner, endtime) assert isinstance(contract_partner, dict) self.policyholder = contract_partner['policyholder'] self.insurer = contract_partner['insurer'] self.obligations['policyholder'] = {'money': premium} self.obligations['insurer'] = {'money': 0} self.excess = excess self.deductible = deductible
def multisig_sender(status, web3, owner, ether_sender): path = os.path.abspath( "../../../../../../MultisigWallet/MultisigWallet/deployment/build") contract_abi, contract_bytecode = Contract.get_abi_and_bytecode( path, "MultiSigWallet") sender_nonce = web3.eth.getTransactionCount(owner) contract_address = Contract.generate_contract_address(owner, sender_nonce) multisig_wallet_contract = web3.eth.contract(address=contract_address, abi=contract_abi, bytecode=contract_bytecode) tx_hash = multisig_wallet_contract.constructor( [owner, ether_sender], 1).transact(transaction=tx_args(owner, gas=3900000)) status(tx_hash) return multisig_wallet_contract
def generate_player(): r = random(); name = '' if r < 0.5: name = rand_male_name() + ' ' + rand_surname() else: name = rand_female_name() + ' ' + rand_surname() pos = Pos.rand_position() weight, height = 0, 0 if pos == Pos.CATCHER: weight, height = catcher_height_weight() elif Pos.is_infield(pos): weight, height = infield_height_weight() elif Pos.is_outfield(pos): weight, height = outfield_height_weight() else: weight, height = pitcher_height_weight() birthdate = generate_birthdate(start_date.year) bats, throws = generate_bats_throws() years_in_majors = int( gauss(years_old(birthdate, start_date) - 23, 2) ) if years_in_majors < 0: years_in_majors = 0 caps = Capabilities.generate_all_caps(height, weight, birthdate, start_date, years_in_majors, pos) pos_caps = PositionCapabilities.generate_pos_caps(pos) contract = Contract(get_FA(), 0, 0) personality = Personality.rand_personality() return Player(name, pos, height, weight, birthdate, bats, throws, caps, pos_caps, contract, personality)
def __init__(self, filename, **kwargs): self.filename = filename self.wb = load_workbook(filename) self.contract = Contract(self.wb.get_sheet_by_name(self.CONTRACT)) self.invoice = Invoice(self.wb.get_sheet_by_name(self.INVOICE)) self.details = Details(self.wb.get_sheet_by_name(self.DETAILS))
def canbeUnlockWith(self, address): if self.outAddr == address: if self.script == "": return True else: contract = Contract(self.script) result = contract.check() if result["errCode"] == 0: if result["result"] == "True": return True else: return False else: return False else: return False
def upload(self, relativeFilePath, lookupKey = None, signatureKey = None, constructorArgs=[]): resolvedPath = resolveRelativePath(relativeFilePath) if self.coverageMode: resolvedPath = resolvedPath.replace("tests", "coverageEnv").replace("source/", "coverageEnv/") lookupKey = lookupKey if lookupKey else path.splitext(path.basename(resolvedPath))[0] signatureKey = signatureKey if signatureKey else lookupKey if lookupKey in self.contracts: return(self.contracts[lookupKey]) compiledCode = self.getCompiledCode(resolvedPath) # abstract contracts have a 0-length array for bytecode if len(compiledCode) == 0: if ("libraries" in relativeFilePath or lookupKey.startswith("I") or lookupKey.startswith("Base") or lookupKey.startswith("DS")): pass#print "Skipping upload of " + lookupKey + " because it had no bytecode (likely a abstract class/interface)." else: raise Exception("Contract: " + lookupKey + " has no bytecode, but this is not expected. It probably doesn't implement all its abstract methods") return None if signatureKey not in ContractsFixture.signatures: ContractsFixture.signatures[signatureKey] = self.generateSignature(resolvedPath) signature = ContractsFixture.signatures[signatureKey] W3Contract = self.w3.eth.contract(abi=signature, bytecode=compiledCode) deploy_address = self.accounts[0] tx_hash = W3Contract.constructor(*constructorArgs).transact({'from': deploy_address, 'gasPrice': 1, 'gas': 750000000}) tx_receipt = self.w3.eth.waitForTransactionReceipt(tx_hash, 180) if tx_receipt.status == 0: raise Exception("Contract upload %s failed" % lookupKey) w3Contract = W3Contract(tx_receipt.contractAddress) contract = Contract(self.w3, w3Contract, self.logListener, self.coverageMode) self.contracts[lookupKey] = contract return contract
def inner_contract_from_address(address, contract_name, path): contract_abi, contract_bytecode = Contract.get_abi_and_bytecode( path, contract_name) contract = web3.eth.contract(address=address, abi=contract_abi, bytecode=contract_bytecode) return contract
def applySignature(self, signatureName, address, signature=None): assert address if signature is None: signature = ContractsFixture.signatures[signatureName] W3Contract = self.w3.eth.contract(abi=signature) w3Contract = W3Contract(address) contract = Contract(self.w3, w3Contract, self.logListener, self.coverageMode) return contract
def get_contract(contract_name: str) -> Contract: return Contract(account=ACCOUNT, private_key=ACCOUNT_PRIVATE_KEY, contract_name=contract_name, abi_file=os.path.join(ABI_DIR, f"{contract_name}.json"), bytecode_file=os.path.join(BIN_DIR, f"{contract_name}.bin"), rpc_url=RPC_URL)
def wrapper(f): @wraps(f) def _function(self, *args, **kwargs): return f(self, *args, **kwargs) i = Input(name, type) if hasattr(f, 'contract'): contract = f.contract contract.addInput(i) else: contract = Contract(f.__name__) contract.addInput(i) _function.__dict__["contract"] = contract _function.func_name = f.func_name return _function
def __init__(self,template, **kwargs): self.template = template #self.dest = dest self.wb = load_workbook(template) self.contract = Contract(self.wb.get_sheet_by_name(self.CONTRACT_SHEET)) self.invoice = Invoice(self.wb.get_sheet_by_name(self.INVOICE_SHEET)) self.details = Details(self.wb.get_sheet_by_name(self.DETAILS_SHEET))
def read_contracts(): contracts = pd.read_excel('contracts.xlsx') companies = contracts['Company Name'] start_dates = contracts['Start Date'] end_dates = contracts['End Date'] for i in range(len(companies)): contract = Contract(companies[i], start_dates[i], end_dates[i]) database.add_contract(contract)
def composition(goals: Set[Goal], name: str = None, description: str = None) -> Goal: if name is None: names = [] for goal in goals: names.append(goal.name) names.sort() conj_name = "" for name in names: conj_name += name + "||" name = conj_name[:-2] set_of_contracts = set() new_goal_world = None for g in goals: set_of_contracts.add(g.specification) if g.world is not None: if new_goal_world is None: new_goal_world = g.world else: if new_goal_world is not g.world: raise GoalException( "conjoining goals that have different 'variables'") try: new_contract = Contract.composition(set_of_contracts) except IncompatibleContracts as e: raise GoalAlgebraOperationFail( goals=goals, operation=GoalFailOperations.composition, contr_ex=e) except InconsistentContracts as e: raise GoalAlgebraOperationFail( goals=goals, operation=GoalFailOperations.composition, contr_ex=e) except UnfeasibleContracts as e: raise GoalAlgebraOperationFail( goals=goals, operation=GoalFailOperations.composition, contr_ex=e) new_goal = Goal(name=name, description=description, specification=new_contract, world=new_goal_world) return new_goal
def test_close(self): from contract import Contract contract = Contract(stubs.SENDER, "", "", "", "", "", "") contract.close("foo") assert contract._close == "foo" contract = Contract("yolo", "", "", "", "", "", "") try: contract.close("foo") assert 0 except Exception as e: assert e.args[0] == 'Only admin can call this entrypoint'
def create_transition_controller(self, start: Types, finish: Types, t_trans: int) -> Controller: t_controller_name = f"TRANS_{start.name}->{finish.name}" if self.session_name is None: folder_name = f"{self.t_controllers_folder_name}/{t_controller_name}" else: folder_name = f"{self.session_name}/{self.t_controllers_folder_name}/{t_controller_name}" typeset = Typeset({start, finish}) realizable = False for n_steps in range(1, t_trans): trans_spec_str = Logic.and_([start.name, Logic.xn_(finish.name, n_steps)]) trans_spec = Atom(formula=(trans_spec_str, typeset)) trans_contract = Contract(guarantees=trans_spec) try: controller_info = trans_contract.get_controller_info(world_ts=self.world.typeset) a, g, i, o = controller_info.get_strix_inputs() controller_synthesis_input = StringMng.get_controller_synthesis_str(controller_info) Store.save_to_file(controller_synthesis_input, f"t_controller_{start.name}_{finish.name}_specs.txt", folder_name) realized, kiss_mealy, time = Strix.generate_controller(a, g, i, o) if realized: realizable = True break except ControllerException as e: raise TransSynthesisFail(self, e) if not realizable: raise Exception( f"Controller [{start.name}, {finish.name}] cannot be synthetized in {t_trans} steps") else: Store.save_to_file(kiss_mealy, f"{start.name}_{finish.name}_mealy", folder_name) # Store.generate_eps_from_dot(dot_mealy, f"{start.name}_{finish.name}_dot", # folder_name) t_controller = Controller(mealy_machine=kiss_mealy, world=self.world, name=t_controller_name, synth_time=time) Store.save_to_file(str(t_controller), f"{start.name}_{finish.name}_table", folder_name) return t_controller
def test_artifacts(self): from contract import Contract contract = Contract(stubs.SENDER, "", "", "", "", "", "") contract.artifacts("url", "hash") assert contract.artifacts_url == "url" assert contract.artifacts_hash == "hash" contract = Contract("yolo", "", "", "", "", "", "") try: contract.artifacts("url", "hash") assert 0 except Exception as e: assert e.args[0] == 'Only admin can call this entrypoint'
def process(self, input_paths, output_paths): # Init steps hs = HashtagSplit() nr = Normalize() ct = Contract() # execute pipeline for input_path, output_path in zip(input_paths, output_paths): # data paths path_0 = input_path path_1 = output_path[:-4] + '_1' + output_path[-4:] path_2 = output_path[:-4] + '_2' + output_path[-4:] path_3 = output_path # set paths hs.set_paths(path_0, path_1) nr.set_paths(path_1, path_2) ct.set_paths(path_2, path_3) # run print("starting with " + os.path.basename(input_path)) hs.run() print(os.path.basename(input_path) + ": hashtag done.") nr.run() print(os.path.basename(input_path) + ": normalize done.") ct.run() print(os.path.basename(input_path) + ": contract done.")
def test_open(self): from contract import Contract contract = Contract(stubs.SENDER, "", "", "", "", "", "") contract.open("foo", "bar", "baz") assert contract._open == "foo" assert contract.manifest_url == "bar" assert contract.manifest_hash == "baz" contract = Contract("yolo", "", "", "", "", "", "") try: contract.open("foo", "bar", "baz") assert 0 except Exception as e: assert e.args[0] == 'Only admin can call this entrypoint'
class OutputWorkbook: CONTRACT_SHEET = u"合同" INVOICE_SHEET = u"箱单发票" DETAILS_SHEET = u"出仓明细" def __init__(self, template, **kwargs): self.template = template #self.dest = dest self.wb = load_workbook(template) self.contract = Contract(self.wb.get_sheet_by_name( self.CONTRACT_SHEET)) self.invoice = Invoice(self.wb.get_sheet_by_name(self.INVOICE_SHEET)) self.details = Details(self.wb.get_sheet_by_name(self.DETAILS_SHEET)) def get_contract_sheet(self): return self.contract def get_invoice_sheet(self): return self.invoice def get_detail_sheet(self): return self.details def save(self, dest=None): if dest is None: dest = self.template self.contract.fix_borders() self.details.fix_borders() #save here self.contract.remove_empty_rows() self.invoice.remove_empty_rows() self.details.remove_empty_rows() self.wb.save(dest)
def wrapper(f): @warps(f) def _function(self, *args, **kwargs): return f(self, *args, **kwargs) if hasattr(f, 'contract'): contract = f.contract contract.setName(name) else: contract = Contract(name) _function.__dict__["contract"] = contract _function.func_name = f.func_name return _function
def make_contract(self, curs, contract_type, fixed_holder, unfixed_holder, price, quantity): con = Contract(contract_type, fixed_holder, unfixed_holder, price, quantity).persist(curs) curs.execute( "UPDATE account SET balance = balance - %s WHERE id = %s", (price * quantity - con.fixed_refund * 1000, fixed_holder), ) curs.execute( "UPDATE account SET balance = balance - %s WHERE id = %s", ((1000 - price) * quantity - con.unfixed_refund * 1000, unfixed_holder), ) self.db.messages.add( "contract_created", fixed_holder, contract_type, self.db.FIXED, price, quantity, contract=con, ) self.db.messages.add( "contract_created", unfixed_holder, contract_type, self.db.UNFIXED, price, quantity, contract=con, ) if con.fixed_refund: self.db.messages.add( "position_covered", fixed_holder, contract_type, quantity=con.fixed_refund, contract=con, ) if con.unfixed_refund: self.db.messages.add( "position_covered", unfixed_holder, contract_type, quantity=con.unfixed_refund, contract=con, )
def generate_manager(): r = random() name = '' if r < 0.5: name = rand_male_name() + ' ' + rand_surname() else: name = rand_female_name() + ' ' + rand_surname() birthdate = generate_birthdate(start_date.year) qualities = [] for param in params(): qualities.append(redistribute(int(gauss(param[0], param[1])))) contract = Contract(get_FA(), 0, 0) return Manager(name, birthdate, qualities[0], qualities[1], qualities[2], qualities[3], qualities[4], qualities[5], qualities[6], contract)
def placeOneOrder(self): con = Contract() con.symbol = "AMD" con.secType = "STK" con.currency = "USD" con.exchange = "SMART" order = Order() order.action = "BUY" order.orderType = "LMT" order.tif = "GTC" order.totalQuantity = 3 order.lmtPrice = 1.23 self.placeOrder(self.nextOrderId(), con, order)