def api_game_list( id = None): try: db = database.open_database('localhost', 'oh_hell', 'db_config.txt') players = database.get_table(db, 'player', 'player_id') games = database.get_table(db, 'game', 'game_id') jsonRep = { 'games' : [], 'players' : [] } count = {} for k in players.keys(): count[k] = 0 tieCount = 0 for id in games.keys(): game = games[id] if game.winner_id > 0: winner = players[game.winner_id].first_name count[game.winner_id] = count[game.winner_id] + 1 else: winner = 'Tie' tieCount = tieCount + 1 jsonRep['games'].append( create_game_stat(id, game.time, game.winner_id)) for k in count.keys(): jsonRep['players'].append( create_player_stat(k, players[k].first_name, count[k])) return jsonRep finally: if db != None: db.close()
def delete_item(tablename): con = database.get_engine().connect() data = request.values.get('key') print(data, file=sys.stderr) if data != '': if tablename == 'Take_Course': data = data.split('&') temp = [] temp.append(data[0].split('=')[1]) temp.append(data[1].split('=')[1]) data = temp else: data = data.split('=')[1] database.delete_data(tablename, data) ##Execute select all from Academy table table = database.get_table(tablename) table = table.select().execute().fetchall() table_name = tablename ##Parse result data columns, results = parse_result(table) con.close() return render_template('delete.html', table_name=table_name, columns=columns, results=results)
def insert_new(tablename): table = database.get_table(tablename) columns = table.columns.keys() data = {} for i in columns: if i == 'DServing' or i == 'Bdate' or i == 'BDATE': temp = request.form.get(i, '') if temp == '': temp = time.strftime('%Y-%m-%d') temp = datetime.datetime.strptime(temp, '%Y-%m-%d') elif i == 'Photo': filename = request.files[i].filename temp = request.files[i].read() if filename == '': temp = read_default() else: temp = request.form.get(i, '') data[i] = temp print(data, file=sys.stderr) database.insert_data(tablename, data) columns, result = database.query_execute( tablename, data[table.primary_key.columns.keys()[0]]) results = parse_query_result(columns, result) return render_template('insert.html', columns=columns, results=results)
def get_deals( db, game_id ): players = database.get_table(db, 'player', 'player_id') game_players = database.get_table_with_composite_key(db, 'game_players', ('game_id', 'player_id'), 'WHERE game_id = ' + str(game_id)) num_players = len(game_players) player_list = num_players*[0] player_ids = [ p[1] for p in game_players.keys()] for i in player_ids: gp = game_players[(game_id,i)] player_list[gp.game_order-1] = players[ gp.player_id] deals = [] for player in player_list: deal = database.get_table(db, 'deal, bid', 'deal_id', 'WHERE deal.deal_id = bid.deal_id' + ' AND game_id = ' + str(game_id) + ' AND player_id = ' + str(player.player_id) + ' ORDER BY deal', 'bid.deal_id, dealer_id, deal, num_cards, bid_id, bid' ) deals.append(deal) return player_list, deals
def get_tricks_won_in_deal( db, deal_id, player_ids): tricks_won = {} for id in player_ids: tricks_won[id] = 0 tricks = database.get_table(db, 'trick', 'trick_id', 'WHERE deal_id = ' + str(deal_id) + ' ORDER BY trick_num') for t in tricks.values(): id = t.winner_id tricks_won[id] = tricks_won[id] + 1 return tricks_won
def gameList( id = None): try: db = database.open_database('localhost', 'oh_hell', 'db_config.txt') players = database.get_table(db, 'player', 'player_id') games = database.get_table(db, 'game', 'game_id') text = '' count = {} for k in players.keys(): count[k] = 0 tieCount = 0 for id in reversed(games.keys()): game = games[id] if game.winner_id > 0: winner = players[game.winner_id].first_name count[game.winner_id] = count[game.winner_id] + 1 else: winner = 'Tie' tieCount = tieCount + 1 link = '<a href="/game/%d">%s</a>' % ( id, game.time[:10]) text += (str(id) + ": " + link + " : " + winner + "<BR>\n") text += ('<p>\n') for k in count.keys(): text += (players[k].first_name + ": " + str(count[k]) + "<BR>\n") if tieCount > 0: text += ( 'Ties : ' + str(tieCount) + "<BR>\n") return "<html><head><title>Oh Hell Games</title></head><body>\n" + text + "\n</body></html>\n" finally: if db != None: db.close()
def get_table(tablename): con = database.get_engine().connect() table = database.get_table(tablename) table = table.select().execute().fetchall() table_name = tablename columns, results = parse_result(table) con.close() return render_template('index.html', table_name=table_name, columns=columns, results=results)
def api_game_hand_summary( game_id, deal): try: db = database.open_database('localhost', 'oh_hell', 'db_config.txt') deal_infos = database.get_table( db, 'deal', 'deal_id', 'where game_id = %d and deal = %d' % (game_id, deal)) deal_info = deal_infos[deal_infos.keys()[0]] tricks = get_query_results(db, 'select trick_id from trick where deal_id = ' + str(deal_info.deal_id) + ' order by trick_id') trick_list = [] for (trick_id,) in tricks: cards = get_query_results(db, 'select player_id, card from trick_cards ' + 'where trick_id = ' + str(trick_id) + ' order by card_num') trick_list.append( [ { 'player_id' : c[0], 'card' : c[1] } for c in cards ]) player_ids = [ "'" + str(trick['player_id']) + "'" for trick in trick_list[0] ] players = database.get_table( db, 'player', 'player_id', 'where player_id in ( ' + ','.join(player_ids) + ')' ) player_map = {} for player_id, row in players.iteritems(): player_map[player_id] = (row.first_name, row.last_name) jsonRep = { 'deal_id' : deal_info.deal_id, 'players' : player_map, 'dealer_id' : deal_info.dealer_id, 'num_cards' : deal_info.num_cards, 'trump' : deal_info.trump, 'tricks' : trick_list } return jsonRep finally: if db is not None: db.close()
def api_game_summary( id ): try: db = database.open_database('localhost', 'oh_hell', 'db_config.txt') players = database.get_table(db, 'player', 'player_id') games = database.get_table(db, 'game', 'game_id', 'WHERE game_id = ' + str(id)) game = games[id] gsc = ohhellquery.GameStateCreator(db) gs = gsc.create(id) if game.winner_id > 0: winner = players[game.winner_id].first_name else: winner = 'Tie' jsonRep = { 'winner' : winner, 'players' : [], 'hands' : []} gsPlayers = gs.getPlayers() scores = gs.currentScores() for player in gsPlayers: jsonRep['players'].append( { 'id' : player[0], 'name' : player[1], 'ip' : player[2] }) nPlayers = len(gsPlayers) scoreSheet = gs.getScoreSheet() for hand in scoreSheet: hand_info = { 'num_cards' : hand[0], 'tricks' : [] } for player in hand[1]: hand_info['tricks'].append( { 'bid' : player[0], 'tricks' : player[1], 'score': player[2] }) jsonRep['hands'].append( hand_info) return jsonRep finally: if db != None: db.close()
def query_request(tablename): con = database.get_engine().connect() query = request.args.get('text', '') if query != '': columns, result = database.query_execute(tablename, query) data = parse_query_result(columns, result) json_data = json.dumps({'columns': columns, 'results': data}) con.close() return json_data else: table = database.get_table(tablename) table = table.select().execute().fetchall() table_name = tablename columns, data = parse_result(table) json_data = json.dumps({'columns': columns, 'results': data}) return json_data
def create_xml_id_to_db_id_map( db, gameState): """ Create a list that maps XML id numbers to database player_id values Params: db : open database connection gameState : game state Returns: list with database player ids in order of listing in XML file """ player_map = [] xml_players = gameState.getPlayers() for p in xml_players: t = database.get_table(db, "player", "player_id", "WHERE first_name = '" + p[1] + "'") player_map.append( t.values()[0].player_id) #print "player_map =", player_map return player_map
import requests import json import time import boto3 import database import ConfigParser import decimal import urllib2, urllib #import kinds of libraries # read table name tablename = "uber_weather" # create database if not exist # dynamodb_table = database.create_database(tablename) dynamodb_table = database.get_table(tablename) # first, get the table order = 0 # initialize order to 0 # start the loop while True: order = order + 1 # update order baseurl = "https://query.yahooapis.com/v1/public/yql?" yql_query = "select item.condition from weather.forecast where woeid = 12761478" # use yahoo query sentence to get manhattan weather yql_url = baseurl + urllib.urlencode( {'q': yql_query}) + "&format=json" # constitute the url to request result = urllib2.urlopen( yql_url).read() # get the result returned by yahoo_weather api preprocess_data = json.loads( result ) # transform result from json format to python dictionary format try:
def create( self, game_id): """ Create a GameState object from the database Parameters: game_id - ID of game in database """ game_state = GameState.GameState() game_stats = database.get_table( self.db, 'game', 'game_id', 'where game_id = ' + str(game_id) ) player_list, deals = get_deals(self.db, game_id) game_state.init_new( len(player_list), game_stats[game_id].time) # player_map maps the database player_id to the game_state # player_id value player_map = {} i = 0 for player in player_list: game_state.addPlayer(i, player.first_name, None) player_map[player.player_id] = i i = i + 1 #print 'Added player id', player.player_id deal_ids = deals[0].keys() deal_ids.sort() deals_table = database.get_table(self.db, 'deal', 'deal_id', 'where game_id = ' + str(game_id) + ' order by deal') for i in deal_ids: hand = GameState.HandState(len(player_list), deals[0][i].num_cards, deals_table[i].trump, player_map[deals_table[i].dealer_id]) tricks = database.get_table( self.db, 'trick', 'trick_id', 'where deal_id = ' + str(i) ) trick_ids = tricks.keys() trick_ids.sort() trick_set = str(trick_ids).replace('[', '(').replace(']',')') where_cause = 'where trick_id in ' + trick_set tricks_made = {} for j in player_list: tricks_made[j.player_id] = 0 cards = database.get_table_with_composite_key( self.db, 'trick_cards', ['trick_id', 'player_id'], where_cause + ' and player_id = ' + str(j.player_id)) card_codes = [ x.card for x in cards.values() ] card_codes.sort() #print j, card_codes hand.setHand( player_map[j.player_id], card_codes) for j in range(len(player_list)): hand.setBid( player_map[player_list[j].player_id], deals[j][i].bid) # Need to add cards dealt to hand first for j in trick_ids: trick = tricks[j] tricks_made[trick.winner_id] = tricks_made[trick.winner_id] + 1 trick_state = GameState.TrickState() cards = database.get_table_with_composite_key( self.db, 'trick_cards', ['trick_id', 'player_id'], 'where trick_id = ' + str(j)) card_list = [ (x, cards[x]) for x in cards.keys() ] card_list.sort( cmp = lambda x,y : cmp(x[1].card_num, y[1].card_num) ) for c in card_list: trick_state.addCard(player_map[c[0][1]], c[1].card) hand.addTrick(trick_state) for p in tricks_made.keys(): hand.setTricksMade(player_map[p], tricks_made[p]) game_state.addHand(hand) return game_state
def gameSummary( id ): try: db = database.open_database('localhost', 'oh_hell', 'db_config.txt') players = database.get_table(db, 'player', 'player_id') games = database.get_table(db, 'game', 'game_id', 'WHERE game_id = ' + str(id)) game = games[id] gsc = ohhellquery.GameStateCreator(db) gs = gsc.create(id) if game.winner_id > 0: winner = players[game.winner_id].first_name else: winner = 'Tie' text = """ <html> <head> <title>Oh Hell game on """ + game.time[:10] + """</title> </head> <body> <table> <tr> <td>Game Id:</td><td> """ + str(id) + """ </td> </tr> <tr> <td>Date :</td><td>""" + game.time[:10] + """</td> </tr> <tr> <td>Winner :</td><td>""" + winner + """ </td> </tr> </table> <p> <p> <table border=1 cellspacing=5 cellpadding=5> """ gsPlayers = gs.getPlayers() scores = gs.currentScores() text += '<tr>\n<td> </td>' for player in gsPlayers: text += '<th>' + player[1] + '</th>' text += ('</tr>\n') nPlayers = len(gsPlayers) scoreSheet = gs.getScoreSheet() oldScores = len(gsPlayers)*[0,] for hand in scoreSheet: text += '<tr><td>%d</td>'% ( hand[0]) i = 0 for player in hand[1]: text += "<td>" font = False if oldScores[i] < player[2]: text += "<font color='green'>" font = True elif oldScores[i] > player[2]: text += "<font color='red'>" font = True text += "(%d, %d) %d" % player if font: text += "</font>" text += "</td>" oldScores[i] = player[2] i = i + 1 text += '</tr>\n' return text + "</table>\n</body>\n</html>" finally: if db != None: db.close()
import requests import json import time import boto3 import database import ConfigParser import decimal import urllib2, urllib #import kinds of libraries # read table name tablename = "uber_weather" # create database if not exist # dynamodb_table = database.create_database(tablename) dynamodb_table = database.get_table(tablename) # first, get the table order = 0 # initialize order to 0 # start the loop while True: order = order + 1 # update order baseurl = "https://query.yahooapis.com/v1/public/yql?" yql_query = "select item.condition from weather.forecast where woeid = 12761478" # use yahoo query sentence to get manhattan weather yql_url = baseurl + urllib.urlencode({'q':yql_query}) + "&format=json" # constitute the url to request result = urllib2.urlopen(yql_url).read() # get the result returned by yahoo_weather api preprocess_data = json.loads(result) # transform result from json format to python dictionary format try: weather = preprocess_data['query']['results']['channel']['item']['condition']['text'].encode('utf-8') # try to get weather result except: continue
# load config file config = ConfigParser.RawConfigParser() config.read('../config.cfg') #with open('location.json') as data_file: # data = json.load(data_file) #company = data["places"][0] # for test # read table name tablename = "uber_weather" # create database if not exist #dynamodb_table = database.create_database(tablename) dynamodb_table = database.get_table(tablename) order = 0 while True: order = order + 1 baseurl = "https://query.yahooapis.com/v1/public/yql?" yql_query = "select item.condition from weather.forecast where woeid = 12761478" yql_url = baseurl + urllib.urlencode({'q':yql_query}) + "&format=json" result = urllib2.urlopen(yql_url).read() preprocess_data = json.loads(result) weather = preprocess_data['query']['results']['channel']['item']['condition']['text'].encode('utf-8') time = preprocess_data['query']['results']['channel']['item']['condition']['date'].encode('utf-8') # insert into dynamodb item = {"weather":weather,"time":time} print(item) database.insert(dynamodb_table, item)
# load config file config = ConfigParser.RawConfigParser() config.read('../config.cfg') #with open('location.json') as data_file: # data = json.load(data_file) #company = data["places"][0] # for test # read table name tablename = "uber_weather" # create database if not exist #dynamodb_table = database.create_database(tablename) dynamodb_table = database.get_table(tablename) order = 0 while True: order = order + 1 baseurl = "https://query.yahooapis.com/v1/public/yql?" yql_query = "select item.condition from weather.forecast where woeid = 12761478" yql_url = baseurl + urllib.urlencode({'q': yql_query}) + "&format=json" result = urllib2.urlopen(yql_url).read() preprocess_data = json.loads(result) weather = preprocess_data['query']['results']['channel']['item'][ 'condition']['text'].encode('utf-8') time = preprocess_data['query']['results']['channel']['item']['condition'][ 'date'].encode('utf-8') # insert into dynamodb item = {"weather": weather, "time": time}