def find_short_name(new_name): # Create a shortened version of this name to appear in URLs # Get ride of spaces and the word "challenge" first short_name = new_name.replace(" ", "") short_name = short_name.replace("Challenge", "") short_name = short_name.replace("challenge", "") if len(short_name) < 25: short_name = short_name[0:15] # For quite long names we'll start short version on second word else: start_short = new_name.find(' ') short_name = short_name[start_short:start_short + 15] # Confirm this particular short name is not already present in the db already_exists = True appended_number = 1 while already_exists: already_exists = Contract.query( Contract.short_name == short_name).get() if already_exists: appendage = str(appended_number) if short_name[-len(appendage):] == appendage: short_name = short_name[-len(appendage):] + str( appended_number + 1) appended_number += 1 # Get the next contract_id in order for the new entry curr_top = Contract.query().order(-Contract.contract_id).get() if curr_top: new_id = curr_top.contract_id + 1 else: new_id = 1 return new_id, short_name
def test_contract_costs(): c = Contract('ticker', 'test', '') c.long_offers = [ Offer(c, 'Yes', .1, 5), Offer(c, 'Yes', .16, 10), Offer(c, 'Yes', .2, 100), ] c.short_offers = [ Offer(c, 'Yes', .4, 6), Offer(c, 'Yes', .5, 4), Offer(c, 'Yes', .6, 10), ] assert c.cost_to_buy_n_long(1000) is None assert c.cost_to_buy_n_short(1000) is None assert c.cost_to_buy_n_long(5) == .5 assert c.cost_to_buy_n_long(10) == 1.3 assert c.cost_to_buy_n_long(20) == 3.1 assert c.cost_to_buy_n_short(6) == 2.4 assert c.cost_to_buy_n_short(10) == 4.4 assert c.cost_to_buy_n_short(12) == 5.6 assert c.cost_to_buy_n_short(20) == 10.4
def product_add_contract(): api_key = request.headers.get('Authorization') response = UserClient.get_user(api_key) if not response: return make_response(jsonify({'message': 'Not logged in'}), 401) user = response['result'] if int(user['id']) == int(request.form['contractor_user_id']): return make_response( jsonify({'message': 'user can not sign contract with himself'}), 401) contract_instance = Contract() contract_instance.title = request.form['title'] contract_instance.content = request.form['content'] contract_instance.user_id = int(user['id']) contract_instance.contractor_user_id = request.form['contractor_user_id'] contract_instance.contract_template_id = request.form[ 'contract_template_id'] contract_instance.value = request.form['value'] contract_instance.duedate = request.form['duedate'] db.session.add(contract_instance) db.session.commit() response = jsonify({'result': contract_instance.to_json()}) return response
def add(self, contract_id, clinic_id): contract = Contract.query.filter_by(id=contract_id).first() if not contract: patient_info = self.medsenger_api.get_patient_info(contract_id) try: patient_id = int(patient_info['id']) except: raise Exception("No patient info, contract_id = {}".format(contract_id)) patient = Patient.query.filter_by(id=patient_id).first() if not patient: patient = Patient(id=patient_id) self.db.session.add(patient) contract = Contract(id=contract_id, patient_id=patient.id, clinic_id=clinic_id) self.db.session.add(contract) contract.is_active = True contract.clinic_id = clinic_id contract.agent_token = self.medsenger_api.get_agent_token(contract_id).get('agent_token') self.__commit__() return contract
def createContract(): """ Contract creation """ try: if "username" in session: if request.method == 'POST': myContract = Contract( contractref=request.form["inputContractReference"], systemname=request.form["inputSystemName"], contractrenewtype=request.form["inputRenewType"], contractcost=request.form["inputContractCost"], contractstartingdate=request. form["inputContractStartingDate"], contractendingdate=request.form["inputContractEndingDate"], contractcomment=request.form["inputContractComment"], contractyear=request.form.get("inputContractYear", type=int)) myContract.save() flash('Contract saved !!! ', 'message') return redirect(url_for('listeContract')) if request.method == 'GET': return render_template('createcontract.html') else: flash('Unknown user !!! ', 'error') return render_template('login.html') except: return redirect(url_for('appError'))
def onSale(id): contract = Contract.get_by_id(id) if (contract.onSale==False): Contract.onSale_True(contract) flash('Contrato puesto a la venta') return redirect (url_for('contract')) flash ('El contrato ya se encuentra a la venta') return redirect (url_for('contract'))
def api_contract_delete(*, userid, contractid): 'delete contract' if not userid: raise APIValueError('userid') if not contractid: raise APIValueError('contractid') affected = yield from Contract.mexecute( 'DELETE FROM contracts WHERE userid=? and contractid=?', [userid, contractid]) affected2 = yield from Contract.mexecute( 'DELETE FROM contracts WHERE userid=? and contractid=?', [contractid, userid]) return {'affected': affected, 'affected2': affected2}
def test_evaluate_notprofitable(): market = Market('test', 0, '', 'SingleMarket') c1 = Contract('test', 'test1', '') c1.long_offers = [ Offer(c1, 'YES', .52, 10) ] c1.short_offers = [ Offer(c1, 'NO', .54, 5)] market.contracts = [ c1 ] r = buy_yes_no.evaluate(market) assert r is None
def api_contract(*, userid, page='1'): 'get person contract' print(userid) page_index = get_page_index(page) num = yield from Contract.findNumber('count(id)') p = Page(num, page_index) if num == 0: return dict(page=p, contract=()) sql = 'SELECT `users`.id,`users`.username,`users`.nickname,`users`.email,`users`.birthday,`users`.sex,`users`.avatar,' \ '`users`.phone,`users`.remark,users.create_date,users.update_date,contracts.create_date AS contract_date,contracts.note ' \ 'FROM users LEFT JOIN contracts ON users.id = contracts.contractid WHERE users.id in (SELECT contractid FROM ' \ 'contracts WHERE `contracts`.userid = ?);' contracts = yield from Contract.mselect(sql, [userid]) print(contracts) return dict(page=p, contract=contracts)
def add_contract_to_actor(): try: print("Input movie name:") movie_name = input() print("Input actor name:") actor_name = input() print("Input studio name:") studio_name = input() print("Input value:") value = int(input()) if movie_name and actor_name and studio_name and value: s = Session() movie = s.query(Movie).filter_by(name=movie_name).first() studio = s.query(Studio).filter_by(name=studio_name).first() actor = s.query(Actor).filter_by(full_name=actor_name).first() if (movie is None) or (actor is None) or (studio is None): View.display_no_results() s.close() else: s.add( Contract(movie_id=movie.id, studio_id=studio.id, actor_id=actor.id, value=value)) s.commit() s.close() View.display_success() else: print("Incorrect input") except SQLAlchemyError as e: View.display_error()
def edit(id): contract = Contract.get_by_id(id) form = ContractForm() if contract.owner_id == current_user.id: return render_template('editar.html', contract = contract, form = form) flash ('No eres el dueño de este contrato') return render_template('contract.html')
def check_user_auth(short_name): user = users.get_current_user() # Can't see it if they're not even logged in! if not user: return False # Find all the users associated with this challenge contract = Contract.query(Contract.short_name == short_name).get() if not contract: logging.info("Couldnt find that one") return False contract_id = contract.contract_id combatants_info = fetch_combatants_info(contract_id) users_array = [] # Get all users associated with each distinct combatant for combatant in combatants_info: users_info = fetch_users_info(combatant.combatant_id) # Fill the array of users associated with combatant.name with their google emails for user_info in users_info: users_array.append(str(user_info.google_username)) # If the current user's id is in users_array then they're good to go return str(user) in users_array
def get(self, short_name): should_be_here = check_user_auth(short_name) if not should_be_here: self.redirect('/') # Build up context that only contains an array of combatant_name : [user1, user2] objects context = {'joined': []} # Show a list of already-joined combatants with their usernames contract_id = Contract.query( Contract.short_name == short_name).get().contract_id combatants_info = fetch_combatants_info(contract_id) # Get all users associated with each distinct combatant for combatant in combatants_info: users_info = fetch_users_info(combatant.combatant_id) users_array = [] # Fill the array of users associated with combatant.name with their google emails for user_info in users_info: users_array.append(user_info.google_username + "@gmail.com") # Put the combatant-users object into context's array of these objects context['joined'].append({ 'combatant': combatant.name, 'users': users_array }) # Render the page in context and display it invite_page = jinja_environment.get_template("pages/invite.html") self.response.out.write(invite_page.render(context))
def get(self, short_name): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) # Check that the user that logged in is someone who was invited to the challenge, or already in invited = check_user_desired(short_name, user.email()) # Add the user to the competition if they were invited if invited: # Grab the username from their email username = grab_username(user.email()) # Create a new user model if this username is not in the db already user_id = create_or_fetch_user(username) # Combatant details combatant_id = create_combatant(username) # Link combatant and user link_combatant_user(combatant_id, user_id) # Get the contract id con_id = Contract.query( Contract.short_name == short_name).get().contract_id # Link contract and combatant link_contract_combatant(con_id, combatant_id) # Tell them to get an invite if they weren't invited context = {"invited": invited} not_invited_page = jinja_environment.get_template("pages/joining.html") self.response.out.write(not_invited_page.render(context))
def add_contract(): """добавление контракта""" agent_id = int(input('id агента: ')) # проверка на правильнось введеного id агента agent_query = session.query(Agent).filter_by(id=agent_id).all() if agent_query: print(f'Выбран контрагент: {agent_query[0]}') else: print('Не вероно указан id агента...\n') return number = input('Номер договора: ') contract_query = session.query(Contract).filter_by(agent_id=agent_id, number=number).all() if contract_query: print( f'У контрагента {agent_query[0]} уже есть договор {contract_query[0]}' ) return description = input('Краткое описание договора: ') new_contract = Contract(agent_id=agent_id, number=number, description=description) session.add(new_contract) session.commit() print(f'Договор №{number} добавлен\n')
def search_by_keyword(request): keyword = request.GET.get('keyword') or '' # we can only do full text search on two words for now if len( re.split("\s*", keyword) ) > 2: keyword = " ".join( re.split("\s*", keyword)[:2] ) template_params = { 'keyword': keyword, 'dev': os.environ["SERVER_SOFTWARE"].find('Development') != -1 } template_params.update(global_template_params()) if keyword: # Search the 'Contract' Entity based on our keyword #query = search.SearchableQuery('Contract') #query.Search(keyword) #results = query.Get(50) query = Contract.all().search(keyword) more_template_params = _process_query(request, query) template_params.update(more_template_params) else: pass return render_to_response('search_results.html', template_params)
def api_contract_check(*, userid, contractid): if not userid: raise APIValueError('userid') if not contractid: raise APIValueError('contractid') contracts = yield from Contract.findAll('userid=? AND contractid=?', [userid, contractid]) return {'count': len(contracts)}
def resolve_bet(txn, bidder, outcome, price, amount, yes_dir): matching_bids = [ b for b in outcome.bids if b.yes_bid != yes_dir and b.price >= 100 - price ] matching_bids = list( sorted(matching_bids, key=lambda b: (-b.price, b.bid_id))) while matching_bids and amount: bid = matching_bids.pop(0) shares_matched = min(amount, bid.amount) amount -= shares_matched c1 = Contract(outcome=outcome, bidder=bidder, price=100 - bid.price, amount=shares_matched, yes_contract=yes_dir) c2 = Contract(outcome=outcome, bidder=bid.bidder, price=bid.price, amount=shares_matched, yes_contract=not yes_dir) if shares_matched == bid.amount: txn.delete(bid) else: bid.amount -= shares_matched txn.add(c1) txn.add(c2) if amount: existing = txn.query(Bid).filter_by(bidder=bidder, outcome=outcome, price=price, yes_bid=yes_dir).first() if existing: existing.amount += amount else: bid = Bid(outcome=outcome, bidder=bidder, price=price, amount=amount, yes_bid=yes_dir) txn.add(bid)
def api_contract_update(*, userid, contractid, note): 'add note for contract' if not userid: raise APIValueError('userid') if not contractid: raise APIValueError('contractid') affected = yield from Contract.mexecute( 'UPDATE contracts SET note = ? WHERE userid = ? AND contractid = ?;', [note, userid, contractid]) return {'affected': affected}
def test_evaluate_profitable(): market = Market("test", 0, "", "SingleMarket") c1 = Contract("test", "test1", "") c2 = Contract("test", "test2", "") c3 = Contract("test", "test3", "") c1.long_offers = [Offer(c1, "YES", 0.1, 10)] c2.long_offers = [Offer(c2, "YES", 0.2, 10)] c3.long_offers = [Offer(c3, "YES", 0.3, 10)] market.contracts = [c1, c2, c3] r = buy_yes.evaluate(market) assert r is not None ret = r[0] gain = r[1] cost = r[2] shares = r[3] assert cost == 6 assert shares == 10 assert round(ret, 2) == 0.6 assert round(gain, 2) == 4
def test_evaluate_profitable(): market = Market('test', 0, '', 'SingleMarket') c1 = Contract('test', 'test1', '') c2 = Contract('test', 'test2', '') c3 = Contract('test', 'test3', '') c1.short_offers = [ Offer(c1, 'NO', .4, 10) ] c2.short_offers = [ Offer(c2, 'NO', .6, 10) ] c3.short_offers = [ Offer(c3, 'NO', .8, 10) ] market.contracts = [ c1, c2, c3 ] r = buy_no.evaluate(market) assert r is not None ret = r[0] gain = r[1] cost = r[2] shares = r[3] assert cost == 18 assert shares == 10 assert round(ret, 2) == .1 assert round(gain, 2) == 1.8
def get(self): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) # Create a dictionary of the number of users in each challenge contract_users = {} all_contract_combatants = ContractCombatant.query().fetch(100) for con_com in all_contract_combatants: users_num = CombatantUser.query( CombatantUser.combatant_id == con_com.combatant_id).count() if con_com.contract_id in contract_users: contract_users[con_com.contract_id] += users_num else: contract_users[con_com.contract_id] = users_num # Find the 3 contract ids with the most users involved desc = sorted(contract_users.iteritems(), key=lambda x: x[1], reverse=True) challenge1_name = challenge2_name = challenge3_name = "" if len(desc) > 0: challenge1_name = Contract.query( Contract.contract_id == desc[0][0]).get().challenge_name if len(desc) > 1: challenge2_name = Contract.query( Contract.contract_id == desc[1][0]).get().challenge_name if len(desc) > 2: challenge3_name = Contract.query( Contract.contract_id == desc[2][0]).get().challenge_name context = { 'exampleText': "Who runs the most miles in a month?", 'topChallenge1': challenge1_name, 'topChallenge2': challenge2_name, 'topChallenge3': challenge3_name } home = jinja_environment.get_template("pages/frontpage.html") self.response.out.write(home.render(context))
def post(): try: parser = reqparse.RequestParser() parser.add_argument('title') parser.add_argument('body') parser.add_argument('usage_limit', type=int) data = parser.parse_args(strict=True) contract = Contract(**data) db.session.add(contract) db.session.commit() except Exception as e: abort(400, message=str(e)) return serialize_contract(contract), 201
def test_evaluate_profitable(): market = Market('test', 0, '', 'SingleMarket') c1 = Contract('test', 'test1', '') c1.long_offers = [ Offer(c1, 'YES', .4, 10) ] c1.short_offers = [ Offer(c1, 'NO', .4, 5)] market.contracts = [ c1 ] r = buy_yes_no.evaluate(market) assert r is not None ret = r[0] gain = r[1] cost = r[2] shares = r[3] assert shares == 5 assert cost == 4 assert round(ret, 2) == .23 assert round(gain, 2) == 1
def check_user_desired(short_name, email): contract = Contract.query(Contract.short_name == short_name).get() des_users = DesiredUsers.query( DesiredUsers.contract_id == contract.contract_id).get() if not des_users: return False user_list = des_users.users if email not in user_list: return False return True
def update_challenge(short_name, args_obj): # Get the contract to be updateds contract = Contract.query(Contract.short_name == short_name).get() # Update all fields represented in args_obj #contract.challenge_name = args_obj["description"] contract.objective_type = str(args_obj["objective"]) contract.time_unit = str(args_obj["unit"]) contract.time_period = int(args_obj["length"]) contract.start_date = datetime.date(int(args_obj["year"]), int(args_obj["month"]), int(args_obj["day"])) if not contract.stakes_id: curr_stakes = [0, 0, 0, 0] else: curr_stakes = contract.stakes_id stakes_ids = enter_stakes(args_obj["stakes"], curr_stakes) contract.stakes_id = stakes_ids contract.put() # Enter in Objective models if contract.objective_type == "highest-occurrence": # Get current highest GeneralObjective id top_objective = GeneralObjective.query().order( -GeneralObjective.gen_objective_id).get() if top_objective: new_id = top_objective.gen_objective_id + 1 else: new_id = 1 # Make new GeneralObjective model GeneralObjective(objective_name=str(args_obj["objective-name"]), contract_id=contract.contract_id, gen_objective_id=new_id).put() elif contract.objective_type == "location": # Get current highest GeolocationObjective id top_objective = GeolocationObjective.query().order( -GeolocationObjective.geo_objective_id).get() if top_objective: new_id = top_objective.geo_objective_id + 1 else: new_id = 1 # Make new GeolocationObjective model GeolocationObjective(checkin_loc=ndb.GeoPt(args_obj["checkin-loc"]), checkin_radius=int(args_obj["radius"]), loc_name=args_obj["checkin-loc-name"], geo_objective_id=new_id, contract_id=contract.contract_id).put()
def post(self): request_dict = request.get_json() if not request_dict: response = {'message': 'No input data provided'} return response, status.HTTP_400_BAD_REQUEST errors = contract_schema.validate(request_dict) if errors: return errors, status.HTTP_400_BAD_REQUEST try: rule_name = request_dict['rule']['name'] rule = Rule.query.filter_by(name=rule_name).first() if rule is None: # Create a new rule rule = Rule(name=rule_name, f_operand=request_dict['f_operand'], s_operand=request_dict['s_operand'], operator=request_dict['operator'], coefficient=request_dict['coefficient']) db.session.add(rule) # create a new contract contract = Contract(contract_name=request_dict['contract_name'], information=request_dict['information'], rule=rule) # requests.put('http://0.0.0.0/{port}/projects', jsonify={ # "project_name": 'project_name', # "contract_id": UUID, # status: status.HTTP_201_CREATED # }) contract.add(contract) query = Contract.query.get(contract.id) result = contract_schema.dump(query).data return result, status.HTTP_201_CREATED except SQLAlchemyError as e: db.session.rollback() resp = jsonify({"error": str(e)}) return resp, status.HTTP_400_BAD_REQUEST
def update(id): contract = Contract.get_by_id(id) form = ContractForm() if form.validate_on_submit(): title = form.title.data description = form.description.data price = form.price.data Contract.update_title(contract, title) Contract.update_description(contract, description) Contract.update_price(contract, price) flash ('Contrato actualizado')
def load(path): raw = json.loads(open(path).read()) markets = [] for r in raw: m = Market(r['name'], r['id'], r['url'], r['type']) if('contracts' in r): for x in r['contracts'].keys(): rc = r['contracts'][x] c = Contract(x, rc['name'], rc['url']) for z in rc['buy_yes_offers']: o = Offer(c, 'buy_yes', z['price'], z['shares']) c.long_offers.append(o) for z in rc['buy_no_offers']: o = Offer(c, 'buy_no', z['price'], z['shares']) c.short_offers.append(o) c.long_offers=sorted(c.long_offers, key=lambda x: x.price) c.short_offers=sorted(c.short_offers, key=lambda x: x.price) m.contracts.append(c) markets.append(m) return markets
def add_desired_user(short_name, email): # Find appropriate contract_id, then get desired users list contract = Contract.query(Contract.short_name == short_name).get() players = DesiredUsers.query( DesiredUsers.contract_id == contract.contract_id).get() # Create new DesiredUsers object if none if not players: DesiredUsers(contract_id=contract.contract_id, users=[email]).put() # Otherwise update list of users that have been invited, then put it back in db else: players.users.append(email) players.put()
def buy(id): contract = Contract.get_by_id(id) #instancio contrato user = User.get_by_id(current_user.id) #instancio comprador if (contract.owner_id == current_user.id): flash('Usted es el dueño de este contrato') return render_template('newContract.html') walletV = Wallet.get_by_idownerunico(contract.owner_id) acctV = w3.eth.account.privateKeyToAccount(walletV.key) #direccion vendedor walletC = Wallet.get_by_idownerunico(current_user.id) acctC = w3.eth.account.privateKeyToAccount(walletC.key) #direccion comprador signed_txn = w3.eth.account.signTransaction(dict( nonce=w3.eth.getTransactionCount(str(acctC.address)), gasPrice=w3.eth.gasPrice, gas=100000, to=str(acctV.address), value=int(contract.price), data=b'', ), str(walletC.key), ) tx_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction) tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) hash = w3.toHex(tx_receipt['transactionHash']) Contract.update_idowner(contract, current_user.id) Contract.onSale_False(contract) #contract_instance = w3.eth.contract(address= contract.address, abi = abi) #tx_hash2 = contract_instance.functions.setOwner(acctC.address).transact() #tx_receipt2 = w3.eth.waitForTransactionReceipt(tx_hash2) #hash2 = w3.toHex(tx_receipt2['transactionHash']) flash('Contract adquired') return render_template('newContract.html', hash=hash) #hash2 = hash2
def monitor_receipt_and_contract(): """ 监听 kafka 交易数据,出现新数据时,从 web3 获取 receipt :return: """ if not config.get('kafka', 'transaction_topic', fallback=None): logger_err.error( 'config.ini 中没有 transaction_topic 参数,退出 monitor_receipt_and_contract 任务' ) return elif not config.get('kafka', 'receipt_topic', fallback=None): logger_err.error( 'config.ini 中没有 receipt_topic 参数,退出 monitor_receipt_and_contract 任务' ) return elif not config.get('kafka', 'contract_topic', fallback=None): logger_err.error( 'config.ini 中没有 contract_topic 参数,退出 monitor_receipt_and_contract 任务' ) return consumer = kafka_consumer(config.get('kafka', 'transaction_topic'), group_id='monitor_receipt') last_block_height = None tx_cnt = 0 # 已处理的交易数 for msg in consumer: tx = msg.value current_block_height = tx["block_number"] if last_block_height != current_block_height: logger.info(f'区块 {last_block_height} 共处理交易 {tx_cnt} 笔') logger.info(f'开始处理区块高度 {current_block_height} 下各交易的 receipt') last_block_height = current_block_height tx_cnt = 1 else: tx_cnt += 1 try: receipt = w3.eth.getTransactionReceipt(tx['hash']) except TransactionNotFound: logger_err.error( f'在区块高度 {current_block_height} 中找不到交易 {tx["hash"]}') continue Receipt(data=receipt).save() if receipt.get('contractAddress'): logger.info(f'在区块高度为 {current_block_height} 的交易 {tx["hash"]} 中' f'发现新创建合约 {receipt.get("contractAddress")}') Contract(data=receipt, block_number=receipt.get('blockNumber')).save()
def contract(id): contracts = Contract.get_by_idowner(current_user.id) #traigo todos los contratos del que este usuario es dueño form = ContractForm() if form.validate_on_submit(): title = form.title.data description = form.description.data price = form.price.data wallet = Wallet.get_by_id(current_user.id) contract_address = newContract(title, price, wallet.key) #inicio contrato y creo en la base de datos contract = Contract(owner_id= current_user.id, address = contract_address, title = title, description = description, price = price) contract.save() Contract.onSale_True(contract) return redirect(url_for('contract')) return render_template('contract.html', contracts=contracts, form=form)
def search_by_prop(request, prop=None, keyword=None): template_params = { 'keyword': keyword, 'prop': prop, } template_params.update(global_template_params()) if keyword and prop: query = Contract.all() query.filter("%s =" % prop, keyword) more_template_params = _process_query(request, query) template_params.update(more_template_params) else: pass return render_to_response('search_results.html', template_params)
def fetch_contract_info(short_name): # Get relevant contract model contract = Contract.query(Contract.short_name == short_name).get() # Will send blanks for the elements of retrieved Contract that are not yet filled in name = contract.challenge_name obj_type = contract.objective_type length = contract.time_period unit = contract.time_unit start = contract.start_date # Get more aspects of challenge using ids to search other Models con_id = contract.contract_id stakes_ids = contract.stakes_id return name, obj_type, length, unit, start, con_id, stakes_ids
def fetch_current_challenges_list(): user = users.get_current_user() if not user: self.redirect('/') username = grab_username(user.email()) user_data = User.query(User.google_username == username).get() if not user_data: return [] # Get all CombatantUser objects for this user com_users = CombatantUser.query( CombatantUser.user_id == user_data.user_id).fetch(20) # Get all ContractCombatant objects for this user con_coms = [] for com_user in com_users: con_coms += ContractCombatant.query( ContractCombatant.combatant_id == com_user.combatant_id).fetch(20) # Create array containing challenge names, links, combatant name in that challenge, and position challenges = [] for con_com in con_coms: con = Contract.query(Contract.contract_id == con_com.contract_id).get() challenge_name = con.challenge_name # Link to details page if competition is in future if not con.start_date or con.start_date > datetime.date.today(): link = '/' + con.short_name + '/details' # Otherwise link to status page else: link = '/' + con.short_name + '/status' com_name = Combatant.query( Combatant.combatant_id == con_com.combatant_id).get().name position = con_com.position challenges.append({ 'challenge_name': challenge_name, 'link': link, 'com_name': com_name, 'position': position }) return challenges, username
def api_contract_new(*, userid, contractid): 'add contract' if not userid: raise APIValueError('userid') if not contractid: raise APIValueError('contractid') fromid = next_id() fcontract = Contract(id=fromid, userid=userid, contractid=contractid) fres = yield from fcontract.save() toid = next_id() tcontract = Contract(id=toid, userid=contractid, contractid=userid) tres = yield from tcontract.save() return {'fres': fres, 'tres': tres}
def contractme(request): name = request.GET.get('name') phone = request.GET.get('phone') email = request.GET.get('email') message = request.GET.get('message') print('name = '+name + 'phone = ' + phone + 'email='+email + 'message='+message ) c = Contract() c.name = name c.phone = phone c.email = email c.message = message now = datetime.now() print now.strftime('%Y-%m-%d %H:%M:%S') #print('date = ' + now) c.save() sendEmail(c) return HttpResponse(json.dumps('succeed'), content_type="application/json")
def fetch_current_combatant(short_name): # Find what user is logged in user = users.get_current_user() if not user: self.redirect('/') # Find all the users associated with this challenge contract_id = Contract.query( Contract.short_name == short_name).get().contract_id combatants_info = fetch_combatants_info(contract_id) # Get all users associated with each distinct combatant for combatant in combatants_info: users_info = fetch_users_info(combatant.combatant_id) # Return current combatant if user is found for user_info in users_info: if user_info.google_username == str(user): return combatant
def test_evaluate_notprofitable(): market = Market("test", 0, "", "SingleMarket") c1 = Contract("test", "test1", "") c2 = Contract("test", "test2", "") c3 = Contract("test", "test3", "") c1.long_offers = [Offer(c1, "YES", 0.4, 10)] c2.long_offers = [Offer(c2, "YES", 0.5, 10)] c3.long_offers = [Offer(c3, "YES", 0.6, 10)] market.contracts = [c1, c2, c3] r = buy_yes.evaluate(market) assert r is None
def search_by_keyword(request): keyword = request.GET.get('keyword') or '' template_params = { 'keyword': keyword, 'dev': os.environ["SERVER_SOFTWARE"].find('Development') != -1 } template_params.update(global_template_params) if keyword: # Search the 'Contract' Entity based on our keyword #query = search.SearchableQuery('Contract') #query.Search(keyword) #results = query.Get(50) query = Contract.all().search(keyword) more_template_params = _process_query(request, query) template_params.update(more_template_params) else: pass return render_to_response('search_results.html', template_params)
def test_evaluate_notprofitable(): market = Market('test', 0, '', 'SingleMarket') c1 = Contract('test', 'test1', '') c2 = Contract('test', 'test2', '') c3 = Contract('test', 'test3', '') c1.short_offers = [ Offer(c1, 'NO', .9, 10) ] c2.short_offers = [ Offer(c2, 'NO', .95, 10) ] c3.short_offers = [ Offer(c3, 'NO', .99, 10) ] market.contracts = [ c1, c2, c3 ] r = buy_no.evaluate(market) assert r is None
def rpc_search_by_keyword(request): keyword = request.GET.get('keyword') or '' offset = int(request.GET.get('offset') or 0) limit = 50 response = { 'keyword': keyword, 'CURRENT_VERSION_ID': os.environ['CURRENT_VERSION_ID'] } if keyword: resultset = [] query = Contract.all().search(keyword) results = query.fetch(limit, offset) #XXX django simplejson can't understand db.Model entities yet for result in results: result.contract_value = result.contract_value.replace('$', '') result.contract_value = result.contract_value.replace(',', '') try: result.contract_value = float(result.contract_value) except: # contract_value could have chars pass resultset.append({ 'agency_name' : result.agency_name, 'vendor_name' : result.vendor_name, 'contract_value' : result.contract_value, 'contract_date': result.contract_date, 'description': result.description, 'comments': result.comments, 'uri': result.uri, }) response['resultset'] = resultset else: pass return HttpResponse(simplejson.dumps(response), mimetype='application/javascript')
def delete_contract(request): contr = Contract(user=request.user, id=int(request.path_info.split("/")[3])) contr.delete() return redirect("/profile/")
def contractAdd(request): user = request.user context = {"user": user} try: if request.method == 'POST': context['post'] = 'y' contract = Contract() contract.department = request.POST['institute'] contract.user = user contract.personell_number = request.POST['personell_id'] cStart = request.POST['contract_start'] cEnd = request.POST['contract_end'] cStart = datetime.strptime(cStart, "%Y-%m-%d") cEnd = datetime.strptime(cEnd, "%Y-%m-%d") contract.contract_begin = cStart contract.contract_end = cEnd contract.personell = request.POST['dp'] contract.hours = request.POST['work_hours'] contract.payment = request.POST['payment'] contract.vacation = round((int(contract.hours) * 20 * 3.95) / 85.0) contract.clean_fields() contract.save() return redirect("/profile") except ValidationError as v: context['error'] = v.messages print(v) except ValueError as v: context['error'] = [v.message] context['postdata'] = request.POST return render(request, 'contract_add.html', context)
from app import db from models import Contract ''' Sunrise''' contractName = Contract() contractName.contract_name ="" contractName.monthly_price =0#setvalues contractName.operator ="" contractName.age_limit =0 contractName.duration= 0#setvalues #calls # --national contractName.limit_same_operator_calls_nat=0#setvalues ##in minutes contractName.limit_other_operator_calls_nat=0#setvalues ##in minutes contractName.limit_fixed_networks_calls_nat=0 contractName.limit_national_calls= 0 # --international contractName.limit_outgoing_international_calls_fromCH=0#setvalues contractName.limit_calls_at_abroad = 0#setvalues #TODO does it include incoming calls as well? #standard rates contractName.rate_call_in_ch = 0.0 contractName.rate_chargable_call_duration = 0#setvalues contractName.rate_calls_to_abroad = 0.0 contractName.rate_incoming_call_at_abroad = 0.0 contractName.rate_call_from_abroad_to_abroad = 0.0 contractName.rate_call_from_abroad_to_CH = 0.0 #--------------------------------------------------------------------------
def view_contract(request, key_name): result = Contract.get_by_key_name(key_name) template_params = {} template_params['result'] = result return render_to_response('contract.html', template_params)