def _update_row_no_commit(): db = Database() id_ = 2 row = db.session.query(models.Customers).get(id_) _print_row(row) row.address = "NEW VALUE" _print_row(row)
class State(): START_TIME = 0 def __init__(self, symbolIndex, reconnectReason=ReconnectReason.KILLED): self.symbolIndex = symbolIndex self.reconnectReason = reconnectReason self.database = Database() self.lastMessageTime = None self.reset() def reset(self): self.previous_socket_sequence = -1 # exchange's first message on connect has socket_sequence 0 self.orderbook = None def __del__(self): print("destroying state") self.database.close()
def main(): parser = argparse.ArgumentParser() parser.add_argument('--num_pages', type=int) parser.add_argument('--update_tag_db', '-u', help='Upsert scraped data to database', required=False, action='store_true') args = parser.parse_args() db = Database() if db.is_empty('Tag') or args.update_tag_db: tag_parser = PageParser("tag") tags = tag_parser.get_pages(Tag, MAX) db.update_tag_table(tags) print("Getting Question Summaries...") summary_parser = PageParser("question_summary") summaries = summary_parser.get_pages(QuestionSummary, args.num_pages) print("Getting Articles...") article_parser = APIParser() articles = article_parser.get_responses(Article, summaries) #Enrich Question Summary with articles for question_summary, articles_list in zip(summaries, articles): question_summary.add_articles(articles_list) print("Populating DB...") db.insert_question_summaries(summaries)
def _update_rows_no_commit(): db = Database() db.session.query(models.Customers).filter(models.Customers.id != 2).update( {models.Customers.name: f"Mr/Ms {models.Customers.name}"}, synchronize_session=False, ) result = db.session.query(models.Customers).all() for row in result: _print_row(row)
def _insert_rows(): db = Database() rows_new = [ models.Customers( name="Komal Pande", address="Koti, Hyderabad", email="*****@*****.**" ), models.Customers( name="Rajender Nath", address="Sector 40, Gurgaon", email="*****@*****.**" ), models.Customers( name="S.M.Krishna", address="Budhwar Peth, Pune", email="*****@*****.**" ), ] db.session.add_all(rows_new) db.session.commit()
def __init__(self): self.nb = Notebook(rootWindow) self.nb.pack() database = Database('Timesheet2.db') clock_frame = tkinter.Frame(self.nb) self.nb.add(clock_frame, text='Clock in') display_frame = tkinter.Frame(self.nb) self.nb.add(display_frame, text='Display hours') alter_frame = tkinter.Frame(self.nb) self.nb.add(alter_frame, text='Alter hours') display_sheet = DisplayGrid(display_frame, database) alter_sheet = AlterHours(alter_frame, database) clock_in = Timestamp(clock_frame, database)
def _select_first_row_in_db(): _print_row(Database().session.query(models.Customers).first())
def _select_row_by_value(): result = (Database().session.query(models.Customers).filter( and_(models.Customers.id > 2, models.Customers.name.like("%a%")))) print(f"Nomber of results {result.count()}") for row in result: _print_row(row)
def _select_row_by_primary_key(): id_ = 2 row = Database().session.query(models.Customers).get(id_) _print_row(row)
from database_connection import Database, Symbols db = Database() A = 0 B = 0 for x in db.getSnapshotsInfo(-1, A, B): print(x)
def __init__(self, symbolIndex, reconnectReason=ReconnectReason.KILLED): self.symbolIndex = symbolIndex self.reconnectReason = reconnectReason self.database = Database() self.lastMessageTime = None self.reset()
from database_connection import Database import models models.meta.create_all(Database().engine)
def _get_rows_using_sql_string(): t = text("SELECT * FROM students") with Database() as connection: result = connection.execute(t) for row in result: print(row)
class Model: def __init__(self): self.db = Database('timesheet.db') @staticmethod def get_current_date(): return datetime.today().strftime('%Y-%m-%d') @staticmethod def get_current_time(): return datetime.today().strftime('%H:%M') def get_name_by_id(self, _id): return self.db.get_name_by_id(_id) def get_id_by_name(self, _name): return self.db.get_id_by_name(_name) def get_time(self, time_type, _id, _date): return self.db.get_time(time_type, _id, _date) def get_latest_emp_clock(self, _id): return self.db.get_last_clock_in_date(_id) def get_num_of_emp(self): return self.db.get_num_of_emp() def get_all_emp(self): return self.db.get_all_emp() def get_num_days_worked(self, dates, _id): days_worked = 0 for date in dates: if self.get_hours_worked(_id, date): days_worked += 1 return days_worked def get_hours_worked(self, _id, _date: str): clock_off_time = TimeCalculation( self.db.get_time('clock_off', _id, _date)) clock_on_time = TimeCalculation( self.db.get_time('clock_on', _id, _date)) # print(clock_on_time.time) # print(type(clock_on_time.time)) try: if clock_on_time.time and clock_off_time.time: time_worked = clock_off_time - clock_on_time return time_worked elif clock_on_time.time and not clock_off_time.time: raise excep.MissingClockOff except excep.MissingClockOff: return 'Amend' # GETS ID AND A LIST OF DATES AND RETURNS THE TOTAL HOURS, MIN # hours_worked input must be a tuple with two integers e.g. (6,30) def get_total_hours(self, _id, dates): total_hours = 0 hours_list = [] for date in dates: hours_worked = self.get_hours_worked(_id, date) if hours_worked and not isinstance(hours_worked, str): hours_list.append(self.get_hours_worked(_id, date)) total_hours = [ sum(sum_hours) for sum_hours in zip(*hours_list) ] return convert_min_overflow(total_hours) def create_time_record(self, time_type, _id, _date, time_value): self.db.insert_time_record(time_type, _id, _date, time_value) def create_new_emp(self, _name): self.db.insert_new_employee(_name) def set_time_record(self, time_type, _id, _date, time_value): self.db.update_time_record(time_type, _id, _date, time_value)
from database_connection import Database db = Database() def getContinuousRegionInfo(self): print("start time,endtime,delta(hrs), count") for startTime, endTime, count in db.getSnapshotsInfo(): print(startTime, endTime, (endTime - startTime) / 3600 / 1000, count)
def _get_rows_using_the_model(): s = models.students.select() with Database() as connection: result = connection.execute(s) for row in result: print(row)
def _select_rows(): result: list = Database().session.query(models.Customers).all() for row in result: _print_row(row)
#generate a graph of market data import matplotlib.pyplot as plt import sys from OrderBookDS import Update, OrderBook from database_connection import Database, SYMBOLS symbol, startTime, endTime = sys.argv[1:] symbolIndex = int(symbol) if symbol.isnumeric() else [ i for i in range(len(SYMBOLS)) if SYMBOLS[i] == symbol ][0] startTime = int(startTime) endTime = int(endTime) database = Database() while True: bids = [] asks = [] time = [] for snapshot in database.getSnapshots(symbolIndex, startTime, endTime): time.append(snapshot.getLastUpdate().getDateTime()) #print(time[-1],snapshot.getBids().getTopBid().getPrice(),snapshot.getAsks().getTopAsk().getPrice()) assert snapshot.getBids().getTopBid().getPrice() < snapshot.getAsks( ).getTopAsk().getPrice() bids.append(snapshot.getBids().getTopBid().getPrice()) asks.append(snapshot.getAsks().getTopAsk().getPrice()) if not time: break print(len(time))
def _create_tables(): models.Base.metadata.create_all(Database().engine)
def __init__(self): self.db = Database('timesheet.db')
def display_time(self): if self.clock_on_status: self.clock_on_label.config(text=self.clock_on_status) else: self.clock_on_label.config(text='None') if self.clock_off_status: self.clock_off_label.config(text=self.clock_off_status) else: self.clock_off_label.config(text='None') if __name__ == '__main__': # db = sqlite3.connect('Timesheet.db') # acursor = db.cursor() database = Database('timesheet2.db') acursor = database.acursor # Main window instantiated rootWindow = tkinter.Tk() # Title and initial opening frame size. rootWindow.title('ClockOn') rootWindow.geometry('300x300') # Configure row/column layout rootWindow.columnconfigure(0, weight=1) rootWindow.columnconfigure(1, weight=1) rootWindow.columnconfigure(2, weight=1) rootWindow.columnconfigure(3, weight=1) rootWindow.rowconfigure(0, weight=1)
from database_connection import Database import Filter_Data database_connect = Database() database_connect.show_databses() default_database_name = 'emp' default_table_name = 'emp_details' default_file_name = 'sample_data.txt' print('''\n Please press enter if you want to use the default values default_database_name = 'emp' default_table_name = 'emp_details' default_file_name = 'sample_data.txt' ''') database_name = input("\nPlease provide a database_name\n").strip() table_name = input("\nPlease provide a table_name\n").strip() file_name = input("\nPlease Provide a file name\n").strip() if database_name is "": database_name = default_database_name if table_name is "": table_name = default_table_name if file_name is "": file_name = default_file_name column_names = Filter_Data.get_column_name_from_file(file_name) data = Filter_Data.get_records_from_file(file_name) database_connect.create_database(database_name)
def main(argv): if argv == []: # no arguments selected print(__doc__) sys.exit() if len(argv) < 2: print(__doc__) sys.exit() start_date = argv[0] end_date = argv[1] db_ssa = Database('SSA') print(db_ssa) if len(argv) == 3: city = argv[2] city_list = check_cities(db_ssa)['city_name'].tolist() if city not in city_list: print('There is NO that city in the database, check city name') sys.exit() else: city = None col1 = 'created_time' col2 = 'last_modified_time' col3 = 'updated_time' col4 = 'scanning_time' main_status_prop = 'NEW' main_status_loc = 'CREATED' columns_proposals = [ 'date', 'weekday', 'ALL', 'NEW', 'ACCEPTED', 'DECLINED' ] columns = ['date', 'weekday', 'ALL', 'CREATED', 'REMOVED'] df_loc_prop = get_loc_proposals(db_ssa, city) column_to_date(df_loc_prop, col1) column_to_date(df_loc_prop, col2) df_unit_prop = get_lus_proposals(db_ssa, city) column_to_date(df_unit_prop, col1) column_to_date(df_unit_prop, col2) df_loc = get_locations(db_ssa) column_to_date(df_loc, col1) column_to_date(df_loc, col3) df_unit = get_units(db_ssa) column_to_date(df_unit, col1) column_to_date(df_unit, col3) df_spots = check_spots(db_ssa) column_to_date(df_spots, col4) column_to_date(df_spots, col2) df_spots = df_spots.rename( columns={'create_new_location_unit_proposal_id': 'proposal_id'}) df_spots = df_spots.fillna(0) df_spots['location_unit_id'] = df_spots['location_unit_id'].astype(int) try: date_range = pd.date_range(start_date, end_date) except ValueError: print('Problem with date, check format of chosen dates') sys.exit() df_l_prop = count_statuses(df_loc_prop, date_range, col1, col2, main_status_prop, columns_proposals) df_lu_prop = count_statuses(df_unit_prop, date_range, col1, col2, main_status_prop, columns_proposals, df_spots) df_l = count_statuses(df_loc, date_range, col1, col3, main_status_loc, columns) df_lu = count_statuses(df_unit, date_range, col1, col3, main_status_loc, columns, df_spots) df_lu['CREATED_to_scan'] = df_lu['CREATED'] - df_lu['CREATED_scanned'] if city is not None: writer = pd.ExcelWriter('status_%s_%s_%s.xlsx' % (city, start_date, end_date)) else: writer = pd.ExcelWriter('status_%s_%s.xlsx' % (start_date, end_date)) df_l_prop.to_excel(writer, 'location_proposals') df_lu_prop.to_excel(writer, 'location_unit_proposals') df_l.to_excel(writer, 'locations') df_lu.to_excel(writer, 'location_units') writer.save()