Ejemplo n.º 1
0
 def post(self):
     venue_id = self.request.get_range('venue_id')
     venue = Venue.get_by_id(venue_id)
     if not venue:
         self.abort(400)
     index = self.request.get_range('index')
     days = []
     for day in DaySchedule.DAYS:
         confirmed = bool(self.request.get(str(day)))
         if confirmed:
             start = datetime.strptime(self.request.get('start_%s' % day),
                                       STR_TIME_FORMAT)
             end = datetime.strptime(self.request.get('end_%s' % day),
                                     STR_TIME_FORMAT)
             days.append(
                 DaySchedule(weekday=day,
                             start=start.time(),
                             end=end.time()))
     schedule = Schedule(days=days)
     if not venue.time_break:
         venue.time_break = [schedule]
     elif len(venue.time_break) > index:
         venue.time_break[index] = schedule
     else:
         venue.time_break.append(schedule)
     venue.put()
     self.redirect('/company/venues')
Ejemplo n.º 2
0
    def post(self):
        venue_id = self.request.get_range('venue_id')
        venue = Venue.get_by_id(venue_id)

        if not venue:
            self.abort(400)

        delivery_type = int(self.request.get('delivery_type'))
        delivery_type = venue.get_delivery_type(delivery_type)

        logging.debug(delivery_type)

        days = []
        for day in DaySchedule.DAYS:
            confirmed = bool(self.request.get(str(day)))
            logging.debug(confirmed)
            if confirmed:
                start = datetime.strptime(self.request.get('start_%s' % day),
                                          STR_TIME_FORMAT)
                end = datetime.strptime(self.request.get('end_%s' % day),
                                        STR_TIME_FORMAT)
                days.append(
                    DaySchedule(weekday=day,
                                start=start.time(),
                                end=end.time()))
        schedule = Schedule(days=days)
        logging.debug("new scheldule: {}".format(schedule))
        delivery_type.schedule_restriction = schedule
        delivery_type.put()
        venue.put()
        self.redirect_to('delivery_types')
Ejemplo n.º 3
0
 def add_schedule(self, **kwargs):
     schedule = Schedule(day=kwargs["day"],
                         chet=kwargs["chet"],
                         group_id=kwargs["group_id"],
                         interval_id=kwargs["interval_id"],
                         subject_id=kwargs["subject_id"],
                         lecturer_id=kwargs["lecturer_id"])
     self.db.session.add(schedule)
     self.db.session.commit()
Ejemplo n.º 4
0
def _get_schedule(schedule_dicts):
    schedule = Schedule()
    for schedule_dict in schedule_dicts:
        start_hour = int(schedule_dict['hours'].split('-')[0]) % 24
        end_hour = int(schedule_dict['hours'].split('-')[1]) % 24
        for day in schedule_dict['days']:
            schedule.days.append(DaySchedule(weekday=int(day),
                                             start=time(hour=start_hour),
                                             end=time(hour=end_hour)))
    return schedule
Ejemplo n.º 5
0
def parse_resto_schedule(resto_schedule):
    schedule = Schedule()
    for resto_schedule in resto_schedule:
        resto_start_hour = int(resto_schedule['hours'].split('-')[0]) % 24
        resto_end_hour = int(resto_schedule['hours'].split('-')[1]) % 24
        for day in resto_schedule['days']:
            schedule.days.append(DaySchedule(weekday=int(day),
                                             start=time(hour=resto_start_hour),
                                             end=time(hour=resto_end_hour)))
    return schedule
 def _create_restaurant_schedule_with_availabilities_for_dates(
         self, restaurant_row, dates):
     restaurant_name = restaurant_row.find(
         id='schedule_place_data').find('a').string
     rows_of_daily_opening_closing_times = restaurant_row.find_all(
         id='schedule_time_data', )
     availabilities = self._get_availabilities_from_rows_for_dates(
         rows_of_daily_opening_closing_times,
         dates,
     )
     return Schedule(restaurant_name, availabilities)
Ejemplo n.º 7
0
def select(id):
    schedule = None
    sql = "SELECT * FROM schedules WHERE id = %s"
    values = [id]
    result = run_sql(sql, values)[0]
    if result is not None:
        instructor = instructor_repository.select(result['instructor_id'])
        gym_class = gym_class_repository.select(result['class_id'])
        room = room_repository.select(result['room_id'])
        schedule = Schedule(result['class_date'], result['start_time'], result['length_mins'], instructor,
                            gym_class, room, result['id'])
    return schedule
Ejemplo n.º 8
0
def select_all():
    schedules = []
    sql = "SELECT * FROM schedules ORDER BY class_date"
    results = run_sql(sql)
    for row in results:
        instructor = instructor_repository.select(row['instructor_id'])
        gym_class = gym_class_repository.select(row['class_id'])
        room = room_repository.select(row['room_id'])
        schedule = Schedule(row['class_date'], row['start_time'], row['length_mins'], instructor,
                            gym_class, room, row['id'])
        schedules.append(schedule)
    return schedules
Ejemplo n.º 9
0
def add_schedule():
    class_date = request.form['class_date']
    start_time = request.form['start_time']
    length_mins = request.form['length_mins']
    instructor_id = request.form['instructor_id']
    class_id = request.form['class_id']
    room_id = request.form['room_id']
    instructor = details_repository.select(instructor_id)
    gym_class = gym_class_repository.select(class_id)
    room = room_repository.select(room_id)
    schedule = Schedule(class_date, start_time, length_mins, instructor,
                        gym_class, room, id)
    schedule_repository.save(schedule)
    return redirect('/schedule')
Ejemplo n.º 10
0
def create_schedule(df=None, d=None, h=None):
    # jobs after d
    early_dict = OrderedDict()

    ba_diff_asc = False

    # best for ba_diff_df descending, for h=0.2, results were better with
    # ba_diff_df ascending
    if h > 0.5:
        ba_diff = 1  # best overall = 1
    elif 0.25 < h <= 0.5:
        ba_diff = 3  # best overall = 3
    else:
        ba_diff = 5  # best overall = 5

    # # best for ba_diff_df ascending
    # if h > 0.75:
    #     ba_diff = 1  # best overall = 1
    # elif 0.5 < h <= 0.75:
    #     ba_diff = 2  # best overall = 2
    # else:
    #     ba_diff = 3  # best overall = 3 for h=0.2 k < 50, else best = 5

    # the idea here is to place the jobs with lower ba_diff in tardy group
    tardy_dict = df[df['b'] - df['a'] <= ba_diff].to_dict('index')

    # we then pick the reamining jobs, order them by highest p/a first and, if
    # they fit, try to place them on early group
    ba_diff_dict = df[df['b'] - df['a'] > ba_diff].sort_values(
        ['pa'], ascending=ba_diff_asc).to_dict(into=OrderedDict,
                                               orient='index')

    start_time = d
    for idx, row in ba_diff_dict.items():
        if idx not in early_dict and idx not in tardy_dict:
            p = int(row['p'])
            if start_time - p >= 0:
                early_dict[idx] = row
                start_time -= p
            else:
                tardy_dict[idx] = row

    tardy_dict = OrderedDict(
        sorted(tardy_dict.items(), key=lambda x: x[1]['pb']))
    early_dict = OrderedDict(
        sorted(early_dict.items(), key=lambda x: x[1]['pa']))

    return Schedule(d, start_time, early_dict, tardy_dict)
Ejemplo n.º 11
0
def select_dates():
    schedules_list = []
    sql = "SELECT * FROM schedules WHERE class_date = %s ORDER BY start_time"
    for index in range(7):
        schedules = []
        values = [date.today() + timedelta(days=index)]
        results = run_sql(sql, values)
        if results is not None:
            for row in results:
                instructor = instructor_repository.select(row['instructor_id'])
                gym_class = gym_class_repository.select(row['class_id'])
                room = room_repository.select(row['room_id'])
                schedule = Schedule(row['class_date'],  row['start_time'], row['length_mins'], instructor,
                                    gym_class, room, row['id'])
                schedules.append(schedule)
        else:
            schedule = None
            schedules.append(schedule)
        schedules_list.append(schedules)
    return schedules_list
Ejemplo n.º 12
0
 def _create_schedules(self, raw_events):
     schedules_dict = {}  # name to schedule object
     for event_json in raw_events:
         name = event_json.get('summary')
         location = event_json.get('location')
         opens_at = self._extract_datetime(event_json, 'start')
         closes_at = self._extract_datetime(event_json, 'end')
         date = opens_at.date() if opens_at is not None else None
         availability = Availability(
             date=date,
             opens_at=opens_at,
             closes_at=closes_at,
             location=location,
         )
         if name in schedules_dict:
             schedules_dict[name].add_availability(availability)
         else:
             schedules_dict[name] = Schedule(
                 name=name,
                 availabilities=[availability],
             )
     return schedules_dict.values()
Ejemplo n.º 13
0
 def post(self):
     promo_id = self.request.get_range('promo_id')
     promo = Promo.get_by_id(promo_id)
     if not promo:
         self.abort(400)
     days = []
     for day in DaySchedule.DAYS:
         confirmed = bool(self.request.get(str(day)))
         if confirmed:
             start = datetime.strptime(self.request.get('start_%s' % day),
                                       STR_TIME_FORMAT)
             end = datetime.strptime(self.request.get('end_%s' % day),
                                     STR_TIME_FORMAT)
             days.append(
                 DaySchedule(weekday=day,
                             start=start.time(),
                             end=end.time()))
     schedule = Schedule(days=days)
     condition = PromoCondition()
     condition.method = self.request.get_range('method')
     condition.schedule = schedule
     promo.conditions.append(condition)
     promo.put()
     self.redirect('/company/promos/list')
Ejemplo n.º 14
0
                                      datetime.date(1990, 8, 14))
instructor_dets_3 = InstructorDetails('John', 'Wilson',
                                      datetime.date(1990, 8, 14))

# instructor_sch = InstructorSchedule('9-5', True, True, True,
#                                              True, True, False, False, datetime.time(9, 0),
#                                              datetime.time(17, 0))
# instructor_tim = InstructorTimetable(datetime.date(2021, 3, 21), instructor_dets, instructor_sch)

details_repository.save(instructor_dets_1)
details_repository.save(instructor_dets_2)
details_repository.save(instructor_dets_3)
# i_schedule_repository.save(instructor_sch)
# timetable_repository.save(instructor_tim)

schedule_1 = Schedule(datetime.date(2021, 5, 3), datetime.time(10, 0), 60,
                      instructor_dets_1, class_1, room_1)
schedule_2 = Schedule(datetime.date(2021, 5, 3), datetime.time(13, 0), 60,
                      instructor_dets_1, class_1, room_1)
schedule_3 = Schedule(datetime.date(2021, 5, 3), datetime.time(16, 0), 60,
                      instructor_dets_1, class_1, room_1)
schedule_4 = Schedule(datetime.date(2021, 5, 5), datetime.time(10, 0), 60,
                      instructor_dets_1, class_1, room_1)
schedule_5 = Schedule(datetime.date(2021, 5, 5), datetime.time(13, 0), 60,
                      instructor_dets_1, class_1, room_1)
schedule_6 = Schedule(datetime.date(2021, 5, 5), datetime.time(16, 0), 60,
                      instructor_dets_1, class_1, room_1)
schedule_7 = Schedule(datetime.date(2021, 5, 7), datetime.time(10, 0), 60,
                      instructor_dets_1, class_1, room_1)
schedule_8 = Schedule(datetime.date(2021, 5, 7), datetime.time(13, 0), 60,
                      instructor_dets_1, class_1, room_1)
schedule_9 = Schedule(datetime.date(2021, 5, 7), datetime.time(16, 0), 60,
Ejemplo n.º 15
0
 def Schedule(self):
     return Schedule(self)
Ejemplo n.º 16
0
def parse(response):
    root = ET.fromstring(response)

    movies = []
    schedules = []
    updates = []

    for program in root \
            .find('sapo:GetChannelByDateIntervalResult', ns) \
            .find('sapo:Programs', ns) \
            .findall('sapo:Program', ns):

        sapo_id = program.find('sapo:Id', ns).text
        sapo_title = program.find('sapo:Title', ns).text
        sapo_title = sapo_title.replace('(V.O.)', '').replace('(V.P.)',
                                                              '').strip()
        sapo_description = program.find('sapo:Description', ns).text

        if _validate_movie(sapo_title):

            # Check if movie is saved under other movie entry
            movie = _resolve_movie(sapo_id, sapo_title, sapo_description)

            # Movie was successfully resolved
            if movie is not None:
                sapo_id = movie.sapo_id

                # Adding id alias
                if movie.sapo_id != sapo_id and sapo_id not in movie.alias_ids:
                    movie.alias_ids.append(sapo_id)
                    updates.append(movie)

                # Adding title alias
                if movie.sapo_title != sapo_title and sapo_title not in movie.alias_titles:
                    movie.alias_titles.append(sapo_title)
                    updates.append(movie)

            # Movie already in the list of movies to be added
            elif any(m.sapo_id == sapo_id for m in movies):
                pass

            # Getting alias_ids for movies not yet in persisted
            elif any(sapo_title.lower() == m.sapo_title.lower()
                     for m in movies):
                movie = next(m for m in movies
                             if sapo_title.lower() == m.sapo_title.lower())
                movie.alias_ids.append(sapo_id)

            # Otherwise add new one
            else:
                movie = Movie()
                movie.sapo_id = sapo_id
                movie.sapo_title = sapo_title
                movie.sapo_description = sapo_description
                movies.append(movie)

            schedule = Schedule()
            schedule.sapo_id = sapo_id
            schedule.sapo_channel = root \
                .find('sapo:GetChannelByDateIntervalResult', ns) \
                .find('sapo:Sigla', ns).text
            schedule.sapo_start_datetime = datetime.datetime.strptime(
                program.find('sapo:StartTime', ns).text, '%Y-%m-%d %H:%M:%S')
            schedule.sapo_end_datetime = datetime.datetime.strptime(
                program.find('sapo:EndTime', ns).text, '%Y-%m-%d %H:%M:%S')
            schedule.sapo_duration = program.find('sapo:Duration', ns).text
            schedules.append(schedule)

    return movies, schedules, updates
Ejemplo n.º 17
0
    def post(self):
        data = json.loads(self.request.body)
        name, phone, email = map(data['info'].get, ('name', 'phone', 'email'))
        phone = '7' + ''.join(c for c in phone if '0' <= c <= '9')

        namespace = self._find_namespace(name)
        password = "******" % random.randint(0, 10000)
        CompanyUser.create_user(namespace,
                                namespace=namespace,
                                password_raw=password,
                                login=namespace,
                                rights=CompanyUser.RIGHTS_MASK_ADMIN)

        namespace_manager.set_namespace(namespace)
        cfg = Config(id=1)
        cfg.APP_NAME = name
        cfg.DELIVERY_PHONES = [phone]
        cfg.DELIVERY_EMAILS = ['*****@*****.**', email]
        cfg.SUPPORT_EMAILS = [email]
        cfg.ACTION_COLOR = "FF25B8CD"
        cfg.put()

        delivery_slot_keys = [
            DeliverySlot(name=u'Сейчас', slot_type=0, value=0).put(),
            DeliverySlot(name=u'Через 5 минут', slot_type=0, value=5).put(),
            DeliverySlot(name=u'Через 10 минут', slot_type=0, value=10).put(),
            DeliverySlot(name=u'Через 15 минут', slot_type=0, value=15).put(),
            DeliverySlot(name=u'Через 20 минут', slot_type=0, value=20).put(),
            DeliverySlot(name=u'Через 25 минут', slot_type=0, value=25).put(),
            DeliverySlot(name=u'Через 30 минут', slot_type=0, value=30).put()
        ]

        menu = data['menu']
        init = MenuCategory(category=None, title="Init")
        init.put()
        for i, category_dict in enumerate(menu):
            MenuCategory.generate_category_sequence_number(
            )  # only to increase counter
            category = MenuCategory(title=category_dict["title"],
                                    sequence_number=i,
                                    category=init.key)
            category.put()
            for j, item in enumerate(category_dict["items"]):
                MenuItem(category=category.key,
                         title=item["title"],
                         description=item["description"],
                         picture=item["imageUrl"],
                         price=int(round(float(item["price"]) * 100)),
                         sequence_number=j).put()
            for _ in category.get_items():
                category.generate_sequence_number()  # only to increase counter

        venue_dict = data['venue']
        venue = Venue(title=venue_dict['title'],
                      description=venue_dict['address'],
                      coordinates=ndb.GeoPt(venue_dict['lat'],
                                            venue_dict['lng']),
                      active=True)
        venue.update_address()
        venue.schedule = Schedule(days=[
            DaySchedule(
                weekday=i, start=datetime.time(0, 0), end=datetime.time(0, 0))
            for i in xrange(1, 8)
        ])

        for delivery_type in (SELF, IN_CAFE):
            delivery = DeliveryType.create(delivery_type)
            delivery.put()
            delivery.status = STATUS_AVAILABLE
            delivery.max_time = DAY_SECONDS + HOUR_SECONDS  # need hour to order on tomorrow
            delivery.delivery_slots = delivery_slot_keys
            venue.delivery_types.append(delivery)

        venue.put()

        PaymentType(id=str(CASH_PAYMENT_TYPE),
                    title="cash",
                    status=STATUS_AVAILABLE).put()

        deferred.defer(_notify_sms, phone, namespace, password)
        deferred.defer(_notify_email, email, phone, name, namespace, password)

        self.render_json({'login': namespace, 'password': password})
Ejemplo n.º 18
0
    #         if 'duration' in schedule_json:
    #             sapo_duration = schedule_json['duration']
    #
    #         if not sapo_duration:
    #             raise Exception('Invalid option')
    #         else:
    #             if 'duration' in schedule_json:
    #                 db.schedule.update({'_id': schedule._id}, {'$unset': {'duration': ""}})
    #             # print(sapo_start_datetime)
    #             # print(sapo_end_datetime)
    #             # print(sapo_duration)
    #             db.schedule.update({'_id': schedule._id}, {'$set': {'sapo_start_datetime': sapo_start_datetime}})
    #             db.schedule.update({'_id': schedule._id}, {'$set': {'sapo_end_datetime': sapo_end_datetime}})
    #             db.schedule.update({'_id': schedule._id}, {'$set': {'sapo_duration': sapo_duration}})

    schedule = Schedule()
    schedule.sapo_id = '123'
    schedule.sapo_channel = 'ABC'
    schedule.sapo_start_datetime = datetime.datetime.now()
    schedule.sapo_end_datetime = datetime.datetime.now()
    schedule.sapo_duration = '12345'

    serialized = json_util.loads(json_util.dumps(schedule.__dict__))
    print(serialized)
    # db.schedule.insert(serialized)
    s = Schedule(
        json.loads(json_util.dumps(
            db.schedule.find_one({'sapo_id': schedule.sapo_id})),
                   object_hook=json_util.object_hook))
    print(
        ms.exists_schedule_in_db(s.sapo_id, s.sapo_channel,
 def setUp(self):
     self.schedule = Schedule(datetime.date(2021, 3, 21), 45)
    """Printing image"""
    file = io.BytesIO(urllib.request.urlopen(uri).read())
    image = Image.open(file)
    image.show()
    im.detect_web_uri(uri)


if __name__ == '__main__':
    unresolved_movies_json = json.loads(dumps(ms.get_all_unresolved_movies()))

    # Solving each unresolved movie
    for unresolved_movie_json in unresolved_movies_json:
        unresolved_movie = Movie(
            unresolved_movie_json)  # Getting object from json

        schedule = Schedule(
            json.loads(dumps(ms.get_channel_movie(unresolved_movie.sapo_id))))

        print('\n')
        print('*** {} *** [{}]'.format(unresolved_movie.sapo_id,
                                       schedule.sapo_channel))
        print('Movie sapo title: {}'.format(unresolved_movie.sapo_title))
        print('Movie sapo description: {}'.format(
            unresolved_movie.sapo_description))
        print('* Choose one of the following candidates *')

        img_uri = CONFIG.SAPO_IMAGE.format(unresolved_movie.sapo_id)
        _print_img(img_uri)  # Printing movie image
        success_google_vision, annotations = im.detect_web_uri(
            img_uri)  # Getting nnotation from Google Vision API

        # Electing the right candidate