def __init__(self, question_id): schedule_list = [] user_list = [] scores = [] answers = AnswerModel.get_question_answers(question_id) for a in answers: uid = a.userID scores.append((UserModel.getTrust(uid), a)) user_list.append(a.userID) scores.sort(key=lambda tup: tup[0]) # TODO: possibly change fixed percentage to variable # IMPORTANT: users that did not give an answer should be able to rate, # not sure if that will happen right now # # initial scheduler shift_count = len(scores) - max(1, int(len(scores) * 0.2)) user_list = user_list[shift_count:] + user_list[0:shift_count] for x in xrange(0, len(scores)): a_id = scores[x][1].id u_id = user_list[x] schedule_list.append((a_id, u_id)) Schedule.add_list(schedule_list)
def __init__(self, request): """ Handle the reviewed answer """ try: fsession['reviewanswer'] except: pass else: # for rating in request.form.getlist('rating'): # Review.add(fsession['reviewanswer'], fsession['user_id'], rating, ) for tag_id in request.form.getlist('remove_tags'): AnswerTag.remove(fsession['reviewanswer'], tag_id) try: request.form['rating'] except KeyError: pass else: Review.add(fsession['reviewanswer'], g.lti.get_user_id(), request.form['rating'], request.form['comments']) # users can review only once per answer so delete from schdule list Schedule.delete(fsession['reviewanswer'], g.lti.get_user_id()) # revoke permission to review answer del fsession['reviewanswer']
def show(id=None): # getting schedule schedule = Schedule(id=id) schedule = schedule.get_by_id() # getting zombie related to specific schedule zombie = Zombie() zombies = zombie.get_by_schedule(schedule) # getting statistics # TODO: statics should be collected in one cycle!! statistics = {} event = Event(resource_id=id, resource_type='schedule') #statistics['views'] = event.get_views_by_schedule() statistics['stars'] = event.get_stars_by_schedule() statistics['links'] = zombie.count_links(zombies) statistics['users'] = zombie.count_users(zombies) statistics['images'] = zombie.count_images(zombies) statistics['zombies'] = zombies.count() photos = zombie.get_photos(zombies) links = zombie.get_links(zombies) # should return schedule and zombies return render_template('show.html', schedule=schedule, zombies=zombies, statistics=statistics, photos=photos, links=links)
def save(): schedule = Schedule() res = schedule.create_schedule(request, rest=False, delta=session['utc_offset']) Event().remember({'request': request, 'description': 'create schedule', 'resource_type': 'schedule', 'resource_id': res.id.__str__(), 'media': 'core', 'type': 'events', 'uid': session['user_id']}) return list()
def get(self): page = self.request.GET.get('page', "1") try: page = int(page) except: self.abort(400, 'page is invalid') page = max(1, page) count = Schedule.count_schedules() start = (page - 1) * PAGE_SIZE schedules = Schedule.gets_schedules(start, PAGE_SIZE) self.render_response('/schedule.html', schedules=schedules, page = page, page_count = -(-count / PAGE_SIZE))
def testInsertOneSchedule(self): aDateFrom = datetime.date(year=2014, month=4, day=27) aDateTo = datetime.date(year=2014, month=7, day=27) anAppointmentLength = datetime.time(minute=20) aProHouse = Professional(key_name="123", name="Gregory", lastName="House", email="*****@*****.**", licenseNumber=123) aProHouse.put() aConsultingRoom = ConsultingRoom(key_name="1", description="Consultorio 1", identification="1") aConsultingRoom.put() aSchedule = Schedule(dateFrom=aDateFrom, dateTo=aDateTo, appointmentLength=anAppointmentLength, professional=aProHouse, consultingRoom=aConsultingRoom) aSchedule.put() self.assertEqual(1, len(Schedule.all().fetch(None)))
def _handle_schedule(schedule_id): schedule = Schedule.get(Schedule.id == schedule_id) if not schedule: logger.warn("Schedule is invalid. ID = %s" % schedule_id) return to_mails = schedule.recipients.split(",") attachments = Attachment.gets_by_schedule(schedule_id) atta_dicts = [a.to_mandrill_dict() for a in attachments] rs = send_mail( subject=schedule.subject, from_mail=SEND_ADDRESS, to_mails=to_mails, html=schedule.content, attachments=atta_dicts, ) if not rs: logger.warn("Schedule send fail. ID = %s" % schedule_id) schedule.fail() return if schedule.repeat_strategy: schedule.wait(schedule.repeat_strategy.get_next_time()) else: schedule.send() for r in rs: logger.info(r) now = datetime.utcnow() History.create( recipient=r.get("email"), send_id=r.get("_id", ""), schedule_id=schedule.id, status=r.get("status"), reason=r.get("reject_reason") or "", send_time=now, update_time=now, )
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')
def dashboard(): from models.user import User from models.schedule import Schedule if 'logged_in' not in session: return redirect(url_for('welcome')) context = {} schedule = Schedule() user = User() context['last_schedules'] = schedule.get_last(8) context['last_users'] = user.get_last(8) context['running'] = schedule.get_running() return render_template('dashboard.html', context=context)
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')
def has_new_review(): answer = Schedule.get_answer(g.lti.get_user_id()) if g.lti.is_instructor() or answer is None: return json.dumps({'has_new': False}) return json.dumps({'has_new': True})
def manual_clustering(): feature_vectors, labels = Schedule.fetch_all(wrap=False) clusterer = Clusterer(feature_vectors, labels) clusterer.backend = MiniBatchKMeans(clusterer.num_clusters) clusterer.fit() print labels[0] print clusterer.predict(feature_vectors[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()
def list(): from models.schedule import ScheduleSimpleForm if 'logged_in' not in session: return redirect(url_for('welcome')) schedules = Schedule() results = schedules.get_by_logged_user(session['user'], timeadapt=True) form = ScheduleSimpleForm() now = datetime.datetime.utcnow() + \ datetime.timedelta(0, session['utc_offset']) defaults = { 'start_date': now.strftime("%Y-%m-%d %H:%M:%S") } return render_template('list.html', entries=results, form=form, defaults=defaults)
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 _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
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)
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
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
def get_user(id=None): from models.user import UserSmallForm if 'logged_in' not in session: return redirect(url_for('welcome')) user = User(id=id) if request.method == 'POST': user.first_name = request.form.get('first_name', None) user.last_name = request.form.get('last_name', None) user.email = request.form.get('email', None) user.update_user() user = user.get_by_id() form = UserSmallForm(obj=user) schedule = Schedule(uid=id) schedules = schedule.get_by_logged_user(user.username, timeadapt=True) return render_template('user.html', user=user, form=form, schedules=schedules)
def delete(self): try: _id = self.request.body _id = int(_id) except: self.abort(400, "request is invalid") if not _id: self.abort(400, "schedule id invalid") schedule = Schedule.get(Schedule.id == _id) if not schedule: self.abort(400, "schedule not found") schedule.invalid() self.json({})
def review(): answer = Schedule.get_answer(g.lti.get_user_id()) if answer == None: return "No answers to review." fsession['reviewanswer'] = answer.id enabledtags = AnswerTag.get_tag_ids(answer.id) reviews = Review.get_list(answer.id) return render_template('reviewanswer.html', answer=answer, tags=Tag.get_all(), enabledtags=enabledtags, reviews=reviews)
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')
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)
def review(): answer = Schedule.get_answer(g.lti.get_user_id()) if answer == None: return "No answers to review." fsession['reviewanswer'] = answer.id enabledtags = AnswerTag.get_tag_ids(answer.id) reviews = Review.get_list(answer.id) question = Question.by_id(answer.questionID) if question is None: return "Question was not found." return render_template('reviewanswer.html', answer=answer, tags=Tag.get_all(), enabledtags=enabledtags, reviews=reviews, question=question)
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
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()
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')
def command_sync(args): logging.info("Syncing from google calendar") # Read calendar items for next 5 days cal_events = ICalClient.get_events(args.id, args.name) # Compare to online garmin workouts with _garmin_client(args) as connection: # First we sync the workouts sync_workouts = {} existing_workouts_by_name = {Workout.extract_workout_name(w): w for w in connection.list_workouts()} try: today = ICalClient.get_today() existing_scheduled_workouts = {s.extract_item_workout(): s.extract_item_date() for s in Schedule.items(connection.get_schedule(today.year, today.month))} # Loop ics calendar items for cal_item in cal_events: w = Workout(cal_item.title, cal_item.description) workout_name = "T | %s - %s" % (w.get_workout_name(), cal_item.uid) local_workout = existing_workouts_by_name.get(workout_name) create_workout = True if local_workout: wid = Workout.extract_workout_id(local_workout) wid_exists = wid in existing_scheduled_workouts wid_is_updated = cal_item.is_changed() wid_is_new_date = wid_exists and existing_scheduled_workouts[wid] != cal_item.get_dt_start() if (not wid_exists or wid_is_updated or wid_is_new_date): if (not wid_exists): logging.info("The workout '%s' on '%s' does not exist in the current scheduled workout list" % (workout_name, cal_item.get_dt_start())) elif (wid_is_updated): logging.info("The workout '%s' on '%s' was updated since last run" % (workout_name, cal_item.get_dt_start())) else: logging.info("The workout '%s' on '%s' (old: '%s') was updated with a new date" % (workout_name, cal_item.get_dt_start(), existing_scheduled_workouts[wid])) # Remove the workout on the garmin client. This way it is also removed from the schedule connection.delete_workout(wid) else: create_workout = False logging.info("Workout exists and is in sync '%s' on '%s'" % (workout_name,cal_item.get_dt_start())) if create_workout: # Create the workout in the garmin site payload = w.create_workout(workout_name) logging.info("Creating workout '%s'", workout_name) created_workout_json = connection.save_workout(payload) existing_workouts_by_name[workout_name] = created_workout_json sync_workouts[Workout.extract_workout_id(created_workout_json)] = cal_item.get_dt_start() # Update the workout as found existing_workouts_by_name[workout_name]["is_calendar_workout"] = True # Delete rest if not found. Only if name starts with T| for w in existing_workouts_by_name: if "is_calendar_workout" not in existing_workouts_by_name[w]: if w[:3] == "T |": # Delete this workout because it is not relevant anymore connection.delete_workout(Workout.extract_workout_id(existing_workouts_by_name[w])) logging.info("Removing workout '%s', because date did not fit time window" % w) # Schedule the items on the garmin calendar for workout_id in sync_workouts: date_workout = sync_workouts[workout_id] connection.schedule(workout_id, date_workout) logging.info("Workout %s was scheduled on '%s'" % (workout_id, date_workout)) except Exception as err: err.message logging.error(err)
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
# 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 get(self): listOfSchedule = Schedule.all().fetch(None) self.response.out.write(self.returnObjectOrResult( resultCode="404", objectToReturn=listOfSchedule, encoderForObject=ScheduleEncoder()))
def Schedule(self): return Schedule(self)
def subject(self): return Schedule.get(Schedule.id == self.schedule_id).subject
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
def delete(self): for aSchedule in Schedule.all().fetch(None): aSchedule.delete() self.response.out.write(self.returnObjectOrResult(resultCode="200"))
def count_schedule(self): from models.schedule import Schedule return Schedule.objects(uid=self.username).count()
def delete_schedule(id=None): schedule = Schedule(id=id).get_by_id() schedule.delete() return redirect(url_for('list'))
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})
def schedule(): schedules = Schedule.gets_ready_schedules() for sche in schedules: logger.info('Get schedule ready to send : %s' % sche.id) handle_schedule.delay(sche.id) sche.queued()
def post(self): recipients = self.request.POST.getall('recipient') subject = self.request.POST.get('subject', '') content = self.request.POST.get('content', '') send_type = self.request.POST.get('send_type') attachment_id = self.request.POST.getall('attachment_id') or [] repeat_strategy = None to_mails = [] for recipient in recipients: if not recipient or not validate_email(recipient): self.abort(400, 'recipient is invalid') to_mails.append(recipient.strip()) to_mails = ','.join(to_mails) if len(to_mails) > RECIPIENTS_MAX_LEN: self.abort(400, 'recipients is too long') if len(subject) > SUBJECT_MAX_LEN: self.abort(400, 'subject is too long') if not send_type or send_type not in ['later', 'estimated', 'repeat']: self.abort(400, 'send type is invalid') now = datetime.utcnow() if send_type == 'later': later_value = self.request.POST.get('later_value') later_type = self.request.POST.get('later_type') if not later_value or not later_type: self.abort(400, 'send time is empty') try: later_value = int(later_value) except: self.abort(400, 'send time invalid') if later_type == 'minute': delta = timedelta(minutes=later_value) elif later_type == 'hour': delta = timedelta(hours=later_value) elif later_type == 'day': delta = timedelta(days=later_value) else: self.abort(400, 'send time invalid') estimated_time = (now + delta).replace(microsecond=0) elif send_type == 'estimated': estimated_time = self.request.POST.get('estimated_time') if not estimated_time: self.abort(400, 'estimated time is empty') try: estimated_time = datetime.strptime(estimated_time, DATE_FORMAT) estimated_time = convert_to_utc(estimated_time) except: self.abort(400, 'estimated time invalid') elif send_type == 'repeat': repeat_type = self.request.POST.get('repeat_type') repeat_time = self.request.POST.get('repeat_time') if not repeat_type or not repeat_time: self.abort(400, 'repeat time is empty') try: r_type = RepeatType(int(repeat_type)) r_time = datetime.strptime(repeat_time, TIME_FORMAT).time() repeat_strategy = RepeatStrategy.init_from_local(r_type, r_time) except: self.abort(400, 'repeat time invalid') estimated_time = repeat_strategy.get_next_time() sche = Schedule.create(recipients=to_mails, subject=subject, content=content, status=ScheduleStatus.inited.value, estimated_time=estimated_time, create_time=now, repeat = repeat_strategy.to_json() if repeat_strategy else '') for aid in attachment_id: Attachment.link(aid, sche.id) return redirect('/schedule')
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,
import datetime from lib.tools import getConfig import logging from zombietweet import tClient from models.zombie import Zombie from models.schedule import Schedule config = getConfig() now = datetime.datetime.utcnow() todo = Schedule.objects(start_date__lte=now, end_date__gte=now) logging.basicConfig(level=logging.DEBUG) logging.debug("Fetching data at %s" % now) fetched = tClient.fetch(todo) for f in fetched: found = Zombie.objects(oid=f['oid']) if len(found) == 0: try: zz = Zombie() zz.create_zombie(f) except: pass