Ejemplo n.º 1
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.º 2
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.º 3
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.º 4
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.º 5
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.º 6
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.º 7
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.º 8
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.º 9
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.º 10
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.º 11
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.º 12
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.º 13
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.º 14
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.º 15
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.º 16
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.º 17
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.º 18
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.º 19
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.º 20
0
  def post(self):
    parameters = pickle.loads(self.request.get('parameters'))

    parser = Parser()
    r = tasks.addTask(['parsecsv'], parser.run, parameters, settings.MAX_TASKSQUEUE_EXECUTED_TIME).get_result()

    if not r:
      new_schedule = Schedule()
      new_schedule.sendgrid_account = parameters.get('sendgrid_account')
      new_schedule.subject = parameters.get('subject')
      new_schedule.sender_name = parameters.get('sender_name')
      new_schedule.sender_email = parameters.get('sender_email')

      new_schedule.category = parameters.get('category')
      new_schedule.reply_to = parameters.get('reply_to')
      new_schedule.type = parameters.get('type')

      new_schedule.txt_object_name = parameters.get('txt_object_name')
      new_schedule.edm_object_name = parameters.get('edm_object_name')
      new_schedule.bucket_name = parameters.get('bucket_name')
      new_schedule.replace_edm_csv_property = parameters.get('replace_edm_csv_property')

      new_schedule.schedule_duration = int(parameters.get('schedule_duration'))
      new_schedule.ip_counts = int(parameters.get('ip_counts'))

      new_schedule.recipient_skip = int(parameters.get('recipient_skip'))
      new_schedule.hour_rate = int(parameters.get('hour_rate'))
      new_schedule.start_time = parameters.get('start_time')
      new_schedule.daily_capacity = int(parameters.get('daily_capacity'))

      new_schedule.error = 'add schedule job taskqueue fail. retry later.'

      new_schedule.is_dry_run = parameters.get('is_dry_run')
      new_schedule.dry_run_fail_rate = parameters.get('dry_run_fail_rate')

      new_schedule.put()
Ejemplo n.º 21
0
    def update(username):
        """update schedules"""
        form = ScheduleForm(obj=request.json, prefix="schedule")

        if form.validate():
            date_exp_weekly = form.date_exp_weekly.data
            date_exp_dates = form.date_exp_dates.data

            date_exp_dates_list = date_exp_dates.split(
                ",") if len(date_exp_dates) > 0 else []

            for date in date_exp_dates_list:
                # remove dates before today
                if date < datetime.date.today().isoformat():
                    date_exp_dates_list.remove(date)

            if len(date_exp_weekly) == 0 and len(date_exp_dates_list) == 0:
                form.date_exp_weekly.errors.append(
                    "Must choose a day of the week or a specific day!")

            starts = request.form.getlist("schedule-schedules-start")
            ends = request.form.getlist("schedule-schedules-end")
            is_active = form.is_active.data

            # check data for schedule time

            # sort with the start time
            for i in range(len(starts)):
                for j in range(i + 1, len(starts)):
                    if starts[i] > starts[j]:
                        [starts[i], starts[j]] = [starts[j], starts[i]]
                        [ends[i], ends[j]] = [ends[j], ends[i]]

            # check end time must bigger than start time
            for i in range(len(starts)):
                if starts[i] >= ends[i]:
                    form.schedules.errors.append(
                        "Ending time must be later than starting time!")
                    break

            # check for time conflick
            for i in range(len(starts) - 1):
                if ends[i] > starts[i + 1]:
                    form.schedules.errors.append(
                        "Schedule time conflick, please check and fix it!")
                    break


            if len(form.errors) == 0:

                items = []

                schedules = [{"start": starts[i], "end":ends[i]}
                             for i in range(len(starts))]

                date_exps = date_exp_weekly + date_exp_dates_list

                for date_exp in date_exps:
                    item = ScheduleHandler.get(username, date_exp)

                    if item is None:
                        item = Schedule(
                            username=username,
                            date_exp=date_exp,
                            schedules=json.dumps(schedules),
                            is_active=is_active)

                        db.session.add(item)
                    else:
                        item.schedules = json.dumps(schedules)
                        is_active = is_active

                    items.append(item)
                try:
                    db.session.commit()

                except:
                    db.session.rollback()
                    # return error message
                    return {"error": "Error when adding an schedule"}

                # success, return new item

                return {"items": [item.serialize() for item in items]}

        # return form errors
        return {"errors": form.errors}
Ejemplo n.º 22
0
    def run(self, MAX_TASKSQUEUE_EXECUTED_TIME=500):
        """
    parse CSV file
    """

        # datetime manipulate
        # all datastore store datetime as utc time
        d = time_to_utc(self.start_time)

        # prepare sending rate
        # [91,83..], 2000 ex
        job_sending_rate, capacity = sending_rate(self.schedule_duration,
                                                  self.ip_counts,
                                                  self.hour_rate,
                                                  self.daily_capacity)
        logging.info(job_sending_rate)
        logging.info(capacity)

        request = self.gcs_service.objects().get_media(
            bucket=self.bucket_name,
            object=self.txt_object_name.encode('utf8'))
        self.gcs_iterator = GCSIterator(request,
                                        capacity=capacity,
                                        progress=self.bytes_read,
                                        chunksize=settings.CHUNKSIZE)

        if self.csv_fieldnames:
            self.csv_reader = csv.DictReader(self.gcs_iterator,
                                             skipinitialspace=True,
                                             delimiter=',',
                                             fieldnames=self.csv_fieldnames)

        else:
            self.csv_reader = csv.DictReader(self.gcs_iterator,
                                             skipinitialspace=True,
                                             delimiter=',')

        try:
            # check edm content
            try:
                content = self.read_edm_file(self.edm_object_name)
                test_ = unicode(content, 'utf8')
                logging.info('%s utf8 check ok.' % self.edm_object_name)

            except Exception:
                raise ValueError('%s encode utf8 error.' %
                                 self.edm_object_name)

            # start parse csv
            for i, row in enumerate(self.csv_reader):
                index = self.init_index + i

                # check recipients skip
                if index < self.recipient_skip:
                    self.count += 1
                    continue

                # create new schedule if hour index move
                if self.hour_index > self.last_hour_index:
                    _d = time_add(d, self.hour_index)

                    if job_sending_rate[self.hour_index] > 0:
                        self.new_schedule = Schedule()
                        self.new_schedule.sendgrid_account = self.sendgrid_account
                        self.new_schedule.subject = self.subject
                        self.new_schedule.sender_name = self.sender_name
                        self.new_schedule.sender_email = self.sender_email
                        self.new_schedule.category = self.category
                        self.new_schedule.type = self.type

                        self.new_schedule.schedule_timestamp = _d.epoch()
                        self.new_schedule.schedule_display = _d.naive()

                        self.new_schedule.hour_delta = (self.hour_index + 1)
                        self.new_schedule.hour_rate = '1/%dhrs' % self.hour_rate

                        self.new_schedule.txt_object_name = self.txt_object_name
                        self.new_schedule.edm_object_name = self.edm_object_name
                        self.new_schedule.replace_edm_csv_property = self.replace_edm_csv_property
                        self.new_schedule.put()

                    self.last_hour_index = self.hour_index

                # append extra index to data row
                if len(self.save_queue) >= self.SAVE_QUEUE_SIZE:
                    self.save()

                # check hour capacity
                if self.count >= job_sending_rate[self.hour_index]:
                    if job_sending_rate[self.hour_index] > 0:
                        self.save()
                        self.add_put_task(self.list_of_rqd, self.total_count)
                        self.list_of_rqd = []

                        # reset recipiensQueueData inner index, count
                        self.count = 0

                    # move hour index to next hour
                    self.hour_index += 1

                # force put to taskqueue if hit max taskqueue send data size limit
                if self.count % self.TASKQUEUE_SIZE == 0 and self.count > 0:
                    self.add_put_task(self.list_of_rqd, self.total_count)

                # break if row index > totoal capacity
                if (index + 1) > capacity:
                    logging.info('index (%d) >= capacity(%d). break parser.' %
                                 (index, capacity))
                    break

                # logging.info('executed time: %d secs, %d' % ((time.time() - self.ts).__int__(), self.gcs_iterator._bytes_read))
                if (time.time() -
                        self.ts).__int__() > MAX_TASKSQUEUE_EXECUTED_TIME:
                    enqueue_task(url='/tasks/parsecsv',
                                 queue_name='parsecsv',
                                 params={
                                     'parameters':
                                     pickle.dumps({
                                         'sendgrid_account':
                                         self.sendgrid_account,
                                         'subject':
                                         self.subject,
                                         'sender_name':
                                         self.sender_name,
                                         'sender_email':
                                         self.sender_email,
                                         'category':
                                         self.category,
                                         'reply_to':
                                         self.reply_to,
                                         'type':
                                         self.type,
                                         'txt_object_name':
                                         self.txt_object_name,
                                         'edm_object_name':
                                         self.edm_object_name,
                                         'bucket_name':
                                         self.bucket_name,
                                         'replace_edm_csv_property':
                                         self.replace_edm_csv_property,
                                         'schedule_duration':
                                         self.schedule_duration,
                                         'ip_counts':
                                         self.ip_counts,
                                         'recipient_skip':
                                         self.recipient_skip,
                                         'hour_rate':
                                         self.hour_rate,
                                         'start_time':
                                         self.start_time,
                                         'daily_capacity':
                                         self.daily_capacity,
                                         'init_index':
                                         index,
                                         'count':
                                         self.count,
                                         'total_count':
                                         self.total_count,
                                         'hour_index':
                                         self.hour_index,
                                         'last_hour_index':
                                         self.last_hour_index,
                                         'bytes_read':
                                         self.gcs_iterator._bytes_read,
                                         'csv_fieldnames':
                                         self.csv_reader.fieldnames,
                                         'new_schedule_key_urlsafe':
                                         self.new_schedule.key.urlsafe()
                                     })
                                 })
                    break

                # check email validation
                if validate_email(row.get('email')):
                    row.update(gi=index, hr=self.hour_index, ii=self.count)
                    self.save_queue.append(row)

                else:
                    row.update(
                        invalid=True,
                        sendgrid_account=self.sendgrid_account,
                        category=self.category,
                        schedule_subject=self.subject,
                        schedule_display=self.new_schedule.schedule_display,
                        hour_rate=self.hour_rate,
                        gi=index,
                        hr=self.hour_index)
                    self.save_queue.append(row)

                self.count += 1
                self.total_count += 1

            # -----------
            # check left self.save_queue have not saved.
            if len(self.save_queue) > 0:
                self.save()
                self.add_put_task(self.list_of_rqd, self.total_count)
                self.list_of_rqd = []

            logging.info('========== parser job done. ==========')

        except Exception as e:
            self.new_schedule = Schedule()
            self.new_schedule.sendgrid_account = self.sendgrid_account
            self.new_schedule.subject = self.subject
            self.new_schedule.schedule_timestamp = d.epoch()
            self.new_schedule.schedule_display = d.naive()
            self.new_schedule.sender_name = self.sender_name
            self.new_schedule.sender_email = self.sender_email
            self.new_schedule.category = self.category
            self.new_schedule.type = self.type
            self.new_schedule.txt_object_name = self.txt_object_name
            self.new_schedule.edm_object_name = self.edm_object_name
            self.new_schedule.replace_edm_csv_property = self.replace_edm_csv_property

            if isinstance(e, HttpError):
                self.new_schedule.error = '%s, %s' % (e.content, e.uri)

            else:
                self.new_schedule.error = e.message

            self.new_schedule.put()

            logging.info(
                '========== parser job throw execption (%s). done. =========='
                % self.new_schedule.error)
Ejemplo n.º 23
0
# For each station
for station in Stations.query.all():

    # Request page with all schedule data for that station
    url = 'http://dv.njtransit.com/mobile/tid-mobile.aspx?sid=' + station.abbr
    request_time = time.time()
    trains_page = requests.get(url)
    request_time = time.time() - request_time
    trains_tree = html.document_fromstring(trains_page.text)

    # Scrape stations
    for elem in trains_tree.xpath('//table'):
        if len(elem.getchildren()) == 1 and len(
                elem.getchildren()[0].getchildren()) == 6:
            values = [
                re.sub('[^a-zA-Z0-9- :_*.]', '',
                       x.text_content().strip())
                for x in (elem.getchildren()[0].getchildren())
            ]
            schedule = Schedule(values[0], values[1], values[2], values[3],
                                values[4], values[5])
            station.schedules.append(schedule)
            print values

    db.session.add(Requests(url, request_time, version))

db.session.commit()

print "Success."
Ejemplo n.º 24
0
import pandas as pd
import xlrd
import main
from models import Schedule
import datetime
from main import preprocess_date
from db_setup import db_session

df = pd.read_excel('jobscope.xlsx')

for i in range(df.size):
    try:
        schedule = Schedule()
        dt = datetime.datetime.now()
        barcode = df.iloc[i].values[0]

        schedule.due_date = datetime.date(2019, 8, 6)
        schedule.job_number = schedule.get_job_number(
            barcode).upper()  # Manual
        schedule.work_number = schedule.get_work_order(barcode)  # Manual
        schedule.part_number = schedule.get_part_number()
        schedule.part_description = schedule.get_description()  # Jobscope

        try:
            schedule.part_quantity = schedule.get_quantity()  # Jobscope
        except Exception as e:
            print(str(e))
            schedule.part_quantity = 0

        schedule.part_location = 'Machine Shop'  # Auto
        schedule.entry_time = dt.strftime("%H:%M:%S")  # Auto
Ejemplo n.º 25
0
import random
from functions import costfunction
from models import Schedule, systems
from mcts import MCTSAgent

if __name__ == "__main__":
    # Set the random seeds for reproducibility
    random.seed(40)
    # Create a set of feedback control systems
    variables = systems(2, 1, 1, 3, 1, 20)
    # Construct a cost function
    costfunc = costfunction(variables)
    for period in range(3, 13):  # period length
        # Create an instant for schedule
        schedule = Schedule([], costfunc, period, variables['no_plants'],
                            variables['no_channels'])
        # Set the number of iterations
        no_iterations = {
            "3": 25,
            "4": 75,
            "5": 125,
            "6": 300,
            "7": 900,
            "8": 1800,
            "9": 4000,
            "10": 6000,
            "11": 15000,
            "12": 40000
        }
        # Create a scheduling bot
        bot = MCTSAgent(no_iterations[str(period)], temperature=1.2)
Ejemplo n.º 26
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)