def get_user(username): events_code, events_content = db_connect( '/getEvents?user_name=%s' % username) profile_code, profile_content = db_connect( '/user/profile?user_name=%s' % username) if (events_code == http.client.NOT_FOUND or profile_code == http.client.NOT_FOUND): return { 'is_success': False, 'error_message': '%s does not exist (redirect to dashboard).' % username } elif events_code == http.client.OK: if profile_code == http.client.NO_CONTENT: return { 'is_success': True, 'events': events_content } elif profile_code == http.client.OK: return { 'is_success': True, 'profile': profile_content, 'events': events_content }
def xhr_get_event_visualisation_data(event_id): interaction_code, interaction_content = db_connect( '/event/interaction?event_id=%s' % event_id) attendees_code, attendees_content = db_connect( '/eventUsers?event_id=%s' % event_id) if interaction_code == http.client.OK and attendees_code == http.client.OK: return { 'interaction': interaction_content, 'attendees': attendees_content } else: return None
def login(username, hashed_password): status_code, _ = db_connect('/login', { 'user_name': username, 'password': hashed_password, 'mac_address': '' # use for mobile, website parse empty string instead }) response_dict = { http.client.OK: { 'is_success': True, 'success_message': 'You have successfully signed in.' }, http.client.CREATED: { 'is_success': True, 'success_message': 'You have successfully signed in with new device.' }, http.client.NOT_FOUND: { 'is_success': False, 'error_message': 'Username or password not found.' }, http.client.CONFLICT: { 'is_success': False, 'error_message': 'You are currently logging in another device' } } return response_dict[status_code]
def delete_product(): connection = db_connect() id = request.form['product_id'] returned_id = pr.delete_product(connection, id) response = jsonify({'product_id': returned_id}) response.headers.add('Access-Control-Allow-Origin', '*') return (response)
def register( username, hashed_password, hashed_confirm_password): if hashed_password != hashed_confirm_password: return { 'is_success': False, 'error_message': 'Password and retyped password is not match.' } status_code, _ = db_connect('/register', { 'user_name': username, 'password': hashed_password, }) response_dict = { http.client.CREATED: { 'is_success': True, 'success_message': 'You have successfully registered.' }, http.client.CONFLICT: { 'is_success': False, 'error_message': 'Username "%s" is already in use by another user.' % username } } return response_dict[status_code]
def get_all_orders(): connection = db_connect() orders = order_dao.get_all_orders(connection) response = jsonify(orders) response.headers.add('Access-Control-Allow-Origin', '*') return (response)
def add_event(start_time, end_time, address, name, description, speaker_id, organiser_id, attendees): attendee_list = attendees.split(' ') if attendees != '' else [] status_code, content = db_connect('/addEvent', { 'start_time': start_time, 'end_time': end_time, 'address': address, 'name': name, 'description': description, 'speaker_id': speaker_id, 'organiser_id': organiser_id, 'attendees': [{'user_name': attendee} for attendee in attendee_list] }) response_dict = { http.client.OK: { 'is_success': True, 'success_message': content['Message'], 'event_id': content['event_id'] }, http.client.CONFLICT: { 'is_success': False, 'error_message': 'Somebody has already used "%s" as event name.' % name } } return response_dict[status_code]
def get_user_profile(username): status_code, content = db_connect( '/user/profile?user_name=%s' % username) if status_code == http.client.OK: return content else: return None
def get_event_profile(event_id): status_code, event_profile = db_connect( '/event_data?event_id=%s' % event_id) if status_code == http.client.OK: event_profile['event_id'] = event_profile['id'] return event_profile else: return None
def insert_product(): connection = db_connect() request_payload = json.loads(request.form['data']) print(request_payload) product_id = pr.insert_new_product(connection, request_payload) response = jsonify({'prodcut_id': product_id}) response.headers.add('Access-Control-Allow-Origin', '*') return (response)
def insert_order(): connection = db_connect() request_payload = json.loads(request.form['data']) print(request_payload) customer_name = request_payload['customer_name'] order_id = order_dao.insert_order(connection, request_payload) response = jsonify({'order_id': order_id}) response.headers.add('Access-Control-Allow-Origin', '*') return response
def get_friends_raw(username): status_code, content = db_connect( '/user/connections?user_name=%s' % username) if status_code == http.client.OK: return [ string.strip() for string in content['connections'][1:-1].split(',') ] else: return []
def get_friends(username, include_detail=False): friend_usernames = get_friends_raw(username) if include_detail: friends = {} for friend_username in friend_usernames: profile_code, profile_content = db_connect( '/user/profile?user_name=%s' % friend_username) if profile_code == http.client.OK: friends[friend_username] = profile_content else: friends[friend_username] = {'name': '', 'photo': ''} return friends else: return friend_usernames
def get_all_event_profile(): status_code, event_list = db_connect('/searchEvent', { 'user_name': '', 'event_search_string': '' }) if status_code == http.client.OK: event_profile_list = [] for event in event_list: event_profile = get_event_profile(event['event_id']) if event_profile: event_profile_list.append(event_profile) return event_profile_list else: return None
def get_event_attendees(event_id): status_code, content = db_connect( '/eventUsers?event_id=%s' % event_id) response_dict = { http.client.OK: { 'is_success': True, 'user_mappings': content['user_mappings'] }, http.client.CONFLICT: { 'is_success': False, 'error_message': 'Event "%s" does not exist.' % event_id } } return response_dict[status_code]
def delete_friends(username, friend_list): status_code, content = db_connect( '/user/connections?user_name=%s' % username, {'operation': 'delete', 'connections': friend_list}) if status_code == http.client.OK: return { 'is_success': True, 'success_message': 'You have successfully deleted %s from friend' % friend_list } else: return { 'is_success': False, 'error_message': 'You cannot delete %s from friend' % friend_list }
def update_profile(username, **kwarg): status_code, content = db_connect( '/user/profile?user_name=%s' % username, kwarg) response_dict = { http.client.CREATED: { 'is_success': True, 'success_message': 'Your have successfully updated your profile', }, http.client.CONFLICT: { 'is_success': False, 'error_message': 'There is an error in your profile' } } return response_dict[status_code]
def __init__(self): pygame.init() self.conn = db_connect(str(Game.DIR / "db" / "words.db")) self.word = random_word(self.conn)[1] self.game_font = pygame.freetype.Font( str(Game.DIR / "fonts" / "classic.TTF"), 26) self.word_font = pygame.freetype.SysFont("comicsans", 50) self.win = pygame.display.set_mode((Game.WIDTH, Game.HEIGHT)) self.caption = pygame.display.set_caption("HangThePyMan") self.gameIcon = pygame.image.load(str(Game.DIR / "icon" / "icon.png")) self.replayIcon = pygame.image.load( str(Game.DIR / "icon" / "replay.png")) self.replayIcon = pygame.transform.scale(self.replayIcon, (50, 50)) self.endIcon = pygame.image.load(str(Game.DIR / "icon" / "cross.png")) self.endIcon = pygame.transform.scale(self.endIcon, (50, 50)) self.icon = pygame.display.set_icon(self.gameIcon) self.clock = pygame.time.Clock() self.b_color = (255, 255, 255) self.run = True self.images = self.load_images() self.letter_coordinates = self.load_buttons() self.state = "Title" self.play_btn = Button((37, 164, 206), 300, 150, 200, 100, "Play") self.quit_btn = Button((37, 164, 206), 300, 300, 200, 100, "Quit") self.replay_btn = Button((37, 164, 206), 315, 300, 50, 50, image=self.replayIcon, imagepos=(315, 300)) self.end_btn = Button((37, 164, 206), 415, 300, 50, 50, image=self.endIcon, imagepos=(415, 300)) try: self.version = pkg_resources.get_distribution( "hangthepyman").version except Exception: self.version = "Beta"
def join_event(event_id, username, status="Attendee"): status_code, content = db_connect( '/event/join?event_id=%s' % event_id, { 'user_name': username, 'status': status}) response_dict = { http.client.OK: { 'is_success': True, 'success_message': 'You have successfully joined event %s' % event_id }, http.client.CONFLICT: { 'is_success': False, 'error_message': ('Event "%s" or username %s does not exist.' % (event_id, username)) } } return response_dict[status_code]
def scenarios_api(): if request.method == "GET": try: company = request.args['company'] con = db_connect() #connct to database if con is not None: cursor = con.cursor() query = "select distinct scenario from company_projections where companyname='" + company + "'" cursor.execute(query) rows = cursor.fetchall() scenarios = [i[0] for i in rows] scenarios.sort() scenerio = {"scenarios": scenarios} json_string = json.dumps(scenerio, sort_keys=True, default=str) con.close() #close database connection return json_string else: return '{"Error":"DB Connection Error"}' except: return '{"Error":"Something went wrong,Make sure that ur passing company name in query params"}'
def actuals_api(): try: company = request.args['company'] con = db_connect() #connct to database if con is not None: cursor = con.cursor() query = "select * from company_actuals where companyname='" + company + "'" cursor.execute(query) rows = cursor.fetchall() field_names = [i[0] for i in cursor.description] json_string = json.dumps([{ description: value for description, value in zip(field_names, row) } for row in rows], sort_keys=True, default=str) con.close() #close database connection return json_string else: return '{"Error":"DB Connection Error"}' except: return '{"Error":"Something went wrong,Make sure that ur passing company name in query params"}'
def projections_api(): if request.method == "GET": try: company = request.args['company'] scenario = request.args['scenario'] con = db_connect() #connct to database if con is not None: cursor = con.cursor() query = "select * from company_projections where companyname='" + company + "' and scenario='" + str( scenario) + "'" cursor.execute(query) rows = cursor.fetchall() field_names = [i[0] for i in cursor.description] json_string = json.dumps([{ description: value for description, value in zip(field_names, row) } for row in rows], sort_keys=True, default=str) con.close() #close database connection return json_string else: return '{"Error":"DB Connection Error"}' except: return '{"Error":"Something went wrong,Make sure that ur passing company name in query params"}' if request.method == "POST": con = db_connect() # connct to database try: if con is not None: cursor = con.cursor() contents = request.json for content in contents: company = content["companyname"] asof = content["asof"] scenario = content["scenario"] latest = content["latest"] totalrevenue = content["totalrevenue"] cogs = content["cogs"] grossprofit = content["grossprofit"] sga = content["sga"] ebit = content["ebit"] ebitmargin = content["ebitmargin"] da = content["da"] ebitda = content["ebitda"] ebitdamargin = content["ebitdamargin"] netinterest = content["netinterest"] otherincome = content["otherincome"] ebt = content["ebt"] ebtmargin = content["ebtmargin"] taxes = content["taxes"] netincome = content["netincome"] netincomemargin = content["netincomemargin"] revenuepercent = content["revenuepercent"] cogspercent = content["cogspercent"] sgapercent = content["sgapercent"] dapercent = content["dapercent"] netinterestdollars = content["netinterestdollars"] otherincomepercent = content["otherincomepercent"] taxespercent = content["taxespercent"] grossprofitmargin = content["grossprofitmargin"] query = "delete from company_projections where companyname='" + company + "' and asof=" + str( asof) + " and scenario='" + str(scenario) + "'" print(query) cursor.execute(query) con.commit() query = "insert into company_projections(companyname,asof,scenario,totalrevenue,latest,cogs,grossprofit,grossprofitmargin,sga," \ "ebit,ebitmargin,da,ebitda,ebitdamargin,netinterest,otherincome,ebt,ebtmargin,taxes,netincome,netincomemargin,revenuepercent," \ "cogspercent,sgapercent,dapercent,netinterestdollars,otherincomepercent,taxespercent) values('" + company + "'," + str(asof) + "," \ "'"+str(scenario)+"',"+str(totalrevenue)+","+str(latest)+","+str(cogs)+","+str(grossprofit)+","+str(grossprofitmargin)+"" \ ","+str(sga)+","+str(ebit)+","+str(ebitmargin)+","+str(da)+","+str(ebitda)+","+str(ebitdamargin)+"" \ ","+str(netinterest)+","+str(otherincome)+","+str(ebt)+","+str(ebtmargin)+","+str(taxes)+","+str(netincome)+"" \ ","+str(netincomemargin)+","+str(revenuepercent)+","+str(cogspercent)+","+str(sgapercent)+","+str(dapercent)+","+str(netinterestdollars)+"" \ ","+str(otherincomepercent)+","+str(taxespercent)+")" print(query) cursor.execute(query) con.commit() return str(request.json) con.close() # close database connection else: return '{"Error":"DB Connection Error"}' except Exception as e: return '{"Error":' + str(e) + '}'
import dash_html_components as html import pandas as pd import config as cfg import plotly.graph_objs as go from db_connection import db_connect # # Establish connection to DB # con = db_connect(cfg.sqlite_config['db']) # data1 = pd.read_sql_query("SELECT * FROM quiniela_table", con.connection()) # Read In Data as CSV data_old = pd.read_csv("results_stacked.csv", index_col=0) data_old.sort_values(["season", 'week'], inplace=True) # Establish connection to DB con = db_connect(cfg.sqlite_config['db']) data = pd.read_sql_query("SELECT * FROM quiniela_table", con.connection()) fig = go.Figure(data=[go.Scatter(x=data["season"].values, y=data["week"].values, mode='markers')]) app = dash.Dash(__name__) app.layout = html.Div( children=[ html.H1(children="Quiniela Analytics",), html.P( children="Analyze Football Predictions" " and the number of avocados sold in the US" " from 2003 to present", ), dcc.Graph(
def get_uom(): connection = db_connect() uom = um.get_uom(connection) response = jsonify(uom) response.headers.add('Access-Control-Allow-Origin', '*') return (response)
def get_uom(connection): cursor = connection.cursor() query = "SELECT * FROM grocery_store.uom;" cursor.execute(query) response = [] for (uom_id, uom_name) in cursor: print(uom_id , uom_name) response.append({ 'uom_id': uom_id, 'uom_name': uom_name }) return response if __name__ == "__main__": from db_connection import db_connect connection = db_connect() print(get_uom(connection))
def get_products(): connection = db_connect() products = pr.get_all_the_products(connection) response = jsonify(products) response.headers.add('Access-Control-Allow-Origin', '*') return (response)