def initDays(config: {}) -> [Day]: days = [Day.fromDict(d) for d in load("days")] # DO NOT Remove old days. They are necessary to properly recreate the schedule for past days # Create new days to remain at 1000 day threshold (20 for debug) # dayCount = 1000 # Real dayCount = 100 # Debug daysToCreate = dayCount - len(days) if days: startDate = days[-1].date else: startDate = arrow.now().date() currentDate = arrow.get(startDate) # Check if the current day is missing and add it if necessary for day in days: if day.date == currentDate.date(): break else: days.append(Day(currentDate.date(), [], [])) # Fill up days to get up to dayCount for _ in range(daysToCreate): currentDate = currentDate.shift(days=1) newDay = Day(currentDate.date(), [], []) days.append(newDay) # Load config-TimeSlots onto days if they don't exist already for day in days: initDay(day, config) # Adds temporary timeslots based on config return days
def show_week(self): for i in range(0, 6): tmp_date = date.today() + timedelta(days=i) apmts = Outlooker.get_events_start_from(tmp_date) day = Day(self, tmp_date, apmts) day.update_label() self.centralWidget.layout().addWidget(day)
class Lemonadestand: def __init__(self): self.glasses = 0 self.price = 0 self.day = Day() self.player = Player() self.lemonadeCost = self.getLemonadeCost(self.day.daynumber) def makeLemonade(self): self.glasses = self.day.makeGlasses() self.price = self.day.setPrice() print(self.glasses, self.price) def showMorningReport(self): print("Today is Day: " + str(self.day.daynumber)) self.day.todaysWeather.displayWeather() self.player.displayAssets() self.displayLemonadeCost(self.lemonadeCost) def displayLemonadeCost(self, cost): print("Cost of Lemonade is " + str(cost) + " cents a glass.") def getLemonadeCost(self, daynumber): if daynumber < 3: answer = 2 else: answer = 4 return answer
class HistoryInterface: ''' This class implements an interface to an external file, which contains a list of gone WorkingDays - that is: Days. Methods are offered for printing out some of those days. ''' HISTORY_FILE = 'history.json' # The maximum number of working days stored in the history file: MAX_DAYS = 30 def __init__(self): self.history_list = [] self.a_day = Day() def load_history_data(self): '''Loads the history data from the disk.''' try: with open(HistoryInterface.HISTORY_FILE, 'r') as fh: self.history_list = json.load(fh) except FileNotFoundError: self.history_list = [] def dump_history_data(self): '''Saves history data into the disk''' with open(HistoryInterface.HISTORY_FILE, 'w') as fh: json.dump(self.history_list, fh, indent=4, separators=(',', ': ')) def show_history_data(self): '''Shows all the days in the history file.''' self.load_history_data() if self.history_list == []: print('\n\tNo history data is available at this point.\n') return for i, working_day in enumerate(self.history_list): # working_day is a dict containing data of one working day. # Suck that data into the instance self.a_day of the class Day. self.a_day.dict_to_day(working_day) print(f'History day number {i}:') print(self.a_day) def append_working_day(self, w_day): ''' Loads the history data from the disk. Appends a new working day to that data. Dumps the updated history data back into the disk. w_day is an instance of the class WorkingDay. ''' #print('\nAppending the following working day into the history file:\n') #print(w_day) self.load_history_data() if len(self.history_list) >= HistoryInterface.MAX_DAYS: # Remove the oldest day to make room for the newest one self.history_list.pop(0) # Make a dict of the new day to be appended into self.history_list working_day = w_day.day_to_dict() self.history_list.append(working_day) self.dump_history_data()
def initialization(self): day = self.first_day_of_month for guard_day in range(self.days_of_month): if guard_day == 0: self.guards_program.append(Day(guard_day, 0, "-")) else: self.guards_program.append(Day(guard_day, day, "-")) day += 1 if day == 7: day = 0
def console_add_record(a_user): """Allows the user to add a Record to a day. Calls the console_create_record function to do so. :param a_user: User """ good_format = False # Will not allow the user to continue without a valid date format. while not good_format: date_string = input("Enter date for record (MM/DD/YYYY, 0 for today: ") # If the user entered a date of their own, check it for validity. if date_string != "0": try: date_obj = datetime.datetime.strptime(date_string, '%m/%d/%Y').date() good_format = True except ValueError: print("Accepted inputs are 0 or the format MM/DD/YYYY. Try again.") # Otherwise, set the date to today's date. else: good_format = True date_obj = datetime.datetime.today().date() current_day = Day(date_of_day=date_obj) # Create a new Day object. # Attempt to insert the day into the user's doubly-linked list of Days. if not a_user.insert_day_in_list(current_day): # If the date was already there, find the appropriate day instead of inserting a new one. current_day = a_user.last_day while current_day.date_of_day != date_obj: current_day = current_day.previous_day # Display menu for adding records. print("Add record for:") print("1. Morning") print("2. Afternoon") print("3. Evening") print("4. Back") choice = int(input("\nEnter number: ")) while choice < 1 or choice > 4: print("Invalid entry.") choice = int(input("Enter number:")) if choice != 4: if choice == 1: current_day.morning_record = console_create_record() elif choice == 2: current_day.afternoon_record = console_create_record() else: current_day.evening_record = console_create_record()
def get_day(date): db_connection = get_db_connection() cursor = db_connection.cursor() q = ''' SELECT * FROM day WHERE substr(date, 1, 10) = ? ''' result = cursor.execute(q,(date,)).fetchone() if result != None: if len(result) > 8: day = Day(result[1],result[2],result[3],result[4],result[5],result[6],result[7],result[8],result[0]) else: day = Day(result[1],result[2],result[3],result[4],result[5],result[6],result[7],None,result[0]) db_connection.close() return day else: db_connection.close() return None
def update_days_list(self): self.daysList = [] # Get days count for i in range(len(self.loadList[0].pattern)): expenses = 0 profit = 0 consumption = 0 production = 0 for load in self.loadList: pattern = load.pattern # TODO Something smart (stupid median right now) if load.type == 'solar' or load.type == 'windgen': production += float(pattern[i][2]) expenses += load.money else: consumption += float(pattern[i][2]) profit += load.money * float(pattern[i][2]) # TODO Set exchange cost? if production > consumption: profit += (production - consumption) * self.commonExchangeCost else: expenses += (consumption - production) * self.commonExchangeCost self.daysList.append(Day(expenses, profit, consumption, production))
def randomize(self): for d in range(self.num_days): workerA = choice(self.workers) workerB = choice(self.workers) workerC = choice(self.workers) day = Day(workerA, workerB, workerC) self.schedule[d] = day
class ConsumerDB(saxutils.DefaultHandler): def __init__(self, from_time=None, to_time=None): self.search_from_time = from_time self.search_to_time = to_time self.days = {} def startElement(self, name, attrs): self.cur_val = "" if name == "day": date = attrs.get("date", None) date = xml.utils.iso8601.parse(date) if self.search_from_time and date < self.search_from_time: return if self.search_to_time and date > self.search_to_time: return date = datetime.date.fromtimestamp(date) self.cur_day = Day(date) elif name == "food": ftime = attrs.get("time", None) ftime = xml.utils.iso8601.parse(ftime) if self.search_from_time and ftime < self.search_from_time: return if self.search_to_time and ftime > self.search_to_time: return self.cur_food = Food(attrs.get("name", None)) time = datetime.datetime.fromtimestamp(ftime, tz.LocalTimezone()) self.cur_food.set_time(time) def characters(self, chr): self.cur_val = self.cur_val + chr def endElement(self, name): if name == "day": self.days[self.cur_day.date.ctime()] = self.cur_day elif name == "food": self.cur_day.add_food(self.cur_food) elif name == "weight": self.cur_day.set_weight(atof(self.cur_val)) elif name == "quantity": self.cur_food.quantity = atof(self.cur_val) elif name == "energy": self.cur_food.energy = atoi(self.cur_val) def getDays(self): return self.days
class ConsumerDB(saxutils.DefaultHandler): def __init__(self, from_time = None, to_time = None): self.search_from_time = from_time self.search_to_time = to_time self.days = {} def startElement(self, name, attrs): self.cur_val = "" if name == "day": date = attrs.get("date", None) date = xml.utils.iso8601.parse(date) if self.search_from_time and date < self.search_from_time: return if self.search_to_time and date > self.search_to_time: return date = datetime.date.fromtimestamp(date) self.cur_day = Day(date) elif name == "food": ftime = attrs.get("time", None) ftime = xml.utils.iso8601.parse(ftime) if self.search_from_time and ftime < self.search_from_time: return if self.search_to_time and ftime > self.search_to_time: return self.cur_food = Food(attrs.get("name", None)) time = datetime.datetime.fromtimestamp(ftime, tz.LocalTimezone()) self.cur_food.set_time(time) def characters(self, chr): self.cur_val = self.cur_val + chr def endElement(self, name): if name == "day": self.days[self.cur_day.date.ctime()] = self.cur_day elif name == "food": self.cur_day.add_food(self.cur_food) elif name == "weight": self.cur_day.set_weight(atof(self.cur_val)) elif name == "quantity": self.cur_food.quantity = atof(self.cur_val) elif name == "energy": self.cur_food.energy = atoi(self.cur_val) def getDays(self): return self.days
def startElement(self, name, attrs): self.cur_val = "" if name == "day": date = attrs.get("date", None) date = xml.utils.iso8601.parse(date) if self.search_from_time and date < self.search_from_time: return if self.search_to_time and date > self.search_to_time: return date = datetime.date.fromtimestamp(date) self.cur_day = Day(date) elif name == "food": ftime = attrs.get("time", None) ftime = xml.utils.iso8601.parse(ftime) if self.search_from_time and ftime < self.search_from_time: return if self.search_to_time and ftime > self.search_to_time: return self.cur_food = Food(attrs.get("name", None)) time = datetime.datetime.fromtimestamp(ftime, tz.LocalTimezone()) self.cur_food.set_time(time)
def read_day_input(date): total = read_positive_number("Enter total number of the tasks in your todo list: ") completed = read_positive_number("Out of %d, how many did you complete? " % total , total) social = read_rating_value("How satisfied are you with your social activities today?\n") health = read_rating_value("How satisfied are you with your health activities today?\n") overall = read_rating_value("Your overall rate for your day?\n") note = input(Fore.BLUE + "Any final note? (press enter directly if you have nothing) " + Style.RESET_ALL) day = Day(user.id,date,total,completed,social,health,overall,note) return day
def runSimulation(self): for i in range(0, self.simulationDuration): if (i > 0): self.Blobs = self.Days[i - 1].getAliveBlobs() if (len(self.Blobs) == 0): return False currentDay = Day(i, self.maximumDayLength, self.world, self.foodQuantity, self.Blobs) self.Days.append(currentDay)
def __init__(self): self.week = {"Monday": Day("Monday"), "Tuesday": Day("Tuesday"), "Wednesday": Day("Wednesday") , "Thursday": Day("Thursday"), "Friday": Day("Friday"), "Saturday": Day("Saturday"), "Sunday":Day("Sunday"), }
def __init__(self, num_workers, num_days): self.num_workers = num_workers self.num_days = num_days self.workers = list(range(num_workers)) self.schedule = [] for d in range(num_days): day = Day(-1, -1, -1) self.schedule.append(day)
def __init__(self, days_in_a_month, daily_employee_required, holidays_in_a_month): self.days_in_a_month = days_in_a_month self.daily_employee_required = daily_employee_required self.holidays_in_a_month = holidays_in_a_month self.total_employee_required = ceil((self.days_in_a_month * self.daily_employee_required) / \ (self.days_in_a_month - self.holidays_in_a_month)) self.rooster = [Day(day + 1) for day in range(self.days_in_a_month)] self.consecutive_work_days = 5 self.week_holidays = 2 self.employees = self.create_employees(self.total_employee_required)
def save(self, _commit): # see if this entry is a duplicate before creating it. existing_entries = self.query.filter_by(timestamp=self.timestamp)\ .filter_by(content=self.content).count() if existing_entries and existing_entries > 0: # if it exists flask.current_app.logger.info("skipping entry because entry already exists") return if not self.day_id: # find the day if it exists from day import Day this_date = datetime.date.fromordinal(self.timestamp.toordinal()) this_day = Day.find(date=this_date) if not this_day: # else create the day right now this_day = Day.create(date=this_date) # now assign a value to this Entry's day self.day = this_day super(Entry, self).save()
def add_record(self, time, new_entry_window, close_on_add=True): """Strips date and Record from new_entry_window. Inserts Record into appropriate spot in the_user's doubly-linked list of Days. (adds spot if not found) :param time: int (represents Morning (1), Afternoon (2), Evening (3) :param new_entry_window: tkinter.Toplevel (specifically a _new_or_view_base window) :param close_on_add: bool (defaults to True) :return: """ # Strip date from window date = datetime.datetime.strptime( new_entry_window.date_entry_box.get(), "%m/%d/%Y").date() # Strip Record from window record_to_add = self._create_record(new_entry_window) # Creates a Day object with the appropriate date current_day = Day(date_of_day=date) # Inserts day in list (unless it is already there) if not the_user.insert_day_in_list(current_day): # Navigates to appropriate day in the list current_day = the_user.last_day while current_day.date_of_day != date: current_day = current_day.previous_day # Inserts record in appropriate spot of Day if time == 1: current_day.morning_record = record_to_add elif time == 2: current_day.afternoon_record = record_to_add elif time == 3: current_day.evening_record = record_to_add else: raise ValueError("Time of day not set.") # Closes window upon successfully adding record if close_on_add is true if close_on_add: new_entry_window.grab_release() new_entry_window.destroy()
def __init__(self, year, month): self.applicationList = [] self.categoryList = [] r = calendar.monthrange(year, month) for i in range(r[0] + 1, r[1] + 1): result = Day(year, month, i) self.applicationList = mergeAppDataList(self.applicationList, result.applicationList) self.categoryList = updateCategory(self.applicationList) self.applicationList.sort() self.categoryList.sort() self.info = "%(year)d-%(month)d" % vars()
def get_all_days(): db_connection = get_db_connection() cursor = db_connection.cursor() q = '''SELECT * FROM day ORDER BY date ASC ''' cursor.execute(q) days = cursor.fetchall() days_list = [] for day in days: d = Day(day[1],day[2],day[3],day[4],day[5],day[6],day[7],day[8],day[0]) days_list.append(d) db_connection.close() return days_list
def get_month_days(month,year): db_connection = get_db_connection() cursor = db_connection.cursor() q = '''SELECT * FROM day WHERE date BETWEEN \'%d-%02d-00\' AND \'%d-%02d-32\''''%(year,month,year,month) cursor.execute(q) days = cursor.fetchall() days_list = [] for day in days: d = Day(day[1],day[2],day[3],day[4],day[5],day[6],day[7],day[8],day[0]) days_list.append(d) db_connection.close() return days_list
def runTest(self): # Generate an XML file first. days = {} for f in range(20): curtime = datetime.datetime(2005, 6, f + 1, 0, 0, 0, 0, tz.LocalTimezone()) day = Day(curtime) day.set_weight(100) for i in range(20): food = Food("Testfood " + str(i)) food.quantity = 10 + i food.energy = 100 * i food.time = curtime day.add_food(food) days[curtime.ctime()] = day gen = ConsumerDBGenerator() gen.generate(XML_FILE, days) # Now read. db = ConsumerDB() self.parser.setContentHandler(db) self.parser.parse(XML_FILE) assert len(db.getDays()) == 20 os.remove(XML_FILE)
def initDay(day: Day, config: {}) -> None: if day.special: # No defaults are applied return if day.date.weekday() >= 5: # Weekend (Sat/Sun) lst = config["weekendTimeSlots"] else: lst = config["weekdayTimeSlots"] for timeSlotDict in lst: timeSlot = TimeSlot.fromDict( timeSlotDict, temporary=True) # These automatic TimeSlots are NOT persisted try: day.addTimeSlot(timeSlot) except ValueError: if timeSlot in day.timeSlots: pass # Already added else: # In case of overlap, avoid a crash by not applying the default timeSlot print( f"WARNING: Default TimeSlot {timeSlot} could not be added to {day} because it overlaps with an existing TimeSlot!" )
def load(self, filename): with open(filename) as f: lines = f.readlines() self.num_workers = int(lines[0].strip()) self.num_days = int(lines[1].strip()) self.schedule = [None] * self.num_days for n, d in enumerate(lines[2:]): m, e, g = map(int, d.split(",")) day = Day(m, e, g) self.schedule[n] = day self.num_workers = max([m, e, g, self.num_workers]) self.workers = list(range(self.num_workers))
def main(): args = parse_arguments() if args.test: run_tests() return assert args.day, "Need to specify day" directories = [ name for name in os.listdir(".") if os.path.isdir(name) and name == "day_{:02d}".format(args.day) ] assert len(directories) == 1 import_module("{name}.{name}".format(name=directories[0])) assert len(Day.__subclasses__()) == 1 day = Day.__subclasses__()[0]() if args.part_1: print("Solution part 1:", day.part_1()) if args.part_2: print("Solution part 2:", day.part_2())
def set_time(): period = request.args.get('period') yy = int(request.args.get('yy')) mm = int(request.args.get('mm')) dd = int(request.args.get('dd')) global the_data if period == 'year': the_data = Year(yy) elif period == 'month': the_data = Month(yy, mm) elif period == 'week': the_data = Week(yy, mm, dd) else: the_data = Day(yy, mm, dd) return the_data.info
def runTest(self): # Generate an XML file first. days = {} for f in range(20): curtime = datetime.datetime(2005, 6, f + 1, 0, 0, 0, 0, tz.LocalTimezone()) day = Day(curtime) day.set_weight(100) for i in range(20): food = Food("Testfood " + str(i)) food.quantity = 10 + i food.energy = 100 * i food.time = curtime day.add_food(food) days[curtime.ctime()] = day gen = ConsumerDBGenerator(); gen.generate(XML_FILE, days) # Now read. db = ConsumerDB() self.parser.setContentHandler(db) self.parser.parse(XML_FILE) assert len(db.getDays()) == 20 os.remove(XML_FILE)
def __init__(self, year, month, day): self.applicationList = [] self.categoryList = [] d = datetime.date.today() if day is not 0: d = datetime.date(year, month, day) d = d + datetime.timedelta(days=-d.weekday()) for i in xrange(7): theday = d + datetime.timedelta(days=i) result = Day(theday.year, theday.month, theday.day) self.applicationList = mergeAppDataList(self.applicationList, result.applicationList) self.categoryList = updateCategory(self.applicationList) self.applicationList.sort() self.categoryList.sort() self.info = (d.isoformat() + " ~ " + (d + datetime.timedelta(days=7)).isoformat())
def __init__(self, soup): self.list_day = [] for i in soup.findAll('div', {'class': 'panel panel-default'}): day = Day(i) for a in day.content.findAll(title="Teachers"): if len(a) > 1: day.teacher_list.append(a.contents[1].contents[1].string) for a in day.content.findAll("div", "address-modal-btn"): day.adress_list.append(a.contents[1].string.strip()) for a in day.content.findAll(title="Time"): day.time_list.append(a.string.strip()) for a in day.content.findAll(title="Subject"): day.subject_list.append(a.string.strip()) for a in day.content.findAll("h4", "panel-title"): day.day.append(a.string.strip()) self.list_day.append(day)
def import_data(self, filename): path = os.path.join("userdata", filename) file = open(path, 'r', encoding="utf-8") data = json.loads(file.read()) file.close() print("Importing schedule from", filename) self.events = [] for e in data["events"]: event_id = e["id"] self.events.append(Event(e, event_id)) self.schedule = [] for d in data["schedule"]: day_name = list(d.keys())[0] self.schedule.append( Day(day=day_name, events=d[day_name], user_events=self.events))
def __init__(self, filename=None): if not os.path.isdir("userdata"): os.mkdir("userdata") if os.path.isfile("userdata/schedule.json") and filename is None: filename = "schedule.json" if filename is not None: self.import_data(filename) else: print("Creating schedule from scratch") self.events = [] self.schedule = [] for _ in range(7): self.schedule.append(Day(_)) self.export()
def get_selected_day(self): # Return the day if it already exists. today_date = self.get_calendar_date() today = self.days.setdefault(today_date.ctime(), Day(today_date)) if today.get_weight() > 0: return today # If it was newly instantiated (get_weight == 0) above, inherit the # weight from the previous day. offset = datetime.timedelta(1) yesterday_date = today_date - offset yesterday = self.days.get(yesterday_date.ctime()) if yesterday: today.set_weight(yesterday.get_weight()) return today # If the previous day was not yet instantiated, get the default weight # from the form. weight = round(self.spinbutton_weight.get_value(), 2) today.set_weight(weight) return today
def run_tests(): directories = [ name for name in os.listdir(".") if os.path.isdir(name) and name.startswith("day_") ] for directory in directories: import_module("{name}.{name}".format(name=directory)) for day_class in tqdm( sorted(Day.__subclasses__(), key=lambda cls: cls.__name__)): day = day_class() if day.part_1_solution is None: tqdm.write("Part 1 of {} is not implemented!".format( day_class.__name__)) else: assert day.part_1() == day.part_1_solution, "Part 1 is broken" if day.part_2_solution is None: tqdm.write("Part 2 of {} is not implemented!".format( day_class.__name__)) else: assert day.part_2() == day.part_2_solution, "Part 2 is broken" if day.part_1_solution is not None and day.part_2_solution is not None: tqdm.write("{} is ok!".format(day_class.__name__))
def test_bad2(self): self.day = Day.check_day("saturn") correct_day = 6 self.assertEqual( correct_day, self.day)
def test_good4(self): self.day = Day.check_day("0") correct_day = 0 self.assertEqual( correct_day, self.day)
def test_good5(self): self.day = Day.check_day("4") correct_day = 4 self.assertEqual( correct_day, self.day)
def test_vgood6(self): self.day = Day.check_day("Friday") correct_day = 5 self.assertEqual( correct_day, self.day)
def test_bad1(self): self.day = Day.check_day("yestuenonlj;") correct_day = 2 self.assertEqual( correct_day, self.day)
def __init__(self): self.glasses = 0 self.price = 0 self.day = Day() self.player = Player() self.lemonadeCost = self.getLemonadeCost(self.day.daynumber)
def test_vbad0(self): self.day = Day.check_day("^%$6bhgwju5rk7!") correct_day = 0 self.assertEqual( correct_day, self.day)
def test_middle3(self): self.day = Day.check_day("10") correct_day = 7 self.assertEqual( correct_day, self.day)
def setUp(self): self.day = Day.check_day("")