Esempio n. 1
0
def convert_to_ics(event):
    ev = Event()

    # name
    if event['significant'] == 'Nazionale':
        ev.name = "Sciopero {} Nazionale".format(event['sector'])
    else:
        ev.name = "Sciopero {} {} ({})".format(event['sector'],
                                               event['region'],
                                               event['province'])

    # date and time
    ev.begin = convert_format(event['start_date'], event['start_time'])
    ev.end = convert_format(event['end_date'], event['end_time'])
    if event['start_time'] == None:
        ev.make_all_day()

    # description
    ev.description = DESCRIPTION.format(
        get_default(event, 'modality'), get_default(event, 'labor_unions'),
        get_default(event, 'categories'),
        get_default(event, 'proclamation_date'),
        get_default(event, 'date_of_receipt'))

    return ev
Esempio n. 2
0
    def export_menu_calendar(self):
        c = Calendar()
        shopping_list = []
        # create calendar event
        for _, row in self.menu.iterrows():
            e = Event()
            e.name = '[' + row['meal'].capitalize() + '] ' + row['recipe']
            t = datetime.datetime.strptime(row['date'], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(hours=2)
            e.begin = t.strftime("%Y-%m-%d %H:%M:%S")
            if row['meal'] == 'lunch':
                e.duration = {"minutes": 30}
            else:
                e.duration = {"minutes": 60}
            try:
                e.description = '\n'.join(row['ingredients']) + f"\n\n{row['notes']}"
                shopping_list.append('\n'.join(row['ingredients']))
            except TypeError:
                e.description = "Please fill the ingredientes for this recipe!"
                shopping_list.append(f"Ingredients for {row['recipe']}")
            c.events.add(e)

        e = Event()
        e.name = "Shopping List"
        e.begin = self.start_date
        e.description = '\n'.join(shopping_list)
        e.make_all_day()
        c.events.add(e)
        fname = "menus/menu_{}.ics".format(self.start_date)
        with open(fname, 'w') as my_file:
            my_file.writelines(c)
        os.system(f"open {fname}")
Esempio n. 3
0
def gen_ics():
    data = json.load(open("assets/data/timings.json"))
    os.system("rm -rf assets/calendars")
    os.system("mkdir assets/calendars")
    for offset in time_offsets:
        for fiqh in data.keys():
            os.system("mkdir assets/calendars/" + fiqh)
            c = Calendar()
            for d in data[fiqh].keys():
                es = Event()
                ei = Event()
                stime = arrow.get(
                    dt.fromtimestamp(data[fiqh][d]["sehri_timestamp"] +
                                     (offset * 60)),
                    'Asia/Kolkata').strftime("%Y-%m-%d %H:%M:00")
                itime = arrow.get(
                    dt.fromtimestamp(data[fiqh][d]["iftar_timestamp"] +
                                     (offset * 60)),
                    "Asia/Kolkata").strftime("%Y-%m-%d %H:%M:00")
                time = dt.now()
                es.name = "Sahar Ending"
                es.begin = stime
                es.created = time
                es.end = stime
                ei.name = "Iftar Beginning"
                ei.created = time
                ei.begin = itime
                ei.end = itime
                c.events.add(es)
                c.events.add(ei)
            with open(
                    "assets/calendars/%s/timings%s.ics" %
                (fiqh, get_offset_string(offset)), "w") as my_file:
                my_file.writelines(c)
Esempio n. 4
0
def create_calendar(token, enrollment_id, options):
    file_list = []
    if options['academicCal'] or options['careerCal']:
        academic_calendar = Calendar()
        career_calendar = Calendar()
        for sess in get_sessions(token, enrollment_id)['calendarSessions']:
            e = Event()
            if (sess['context']['id'] == 1) and options['academicCal']:
                start_time = datetime.strptime(sess['session']['startTime'], '%Y-%m-%dT%H:%M:%SZ')
                end_time = datetime.strptime(sess['session']['endTime'], '%Y-%m-%dT%H:%M:%SZ')
                e.name = str(sess['session']['chapter']) + ': ' + sess['session']['name']
                e.transparent = True if options['academicIsTrans'] else False
                if options['officeHours']:
                    e.begin = start_time - timedelta(minutes=45)
                    e.end = end_time + timedelta(minutes=30)
                else:
                    e.begin = start_time
                    e.end = end_time
                academic_calendar.events.add(e)

            elif (sess['context']['id'] == 2) and options['careerCal']:
                e.name = sess['session']['name']
                e.begin = sess['session']['startTime']
                e.end = sess['session']['endTime']
                e.transparent = True if options['careerIsTrans'] else False
                career_calendar.events.add(e)

        if len(academic_calendar.events) > 0:
            academic_file_name = str(enrollment_id) + '-academic-calendar'
            academic_file_name = academic_file_name + '-oh.ics' if options['officeHours'] else academic_file_name + '.ics'
            file_list.append(academic_file_name)
            with open('files/' + academic_file_name, 'w') as f:
                f.writelines(academic_calendar)

        if len(career_calendar.events) > 0:
            career_file_name = str(enrollment_id) + '-career-calendar.ics'
            file_list.append(career_file_name)
            with open('files/' + career_file_name, 'w') as f:
                f.writelines(career_calendar)

    if options['assignmentCal']:
        assignment_calendar = Calendar()
        for assignment in get_assignments(token, enrollment_id)['calendarAssignments']:
            e = Event()
            if assignment['context']['id'] == 1:
                e.name = assignment['title']
                e.begin = datetime.strptime(assignment['effectiveDueDate'], '%Y-%m-%dT%H:%M:%SZ') - timedelta(days=1)
                e.end = datetime.strptime(assignment['effectiveDueDate'], '%Y-%m-%dT%H:%M:%SZ') - timedelta(days=1)
                e.make_all_day()
                e.transparent = True if options['assignmentsIsTrans'] else False
                assignment_calendar.events.add(e)
        assignment_file_name = str(enrollment_id) + '-assignment-calendar.ics'
        file_list.append(assignment_file_name)
        with open('files/' + assignment_file_name, 'w') as f:
            f.writelines(assignment_calendar)

    return file_list
Esempio n. 5
0
def create_ics(sender, instance, **kwargs):
    c = Calendar()
    alarm = [DisplayAlarm(trigger=timedelta(minutes=30))]

    e = Event()
    e.name = instance.title
    e.begin = instance.date
    e.end = instance.dateend
    e.alarms = alarm
    if instance.duration != None:
        e.duration = instance.duration
    if (instance.cost == 0 or instance.cost == None):
        cost = 'Бесплатно'
        e.description = str(instance.intro) + ' Стоимость: ' + str(cost)
    else:
        e.description = str(instance.intro) + ' Стоимость: ' + str(instance.cost)+  'р.'
    e.location = instance.location
    if instance.timepad != None:
        e.url = instance.timepad
    c.events.add(e)

    instance.ics.delete(save=False)
    instance.ics.save(instance.title +'.ics', ContentFile(str(c)), save=True)
    #Формирование глобального файла со всеми мероприятиями
    global_ics = EventIndex.objects.all()[0]
    events = global_ics.get_children()
    c = Calendar()
    for event in events:
        if (event.specific.date < timezone.now()):
            pass
        else:
            e = Event()
            e.name = event.title
            e.begin = event.specific.date
            e.end = event.specific.dateend
            e.alarms = alarm
            if event.specific.duration != None:
                e.duration = event.specific.duration
            if (event.specific.cost == 0 or event.specific.cost == None):
                cost = 'Бесплатно'
                e.description = str(event.specific.intro.strip("<p>*</p>")) + ' Стоимость: ' + str(cost)
            else:
                e.description = str(event.specific.intro.strip("<p>*</p>")) + ' Стоимость: ' + str(event.specific.cost)+  'р.'
            e.location = event.specific.location
            if event.specific.timepad != None:
                e.url = event.specific.timepad
            c.events.add(e)
    global_ics.calenadar_file.delete(save=False)
    global_ics.calenadar_file.save('global.ics', ContentFile(str(c)), save=True)
    def add_course(self, course_name, start):
        local = self.info[start].lstrip(
            str(re.search(r'<td>|<td rowspan=\"\d\">',
                          self.info[start]))).rstrip('</td>')
        weekday = re.findall(r"星期.", self.info[start + 1])[0].lstrip('星期')
        weekday = self.map.index(weekday)
        time = re.findall(r"\d+", self.info[start + 1])
        week = self.info[start + 2].lstrip('</td>第').rstrip('周</td>')
        remark = self.info[start + 3].lstrip('</td>').rstrip('</td>')

        e = Event()
        if ('-' in week):
            week = week.split('-')
            #print(week)
            week_cur = int(week[0])
            week_end = int(week[1])
            while week_cur <= week_end:
                e = Event()
                e.name = course_name
                e.location = local
                e.description = remark
                offset = datetime.timedelta(days=(week_cur - 1) * 7 + weekday,
                                            hours=self.start_h[int(time[0])],
                                            minutes=self.start_m[int(time[0])])
                e.begin = self.term_start_time + offset
                offset = datetime.timedelta(days=(week_cur - 1) * 7 + weekday,
                                            hours=self.end_h[int(time[1])],
                                            minutes=self.end_m[int(time[1])])
                e.end = self.term_start_time + offset
                week_cur += 1
                self.c.events.add(e)
        else:
            week = week.split(',')
            #print(week)
            for we in week:
                e = Event()
                e.name = course_name
                e.location = local
                e.description = remark
                offset = datetime.timedelta(days=(int(we) - 1) * 7 + weekday,
                                            hours=self.start_h[int(time[0])],
                                            minutes=self.start_m[int(time[0])])
                e.begin = self.term_start_time + offset
                offset = datetime.timedelta(days=(int(we) - 1) * 7 + weekday,
                                            hours=self.end_h[int(time[1])],
                                            minutes=self.end_m[int(time[1])])
                e.end = self.term_start_time + offset
                self.c.events.add(e)
def create_event(name, date):
    e = Event()
    e.name = name
    e.begin = date
    e.make_all_day()

    return e
Esempio n. 8
0
def _add_event(c, title, year, month, day, start_time):
    e = Event()
    e.name = title
    e.begin = _build_arrow(
        f'{year}/{month.zfill(2)}/{day.zfill(2)} {start_time}')
    e.end = _build_arrow(f'{year}/{month.zfill(2)}/{day.zfill(2)} 20:00:00')
    c.events.add(e)
Esempio n. 9
0
def populate_birthdays_calendar(birthdays):
    """ Populate a birthdays calendar using birthday objects """

    c = Calendar()
    c.scale = 'GREGORIAN'
    c.method = 'PUBLISH'
    c.creator = f'fb2cal v{__version__} ({__status__}) [{__website__}]'
    c.extra.append(
        ContentLine(name='X-WR-CALNAME', value='Facebook Birthdays (fb2cal)'))
    c.extra.append(ContentLine(name='X-PUBLISHED-TTL', value='PT12H'))
    c.extra.append(
        ContentLine(name='X-ORIGINAL-URL', value='/events/birthdays/'))

    cur_date = datetime.now()

    for birthday in birthdays:
        e = Event()
        e.uid = birthday.uid
        e.name = f"{birthday.name}'s Birthday"

        # Calculate the year as this year or next year based on if its past current month or not
        # Also pad day, month with leading zeros to 2dp
        year = cur_date.year if birthday.month >= cur_date.month else (
            cur_date + relativedelta(years=1)).year
        month = '{:02d}'.format(birthday.month)
        day = '{:02d}'.format(birthday.day)
        e.begin = f'{year}-{month}-{day} 00:00:00'
        e.make_all_day()
        e.duration = timedelta(days=1)
        e.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY'))

        c.events.add(e)

    return c
Esempio n. 10
0
def get_events(item):
    time_table = [
        [8, 30],  #1
        [10, 20],  #3
        [14, 30],  #5
        [16, 20],  #7
        [19, 30]  #9
    ]
    course_long = [0, 0, 95, 145, 205]
    begin_time = time_table[item['begin_time'] // 2]

    event_list = []
    for i in range(item['begin_week'], item['end_week'] + 1):
        b_time = datetime(2019, 9, 2, begin_time[0], begin_time[1],
                          0) + timedelta(
                              hours=-8, days=item['week'] - 1, weeks=i - 1)
        e_time = b_time + timedelta(minutes=course_long[item['num']])
        ##print(b_time,'-------',e_time)
        e = Event()
        e.name = item['name']
        e.location = item['location']
        e.begin = str(b_time)
        e.end = str(e_time)
        event_list.append(e)
    return event_list
Esempio n. 11
0
def hook_default_time(task):
    """
    Create ics file based on task data.
    """

    command = get_command(sys.argv)
    delete = command in ('delete', 'done')

    if task['due'] and delete:
        ics_path = os.path.join(CALENDAR, task['uuid'] + '.ics')

        if os.path.exists(ics_path):
            os.remove(ics_path)

        print('Removed task from taskwarrior calendar.')

    if task['due'] and not delete:
        cal = Calendar()
        event = Event()
        event.name = task['description']
        event.begin = task['due']

        cal.events.add(event)

        ics_path = os.path.join(CALENDAR, task['uuid'] + '.ics')

        if not os.path.exists(CALENDAR):
            os.makedirs(CALENDAR)

        with open(ics_path, 'w') as ics_file:
            ics_file.writelines(cal)

        print('Updated taskwarrior calendar.')
Esempio n. 12
0
def unibo_calendar():
    print("Options:")
    print("Year: " + YEAR)
    print("Course: " + COURSE)

    # Get data
    print("Getting json data...")
    url = 'https://corsi.unibo.it/laurea/' + \
        str(COURSE) + "/orario-lezioni/@@orario_reale_json?anno=" + str(YEAR)
    events = requests.get(url).json()
    print(str(len(events)) + " events found!")

    # Build calendar
    calendar = Calendar()
    for event in events:
        # Build event
        e = Event(location=event.get("aule")[0].get("des_ubicazione"),
                  alarms=None)
        e.name = event.get("title").title() + " - " + \
            event.get("aule")[0].get("des_risorsa")
        e.begin = arrow.get(event.get("start")).replace(tzinfo="Europe/Rome")
        e.end = arrow.get(event.get("end")).replace(tzinfo="Europe/Rome")

        # Add event to calendar
        calendar.events.add(e)

    # Print file
    print("Writing .ics...")
    with open('UniboCalendar.ics', 'w') as file:
        file.writelines(calendar)
        print("Done!")
Esempio n. 13
0
def CreateCalendar(groups, Classes, periods):
    global NbEventsCreated
    cal = Calendar()
    dateFormat = "%Y-%m-%d %H:%M:%S"
    for period in periods:
        FirstWeekDay = period[0].weekday()
        LastWeekDay = period[1].weekday()
        for i in range(FirstWeekDay, LastWeekDay + 1):
            for Class in Classes:
                if Class[2] == i:
                    if Class[5] == 1 or getGroupOfClass(
                            groups, Classes.index(Class)
                    ) == period[
                            2]:  #if frequency is 1 (class occuring each week) or if group matches period
                        e = Event()
                        startDT = period[0] + timedelta(Class[2] -
                                                        period[0].weekday())
                        startDT = startDT.replace(
                            hour=int(Class[3][:Class[3].index(':')]))
                        startDT = startDT.replace(
                            minute=int(Class[3][Class[3].index(':') + 1:]))
                        endDT = startDT.replace(
                            hour=int(Class[4][:Class[4].index(':')]))
                        endDT = endDT.replace(
                            minute=int(Class[4][Class[4].index(':') + 1:]))
                        e.begin = startDT.strftime(dateFormat)
                        e.end = endDT.strftime(dateFormat)
                        e.location = Class[6]
                        e.name = Class[0] + " (" + Class[1] + ")"
                        cal.events.add(e)
                        NbEventsCreated += 1
    return cal
 def exportClass(self, day):
     e = Event()
     e.name = self.name
     e.begin = datetime.combine(day, self.begin) + timedelta(hours=4)
     e.end = datetime.combine(day, self.end) + timedelta(hours=4)
     e.location = self.location
     return (e)
Esempio n. 15
0
def calendar_entry(request, offer_code):
    try:
        offer = models.PoolSpotOffer.objects.get(offer_code=offer_code)

        if offer.pool_spot:
            c = Calendar()
            e = Event()
            e.name = "%s: trip to %s" % (offer.pool_spot.seat,
                                         offer.pool_spot.trip.location)
            e.description = "%s accepted by %s for the %s trip, %s through %s." % (
                offer.pool_spot.seat, offer.resolving_user,
                offer.pool_spot.trip.location, offer.pool_spot.trip.start_date,
                offer.pool_spot.trip.end_date)
            e.begin = offer.date.isoformat()
            e.make_all_day()
            c.events.append(e)
            return HttpResponse(str(c), content_type="text/calendar")

            # For debuggging the ICS file.
            # return HttpResponse(str(c))

        else:
            return HttpResponse('400 error')
    except models.PoolSpotOffer.DoesNotExist:
        return HttpResponse('400 error')
Esempio n. 16
0
def create_birthday_event(uid: str, name: str,
                          birthday_date: datetime) -> Event:
    """ Create a birthday event with the provided parameters.
    :param uid:             Friend's FB UID
    :param name:            Friend's FB name
    :param birthday_date:   Friend's birthday date
    :return:                Birthday event
    """
    # Initialize birthday_event to a new event
    birthday_event = Event()
    birthday_event.uid = uid
    birthday_event.name = f"{name}'s Birthday"
    today = datetime.today()
    # Calculate the year as this year or next year based on if its past
    # current month or not
    year = today.year if birthday_date.month >= today.month else (
        today + relativedelta(years=1)).year
    # Pad day, month with leading zeros to 2dp
    month = '{:02d}'.format(birthday_date.month)
    day = '{:02d}'.format(birthday_date.day)
    birthday_event.begin = f'{year}-{month}-{day} 00:00:00'
    birthday_event.make_all_day()
    birthday_event.duration = timedelta(days=1)
    birthday_event.extra.append(ContentLine(name='RRULE', value='FREQ=YEARLY'))
    return birthday_event
Esempio n. 17
0
def schedule(dateSaveDict, summaryDict, timezone, type, timeStart):

    i = 0

    while i < len(dateSaveDict):
        c = Calendar()
        e = Event()
        e.name = "VTuber " + type + " Schedule for " + str(
            dateSaveDict[i][0:5])
        e.begin = arrow.get(
            str(datetime.now().year) + '-' + str(dateSaveDict[i][0:2]) + '-' +
            str(dateSaveDict[i][3:5]) + ' ' + timeStart +
            ":00").replace(tzinfo=timezone)
        if int(dateSaveDict[i][0:2]) == 1 and int(dateSaveDict[i][3:5]) == 1:
            e.begin = arrow.get(
                str(datetime.now().year + 1) + '-' +
                str(dateSaveDict[i][0:2]) + '-' + str(dateSaveDict[i][3:5]) +
                ' ' + timeStart + ":00").replace(tzinfo=timezone)

        summaryDict[i + 1] = "\n".join(summaryDict[i + 1])
        e.description = str(summaryDict[i + 1])

        c.events.add(e)

        print(c.events)

        with open('vtub_' + type + "_" + str(dateSaveDict[i][0:2]) + '-' +
                  str(dateSaveDict[i][3:5]) + '.ics',
                  'w',
                  encoding='utf8') as f:
            f.writelines(c)
        i += 1
def generate_ics():
    recommended_recipes, ingredients = get_expiring_items_and_recipes()

    event_description = ""
    expired_items = pd.read_csv('expiring_items.csv')

    for index, row in expired_items.iterrows():
        event_description = event_description + str(
            row['Name']) + " in " + str(row['days to expire']) + " days\n"

    event_description = event_description + "\n" + "Suggested Recipes: \n"
    for recipe in recommended_recipes:
        event_description = event_description + recipe + "\n"

    c = Calendar()
    e = Event()
    e.name = "Items expiring this week"
    e.description = event_description
    today = pd.to_datetime("today")
    e.begin = today + timedelta(days=6)
    c.events.add(e)
    c.events

    with open('expiry_reminder.ics', 'w') as my_file:
        my_file.writelines(c)

    return ingredients
Esempio n. 19
0
def create_ical_event_from_session(session):
    e = Event()
    e.name = session.title
    e.begin = session.start_time
    e.end = session.end_time
    e.location = session.location
    return e
Esempio n. 20
0
    def loadCal(self):
        with open("CAL_REQ.json", "r") as f:
            global c
            c2 = Calendar()
            data = json.load(f)
            headers = {"Authorization": "basic T64Mdy7m["}
            r = requests.post(
                "https://opentimetable.dcu.ie/broker/api/categoryTypes/241e4d36-60e0-49f8-b27e-99416745d98d/categories/events/filter",
                json=data,
                headers=headers,
            )
            if r.status_code == 200:
                response = json.loads(r.text)
                for event in response[0]["CategoryEvents"]:
                    e = Event()
                    e.begin = event["StartDateTime"]
                    e.end = event["EndDateTime"]
                    e.location = event["Location"]
                    e.description = ""
                    for item in event["ExtraProperties"]:
                        if item["DisplayName"] == "Module Name":
                            e.name = "{} - {}".format(item["Value"],
                                                      event["EventType"])
                        e.description += "{}: {}\n".format(
                            item["DisplayName"], item["Value"])

                    c2.events.add(e)
                c = c2
                return True
            else:
                print("Request Failed: %d" % r.status_code)
                return False
Esempio n. 21
0
def add_course(kurs):
    r = requests.get(f"https://www.fu-berlin.de/vv/de/search?query={kurs}")
    soup = BeautifulSoup(r.text)
    dates = [(text.text.strip().split(" ")[1], text.text.strip().split(" ")[2],
              text.text.strip().split(" ")[4])
             for text in soup.find_all(class_="course_date_time")]
    for date in dates:
        e = Event()
        e.name = soup.find_all("h1")[1].text
        year = date[0].split(".")[2]
        month = date[0].split(".")[1]
        day = date[0].split(".")[0]

        starthours = date[1].split(":")[0]
        startminutes = date[1].split(":")[1]

        endhours = date[2].split(":")[0]
        endminutes = date[2].split(":")[1]

        seconds = "00"
        begin = arrow.get(
            year + "-" + month + "-" + day + " " + starthours + ":" +
            startminutes + ":" + seconds, 'YYYY-MM-DD HH:mm:ss')
        begin = begin.replace(tzinfo='Europe/Paris')
        begin = begin.to("utc")
        e.begin = begin.format('YYYY-MM-DD HH:mm:ss')
        end = arrow.get(
            year + "-" + month + "-" + day + " " + endhours + ":" +
            endminutes + ":" + seconds, 'YYYY-MM-DD HH:mm:ss')
        end = end.replace(tzinfo='Europe/Paris')
        end = end.to("utc")
        e.end = end.format('YYYY-MM-DD HH:mm:ss')
        c.events.add(e)
Esempio n. 22
0
    def make_event(self):

        ics = Calendar()
        event = Event()

        # check for existing work shift
        # if there is one, delete it and replace with the new one
        # because it's possible the shift has changed
        split = self.date.split('-')
        # print("looking in calendar for date: " + self.date)

        try:
            todayshift = calendar.date_search(
                datetime(int(split[0]), int(split[1]), int(split[2])),
                datetime(int(split[0]), int(split[1]),
                         int(split[2]) + 1))
        except ValueError:
            print("it's next month for next day.")
            todayshift = calendar.date_search(
                datetime(int(split[0]), int(split[1]), int(split[2])),
                datetime(int(split[0]),
                         int(split[1]) + 1, 1))
        for e in todayshift:
            e.load()
            if "<SUMMARY{}work" in str(e.instance.vevent):
                # print("deleting existing shift")
                e.delete()
        event.name = "work - " + self.position
        event.begin = self.date + " " + self.start_time
        event.end = self.date + " " + self.end_time
        ics.events.add(event)
        # we need to get rid of the Z in the times because it implies we're using UTC
        # we are just using 'local' time, no time zone and ics module only supports UTC
        calendar.add_event(str(ics).replace("Z", ""))
Esempio n. 23
0
def calendar_entry(request, offer_code):
    try:
        offer = models.PoolSpotOffer.objects.get(offer_code=offer_code)

        if offer.pool_spot:
            c = Calendar()
            e = Event()
            e.name = "%s: trip to %s" % (offer.pool_spot.seat, offer.pool_spot.trip.location)
            e.description = "%s accepted by %s for the %s trip, %s through %s." % (
                    offer.pool_spot.seat,
                    offer.resolving_user,
                    offer.pool_spot.trip.location,
                    offer.pool_spot.trip.start_date,
                    offer.pool_spot.trip.end_date)
            e.begin = offer.date.isoformat()
            e.make_all_day()
            c.events.append(e)
            return HttpResponse(str(c), content_type="text/calendar")

            # For debuggging the ICS file.
            # return HttpResponse(str(c))

        else:
            return HttpResponse('400 error')
    except models.PoolSpotOffer.DoesNotExist:
        return HttpResponse('400 error')
Esempio n. 24
0
def run(output_file):
    calendar = Calendar()
    datenames, missiondatas, descriptions = parse_website()

    for datename, data, desc in zip(datenames, missiondatas, descriptions):
        mission = get_mission(datename)
        location = get_location(data)
        begin, is_all_day = get_full_launchtime(datename, data)

        if begin:
            event = Event()
            event.begin = begin
            event.description = desc.text
            event.name = mission
            if is_all_day:
                event.make_all_day()
            event.location = location
            event.uid = mission.replace(" ", "")

            calendar.events.add(event)

    with open(output_file, "w") as outfile:
        outfile.writelines(calendar)

    print(calendar.events)
    print(len(calendar.events))
Esempio n. 25
0
def checkOutput(year, month):
    if int(month) < 10:
        month = '0' + month

    page = requests.get(
        "http://www.weeia.p.lodz.pl/pliki_strony_kontroler/kalendarz.php?rok="
        + year + "&miesiac=" + month)
    soup = BeautifulSoup(page.content, 'html.parser')

    events = soup.find_all('a', class_='active')
    print(events[0]['href'])

    desc = soup.find_all(class_='InnerBox')
    print(desc[0].getText())

    c = Calendar()
    for i in range(len(events)):
        e = Event()
        e.name = desc[i].getText()
        if int(events[i].getText()) < 10:
            e.begin = year + '-' + month + '-0' + events[i].getText(
            ) + ' 00:00:00'
            e.make_all_day()
        else:
            e.begin = year + '-' + month + '-' + events[i].getText(
            ) + ' 00:00:00'
            e.make_all_day()
        c.events.add(e)

    filename = year + month + ".ics"
    with open(filename, 'w') as my_file:
        my_file.writelines(c)

    return send_file(filename, as_attachment=True)
Esempio n. 26
0
def download():
  if request.method =="GET":
    c = Calendar()

    events=query_db("SELECT * FROM events WHERE user_id=?",[session["user_id"]])

    for x in events:
      utc=pytz.utc
      eastern=pytz.timezone('US/Eastern')
      if x[8]:
        local_datetime = datetime(int(x[3][0:4]), int(x[3][5:7]), int(x[3][8:]),int(x[8][0:2]),int(x[8][3:5]))
      else:
        local_datetime = datetime(int(x[3][0:4]), int(x[3][5:7]), int(x[3][8:]))
      date_eastern=eastern.localize(local_datetime,is_dst=None)
      date_utc=date_eastern.astimezone(utc)

      e = Event()
      e.name = x[1]
      e.begin = date_utc.strftime('%Y-%m-%d %H:%M:%S') #x[3] + " " + x[8] + ":00"
      c.events.add(e)

    with open('calendars/'+str(session["user_id"])+'.ics', 'w') as f:
      f.write(str(c))
    
    ##download file
    path = "calendars/"+str(session["user_id"])+".ics"
    
    return send_file(path, as_attachment=True, cache_timeout=0)
  if request.method=="POST":
    return redirect("/")
Esempio n. 27
0
def build_ical(lent_list):
    """Builds ical from a lent list.

    It takes a lent list that ran through a Marshmallow scheme.

    :param lent_list: Marshmallowed lent list.
    :type lent_list: dict
    :return: ical.
    :rtype: str
    """
    cal = Calendar()

    item_dict = defaultdict(list)
    for i in lent_list['items']:
        item_dict[i['due_date']].append('{}: {}'.format(i['author'],
                                                        i['title']))

    for k, v in item_dict.items():
        event = Event()

        event.begin = '{} 00:00:00'.format(k)

        items = '\n'.join(v)
        event.description = items

        event.name = 'Bibliotheksrueckgaben: {}'.format(len(v))

        cal.events.append(event)

    return cal
Esempio n. 28
0
    def scheduler(self):
        c = Calendar()

        for x in range(Calc.dates.__len__()):
            e = Event()
            calc1 = Calc()
            date = Calc.dates[x]
            name = ""
            for y in range(4):
                name += str(calc1.assignShifts(calc1.dates[x])) + " "
            time = " 21:30:00"
            date_time = str(date) + time
            datetime_obj_naive = datetime.strptime(
                date_time, "%Y-%m-%d %H:%M:%S")  #Get date and time
            datetime_obj_eastern = timezone('US/Eastern').localize(
                datetime_obj_naive)  #Convert to EST
            Calc.dates[x] = datetime_obj_eastern.strftime(
                "%Y-%m-%d %H:%M:%S %Z%z")
            print(Calc.dates[x])
            e.begin = datetime_obj_eastern
            e.name = "Designated Drivers"
            e.duration = timedelta(hours=5)
            e.description = " "
            e.description = e.description + str(name)
            c.events.add(e)
            c.events
        with open('DD_Calendar.ics', 'a') as my_file:
            my_file.writelines(c)
Esempio n. 29
0
def team_ics(team):
    matches = Matches().get_matches(lambda m: m.doesFeature(team))
    c = Calendar()
    for m in matches:
        if not m._date:
            continue

        e = Event(uid=fixture_uid(m), location=m.venue)
        e.name = "%s vs %s" % (m.home, m.away)


        if not m._time:
            m._time = time(0,0,0)

        begin = datetime(m._date.year,
                         m._date.month,
                         m._date.day,
                         m._time.hour,
                         m._time.minute,
                         m._time.second)
        begin = arrow.get(begin, 'Europe/London')
        e.begin = begin
        e.duration = timedelta(minutes=90)
        c.events.append(e)
    return Response(c, mimetype='text/calendar')
Esempio n. 30
0
 def as_ical(self):
     event = Event()
     event.name = ' and '.join(collection.type
                               for collection in self._collections)
     event.begin = self.date
     event.end = self.date.replace(hour=8, minute=10)
     return event
Esempio n. 31
0
def main(args):
    res = requests.get('http://www.febclub2017.com/events')
    print "Encoding: {}".format(res.encoding)
    soup = BeautifulSoup(res.text, 'html.parser')

    cal = Calendar()

    for link in soup.find_all("div", { "class" : "detail" }):
        # Parse and format data
        paragraphs = [p.text for p in link.find_all('p')]
        date = paragraphs[2].split('\n')

        start_date = dp.parse("{} {}".format(date[0], date[1].split('-')[0].strip()))
        end_date = dp.parse("{} {}".format(date[0], date[1].split('-')[1].strip()))

        if end_date < start_date:
            end_date = end_date + timedelta(days=1)

        start_date = pytz.timezone('US/Eastern').localize(start_date)
        end_date = pytz.timezone('US/Eastern').localize(end_date)

        description = paragraphs[1].encode('ascii', errors='backslashreplace')

        event = Event()
        event.name = link.h1.text
        event.begin = start_date.isoformat()
        event.end = end_date.isoformat()
        event.description = u"{}\n{}\n\n{}".format(paragraphs[0], paragraphs[4], description)
        event.location = paragraphs[3]

        cal.events.append(event)
        print "Added event {}".format(link.h1.text)

    with open('febclub.ics', 'w') as f:
        f.writelines(cal)
Esempio n. 32
0
def make(parsed, monday):
    calendar = Calendar()
    calendar.creator = "eAUrnik - Fork me on GitHub: https://git.io/JO5Za"
    
    durations = []
    for duration in parsed[0]:
        start, end = duration.split(" - ")
        start_hours, start_minutes = map(int, start.split(":"))
        end_hours, end_minutes = map(int, end.split(":"))
        durations.append(((start_hours, start_minutes), (end_hours, end_minutes)))
        
    data = parsed[1]
    for day_index in range(0, len(data)):
        day = monday + timedelta(days = day_index)
        lessons = data[day_index]
        for lesson_index in range(0, len(lessons)):
            for lesson in lessons[lesson_index]:
                title = lesson[0]
                subtitle = lesson[1]
                
                duration = durations[lesson_index]
                timezone = ZoneInfo("Europe/Ljubljana")
                start = datetime(day.year, day.month, day.day, duration[0][0], duration[0][1], tzinfo = timezone)
                end = datetime(day.year, day.month, day.day, duration[1][0], duration[1][1], tzinfo = timezone)

                event = Event()
                event.name = title
                event.location = subtitle
                event.begin = start
                event.end = end
                calendar.events.add(event)

    return string(calendar)
Esempio n. 33
0
def send_appointment_reminder(signup: AppointmentSignup):
    appointment = signup.appointment
    user = signup.user

    c = Calendar()
    e = Event()
    e.name = f"{format_coursecode(get_course())} Appointment"
    e.begin = pytz.timezone("America/Los_Angeles").localize(appointment.start_time)
    e.end = e.begin + appointment.duration
    e.location = appointment.location.name
    c.events.add(e)

    helper_msg = (
        f"It will be led by {appointment.helper.name}.\n" if appointment.helper else ""
    )

    send_email(
        sender="OH Queue <*****@*****.**>",
        target=user.email,
        subject=f"{format_coursecode(get_course())} Appointment Scheduled",
        body=(
            f"""
    Hi {user.short_name},

    An appointment has been scheduled for you using the {format_coursecode(get_course())} OH Queue. 
    It is at {appointment.start_time.strftime('%A %B %-d, %I:%M%p')} Pacific Time, at location {appointment.location.name}.
    {helper_msg}
    To edit or cancel this appointment, go to https://{get_domain()}.

    Best,
    The 61A Software Team
    """.strip()
        ),
        attachments={"invite.ics": b64encode(str(c).encode("utf-8")).decode("ascii")},
    )
Esempio n. 34
0
def parseEvents(events, curEvent):
    c = Calendar()
    for e in events:
        event = Event()
        event.name = e['Subject']
        event.begin = e['Start']['DateTime']
        event.end = e['End']['DateTime']
        if event.begin >= curEvent.startDate and event.end <= curEvent.endDate:
          c.events.append(event)
    return c
Esempio n. 35
0
def matrix_to_ics(matrix_dict, group, begin, end, directory):
    c = Calendar()

    day, month, year = begin.split(" ")
    begin = "{} {} {}".format(day if int(day) > 9 else '0%s' % (day), MONTHS[month], year)

    day, month, year = end.split(" ")
    end = "{} {} {}".format(day if int(day) > 9 else '0%s' % (day), MONTHS[month], year)

    begin = arrow.get("{} {}".format(begin, HOURS[0]), 'DD MM YYYY HH:mm')
    end = arrow.get("{} {}".format(end, HOURS[-1]), 'DD MM YYYY HH:mm')

    # for each day of the week
    for i, day in enumerate(matrix_dict[group]):
        # for each course of the day
        for j, course in enumerate(day):

            if course:
                # get begin hour
                hour = int(HOURS[j].split(':')[0])
                minute = int(HOURS[j].split(':')[1])

                e = Event()

                e.name = course
                e.begin = begin.replace(hour=hour, minute=minute)
                e.end = e.begin.replace(hours=+1)

                c.events.append(e)

                while (e.begin <= end):
                    e = e.clone()

                    e.end = e.end.replace(days=+7)
                    e.begin = e.begin.replace(days=+7)
                    e.uid = uid_gen()

                    c.events.append(e)

        # next day
        begin = begin.replace(days=+1)

    holidays = convert_holidays()
    for event in c.events:
        for date in holidays:
            if str(event.begin.date()) == str(date):
                c.events.remove(event)

    if not os.path.exists("ics/" + directory):
        os.makedirs("ics/" + directory)

    with open('ics/{}/{}.ics'.format(directory, group), 'w') as f:
        f.writelines(c)
	def addevent(self):
		self.bigDate = ("2015-" + self.finalisedDate2 + " " + self.finalisedPeriod + ":00")
		self.bigDate2 = ("2015-" + self.finalisedDate2)


		c = Calendar()
		e = Event()
		e.name = "Practical request from " + self.teacherVar.get() + " on " + self.dateEntry.get()
		e.begin = arrow.get(self.bigDate, 'YYYY-MM-DD HH:mm:ss')
		e.description = ("Practical Request from " + self.teacherVar.get() + ". " + self.teacherVar.get() + " has requested the following equipment: " + self.equipment.get("1.0","end-1c").replace("\n", "<br>") + "It is needed during " + self.periodVar.get() + " on " + self.dateEntry.get() + ".")
		c.events.append(e)
		print(c.events)
		with open('reminder.ics', 'w') as my_file:
			my_file.writelines(c)
Esempio n. 37
0
def bis_cal(team):

    mt = pytz.timezone('US/Mountain')
    utc = pytz.utc

    link, team_name, session = getUrl(team)

    if link:
        with requests.Session() as s:
            url_root = 'http://www.boulderindoorsoccer.com/schedules/'
            url = url_root + link
            soup = BeautifulSoup(s.get(url).text)
            table = soup.find("table", attrs={"class":"scheduleTable"})
            c = Calendar()
            for tr in table.findAll("tr"):
                good_line = False
                column = 1
                for td in tr.findAll("td"):
                    if good_line == True:
                        if column == 2:
                            home_team = td.text.strip()
                        elif column == 5:
                            away_team = td.text.strip()
                        column += 1
                    for span in td.findAll("span"):
                        date = span.text[9:-1].strip()
                    if td.text[0].isdigit() and good_line == False:
                        time = td.text
                        good_line = True
                        column += 1
                # Create calendar event
                if good_line:
                    e = Event()
                    e.name = "Soccer: " + home_team + " v.s. " + away_team
                    timestamp = parse(date + " " + time)
                    mt_time = mt.localize(timestamp)
                    e.begin = mt_time#.astimezone(utc)
                    e.duration = timedelta(minutes=50)
                    e.location = "Boulder Indoor Soccer, 3203 Pearl Street, Boulder, CO 80301, United States"
                    c.events.append(e)

            cname = team_name + ' ' + session + '.ics'
            with open(cname, 'w') as ics_file:
                ics_file.writelines(c)
            print "Calendar succesfully written for {team_name}, {session}: \"{cname}\"".format(**locals())
    else:
        return None
Esempio n. 38
0
def json2ics(inputfile):
    """ convert json containing tuebix 2016 papers to ics """
    cal = Calendar()
    with open(inputfile) as data_file:
        data = json.load(data_file)
    next120 = datetime(2016, 5, 1, 8, 0)
    next55 = datetime(2016, 5, 4, 8, 0)
    next25 = datetime(2016, 5, 7, 10, 0)
    for talk in data:
        event = Event()
        event.name = talk["titel"]
        event.description = talk["name"] + "\n" + talk["inhalt"]
        # keep Ingo out and use him as a Joker at the end
        if talk["type"]["workshop"] and talk["name"] != "Ingo Blechschmidt":
            event.begin = next120
            event.end = next120 + timedelta(hours=2)
            next120 += timedelta(hours=2)
            if next120.hour > 15:
                next120 += timedelta(hours=16)
            cal.events.append(event)
            for cfptype, possible in talk["type"].items():
                if possible and cfptype != "workshop":
                    event.name += " ### " + cfptype
        elif talk["type"]["v55"] and talk["name"] != "Ingo Blechschmidt":
            event.begin = next55
            event.end = next55 + timedelta(hours=1)
            next55 += timedelta(hours=1)
            if next55.hour > 15:
                next55 += timedelta(hours=16)
            cal.events.append(event)
            for cfptype, possible in talk["type"].items():
                if possible and cfptype != "v55":
                    event.name += " ### " + cfptype
        elif talk["type"]["v25"] and talk["name"] != "Ingo Blechschmidt":
            event.begin = next25
            event.end = next25 + timedelta(minutes=30)
            next25 += timedelta(minutes=30)
            if next25.hour > 15:
                next25 += timedelta(hours=16)
            cal.events.append(event)
            for cfptype, possible in talk["type"].items():
                if possible and cfptype != "v25":
                    event.name += " ### " + cfptype

    with open(icsfile, 'w') as my_file:
        my_file.writelines(cal)
Esempio n. 39
0
def writeICS():
    conn = sqlite3.connect('xueshu.sqlite3', detect_types=sqlite3.PARSE_DECLTYPES)
    c = conn.cursor()
    now = datetime.now()
    future = now + timedelta(days=60)
    items = c.execute('select * from xueshu where startdate>=? and startdate<=?', (now.date(), future.date()))
    c = Calendar()
    c.creator = 'meelo'
    for item in items:
        e = Event()
        e.name = item[1].replace(' ','') + '【{}】'.format(item[10]) + item[9]
#        e.begin = arrow.get(item[3], 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=tz.gettz('Asia/Chongqing'))
        e.begin = arrow.get(item[3], 'YYYY-MM-DD HH:mm:ss').replace(tzinfo='+08:00')
        e.duration = timedelta(hours=2)
        e.location = item[4]
        e.description = item[12]
        c.events.append(e)
#    print(c.events)
    conn.close()
    with open('xueshu.ics', 'w', encoding='utf-8') as f:
        f.writelines(c)
Esempio n. 40
0
File: ics.py Progetto: La0/coach
    def build_calendar(self, stream=None):
        """
    Build calendar from sessions
    """

        cal = Calendar()
        # Add sessions and dates to lines
        for week_pos in range(0, self.plan.weeks_nb):
            week = []

            for day_pos in range(0, 7):
                sessions = []

                date = self.plan.calc_date(week_pos, day_pos)

                # Render sessions using html template
                for session in self.plan.sessions.filter(week=week_pos, day=day_pos):
                    e = Event()
                    e.name = session.name

                    e.description = session.sport.name + " - " + session.type + "\n"
                    # [TODO] check hour planned for training
                    e.begin = datetime.combine(date, datetime.min.time()) + timedelta(hours=19)
                    if session.distance is not None:
                        e.description += "Distance: %f \n " % session.distance
                    if session.time is not None:
                        e.description += "Duration: %s \n " % session.time
                        e.duration = session.time
                    else:
                        e.duration = timedelta(hours=2)

                    cal.events.append(e)

                week.append(sessions or "")

        stream.write(str(cal))
gclient = gspread.authorize(credentials)
gspread = gclient.open(agenda_gsheet_name)
gwsheet = gspread.get_worksheet(1)

# generate Calendar
cal = Calendar()
for grow in gwsheet.get_all_records():
	if grow["ICSDate"]!="":
		try:
			# print "%s | %s | %s " % (grow["DESC"], grow["ICSDate"], grow["ICSTime"])
			evt = Event()
			# evt.name = unicodedata.normalize('NFKD', unicode(grow["DESC"]))
			# evt.name = "Nombre evento"
			# evt.name = grow["DESC"].encode('ascii', 'replace')
			# evt.name = grow["DESC"]
			evt.name = unidecode(grow['DESC'])
			evt.location = unidecode(grow['SALA'])
			(t_begin, t_end) = grow["TIME"].split("-")
			d_begin = "%sT%s:00%s" % (grow["ICSDate"], t_begin.strip(), utc_offset)
			evt.begin = d_begin.replace(":","").replace(".","")
			d_end = "%sT%s:00%s" % (grow["ICSDate"], t_end.strip(), utc_offset)
			evt.end = d_end.replace(":","").replace(".","")
			cal.events.append(evt)
			print "Added %s starting %s ending %s" % (evt.name, d_begin, d_end)
			# print "Added %s, event %s" % (grow['DESC'],evt)
		except:
			print grow
			raise
# END for grow

# Write ics file to disk
Esempio n. 42
0
# style times in ical format
for i in range(len(stime)):
    stime[i] = stime[i].replace(":", "") + "00"


for i in range(len(etime)):
    etime[i] = etime[i].replace(":", "") + "00"


"""########################### FILE CREATION ###########################"""
output_file = open(output_path + output_filename, 'w+')

# LOGIC

c = Calendar()
e = Event()

# ics library stuff, generates the ics format
for i in range(len(sesh)):
    e = Event()
    e.name = str(sesh[i])
    e.description = stype[i]
    e.begin = date[i] + "T" + stime[i] + "+0100"  # "20170906T140000"
    e.end = date[i] + "T" + etime[i] + "+0100"  # "20170906T15000"
    e.location = loc[i]
    c.events.append(e)

output_file.writelines(c)

output_file.close()
Esempio n. 43
0
    try:
        for each in range(len(subject)):
            subject[each] = str(subject[each])[:n.search(str(subject[each])).start()]+"/"+str(subject[each])[n.search(str(subject[each])).end():]
    except Exception as e:
        break;
for each in subject:
    subject[num] = each.split("/")
    num = num + 1
d = datetime.datetime.today()
today = datetime.date.today()
begindate = []
c = Calendar()
num = 0
for r in range(10):
    num = 0
    for i in range(1):
        for each in subject:
            e = Event()
            if(r == 0):
                juli = abs(int(changeWeekday(each[2]))-1)
                begindate.append(today + datetime.timedelta(days = juli))
            e.name = each[1]
            e.begin = str(begindate[num]).replace("-","") +" "+changeTimeStart(each[2])
            e.end = str(begindate[num]) +changeTimeEnd(each[2])
            begindate[num] = begindate[num]+datetime.timedelta(days = 7)
            num = num + 1
            e.location = each[4]
            c.events.append(e)
            

            game = Game(clean_team(game_match['home']),
                        clean_team(game_match['away']),
                        clean_time(year, month, day, game_match['tod']),
            )
            logging.info('Parsed: %s' % str(game))

            games.append(game)

# Collect games by team
teams = defaultdict(list)

# Exhibition Games
games.append(Game('Trois-Rivières', 'Ottawa', arrow.get(datetime.datetime(year, 5, 16, 13, 35, 0), 'US/Eastern')))
games.append(Game('Ottawa', 'Trois-Rivières', arrow.get(datetime.datetime(year, 5, 17, 13, 35, 0), 'US/Eastern')))

for g in games:
    teams[g.home].append(g)
    teams[g.away].append(g)

# Create calendars
for team in ical_teams:
    c = Calendar()
    for g in teams[team]:
        e = Event()
        e.name = g.away if g.home == team else '@ %s' % g.home
        e.begin = g.time
        e.duration = {'hours': 3}
        c.events.append(e)
        with open('%s.ics' % team, 'w') as ical:
            ical.writelines(c)
Esempio n. 45
0
 def save(self, item):
     e = Event()
     e.name = item['title'][0].strip()
     e.begin = time.strftime('%Y%m%dT%H%M00Z', time.strptime(item['startDate'][0].strip() + ' ' + item['startTime'][0].strip(), "%d-%m-%Y %H:%M"))
     e.end = time.strftime('%Y%m%dT%H%M00Z',time.strptime(item['startDate'][0].strip() + ' ' + item['endTime'][0].strip(), "%d-%m-%Y %H:%M"))
     self.c.events.append(e)
Esempio n. 46
0
from ics import Calendar
from ics import Event
c = Calendar
e = Event()
e.name = "f*****g bitches"
e.begin = '20160122 00:00:00'
#e.end = '20160122 01:00:00'
#c.events.append(e)
c.events

with open('test.ics','w') as f:
	f.writelines(c)

Esempio n. 47
0
                locode = locode[:-1]
            x = 1
            length = len(r['events'])
            if i + 1 < length:
                for otherevent in r['events']:
                    if (event['locCode'][:-2] == otherevent['locCode'][:-2]  
                        and event['desc2'] == otherevent['desc2'] \
                        and event['start'] == otherevent['start'] \
                        and event['locCode'] != otherevent['locCode']):
                            locode = locode + otherevent['locCode'][-2:-1]
                            ids.append(otherevent['id'])

            #I wanted to add the tye of lecture to the start of the title, Again this could probably be improved
            if "[" in event['desc2']:
                class_name = event['desc2'].split('[')
                e.name = '[' + class_name[1] + ' ' \
                    + (class_name[0])[:-2] + ' (' + event['desc1'] + ')'
            else:
                class_name = event['desc2']
                e.name = class_name + ' (' + event['desc1'] + ')'
#That mess of a code is over now, lets just add everything to the event now

            logging.debug(e.name + ' - ' + locode)
            e.begin = event['start']
            e.end = event['end']
            e.description = event.get('teacherName', '')
            e.location = locode
            c.events.append(e)


#write it all to file
icalfile = ical_loc + username + '.ics'
Esempio n. 48
0
def add_event(date, location, my_name):

        for specific_event in date:

                #       If there is a specified date
                if specific_event["date"]["start_date"]:

                        if specific_event["date"]["start_date"] != \
                           specific_event["date"]["end_date"]:
                                print "Error! Unexpected api return! Start date not same as end date!"
                                break

                        start_time = specific_event["date"]["start_time"]
                        end_time = specific_event["date"]["end_time"]

                        format_time = '%H:%M'
                        time_dur = datetime.strptime(end_time, format_time) - \
                                   datetime.strptime(start_time, format_time)

                        if specific_event["location"]["building"] and \
                           specific_event["location"]["room"]:
                                location_str = str(specific_event["location"]["building"]) \
                                               + " " + str(specific_event["location"]["room"])
                        else:
                                location_str = " "

                        start_date = specific_event["date"]["start_date"]
                        date_year = term_dates[str(term_num)]["start"].year

                        my_time_zone = timezone('US/Eastern')
                        dt = my_time_zone.localize(datetime(date_year, int(start_date[:2]),
                                                            int(start_date[-2:]), int(start_time[:2]),
                                                            int(start_time[-2:]),0,0))
                        datetime_str_start = arrow.get(dt)

                        new_event = Event()
                        new_event.name = my_name
                        new_event.location = location_str
                        new_event.begin = datetime_str_start
                        new_event.duration = {"hours":time_dur.seconds//3600,
                                              "minutes":(time_dur.seconds//60)%60}


                        if datetime_str_start in events_stack:
                                print "Warning! Duplicate event detected! Event: " \
                                      + my_name + " discarded!"
                        else:
                                events_stack.append(datetime_str_start)
                                cal.events.append(new_event)

                #       If there is no specified date (interates through every day in term)
                else:
                        start_time = specific_event["date"]["start_time"]
                        end_time = specific_event["date"]["end_time"]

                        format_time = '%H:%M'
                        time_dur = datetime.strptime(end_time, format_time) - \
                                   datetime.strptime(start_time, format_time)


                        location_str = str(specific_event["location"]["building"]) \
                                       + " " + str(specific_event["location"]["room"])

                        start_date = term_dates[str(term_num)]["start"]
                        end_date = term_dates[str(term_num)]["end"]

                        weekdays = specific_event["date"]["weekdays"]

                        counter = 0;
                        date_days = [0,0,0,0,0,0,0]
                        while  counter < len(weekdays):
                                if weekdays[counter] == "T":
                                        if (counter + 1) != len(weekdays):
                                                if weekdays[counter + 1] == "h":
                                                        date_days[3] = 1
                                                        counter += 1
                                                else:
                                                        date_days[1] = 1
                                        else:
                                                date_days[3] = 1
                                elif weekdays[counter] == "S":
                                        date_days[5] = 1
                                elif weekdays[counter] == "M":
                                        date_days[0] = 1
                                elif weekdays[counter] == "W":
                                        date_days[2] = 1
                                elif weekdays[counter] == "F":
                                        date_days[4] = 1
                                elif weekdays[counter] == "U":
                                        date_days[6] = 1

                                counter += 1


                        days_in_term = (end_date - start_date).days + 1

                        for index in range(days_in_term):

                                one_day = timedelta(days = 1)
                                current_date = start_date + one_day * index

                                if date_days[current_date.weekday()] == 1:

                                        my_time_zone = timezone('US/Eastern')
                                        dt = my_time_zone.localize\
                                             (datetime(current_date.year, current_date.month,
                                                       current_date.day, int(start_time[:2]),
                                                       int(start_time[-2:]), 0, 0))
                                        datetime_str_start = arrow.get(dt)

                                        new_event = Event()
                                        new_event.name = my_name
                                        new_event.location = location_str
                                        new_event.begin = datetime_str_start
                                        new_event.duration = {"hours":time_dur.seconds//3600,
                                                              "minutes":(time_dur.seconds//60)%60}

                                        if datetime_str_start in events_stack:
                                                print "Warning! Duplicate event detected! Event: " \
                                                      + my_name + " discarded!"
                                        else:
                                                events_stack.append(datetime_str_start)
                                                cal.events.append(new_event)
        return