Esempio n. 1
0
class FullscreenWindow:
    def __init__(self):
        self.tk = Tk()
        self.tk.configure(background='black')
        self.topFrame = Frame(self.tk, background='black')
        self.bottomFrame = Frame(self.tk, background='black')
        self.topFrame.pack(side=TOP, fill=BOTH, expand=YES)
        self.bottomFrame.pack(side=BOTTOM, fill=BOTH, expand=YES)
        self.state = False
        self.tk.bind("<Return>", self.toggle_fullscreen)
        self.tk.bind("<Escape>", self.end_fullscreen)
        # weather
        self.weather = Weather(self.topFrame)
        self.weather.place(x=0, y=5, anchor=NW, width=700, height=400)
        # Date
        self.date = Date(self.topFrame)
        self.date.place(x=1015, y=10, anchor=NE, width=350, height=90)
        # Day
        self.day = Day(self.topFrame)
        self.day.place(x=860, y=10, anchor=NE, width=300, height=90)
        # clock
        self.clock = Clock(self.topFrame)
        self.clock.place(x=940, y=60, anchor=NE, width=250, height=90)
        #Seconds
        self.sec = Sec(self.topFrame)
        self.sec.place(x=1015, y=60, anchor=NE, width=80, height=85)
        # news
        self.news = News(self.bottomFrame)
        self.news.pack(side=LEFT, anchor=S, padx=0, pady=10)
        # Facial rec
        #self.FacialRecognition = News(self.bottomFrame)
        #self.FacialRecognition.pack(side=LEFT, anchor=N, padx=100, pady=60)
        # calender
        self.calender = Calendar(self.topFrame)
        self.calender.place(x=1015, y=150, width=250, anchor=NE)
        # calender Time
        self.calenderTime = CalendarTime(self.topFrame)
        self.calenderTime.place(x=850, y=172, width=250, anchor=NE)
        #Traffic
        self.traffic = Traffic(self.topFrame)
        #Launch
        self.launch = Launch(self.topFrame)
        #crypto name
        self.crypto = Crypto(self.topFrame)
        self.crypto.pack(side=TOP, anchor=NE)
        #Crypto Time
        self.cryptoPrice = CryptoPrice(self.topFrame)
        self.cryptoPrice.pack(side=TOP, anchor=NE)
        #camera
        s = FacialRec()

    def toggle_fullscreen(self, event=None):
        self.state = not self.state  # Just toggling the boolean
        self.tk.attributes("-fullscreen", self.state)
        return "break"

    def end_fullscreen(self, event=None):
        self.state = False
        self.tk.attributes("-fullscreen", False)
        return "break"
Esempio n. 2
0
def generate_Day(
    breakfast_alt_list, breakfast_list, main_dish_alt_list, main_dish_list, args_from_ui, Day1=None, Day2=None
):
    """
    Generate a day with three meals under user-specified requirements. 
    Ideally not repeating major ingredients from the previous 2 days.
    
    Inputs:
        4 lists of available recipes
        args_from_ui: a dict of user-specified parameters
        Day1: the day object for the previous day, optional
        Day2: the day object for the day before yesterday, optional
    
    Returns the generated day object
    """

    # Set a default calories range if none is given
    if "calories_per_day" not in args_from_ui:
        args_from_ui["calories_per_day"] = [1, 5000]

    # first initialization
    day = Day(args_from_ui["calories_per_day"])
    total_trial = 0

    # while calories requirement not met
    while total_trial < MAX_TRIAL_BEFORE_IGNORING_CALORIES and not day.is_qualified():
        total_trial += 1
        day = Day(args_from_ui["calories_per_day"])
        used_ingredients = set()
        if Day1:
            used_ingredients.update(set(Day1.major_ingredients))
        if Day2:
            used_ingredients.update(set(Day2.major_ingredients))

        day, used_ingredients, breakfast_from_alt = set_meal(
            day, "breakfast", breakfast_list, breakfast_alt_list, used_ingredients
        )
        day, used_ingredients, lunch_from_alt = set_meal(
            day, "lunch", main_dish_list, main_dish_alt_list, used_ingredients
        )
        day, used_ingredients, dinner_from_alt = set_meal(
            day, "dinner", main_dish_list, main_dish_alt_list, used_ingredients, day.lunch
        )

    # at this point meals are already set regardless of whether meeting calories limits
    breakfast_list, breakfast_alt_list, main_dish_list, main_dish_alt_list = update_recipe_lists(
        day,
        (breakfast_list, breakfast_alt_list, main_dish_list, main_dish_alt_list),
        [breakfast_from_alt, lunch_from_alt, dinner_from_alt],
    )
    return day
Esempio n. 3
0
 def __init__(self):
     self.data = {}
     rawData = json.load(open(r'data.json', 'r', encoding="utf-8"))
     for day in rawData:
         tempDay = Day(day['month'], day['day'], day['weekday'])
         for event in day['event']:
             tempEvent = Event(event['time'], event['place'],
                               event['celebration'], event['description'])
             for guest in event['aGuestList']:
                 tempGuest = Guest(guest['title'], guest['surname'],
                                   guest['name'], guest['patronymic'],
                                   guest['sequenceNumber'])
                 tempEvent.addAGuestList(tempGuest)
             tempDay.addEvent(tempEvent)
         self.data[str(day['day']) + ' ' + day['month']] = tempDay
Esempio n. 4
0
def addClass():
    """
    Method add class takes user inputs and adds a class to the ongoing list of classes, sorted
    """
    print(
        "\nEnter classes by day. For example enter all your Monday classes first, then Tuesday, etc."
    )
    print(
        "When asked to put in class meeting times enter in 24 hr format. Example: 1:00 p.m = 1300 8:00 a.m = 0800"
    )

    day = input("Day of Class: ")
    while not properDayInput(
            day
    ):  #While format is not correct, persist on getting the correct entry
        print("Please enter a day of the week")
        day = input("Day of Class: ")

    className = input("Name of Class: ").strip()
    if className == "":  #If user does not put in a field (or just a bunch of spaces)
        className = "EMPTY ENTRY!"

    startTime = input("Starting Time: ")
    while not properTimeInput(startTime):
        startTime = input("StartingTime: ")

    endTime = input("Ending Time: ")
    while not properTimeInput(endTime):
        endTime = input("Ending Time: ")

    class_ = Class(className, Day(day), startTime,
                   endTime)  #Creating class object from user's entries
    for i in range(0, len(classes),
                   1):  #Checking for overlaping/duplicate classes
        classInList = classes[i]
        if (class_ == classInList):
            print("\nThere is a scheduling conflict with class: " +
                  str(classInList) + " and " + str(class_))
            print(
                "The class you just entered was not added to schedule. Please try another entry or edit an existing class\n"
            )
            return  #Break out of function

    classes.append(Class(className.upper(), Day(day), startTime, endTime))
    print("\nClass added to schedule")
    classes.sort()
    delay()
    clearTerminal()
Esempio n. 5
0
def main():
    # Getting all the unique classes from all the Periods
    periodOneClasses = getClassesfromPeriod("Period 1 Class")
    periodTwoClasses = getClassesfromPeriod("Period 2 Class")
    periodThreeClasses = getClassesfromPeriod("Period 3 Class")
    periodFourClasses = getClassesfromPeriod("Period 4 Class")

    #Adding all the courses in the periods
    Period1Classes = addCourses(periodOneClasses)
    Period2Classes = addCourses(periodTwoClasses)
    Period3Classes = addCourses(periodThreeClasses)
    Period4Classes = addCourses(periodFourClasses)

    #Now adding students according to grades in each class
    addPeople(1, Period1Classes)
    addPeople(2, Period2Classes)
    addPeople(3, Period3Classes)
    addPeople(4, Period4Classes)

    #Making a new Day variable which has all the periods with all classes inside them
    newDay = Day(Period1Classes, Period2Classes, Period3Classes,
                 Period4Classes)

    FinalAnswer = set([])
    #Making a new excel sheet using the data
    for period in newDay.periods:
        for row in period[-1]:
            for test in row.peopleInClass:
                FinalAnswer.add(test)

    test = sorted(FinalAnswer, key=element)
    for row in test:
        print(row.id, row.fname, row.sickness)
Esempio n. 6
0
def get_timetable(school, user, password):
    # App4 Timetable Url with school identifier
    url = "http://{}.app4.ws/portal/timetable.php".format(school)
    # Creates a browser. Then opens the Timetable Url which leads to a login page
    br = mechanicalsoup.StatefulBrowser()
    br.open(url)
    # Log in using user and password
    br.select_form(nr=0)
    br["txtLoginUserID"] = user
    br["txtLoginPassword"] = password
    br.submit_selected()
    # With Permission reopens the Timetable page
    br.open(url)
    # Makes a soup of the pages html
    page = br.get_current_page()
    # Gets everyday's html
    daysRaw = page.find_all('td', {"width": '18%'})
    # Empty Container to be populated with day objects
    timetable = []
    for day in daysRaw:
        # Variables with Day args
        day_name = day.find_all("td", {"class": re.compile("^ttdark")})[0].string.extract()
        day_id = daysRaw.index(day)+1
        # Appends a Day Object and Passes an empty list to be populated bt Session Objects, day_name and day_id
        timetable.append(Day([], day_name, day_id))
        # List with all day's sessions html
        sessions = day.find_all("td", {"class": re.compile("^tt")})
        # Iterates through all sessions appending a Session object to each Day object
        for session in sessions:
            # If session is a session continue
            if len(session.find_all("td")) > 0:
                # Variables with Session args
                session_number = int(session.find_all("td")[0].string.extract())
                session_code = session.find_all("td")[1].find_all("span")[0].string.extract()
                # List of teacher, room and time
                session_periph = session.find_all("td")[1].find_all("span")[1].get_text("|").split("|")
                # Appends a Session Object to current day (i.e, days[-1])
                # Checks if it is not an empty session (e.g, Lunch, Community Service)
                if len(session_periph) > 2:
                    timetable[-1].append(
                        Session(
                            session_number,
                            session_code,
                            session_periph[0],
                            str(session_periph[1]).strip(),
                            session_periph[2]
                        )
                    )
                # If it is an empty session do not pass a teacher or room
                else:
                    timetable[-1].append(
                        Session(
                            session_number,
                            session_code,
                            session_periph[0],
                            None,
                            None
                        )
                    )
    return timetable
Esempio n. 7
0
def main():
    # Getting all the unique classes from all the Periods
    periodOneClasses = getClassesfromPeriod("Period 1 Class")
    periodTwoClasses = getClassesfromPeriod("Period 2 Class")
    periodThreeClasses = getClassesfromPeriod("Period 3 Class")
    periodFourClasses = getClassesfromPeriod("Period 4 Class")

    #Adding all the courses in the periods
    Period1Classes = addCourses(periodOneClasses)
    Period2Classes = addCourses(periodTwoClasses)
    Period3Classes = addCourses(periodThreeClasses)
    Period4Classes = addCourses(periodFourClasses)

    #Now adding students according to grades in each class
    addPeople(1, Period1Classes)
    addPeople(2, Period2Classes)
    addPeople(3, Period3Classes)
    addPeople(4, Period4Classes)

    #Making a new Day variable which has all the periods with all classes inside them
    newDay = Day(Period1Classes, Period2Classes, Period3Classes,
                 Period4Classes)

    #Making a new excel sheet using the data
    for period in newDay.periods:
        for row in period:
            for test in row.peopleInClass:
                print(test.id, test.sickness)
Esempio n. 8
0
def random_timetable(teachers, audiences, subjects, specialities):
    current_timetable = []
    for speciality in specialities:
        days_in_week = []
        for day in day_of_week:
            lessons_in_day = []
            num_of_lessons = random.choice(range(1, 7))
            for numb in range(num_of_lessons):
                num_of_lesson = random.choice(range(1, 7))
                type_of_lesson = random.choice(l_or_p)
                subject = random.choice(subjects)
                teacher = random.choice(teachers)
                audience = random.choice(audiences)
                if type_of_lesson == 'practice':
                    group = random.choice([1, 2])
                    lesson = Lesson(num_of_lesson, type_of_lesson, subject,
                                    teacher, audience, group)
                else:
                    lesson = Lesson(num_of_lesson, type_of_lesson, subject,
                                    teacher, audience)
                lessons_in_day.append(lesson)
            current_day = Day(day, lessons_in_day)
            days_in_week.append(current_day)
        current_week = Week(speciality, days_in_week)
        current_timetable.append(current_week)
    timetable = Timetable(current_timetable)
    return timetable
Esempio n. 9
0
def editClass():
    """
    Method edit class accepts user inputs to change fields of a user-selected class in the list
    """
    noChangesMade = True  #Keeps track if changes were made at all
    displayClassList(True)
    if len(classes) == 0:  #if no classes, return
        return

    print("\nWhich class would you like to edit?")
    classIndex = input("Choice: ")
    while not properMenuChoice(classIndex):
        classIndex = input("Choice: ")
    if int(classIndex) == len(
            classes
    ) + 1:  #If the user selected the "none" option from displayClassList
        return
    classIndex = int(classIndex)

    class_ = classes[classIndex - 1]
    print(
        "\nEnter the data for the class. Press <Enter/Return> to leave unchanged."
    )

    newClassDay = input("Enter new day for class: ")
    if (newClassDay.islower()
            or newClassDay.isupper()):  #If the user put in some kind of string
        while not properDayInput(
                newClassDay):  #Make sure that it is a valid day of the week
            newClassDay = input("Please enter a day of the week: ")
        class_.setDay(Day(newClassDay))
        noChangesMade = False

    newClassName = input("Enter new name for class: ")
    if not newClassName.strip() == "":  #Check for all blanks/spaces
        class_.setName(newClassName.upper())
        noChangesMade = False

    newStartTime = input("Enter new starting time for class: ")
    if not newStartTime.strip() == "":  #Check for entry
        while not properTimeInput(newStartTime):  #persist for proper entry
            newStartTime = input(
                "Enter a valid new starting time (24 hr format): ")
        class_.setstartTime(newStartTime)
        noChangesMade = False

    newEndTime = input("Enter new ending time for class: ")
    if not newStartTime.strip() == "":
        while not properTimeInput(newEndTime):
            newEndTime = input(
                "Enter a valid new ending time (24 hr format): ")
        class_.setendTime(newEndTime)
        noChangesMade = False

    if noChangesMade:
        print("\n No Changes Made")
        delay()
    else:
        print("\nChanges Made")
        delay()
Esempio n. 10
0
def load_class_list():
    """
    Method load_class_list reads class information from a csv file and adds classes to the
    classes list and the classStringList
    """
    try:
        firstLine = True  #keeping track of the first line in the csv file (the header)
        index = 0
        if os.access("mySchedule.csv", os.F_OK):  #If the file exists
            f = open("mySchedule.csv")
            for row in csv.reader(f):
                if firstLine:
                    firstLine = False
                    continue  #skip first line
                classStringList.insert(
                    index,
                    row)  #load file to classString list and to classes list
                classes.insert(
                    index,
                    Class(row[1], Day(row[0]), formatFromCSV(row[2]),
                          formatFromCSV(row[3])))
                index += 1
            f.close()
    except Exception as e:
        print("Exception found:" + e)
Esempio n. 11
0
def read_db(db):
    # Clears timetable so it can be overwritten
    timetable = []
    # Loops over timetable every day and
    for day in db.all():
        # Creates a local empty lsit to be populated with database session
        sessions = []
        # Appends a Session to current day passing session number, code, teacher, room, time
        for session in day['sessions']:
            sessions.append(Session(
                session['number'],
                session['code'],
                session['teacher'],
                session['room'],
                session['time']
            ))
        # Appends a Day object passing session, day_name, day_id
        timetable.append(
            Day(
                sessions,
                day['day_name'],
                day['day_id']
            )
        )
    return timetable
Esempio n. 12
0
def read_from_file(filename):
    file = open(filename, "r+")
    list1 = []
    for line in file:
        parts = line.split(",", 2)
        list1.append(Day(int(parts[0]), parts[1], parts[2]))
    file.close()
    return list1
Esempio n. 13
0
def calculate_max_and_average(list_days):
    max_mood = Day(0, "01-01-10", "Shat ma self")
    worst_mood = Day(500000, "01-01-10", "Shat ma self")
    counter = 0
    sum_of_moods = 0
    for d in list_days:
        if d.mood > max_mood.mood:
            max_mood = d

        if d.mood < worst_mood.mood:
            worst_mood = d

        sum_of_moods += d.mood
        counter += 1
    average_mood = sum_of_moods / counter
    return "==================STATS=================="+"\nBEST MOOD\nDay: " + max_mood.date + "\tMood: " \
           + str(max_mood.mood) + "\nComment of that day: " + max_mood.comment+"\nWORST MOOD\nDay: "\
           + worst_mood.date + "\tMood: " + str(worst_mood.mood) + "\nComment of that day: "\
           + worst_mood.comment + "\nAVERAGE MOOD: "+str(average_mood)
Esempio n. 14
0
    def getDays(self):
        self.conn.execute_query('SELECT * FROM Edu_Days')
        days = {}
        for row in self.conn:
            day = Day(row['ID'], row['Title'])
            days[row['ID']] = day

        self._days = days
        print 'Days: ', len(self._days)
        return days
Esempio n. 15
0
    def addReminder(self, reminder):

        year = reminder.when.year
        month = reminder.when.month
        day = reminder.when.day

        # insert new entries into the calendar if need be
        if year not in self.calendar:
            self.calendar[year] = dict()

        if month not in self.calendar[year]:
            self.calendar[year][month] = dict()

        if day not in self.calendar[year][month]:
            self.calendar[year][month][day] = Day()

        self.calendar[year][month][day].addReminder(reminder)
Esempio n. 16
0
    def __init__(self, name):
        self.name = name
        self.months = []
        monthNames = [
            'january', 'february', 'march', 'april', 'may', 'june', 'july',
            'august', 'september', 'october', 'november', 'december'
        ]
        weekdays = [
            'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
            'Saturday'
        ]

        # An algorithm to determine if it is a leap year, adapted from the
        # logic shown in this wikipedia page:
        # Accessed September, 2016
        # https://en.wikipedia.org/wiki/Leap_year#Algorithm
        if (name % 4 == 0 and name % 100 != 0) or name % 400 == 0:
            monthLengths = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        else:
            monthLengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

        # An algorithm to determine the day of the week of the first day
        # of the year, adapted from the algortihm on the "disparate variation"
        # of Gauss's algorithm, shown here:
        # Accessed September, 2016
        # https://en.wikipedia.org/wiki/Leap_year#Algorithm
        y = (name % 100) - 1
        c = name // 100
        weekOffset = int((2.4 + name + y / 4 + c / 4 - 2 * c) % 7)

        dayCount = 0
        for i in range(12):
            days = []
            for j in range(monthLengths[i]):
                days.append(
                    Day(weekdays[(dayCount + weekOffset) % 7], j + 1, None))
                dayCount += 1
            self.months.append(Month(monthNames[i], days, self))

        for i in range(12):
            if i > 0:
                self.months[i].setPrev(self.months[i - 1])
            if i < 11:
                self.months[i].setNext(self.months[i + 1])
Esempio n. 17
0
def readFile():
    # open notes.txt file
    with open("res/notes.txt", "r") as f:
        days = []
        skip_first = False
        list_ex = []
        line = f.readline().rstrip('\n')
        while 1:
            if 'new' in line:
                print('\033[94m' + "New day!" + "\033[0m")
                if skip_first is True:
                    day = Day(line, list_ex)
                    days.append(day)
                skip_first = True
                line = f.readline().rstrip('\n')
            # ex name
            if ':' in line:
                reps = 0
                ex_time = line.split(":")
                ex = Exercise(ex_time[0], ex_time[1])
                while 1:
                    line = f.readline().rstrip('\n')
                    # Set
                    if ('[' in line) & (']' in line):
                        reps = reps + 1
                        set_info = re.split('x |- ', line)
                        slice_object = slice(4, -1)
                        # Set has no weight
                        if len(set_info) == 2:
                            sets = Set(int(set_info[0][slice_object]),
                                       int(set_info[1]))
                        else:
                            sets = Set(int(set_info[0][slice_object]),
                                       int(set_info[2]), int(set_info[1]))
                        ex.addSet(sets)
                    # save exercise
                    else:
                        ex.setNReps(reps)
                        list_ex.append(ex)
                        break
            if line == '':
                break
    f.close()
    return days
Esempio n. 18
0
 def __init__(self):
     """
     Initializes the Week with 7 objects "Day" corresponding to the 7 days of the week
     ----------
     Parameters :
         - one Day per day of the week
     Returns :
         No return.
     """
     self.monday = Day("Monday")
     self.tuesday = Day("Tuesday")
     self.wednesday = Day("Wednesday")
     self.thursday = Day("Thursday")
     self.friday = Day("Friday")
     self.saturday = Day("Saturday")
     self.sunday = Day("Sunday")
     self.daysList = [
         self.monday, self.tuesday, self.wednesday, self.thursday,
         self.friday, self.saturday, self.sunday
     ]
Esempio n. 19
0
    def GetWeather(self, api_key):
        units = 'imperial'
        url = f'https://api.openweathermap.org/data/2.5/onecall?lat={self.latitude}&lon={self.longitude}&appid={api_key}&units={units}'

        response = requests.get(url)

        if response.status_code == 200:

            data = json.loads(response.content.decode('utf-8'))

            # create a Day object for each Day node in JSON response and store in list at self.days
            for day in data['daily']:
                # date only
                d = datetime.fromtimestamp(day['dt']).date()
                r = datetime.fromtimestamp(day['sunrise'])
                s = datetime.fromtimestamp(day['sunset'])
                self.days.append(Day(d, r, s))

            # create an Hour object for each Hour node in JSON response to falls within window
            for hour in data['hourly']:
                n = datetime.now().replace(microsecond=0, second=0, minute=0)
                # date only
                d = datetime.fromtimestamp(hour['dt'])
                r = None
                s = None

                # get hour difference between JSON response datetime and datetime.now()
                delta = d - n
                delta_to_hours = (delta.total_seconds() / 60) / 60

                # if delta falls within walk window, create Hour object, score and add to self.hours
                if delta_to_hours >= self.start and delta_to_hours <= self.end:
                    for day in self.days:
                        if day.date == d.date():
                            r = day.sunrise
                            s = day.sunset
                    h = Hour(hour, r, s)
                    h.Score()
                    self.hours.append(h)
Esempio n. 20
0
 def __init__(self):
     self.week = []
     for i in range(5):
         self.week.append(Day())
Esempio n. 21
0
 def setStartTime(self, day, start):
     day = Day.getName(day)
     self.startTime = day + str(start)
Esempio n. 22
0
from environment import *
from time_constraint import *
from room_constraint import *
from Day import Day
from LectureRoom import LectureRoom
from csv_process import writeCsvFile
import random

dayDomain = [Day(i) for i in range(5)]
timeDomain = [9 + i for i in range(8)]

# 담헌 실학관을 제해준다.
theoryRoomDomain = roomsForTheory[:-1]
practiceRoomDomain = roomsForPractice


def rotate(lst, n):
    return lst[-n:] + lst[:-n]


# 강의시간을 배정한다.
# @param
# subject : 과목
# room : 강의실
# @return
# 배정에 성공한 경우 True를 반환한다.
def assignTime(subject, room):
    random.shuffle(dayDomain)

    for day in dayDomain:
        # 실습 과목일 경우, 이론 수업과 다른 날짜인가?
Esempio n. 23
0
def isSameAsTheory(subject, day):
    theory = theorySubjects[subject.ID]
    time = theory.startTime
    return Day.getName(day) == time[0]
Esempio n. 24
0
import simpy

from World import World
from Day import Day
from BroadcastPipe import BroadcastPipe

world = None
day_duration = 30
night_duration = 30


def clock(env, tick):
    while True:
        print("Tick:", env.now)
        yield env.timeout(tick)


if __name__ == "__main__":

    env = simpy.rt.RealtimeEnvironment(factor=1)
    proc = env.process(clock(env, 1))

    dayCycle_pipe = BroadcastPipe(env)
    dayCycle = Day(env, day_duration, night_duration, dayCycle_pipe)
    world = World(env, dayCycle_pipe)

    env.run(until=proc)
Esempio n. 25
0
def get_day_list(article_folder_path):
    day_list = []
    for json_path in Functions.get_path_list_from_directory(
            article_folder_path):
        day_list.append(Day(json_path))
    return day_list
Esempio n. 26
0
def get_day(tt, day_name, week):
    days = list(filter(lambda day: day.day_name == day_name, tt))
    try:
        return days[0] if days[0].week_id == week else days[1]
    except IndexError:
        return Day([], day_name, 0)