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 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 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 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 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
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)
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, 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 __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 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 __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 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 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 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 __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 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 __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 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 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 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
parser = argparse.ArgumentParser() parser.add_argument('csv_path') parser.add_argument('roster_path') parser.add_argument('output_path') args = parser.parse_args() csv_pth = args.csv_path roster_pth = args.roster_path out_path = args.output_path roster = [] #grab the roster file and create a roster list with open(roster_pth) as r_file: for line in r_file: roster.append(line) d1 = Day("Tuesday") d1.insertTime(10) d1.insertTime(13) d2 = Day("Wednesday") d2.insertTime(10) d2.insertTime(14) s1 = Student("Hope, Bob", "*****@*****.**") days = [d1, d2] filters1 = {} filters1['Meeting Times'] = days s1.setFilters(filters1) s2 = Student("Jensen, Emily", "") days = [d2] filters2 = {}
def __init__(self): self.history_list = [] self.a_day = Day()
import datetime from business import Business from day import Day from days import Days from datetime_period import DateTimePeriod from util import next_weekday # Opening hours for each week day. If not specified, it is considered closed days = [ # Standard days with fixed opening hours Day(Days.MONDAY, [['09:00', '14:00'], ['14:45', '18:00']]), Day(Days.TUESDAY, [['09:00', '14:00'], ['14:45', '18:00']]), Day(Days.WEDNESDAY, [['09:00', '14:00'], ['14:45', '18:00']]), Day(Days.THURSDAY, [['09:00', '14:00'], ['14:45', '18:00']]), Day(Days.FRIDAY, [['09:00', '14:00'], ['14:45', '16:45']]), Day(Days.SATURDAY, [['09:00', '10:00'], ['11:00', '12:00'], ['13:00', '14:00'], ['15:00', '16:45']]), ] # Create a new Business instance business = Business(days) if False: nextDate = business.closest(datetime.datetime(2015, 5, 11, 10, 0)) print nextDate if False: start = datetime.datetime(2015, 5, 11, 10, 0) end = datetime.datetime(2015, 5, 14, 10, 0)
def day(self, d): assert isinstance(d, basestring) self._day = Day(d) self.conference.get_day(self._day)
from datetime import date from email.message import EmailMessage from general import DAYS, URLS, WORKDAYS from day import Day from util import box EMAIL_ADRESS = os.environ.get("GMAIL_USER") EMAIL_PASSWORD = os.environ.get("GMAIL_PASS") RECEIVER = "*****@*****.**" body = "" for d in WORKDAYS: body += box(d.upper()) body += Day(d, URLS).summary body += "\n \n \n" # basic email parameters today = date.today() week_nbr = today.isocalendar()[1] subject = f"Mensa plan for week {week_nbr}" ### set up message with EmailMessage msg = EmailMessage() msg["Subject"] = subject msg["From"] = EMAIL_ADRESS msg["To"] = RECEIVER msg.set_content(body) # msg.add_alternative(