Ejemplo n.º 1
0
    def parse_table_section(self, section):
        data = section[0]
        text = section[1]
        schooldays = section[2]

        hourarrivals = []

        datarows = data.split("@")
        for datarow in datarows:
            columns = datarow.split("$")

            if datarow == "":
                continue

            hourarrival = HourArrivals()
            hourarrival.hour = int(columns[1])
            hourarrival.arrivals = map(self.parse_arrival, columns[3:])

            hourarrivals.append(hourarrival)

        schedule = Schedule()
        schedule.type = text
        schedule.schooldays = schooldays
        schedule.hour_arrivals = hourarrivals

        return schedule
Ejemplo n.º 2
0
    def post():
        from app import db

        data = request.get_json()
        schedule = Schedule(data['name'], data['start'], data['end'])
        db.session.add(schedule)
        db.session.commit()

        times = []
        for time in data['time']:
            times.append(str(time))
        dates = schedule.getActiveDates()
        dateTimes = []
        for date in dates:
            for time in times:
                dateTime = getDateTimeFromString(date, time)
                dateTimes.append(dateTime)

        saveObjs = []
        for dateTime in dateTimes:
            newOccurence = Occurance(dateTime, schedule.id)
            db.session.add(newOccurence)
            db.session.commit()
            saveObjs.append(newOccurence.toJSON())

        return {"item": schedule.toJSON(), "events": saveObjs}
Ejemplo n.º 3
0
def index():
    location = request.cookies.get('location')

    if not location:
        flash("Enter your location.")
        return redirect(url_for('add_location'))

    form = SchedulerDataEntryForm(request.form)

    if request.method == 'POST':
        ''' Scanning at QC removing disabled because process was not defined.
        if (location == 'QUALITY CONTROL' or location == 'QC') and :
            try:
                archive(form)
            except Exception as e:
                flash('error: ' + str(e))
        else:
        '''
        try:
            schedule = Schedule()
            schedule.save_changes(form)

            if schedule.is_duplicate():
                flash('The entry you made was a duplicate')
        except Exception as e:
            flash('Scan barcode from work order and include finish date. ' +
                  str(e))

        return redirect(url_for('index'))
    return render_template('index.html', form=form)
Ejemplo n.º 4
0
async def api_create_schedule(request, *, schedule):
    #check_admin(request)
    if not schedule or not schedule.strip():
        raise APIValueError('content', 'content cannot be empty.')
    schedule = Schedule(schedule=schedule.strip())
    await schedule.save()
    return schedule
Ejemplo n.º 5
0
def schedule_add(request):
    echo = {}
    if request.method == "POST":
        try:
            try:
                params = json.loads(request.body)
            except Exception, ex:
                echo["code"] = "400"
                echo["msg"] = "Params is not JSON format"
                return HttpResponseBadRequest(json.dumps(echo))

            if not params_check(params, echo):
                return HttpResponseBadRequest(json.dumps(echo))

            schedule = Schedule(module_name=params.get("module_name"),
                                status="new",
                                case_plan=json.dumps(params.get("case_plan")),
                                created_at=datetime.now(),
                                started_at=datetime.now())
            schedule.save()
            echo["code"] = 200
            echo["msg"] = {"schedule_id": schedule.id}
            return HttpResponse(json.dumps(echo))
        except Exception, ex:
            echo["code"] = 500
            echo['msg'] = str(ex)
            return HttpResponseServerError(json.dumps(echo))
Ejemplo n.º 6
0
def create_schedule(session, day=1):
    schedule = Schedule()
    schedule.station_id = 1
    schedule.day = day
    session.add(schedule)
    session.commit()
    time.sleep(config.SPI_GENERATION_INTERVAL * 3)
    return schedule
Ejemplo n.º 7
0
def create_schedule(session, day=1):
    schedule = Schedule()
    schedule.station_id = 1
    schedule.day = day
    session.add(schedule)
    session.commit()
    time.sleep(config.SPI_GENERATION_INTERVAL * 3)
    return schedule
Ejemplo n.º 8
0
    def test_duplicate_update(self):
        """Test whether duplicates are actually updated or re-inserted."""

        initial = self.from_file("tests/data/schedule_initial.xml")
        duplicate = self.from_file("tests/data/schedule_duplicate.xml")

        # just to be sure
        assert(initial.uid == duplicate.uid)
        assert(initial.rid == duplicate.rid)

        # force messages directly to listener
        listener = MyListener(None, None)

        listener.on_schedule_message(initial)

        res = Schedule.select().where(
            (Schedule.uid==initial.uid) & (Schedule.rid==initial.rid)
        )

        assert(res.count() == 1)
        s = res[0]
        assert(s.uid == initial.uid)
        assert(s.rid == initial.rid)
        assert(s.toc_code == initial.toc_code)

        cps = CallingPoint.select().where(
            CallingPoint.schedule==s
        ).order_by(CallingPoint.id.asc())

        assert(cps.count() == 2)
        destination_cp = cps[1]
        assert(destination_cp.public_arrival == datetime.time(
            hour=10,
            minute=14))

        listener.on_schedule_message(duplicate)

        res = Schedule.select().where(
            (Schedule.uid==initial.uid) & (Schedule.rid==initial.rid)
        )

        assert(res.count() == 1)
        s_after = res[0]
        assert(s_after.uid == initial.uid) # same uid
        assert(s_after.rid == initial.rid) # same rid
        assert(s_after.toc_code == duplicate.toc_code) # different toc

        # get calling points
        cps = CallingPoint.select().where(
            CallingPoint.schedule == s_after
        ).order_by(CallingPoint.id.asc())

        assert(cps.count() == 2) # should be only two
        destination_cp = cps[1]
        assert(destination_cp.public_arrival == datetime.time(
            hour=10,
            minute=17)) # updated time
Ejemplo n.º 9
0
def generate_playoff_schedule(league):
    year = Year.objects.get(universe=league.universe,
                        current_year=True)
    current_field = list(PlayoffTeams.objects.filter(universe=league.universe,
                                            year=year,
                                            league=league).filter(eliminated=False).order_by('seed'))
    
    if len(current_field) == 1:
        champ = Champions(universe=league.universe,
                          year=year,
                          league=league,
                          team=current_field[0].team)
        champ.save()
        return False

    current_round_teams=[]
    s=2
    c=1
    while s > 1:
        c *= 2
        s=len(current_field) / c
    remainder = len(current_field) % c
    
    if remainder:
        cf_deque=deque(current_field)
        cf_deque.rotate(remainder*2)
        for x in xrange(remainder*2):
            current_round_teams.append(cf_deque.popleft())
    else:
        current_round_teams=current_field

    round_games=[]
    for x in xrange(len(current_round_teams)/2):
        round_games.append(Game(universe=league.universe,
                                year=year,
                                home_team=current_round_teams[x].team,
                                away_team=current_round_teams[-x-1].team,
                                use_overtime=True,
                                playoff_game = True))

    max_week = Schedule.objects.filter(universe=league.universe,
                                    year=year,
                                    league=league).aggregate(Max('week'))['week__max']
    for game in round_games:
        game.save()
        schedule = Schedule(universe=league.universe,
                     year=year,
                     league=league,
                     game=game,
                     week=max_week + 1,
                     game_number=round_games.index(game) + 1)
        schedule.save()

    return True
Ejemplo n.º 10
0
 def get(self):
     #get the schedule
     MSchedule = Schedule.query(Schedule.club == 'mens').get()
     WSchedule = Schedule.query(Schedule.club == 'womens').get()
     print MSchedule
     params = {
             'Mschedule': MSchedule,
             'Wschedule': WSchedule,
             'Mscheduleindex' : range(len(MSchedule.teamname)),
             'Wscheduleindex' : range(len(WSchedule.teamname))
              }
     return self.render_template('schedule.html', **params)
Ejemplo n.º 11
0
def create():
    form = ScheduleForm()
    if form.validate_on_submit():
        Schedule.create(name=form['name'].data
                        , url= form['url'].data
                        , check_interval=form['check_interval'].data)
        flash('Your actor has been created', 'success')
        return redirect(url_for('index'))
    elif form.errors:
        handle_form_errors(form.errors)

    return render_template("form.html", form=form)
Ejemplo n.º 12
0
def check():
    rand_flag = 0
    while True:
        if datetime.now(tz).hour == 0:
            rand_flag = 0
        schedules = Schedule.select()
        random_slot = [x for x in schedules if x.afterWhat == 'rm']
        before_slot = [x for x in schedules if x.afterWhat == 'bfm']
        after_slot = [x for x in schedules if x.afterWhat == 'afm']
        if datetime.now(tz).hour in STD_TIMES:
            for i in before_slot:
                tempBox = i.boxName
                tempMsg = "Take " + i.medicineName + " " + str(
                    i.numTabs) + "Tabs."
                send_mqtt(tempBox, tempMsg)
        if datetime.now(tz).hour == randint(8, 20) and rand_flag == 0:
            rand_flag = 1
            for i in random_slot:
                tempBox = i.boxName
                tempMsg = "Take " + i.medicineName + " " + str(
                    i.numTabs) + "Tabs."
                send_mqtt(tempBox, tempMsg)
        if datetime.now(tz).hour in STD_TIMES and datetime.now(
                tz).minute >= 30 and datetime.now(tz).minute <= 40:
            for i in after_slot:
                tempBox = i.boxName
                tempMsg = "Take " + i.medicineName + " " + str(
                    i.numTabs) + "Tabs."
                send_mqtt(tempBox, temp_Msg)
Ejemplo n.º 13
0
	def post(self, action):
		if action == 'create':
			c_per = memcache.get('current_person')
			
			if not c_per:
				return	# ERROR! Invalid attempt to post schedules
			if c_per.schedule:
				return # ERROR! Person already has an schedule ... probably an invalid attempt
			
			sched = Schedule()
			sched.put()
			c_per.schedule = sched
			c_per.put()
			
			memcache.set('current_person',c_per,PERSON_EXPIRE_TIME)
		
		self.redirect('/')
Ejemplo n.º 14
0
def add_schedule_query(spot_id, week_day, opening_time, closing_time):
    schedule = Schedule(spot_id=spot_id,
                        week_day=week_day,
                        opening_time=opening_time,
                        closing_time=closing_time)
    db.session.add(schedule)
    db.session.commit()
    return True
Ejemplo n.º 15
0
def save_schedule(user):
    start_time = request.json.get("startTime")
    end_time = request.json.get("endTime")
    if not start_time or not end_time:
        return abort(
            make_response(
                jsonify(code="BAD_REQUEST",
                        message="\"startTime\" or \"endTime\" not provided."),
                400))
    schedule = Schedule(user_id=user.id,
                        days_available=request.json.get("daysAvailable"),
                        start_time=time.fromisoformat(start_time),
                        end_time=time.fromisoformat(end_time))
    validate_schedule(schedule)
    schedule.insert()

    return jsonify({"success": True}), 201
Ejemplo n.º 16
0
 def post(self, request, tourney_uuid, prop_id):
     change_schedule_form = ChangeScheduleForm(request.POST)
     if change_schedule_form.is_valid(request.user):
         prop = change_schedule_form.get_proposition()
         open_at = change_schedule_form.cleaned_data["open_wager_at"]
         close_at = close_wager_at=change_schedule_form.cleaned_data["close_wager_at"]
         if prop.schedule.game_database_id:
             new_schedule = Schedule()
             new_schedule.save()
             prop.schedule = new_schedule
             prop.save()
         prop.schedule.open_wager_at = open_at
         prop.schedule.close_wager_at = close_at
         prop.schedule.save()
         messages.add_message(self.request, messages.SUCCESS, "Schedule changed.")
         return redirect("tournament-admin", tourney_uuid)
     else:
         return HttpResponseForbidden("You can't do that.")
Ejemplo n.º 17
0
 def post(self, request, tourney_uuid, prop_id):
     change_schedule_form = ChangeScheduleForm(request.POST)
     if change_schedule_form.is_valid(request.user):
         prop = change_schedule_form.get_proposition()
         open_at = change_schedule_form.cleaned_data["open_wager_at"]
         close_at = close_wager_at=change_schedule_form.cleaned_data["close_wager_at"]
         if prop.schedule.game_database_id:
             new_schedule = Schedule()
             new_schedule.save()
             prop.schedule = new_schedule
             prop.save()
         prop.schedule.open_wager_at = open_at
         prop.schedule.close_wager_at = close_at
         prop.schedule.save()
         messages.add_message(self.request, messages.SUCCESS, "Schedule changed.")
         return redirect("tournament-admin", tourney_uuid)
     else:
         return HttpResponseForbidden("You can't do that.")
Ejemplo n.º 18
0
	def test_produce_data(self):
		dbh = DatabaseHandler(self.dbfile)
		dbh.init_database()
		dh = DataHandler(self.xmlfile)
		phrases = dh.read_phrases()

		delta = 1
		for phrase in phrases:
			phrase_id = dbh.insert_phrase(phrase)
			schedule = Schedule()
			schedule.set_phrase_id(phrase_id)
			
			repetition_date = datetime.date.today() + datetime.timedelta(days=delta)
			delta += 1
			schedule.set_next_repetition(repetition_date)
			schedule_id = dbh.insert_schedule(schedule)

		schedules = dbh.get_schedules()
		assert len(schedules) > 0 and len(schedules) == len(phrases)
Ejemplo n.º 19
0
def home():
    form = DosageForm()
    if form.validate_on_submit():
        new_med = Schedule.create(medicineName=form.medicineName.data,
                                  boxName=form.boxName.data,
                                  afterWhat=form.afterWhat.data,
                                  numberTabs=form.numberTabs.data)
        flash("Record successfully saved")
        return redirect(url_for('home'))
    return render_template('main.html', form=form)
Ejemplo n.º 20
0
def edit(id):
    form = ScheduleForm(obj=Schedule.select().where(Schedule.id == id).get())
    if form.validate_on_submit():

        if 'active' in request.form:
            active = 1
        else:
            active = 0

        Schedule.update(name=request.form['name']
                        , url=request.form['url']
                        , check_interval=request.form['check_interval']
                        , active=active
                        ).where(Schedule.id == id).execute()
        flash('Your actor has been updated', 'success')
        return redirect(url_for('index'))
    elif form.errors:
        handle_form_errors(form.errors)

    return render_template("form.html", form=form)
Ejemplo n.º 21
0
def schedule_controller(id):
	name = request.values.get('name')
	subject_id = request.values.get('subject_id')
	student_id = request.values.get('student_id')
	teacher_id = request.values.get('teacher_id')

	if id:
		schedule = Schedule.query(Schedule.id==id).get()
		if schedule:
			if request.method == 'GET':
				if request.values.get('json'):
					return json.dumps(dict(schedule=schedule.json))
				return render_template('schedule_view.html',schedule = schedule, title = "Schedule List")
			elif request.method == 'PUT':
				schedule = edit_parser(schedule,request)
				schedule.put()
				return 'Value Updated', 204
			elif request.method == 'DELETE':
				schedule.key.delete()
				return 'Item deleted', 204
			else:
				return 'Method Not Allowed'
	else:
		if request.method == 'GET':
			schedule_list = Schedule.query().fetch(1000)
			entries=None
			if schedule_list:
				entries = [schedule.json() for schedule in schedule_list]
			if request.values.get('json'):
				return json.dumps(dict(schedule=entries))
			return render_template('schedule.html',schedule_entries = entries, title = "Schedule List")
		elif request.method == 'POST':
			schedule = Schedule()
			schedule = new_parser(schedule,request)
			schedule.put()
			url = '/schedule/'
			if request.values.get('json'):
				url = '/schedule/json=true'
			return redirect(url)
		else:
			return abort(405)
Ejemplo n.º 22
0
  def get(self):
    now = Delorean().truncate('minute')
    mtime = self.request.get('mtime')

    logging.info('match schedule_timestamp query = %f' % now.epoch())

    if mtime:
      logging.debug('manual fire schedule %s ' % mtime)
      jobs = Schedule.query(Schedule.schedule_timestamp == float(mtime), Schedule.error == None, Schedule.status == '').fetch()

    elif settings.DEBUG:
      jobs = Schedule.query(Schedule.schedule_timestamp == 1432634400.0, Schedule.error == None, Schedule.status == '').fetch()

    else:
      jobs = Schedule.query(Schedule.schedule_timestamp == now.epoch(), Schedule.error == None, Schedule.status == '').fetch()

    for job in jobs:
      logging.info('job schedule found!!, categroy:%s, hour_capacity= %d' % (job.category, job.hour_capacity))

      mailer2_async = Mailer2Async(job.key, ['mailer'])
      tasks.addTask(['mailer'], mailer2_async.run)
Ejemplo n.º 23
0
def edit(id):
    if 'schedules' in request.headers.get('Referer'):
        referer = request.headers.get('Referer')
        referrers.clear()
        referrers.append(referer)

    qry = db_session.query(Schedule).filter(Schedule.id == id)
    entry = qry.first()

    form = SchedulerDataEntryForm(formdata=request.form, obj=entry)
    form.work_center.data = entry.machine_center
    flash('Part: ' + entry.part_number)

    if request.method == 'POST':
        schedule = Schedule()
        schedule.edit_entry(form, entry)
        try:
            return redirect(referrers[0])
        except LookupError as e:
            return redirect(url_for('master'))
    return render_template('edit.html', form=form)
Ejemplo n.º 24
0
def index(request):
    context = {
        "courses": Course.objects.all(),
        "classes": Class.objects.all(),
        "venues": Venue.objects.all(),
        "academic_years": AcademicYear.objects.all(),
        "schedules": Schedule.objects.all(),
        "nav_title": "Schedules Setup",
        "page_title": "Schedules | Setup",
    }
    if request.method == "POST":
        template = Schedule(
            group=Class.objects.get(pk=request.POST.get("class", "")),
            academic_year=AcademicYear.objects.current(),
            lecturer=request.user,
        )
        template.save()

        for c in request.POST.get("courses[]", []):
            course = Course.objects.get(pk=int(c))
            template.courses.add(course)

        for c in request.POST.get("venues[]", []):
            venue = Venue.objects.get(pk=int(c))
            template.venues.add(venue)

        template.save()
        return redirect(reverse("staff.schedule.index"))

    return render(request, "staff/schedule/index.html", context)
Ejemplo n.º 25
0
def clone_table(token):
    table = Schedule.query.filter(Schedule.key == token).first()
    new_table = Schedule(name=table.name + " clone", admin_user=current_user.username)

    db_session.add(new_table)
    for lesson in table.lessons:
        new_lesson = Lessons(name=lesson.name,link=lesson.link,start=lesson.start,end=lesson.end,day=lesson.day,
                             col=lesson.col, number=lesson.number,table_id=new_table.id)
        db_session.add(new_lesson)

    db_session.commit()
    flash("Schedule cloned successfully","success")
    return redirect(url_for("table_bp.edit_table",token=table.key))
Ejemplo n.º 26
0
def details(id, page=20):
    actor = Schedule.select().where(Schedule.id == id).get()
    actor_requests = Request.select().where(Request.url_id == id).order_by(Request.insert_date.desc())
    pages = PaginatedQuery(actor_requests, page)
    content = pages.get_list()

    stats = {}
    stats['site_changes'] = actor_requests.select(Request.content_len).distinct().count()
    stats['total_hits'] = actor_requests.count()
    stats['ok_hits'] = actor_requests.select(Request.id).where(Request.status_code == '200').count()
    stats['avg_response_time'] = (sum([row.response_time for row in actor_requests])/stats['total_hits'])

    return render_template('details.html', actor=actor, actor_requests=content, pages=pages, stats=stats)
Ejemplo n.º 27
0
    def update_db(self, show_list):
        """
        Insert the found scheduled shows into the database
        
        Parameters
        ----------
        show_list
            List of shows with formatted and standardised text
        """
        logging.info("Adding shows to database")

        # For each show in the list, add it to the DB
        for show in show_list:
            # If show isn't already in DB, save it
            # Query has to be based on promotion, date AND time at minimum in case of 2 shows from one promotion in a day
            if not Schedule.objects(promotion=show['promotion'],
                                    date=show['date'],
                                    time=show['time']):
                db_show = Schedule(**show).save()
                logging.info(
                    f"Saved document ID {db_show.id} for  {show['promotion']}, {show['time']}"
                )

            # If the show is already present in the DB, update it incase the script is being re-run on a specific day
            # Run an update in case of changes since the last time the scraper ran (or changes were made to the clean_schedule method)
            else:
                update = Schedule.objects(
                    promotion=show['promotion'],
                    date=show['date'],
                    time=show['time']).update(**show, full_result=True)
                if update.modified_count > 0:
                    logging.info(
                        f"Updated DB entry for {show['promotion']}, {show['time']}"
                    )
                else:
                    logging.info(
                        f"DB entry exists for {show['promotion']}, {show['time']}"
                    )
Ejemplo n.º 28
0
 def get_new_schedule(self, phrase, grade, repetition_list=None):
     """
     @param repetition_list: sorted repetition list (earliest rep first)
     @type repetition_list: list of models.Repetition
     @return: new schedule
     @rtype: models.Schedule
     """
     schedule = Schedule()
     schedule.set_phrase_id(phrase.id)
     new_interval = 1
     if repetition_list and len(repetition_list) > 1:
         rep1 = repetition_list[-2]
         rep2 = repetition_list[-1]
         date1 = rep1.get_date()
         date2 = rep2.get_date()
         delta = date2 - date1
         new_interval = self._get_new_interval(delta.days, grade)
     elif repetition_list:
         new_interval = self._get_new_interval(1, grade)
     else:
         new_interval = self._get_new_interval(0, grade)
     schedule.set_next_repetition(datetime.date.today() + datetime.timedelta(days=new_interval))
     return schedule
Ejemplo n.º 29
0
def handle_schedule(id):
    schedule = Schedule.query.get(id)
    if request.method == 'GET':
        return toJson(schedule), 200
    if request.method == 'PUT':
        body = request.get_json()
        date = schedule.date
        space_id = schedule.space_id
        if body['date']: date = body['date']
        if body['space_id']: space_id = body['space_id']
        if Schedule.isSpaceReservedThisHour(date, space_id):
            return json.dumps({"Message": "Duplicate entity"}), 409
        schedule.updateModel(body)
        schedule.store()
        return json.dumps({"Message": "Correctly scheduled"}), 200
Ejemplo n.º 30
0
def addFilter():
    data = json.loads(request.get_data())
    if data['uemail'] in session:
        ofilter = Filter(data['ffrom'], data['ftag'], data['flongi'],
                         data['flati'], data['fradius'], data['ftime'],
                         data['fstate'])
        ofilter.schedule = Schedule(data['starttime'], data['endtime'],
                                    data['repetition'])
        ofilter.user = User.query.filter_by(
            uid=session[data['uemail']]).first()
        db.session.add(ofilter)
        db.session.commit()
        return jsonify({'status': 1})
    else:
        return jsonify({'status': 0, 'message': 'User haven\'t login yet!'})
Ejemplo n.º 31
0
 def _advance_time(self, target):
     # For every second between the origin and the target
     # we must check the scheduled operations
     self.log('Requested advance time to {} delta {}'.format(target, target - self.clock.time))
     while self.clock < target:
         op = Schedule.objects(timestamp__lte=target).order_by('timestamp').first()
         if op:
             self.log('Handling schedule {} scheduled {}'.format(op.opcode, op.timestamp))
             self.clock.advance_to(op.timestamp)
             commits = self._evaluate_schedule(op)
             if commits:
                 self.execute(commits)
             # Delete the runned schedule
             op.delete()
         else:
             self.clock.advance_to(target)
Ejemplo n.º 32
0
    def save_object(self, obj, **kwargs):
        schedule = Schedule.objects.filter(id=obj.schedule_id).first()
        if not schedule:
            logger.debug("no schedule")
            schedule = Schedule()
        logger.debug(schedule)
        if obj.schedule_title:
            schedule.title = obj.schedule_title
        if obj.event_id:
            schedule.event = Event.objects.filter(id=obj.event_id).first()
        if obj.schedule_date:
            schedule.schedule_date = obj.schedule_date
        if obj.schedule_time_from:
            schedule.schedule_time_from = obj.schedule_time_from
        if obj.schedule_time_to:
            schedule.schedule_time_to = obj.schedule_time_to
        if obj.sort_id:
            schedule.sort_id = obj.sort_id
        logger.debug("event:")
        logger.debug(obj.event_id)
        schedule.save()

        obj.schedule_id = schedule.id
Ejemplo n.º 33
0
def create_table():
    name = request.form["name"]
    s = Schedule(name=name, admin_user=current_user.username)
    db_session.add(s)
    db_session.commit()

    days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
    for day in days:
        for i in range(7):
            lesson = Lessons(name="none",table_id=s.id,day=day,number=i+1)
            db_session.add(lesson)

    current_user.tables.append(s)
    current_user.active_table_id = s.id
    db_session.commit()

    flash("Now you can add your lessons","info")
    return redirect(url_for("table_bp.edit_table",token=s.key))
Ejemplo n.º 34
0
    def test_schedule(self):
        dbh = DatabaseHandler(self.dbfile)
        dbh.init_database()
        phrase = self._create_phrase()
        phrase_id = dbh.insert_phrase(phrase)

        schedule = Schedule()
        schedule.set_phrase_id(phrase_id)
        schedule_id = dbh.insert_schedule(schedule)
        assert schedule_id != None

        new_schedule = dbh.get_schedule_by_id(schedule_id)
        assert schedule == new_schedule

        schedule1 = Schedule()
        schedule1.set_phrase_id(phrase_id)
        schedule2 = Schedule()
        schedule2.set_phrase_id(phrase_id)

        dbh.insert_schedule(schedule1)
        dbh.insert_schedule(schedule2)

        schedules = dbh.get_schedules()
        assert len(schedules) == 3
Ejemplo n.º 35
0
def handle_schedules():
    body = request.get_json()
    schedulesToAdd = []
    enterprise = Enterprise.query.get(body[0]['enterprise_id'])
    if enterprise.userHasNotEnoughHours(len(body)):
        return json.dumps({"Message": "Enterprise has not enough hours"}), 424
    for schedule in body:
        newSchedule = Schedule.newInstance(schedule)
        if newSchedule.isSpaceReservedThisHour(newSchedule.date,
                                               newSchedule.space_id):
            return json.dumps({"Message": "Duplicate entity"}), 409
        if ConvertDate.stringToDate(
                newSchedule.date) > ConvertDate.fixedTimeZoneCurrentTime():
            schedulesToAdd.append(newSchedule)
    if len(schedulesToAdd) == len(body):
        enterprise.subtractHours(len(schedulesToAdd))
        addCommitArray(schedulesToAdd)
        return json.dumps({"Message": "Correctly scheduled"}), 201
    return json.dumps({"Message": "Past dates are not selectable"}), 422
Ejemplo n.º 36
0
    def save_db(self):
        """
        DBに保存する
        """
        schedules = []

        for stage in self.all:
            rule_id = Rule.find_by_key(stage.rule_key).id
            game_mode_id = GameMode.find_by_key(stage.game_mode_key).id

            for stage_id in stage.stage_ids:
                s = Schedule(rule_id=rule_id,
                             game_mode_id=game_mode_id,
                             stage_id=stage_id,
                             start_time=stage.start_time,
                             end_time=stage.end_time)
                schedules.append(s)

        db.session.add_all(schedules)
        db.session.commit()
Ejemplo n.º 37
0
def follow(cn, et, ec):
    if 'email' not in session:
        return redirect(url_for('signin'))

    user = User.query.filter_by(email=session['email']).first()

    if user is None:
        return redirect(url_for('signin'))

    if Schedule.query.filter_by(class_number=cn).first() is None:
        s = Schedule(class_number=cn,
                     enrollment_total=et,
                     enrollment_capacity=ec)
    else:
        s = Schedule.query.filter_by(class_number=cn).first()

    user.followed.append(s)
    db.session.commit()

    return redirect(url_for('profile'))
Ejemplo n.º 38
0
def scheduleRegistration():
    if(request.method == 'GET'):
        return render_template('classScheduleRegistration.html')

    if(request.method == 'POST'):
        try:
            class_id = request.json['class_id']
            schedule_id = request.json['schedule_id']
            day = request.json['day']
            start_time = request.json['start_time']
            end_time = request.json['end_time']

            newSchedule = Schedule(schedule_id, day, start_time, end_time)
            new_class_schedule = Class_schedule(class_id, schedule_id)
            DataPipelineObj.insert_data(newSchedule)                    #add new schedule to the database
            DataPipelineObj.insert_data(new_class_schedule)             #update class_schedule table
            return jsonify({'status':"Schedule successfully registered"}) #update teache_class table

        except:
             return jsonify({'status':"There is something wrong. Check whether you have filled require details correctly"})
Ejemplo n.º 39
0
def radioepg_schedule_add_events(request, id):
    """Add a new event in a station schdule"""

    station = Station.query.filter_by(orga=int(
        request.args.get('ebuio_orgapk')),
                                      id=int(id)).first()
    show = Show.query.filter_by(station_id=station.id,
                                id=int(request.args.get('showPk'))).first()

    (hour, minutes) = request.args.get('start').split(':')

    sche = Schedule()
    sche.show_id = show.id
    sche.station_id = station.id
    sche.day = request.args.get('timeday')
    sche.start_hour = hour
    sche.start_minute = minutes
    sche.length = 60

    db.session.add(sche)
    db.session.commit()

    return {}
Ejemplo n.º 40
0
def radioepg_schedule_add_events(request, id):
    """Add a new event in a station schdule"""

    station = Station.query.filter_by(orga=int(request.args.get('ebuio_orgapk')), id=int(id)).first()
    show = Show.query.filter_by(station_id=station.id, id=int(request.args.get('showPk'))).first()

    (hour, minutes) = request.args.get('start').split(':')

    sche = Schedule()
    sche.show_id = show.id
    sche.station_id = station.id
    sche.day = request.args.get('timeday')
    sche.start_hour = hour
    sche.start_minute = minutes
    sche.length = 60

    db.session.add(sche)
    db.session.commit()

    return {}
Ejemplo n.º 41
0
def addNote():
    if request.method == 'POST':
        data = json.loads(request.get_data())
        if data['uemail'] in session:
            note = Note(data['ntext'], data['ntime'], data['nlongi'],
                        data['nlati'], data['nradius'], data['visibility'],
                        data['commentable'])
            schedule = Schedule(data['starttime'], data['endtime'],
                                int(data['repetition'], 2))
            note.schedule = schedule
            note.user = User.query.filter_by(
                uid=session[data['uemail']]).first()
            for element in data['tag']:
                ntag = Notetag(element)
                ntag.note = note
                db.session.add(ntag)
            db.session.commit()
            return jsonify({'status': 1})
        else:
            return jsonify({
                'status': 0,
                'message': 'User haven\'t login yet!'
            })
Ejemplo n.º 42
0
def schedule_controller(id):
    name = request.values.get('name')
    subject_id = request.values.get('subject_id')
    student_id = request.values.get('student_id')
    teacher_id = request.values.get('teacher_id')

    if id:
        schedule = Schedule.query(Schedule.id == id).get()
        if schedule:
            if request.method == 'GET':
                if request.values.get('json'):
                    return json.dumps(dict(schedule=schedule.json))
                return render_template('schedule_view.html',
                                       schedule=schedule,
                                       title="Schedule List")
            elif request.method == 'PUT':
                schedule = edit_parser(schedule, request)
                schedule.put()
                return 'Value Updated', 204
            elif request.method == 'DELETE':
                schedule.key.delete()
                return 'Item deleted', 204
            else:
                return 'Method Not Allowed'
    else:
        if request.method == 'GET':
            schedule_list = Schedule.query().fetch(1000)
            entries = None
            if schedule_list:
                entries = [schedule.json() for schedule in schedule_list]
            if request.values.get('json'):
                return json.dumps(dict(schedule=entries))
            return render_template('schedule.html',
                                   schedule_entries=entries,
                                   title="Schedule List")
        elif request.method == 'POST':
            schedule = Schedule()
            schedule = new_parser(schedule, request)
            schedule.put()
            url = '/schedule/'
            if request.values.get('json'):
                url = '/schedule/json=true'
            return redirect(url)
        else:
            return abort(405)
Ejemplo n.º 43
0
def load_data(data: dict) -> Schedule:
    """
    Args:
        data: {
            'shifts': [
                {
                    'id': int
                    'begin': timestamp
                    'end': timestamp
                    'capacity': int
                    'position': wiw_id
                }
            ]
            'timezone': tzname
            'users' [
                {
                    'email': str
                    'hours_adjusted': float
                
                    'hours_max': float
                    'wiw_id': wiw_id
                    'preferences': {
                        shiftid: priority
                    }
                }
            ]
        }
    Returns:
        Schedule with the associated data"""
    rshifts = data['shifts']
    rtimezone = data['timezone']
    rusers = data['users']
    shifts = get_shifts(rshifts, rtimezone)
    users = get_users(rusers)
    preferences = get_preferences(users, shifts, rusers)
    return Schedule(users,shifts,preferences)
Ejemplo n.º 44
0
def homework_add_controller():
	#this is the controller to add new model entries
	schedules = Schedule.query().fetch(1000)
	return render_template('homework_add.html', title = "Add New Entry", schedules = schedules)
Ejemplo n.º 45
0
    def bulk_add(self, directory, config, tagline):
        directory = os.path.expanduser(config.MUSIC_DIRECTORY) + directory
        image_files = glob.glob('%s/*.png' % directory)
        sound_files = glob.glob('%s/*.mp3' % directory)

        grouped_files = dict()
        for item in image_files + sound_files:
            item = item.replace(os.path.expanduser(config.MUSIC_DIRECTORY), '')
            key = item[:-4]
            if key not in grouped_files.keys():
                grouped_files[key] = []
            grouped_files[key].append(item)

        inserted_items = []
        item_keys = sorted(grouped_files)
        item_keys.reverse()
        for key in item_keys:
            items = grouped_files[key]
            image = None
            sound = None
            for item in items:
                if item.lower().endswith('.png'):
                    image = item
                elif item.lower().endswith('.mp3'):
                    sound = item

            if image is not None and self.image_present(image):
                print "Image already added: %s. Skipping..." % image
                continue
            if sound is not None and self.sound_present(sound):
                print "Sound already added: %s. Skipping..." % sound
                continue
            if image is None and sound is None:
                print "No image/sound recognized for item: %s" % key
                continue
                
            phrase = Phrase()
            phrase.set_name(key)
            if sound is not None:
                phrase.set_filename(sound)
            if image is not None:
                phrase.set_image(image)
            phrase.set_tagline(tagline)
            phrase.set_from_position(0.0)
            phrase.set_to_position(0.0)
            phrase.set_loop(True)
            phrase.set_speed(100)
            phrase.set_pitch(0)
            phrase.set_comment('')            
            phrase_id = self.insert_phrase(phrase)
            if not phrase_id:
                print "Failed to add phrase to database"
                return
            schedule = Schedule()
            schedule.set_phrase_id(phrase_id)
            schedule.set_next_repetition(datetime.date.today())
            schedule_id = self.insert_schedule(schedule)
            if not schedule_id:
                print "Failed to schedule the new phrase"
                return
            metronome_setup = MetronomeSetup()
            metronome_setup.phrase_id = phrase_id
            metronome_setup.speed = 100
            metronome_setup.meter = 0
            metronome_setup.duration = 300
            metronome_setup.increment = 2
            metronome_setup_id = self.insert_metronome_setup(metronome_setup)
            if not metronome_setup_id:
                print "Failed to insert metronome setup"
                return
            inserted_items.append(key)

        if inserted_items:
            print "Inserted items"
            for item in inserted_items:
                print item
        else:
            print "No items inserted"
Ejemplo n.º 46
0
	def _build_schedule(self, data):
		s = Schedule()
		s.id = data['id']
		s.set_next_repetition(data['next_repetition'])
		s.set_phrase_id(data['phrase_id'])
		s.set_speed(data['speed'])
		s.set_pitch(data['pitch'])
		s.set_comment(data['comment'])
		s.set_priority(data['priority'])
		return s
Ejemplo n.º 47
0
def edit_schedule(request, *args, **kwargs):
    if request.method == 'POST':

        if request.user and request.user.is_active:
            user_id = request.user.id
        else:
            # @TODO trhow exception
            user_id = 0

        schobj = Schedule()
        dt_start_temp = request.POST.get('dt-start', None)
        dt_start = datetime.strptime(dt_start_temp, '%d/%m/%Y').strftime("%Y-%m-%d")
        dt_end_temp = request.POST.get('dt-end', None)
        dt_end = datetime.strptime(dt_end_temp, '%d/%m/%Y').strftime("%Y-%m-%d")

        schobj.price = float(request.POST.get('sch-price', 0))
        schobj.price_lower = float(request.POST.get('sch-price-lower', 0))
        schobj.price_highter = float(request.POST.get('sch-price-highter', 0))
        schobj.departure_date = dt_start
        schobj.landing_date = dt_end
        schobj.days_in_place = get_interval_from_diffdays(diffdays(dt_start_temp, dt_end_temp))

        schobj.user_id = user_id

        # departure_in_weekend_only = request.POST.get('departure_in_weekend_only', False)
        # if departure_in_weekend_only == 'on':
        #     departure_in_weekend_only = True
        # landing_in_weekend_only = request.POST.get('landing_in_weekend_only', False)
        # if landing_in_weekend_only == 'on':
        #     landing_in_weekend_only = True

        landing_in_weekend_only = True
        departure_in_weekend_only = True

        schobj.departure_in_weekend_only = departure_in_weekend_only
        schobj.landing_in_weekend_only = landing_in_weekend_only
        # schobj.exactly_days_check = request.POST.get('sch-', None)

        departure_id = request.POST.get('sch-place-departure', None)
        placeobj = Place.objects.get(pk=departure_id)
        schobj.departure = placeobj

        id = request.POST.get('sch-id', None)

        if id:
            Schedule.objects.filter(pk=id).update(logic_delete=True)
            remove_automatic_scheduled_jobs(id)

        schobj.save()
        landings = request.POST.getlist('sch-place-landing', None)
        places = Place.objects.filter(pk__in=landings)
        schobj.landing = places
        schobj.save()
        return HttpResponseRedirect( reverse( 'flyerapp:home' ) )
Ejemplo n.º 48
0
def delete(id):
    Schedule.delete().where(Schedule.id == id).execute()
    flash('Your actor has been deleted', 'warning')
    return redirect(url_for('index'))
Ejemplo n.º 49
0
def json_add_show(request, band_id):
    if isInBand(request.user, band_id):
        #current user is in this band
        if isManager(request.user, band_id):
            #user is a manager
            data = json.loads(request.body)
            dateOfShow = data["dateOfShow"]
            if "venue" in data:
                venue = data["venue"]
            else:
                venue = None
            if "address" in data:
                address = data["address"]
            else:
                address = None
            if "cityState" in data:
                cityState = data["cityState"]
            else:
                cityState = None
            if "cost" in data:
                cost = data["cost"]
            else:
                cost = None
            if "promoter" in data:
                promoter = data["promoter"]
            else:
                promoter = None
            if "promoterEmail" in data:
                promoterEmail = data["promoterEmail"]
            else:
                promoterEmail = None
            if "promoterPhone" in data:
                promoterPhone = data["promoterPhone"]
            else:
                promoterPhone = None
            if "drinks" in data:
                drinks = data["drinks"]
            else:
                drinks = None
            if "meals" in data:
                meals = data["meals"]
            else:
                meals = None
            if "guarantee" in data:
                guarantee = data["guarantee"]
            else:
                guarantee = None
            if "parking" in data:
                parking = data["parking"]
            else:
                parking = None
            if "lodging" in data:
                lodging = data["lodging"]
            else:
                lodging = None
            if "lodgingAddress" in data:
                lodgingAddress = data["lodgingAddress"]
            else:
                lodgingAddress = None
            if "guestList" in data:
                guestList = data["guestList"]
            else:
                guestList = None
            if "notes" in data:
                notes = data["notes"]
            else:
                notes = None
            band = Band.objects.get(id=band_id)
            theShow = Show(band=band,dateOfShow=dateOfShow,venue=venue,address=address,cityState=cityState,cost=cost,promoter=promoter,promoterEmail=promoterEmail,promoterPhone=promoterPhone,drinks=drinks,meals=meals,guarantee=guarantee,parking=parking,lodging=lodging,lodgingAddress=lodgingAddress,guestList=guestList,notes=notes)
            theShow.save()
            if "scheduleItems" in data:
                scheduleItems = data["scheduleItems"]
                for item in scheduleItems:
                    time = item["time"]
                    if "description" in item:
                        desc = item["description"]
                    else: 
                        desc = None
                    if "website" in item:
                        website = item["website"]
                    else:
                        website = None
                    newItem = Schedule(band=band, show=theShow, time=time, description=desc, website=website)
                    newItem.save()
            return HttpResponse(data)
    return HttpResponse("failure")
Ejemplo n.º 50
0
	def get_schedule(self):
		from models import Schedule
		classes = Schedule.query(Schedule.teacher_id == self.id).fetch(1000)
		return classes if classes else []
Ejemplo n.º 51
0
def index():
    data = Schedule.select()
    return render_template("index.html", data=data)
Ejemplo n.º 52
0
        u"..D.........................N..",
        u"...D.................UUUUUUN...",
        u"....D.....................N....",
        u".....D...................N.....",
        u"......D.................N......",
        u".......D...............N.......",
        u"........D.............N........",
        u"UUU...UUUUUUU........N.........",
        u"..........D.........N..........",
        u"...........D..UUUUUUUU.........",
        u"............D.....N............",
        u".............D...N.............",
        u"..............D.N..............",
    ]

    first_schedule = Schedule(schedule_name, creation_date, month, year, crew, schedule)

    first_schedule.schedule = fill_the_schedule(
        first_schedule, number_of_working_days, person_per_day, person_per_night
    )

    for no, (name, one_schedule) in enumerate(zip(first_schedule.crew, first_schedule.schedule)):
        person = Person(name, one_schedule)

        print(
            name,
            one_schedule,
            person.get_number_of_nights(),
            person.get_number_of_days(),
            person.get_working_days_number_person(),
        )
Ejemplo n.º 53
0
    def get(self):
      list_of_keys = Schedule.query().fetch(keys_only=True)
      ndb.delete_multi(list_of_keys)
      MSchedule = Schedule(key_name='mens_schedule')
      MSchedule.club=('mens')
      MSchedule.date = ["8/31/2014",
                  "9-4-2014",
                  "9-11-2014",
                  "9-16-2014",
                  "9-18-2014",
                  "9-20-2014",
                  "9-22-2014",
                  "9-25-2014",
                  "9-27-2014",
                  "9-30-2014",
                  "10-2-2014",
                  "10-4-2014",
                  "10-8-2014",
                  "10-12-2014",
                  "10-16-2014",
                  "10-22-2014",
                  "10-25-2014",
                  "31-2 Oct ",
                  "11-1-2014",
                  "20-23 Nov "]

      MSchedule.teamname = ["Upper Iowa University",
                    "Waldorf College",
                    "AIB College ",
                    "AIB College " ,
                    "William Penn University",
                    "Loras College ",
                    "Waldorf College", 
                    "Wartburg College",
                    "St Ambrose College" ,
                    "Marshalltown CC ",
                    "Grandview University",
                    "Minnesota (Club)",
                    "Iowa Central CC" ,
                    "St Ambrose College",
                    "William Penn University",
                    "Iowa Central CC ",
                    "Shattuck",
                    "Region 5 Tournament" ,
                    "Loras College",
                    "NIRSA Nat. Championships "]

      MSchedule.location = [ 
                    "Fayette, IA",
                    "Ames, IA (Lied)",
                    "Des Moines, IA",
                    "Ames, IA (Lied)",
                    "Ames, IA (Lied)",
                    "Ames, IA (SWAC)",
                    "Foreset City, IA",
                    "Waverly, IA",
                    "Davenport, IA",
                    "Ames, IA (Lied)",
                    "Des Moines, IA",
                    "Ames, IA (TBD)",
                    "Ames, IA (Lied)",
                    "Ames, IA (SWAC)",
                    "Oskaloosa, IA",
                    "Fort Dodge, IA",
                    "Away",
                    "Fort Colins, CO",
                    "Dubuque, IA ",
                    "Memphis, TN"]

      MSchedule.time  = [
                    "2:00 PM",
                    "7:00 PM",
                    '-',
                     '-',
                     '-',
                    '2:00',
                    '7:00',
                    '7:00',
                    '10:00',
                    '5:00',
                    '5:00',
                    '12:00',
                    '7:00',
                    '10:00',
                    '7:00',
                    '5:00',
                     '-',
                     '-',
                    '2:00',
                     '-']

      MSchedule.side = [  'V',
                  'J',
                  'J',
                  'V',
                  'J',
                  'V',
                  'J',
                  'V',
                  'J',
                  'J',
                  'V',
                  'V',
                  'J',
                  'V',
                  'J',
                  'V',
                  'V',
                  'V/J',
                  'V',
                  'V/J']
      MSchedule.result = [  '2-3',
                  '3-0',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-',
                  '-']

      WSchedule = Schedule(key_name="womens_schedule")

      WSchedule.club=('womens')
      WSchedule.date=['-']
      WSchedule.side=['-']
      WSchedule.time = ['-']
      WSchedule.location=['-']
      WSchedule.teamname=['-']
      WSchedule.put()
      MSchedule.put()
      return self.render_template('home.html')
Ejemplo n.º 54
0
 def get(self):
   schedules = Schedule.query(Schedule.status == 'deleting').fetch()
   for schedule in schedules:
     self.check_schedule_procress(schedule)
Ejemplo n.º 55
0
def schedule_init_commit():
    # print request.json['year'], request.json['month'], request.json['staff']
    year = int(request.json['year'])
    month = int(request.json['month'])

    if month == 1:
        start = datetime.date(year-1, 12, 26)
    else:
        start = datetime.date(year, month-1, 26)
    
    days = rrule(DAILY, dtstart=start, until=datetime.date(year, month, 25)).count()

    #staff [u'1,张三,12-26,1', u'2,李四,12-27,1', u'3,王五,12-28,1', u'4,候六,12-29,1',  u'5,孟七,12-26,2']

    # 排班处理
    separator = ','
    for staff in request.json['staff']:
        day = [0 for i in xrange(1, days+1)] # 数组初值0,代表全月休息

        id, name, start_date, type = staff.split(',')

        if int(type) == 1: # 1轮班,2白班 
            start_date_m, start_date_d = start_date.split('-')

            if month == 1:
                start_day_id = rrule(DAILY, dtstart=start, \
                    until=datetime.date(year-1, int(start_date_m), int(start_date_d))).count()
            else:
                start_day_id = rrule(DAILY, dtstart=start, \
                    until=datetime.date(year, int(start_date_m), int(start_date_d))).count()
        
            # 排班算法,4人2班,对4求余
            '''
            if start_day_id == 1:
                for i in xrange(1, days+1):
                    day[i-1] = (i % 4) if (i % 4) in [1, 2] else 0
            elif start_day_id == 2:
                for i in xrange(1, days+1):
                    day[i-1] = ((i - 1) % 4) if ((i - 1) % 4) in [1, 2] else 0
            elif start_day_id == 3:
                for i in xrange(2, days+1):
                    day[i-1] = ((i - 2) % 4) if ((i - 2) % 4) in [1, 2] else 0
            elif start_day_id == 4:
                day[0] = 2
                for i in xrange(3, days+1):
                    day[i-1] = ((i - 3) % 4) if ((i - 3) % 4) in [1, 2] else 0
            '''

            # 排班算法, 6人2班, 对6求余, 余2晚班, 余4晚班, 余1早班
            if start_day_id == 1:
                for i in xrange(1, days+1):
                    if (i % 6) == 1:
                        day[i-1] = 1
                    if (i % 6) in [2, 4]:
                        day[i-1] = 2
            elif start_day_id == 2:
                for i in xrange(1, days+1):
                    if ((i -1) % 6) == 1:
                        day[i-1] = 1    
                    if ((i -1) % 6) in [2, 4]:
                        day[i-1] = 2  
            elif start_day_id == 3:
                for i in xrange(2, days+1):
                    if ((i -2) % 6) == 1:
                        day[i-1] = 1    
                    if ((i -2) % 6) in [2, 4]:
                        day[i-1] = 2  
            elif start_day_id == 4:
                day[0]=2
                for i in xrange(3, days+1):
                    if ((i -3) % 6) == 1:
                        day[i-1] = 1    
                    if ((i -3) % 6) in [2, 4]:
                        day[i-1] = 2  
            elif start_day_id == 5:
                day[1] = 2
                for i in xrange(4, days+1):
                    if ((i -4) % 6) == 1:
                        day[i-1] = 1    
                    if ((i -4) % 6) in [2, 4]:
                        day[i-1] = 2  
            elif start_day_id == 6:
                day[0], day[2] = 2, 2
                for i in xrange(5, days+1):
                    if ((i -5) % 6) == 1:
                        day[i-1] = 1    
                    if ((i -5) % 6) in [2, 4]:
                        day[i-1] = 2  
        else:
            for i, v in enumerate(rrule(DAILY, dtstart=start, until=datetime.date(year, month, 25))):
                if v.weekday() in [0, 1, 2, 5, 6]:
                    day[i] = 1

        #保存数据库
        schedule = Schedule()
        schedule.name = name    
        schedule.year = year
        schedule.month = month
        schedule.days = days
        schedule.type = type
        schedule.list = separator.join([str(i) for i in day])
        schedule.morning =  0 if len([i for i in day if i == 1]) == 0 else len([i for i in day if i == 1])
        schedule.evening = len([i for i in day if i == 2])
        schedule.rest = 0
        schedule.overtime = 0
        
        schedule.updated_user = current_user.name
        schedule.updated_time = datetime.datetime.now()
        schedule.updated_count = 0

        db.session.add(schedule)
        
    db.session.commit()

    return jsonify(json=True)
Ejemplo n.º 56
0
	def get_schedule(self):
		from models import Schedule
		classes = Schedule.query(Schedule.id == self.schedule_id).get()
		return classes if classes else None
Ejemplo n.º 57
0
def create_schedule(league):
        y = Year.objects.get(universe=league.universe,
                             current_year=True)
        teams = LeagueMembership.objects.filter(universe=league.universe,
                                                year=y,
                                                league=league)
        structure = {}
        for team in teams:
                structure.setdefault(team.conference, {})
                structure[team.conference].setdefault(team.division, [])
                structure[team.conference][team.division].append(team.team)

        total_weeks = 0
        schedule = []
        for conference, divisions in structure.iteritems():
                for div_nbr, division in divisions.iteritems():
                        shuffle(division)
                        anchor_team = None
                        # 'balanced' will contain 1 if even number of teams,, 0 if odd
                        # used later to calculate number of weeks needed, since odd
                        # numbered divisions require an extra week due to each team having a bye
                        balanced = 1 - (len(division) % 2)
                        nbr_weeks = len(division) - balanced
                        max_weeks = 2 * nbr_weeks
                        # To ensure all league teams play the same number of games
                        # regardless of the number of teams in their division
                        # capture the highest number of games played in a division
                        # and apply that to all. The largest division should be 
                        # processed first.
                        if nbr_weeks > total_weeks:
                            total_weeks = nbr_weeks
                        else:
                            nbr_weeks = total_weeks - balanced

                        try:
                                schedule[max_weeks]
                        except:
                                for x in xrange(max_weeks - len(schedule)):
                                        schedule.append([])
                        ## gpw is games per week
                        gpw = len(division) / 2
                        rotation1 = deque(division[:gpw])
                        rotation2 = deque(division[gpw:])
                        if balanced:
                                anchor_team = rotation1.popleft()
                        for week in range(nbr_weeks):
                                if anchor_team:
                                        schedule[week].append(Game(universe=league.universe,
                                                                 year=y,
                                                                 home_team=anchor_team, 
                                                                 away_team=rotation2[-1],
                                                                 use_overtime = True))
                                        schedule[week+nbr_weeks].append(Game(universe=league.universe,
                                                                             year=y,
                                                                             home_team=rotation2[-1], 
                                                                             away_team=anchor_team,
                                                                             use_overtime = True))
                                for t1, t2 in zip(rotation1,rotation2):
                                        schedule[week].append(Game(universe=league.universe,
                                                                 year=y,
                                                                 home_team=t1,
                                                                 away_team=t2,
                                                                 use_overtime = True))
                                        schedule[week+nbr_weeks].append(Game(universe=league.universe,
                                                                             year=y,
                                                                             home_team=t2,
                                                                             away_team=t1,
                                                                             use_overtime = True))

                                rotation1.append(rotation2.pop())
                                rotation2.appendleft(rotation1.popleft())

        for week in schedule:
                for game in week:
                        game.save()
                        s = Schedule(universe=league.universe,
                                     year=y,
                                     league=league,
                                     game=game,
                                     week=schedule.index(week) + 1,
                                     game_number=week.index(game) + 1)
                        s.save()
Ejemplo n.º 58
0
def schedule_edit_controller(id):
	#this is the controller to edit model entries
	schedule_item = Schedule.query(Schedule.id==id).get()
	return render_template('schedule_edit.html', schedule_item = schedule_item, title = "Edit Entries")