Пример #1
0
def schedule(option, opt_str, value, parser):
	sched = Schedule()
	schedate = datetime.strptime(value, '%m/%d/%Y')

	print "Games scheduled for %s:" %schedate.strftime("%m/%d/%Y")
	for match in sched.date(schedate):
		print match.without_date()
Пример #2
0
def theLoop(adapters,log):
    log.debug("starting scheduler class")
    sch=Schedule(log)
    while 1:
        log.debug("starting loop")
        log.debug("updating schedule")
        sch.makeschedule()
        row=sch.getnextschedule()
        now=int(time.time())
        left=3600
        togo=3600
        if len(row):
            togo=row["start"] - now
            log.debug("next recording: %s in %s" % (row["title"],timeformat(togo)))
        else:
            log.debug("no recordings scheduled")

        rrows=sch.getcurrentrecordings()
        cn=len(rrows)
        if cn:
            log.debug("%d programmes currently being recorded" % cn)
            nextend=rrows[0]["end"]
            left=nextend - now
            log.debug("%s finishes in %s" % (rrows[0]["title"],timeformat(left)))
        else:
            log.debug("nothing currently recording")
        if togo<left:
            timeleft=togo
        else:
            timeleft=left
        log.debug("sleeping for %s" % timeformat(timeleft))
        signal.alarm(left)
        signal.pause()
        log.debug("ending loop")
Пример #3
0
def json_hor(request):
    sched = Schedule(DBSession)
    stop_id = request.GET.get("stop_id").strip().upper()
    stop = sched.getstop(stop_id)
    if stop is None :
        data = {}
    else :
        if stop.is_station :
            liste_stops = stop.child_stations
        else :
            liste_stops = [stop]
        d = request.GET.get("date")
        if d is None :
            ddate = date.today()
        else :
            d = d.replace('-','')
            ddate = date(int(d[4:8]), int(d[2:4]), int(d[0:2]))
        routedir_id = request.GET.get("routedir_id")
        print "route:", routedir_id
        if routedir_id is None or routedir_id == 'ALL' :
            route_id = None
            direction_id = None
        else:
            route_id, direction_id = routedir_id.split('#')
        trips = sched.horaire(liste_stops, d=ddate, route_id=route_id, direction_id=direction_id)
        data = [{'heure': h.departure,
            'ligne': t.route.route_short_name,
            'sens': 'gauche' if t.direction_id == 1 else 'droite',
            'terminus': t.terminus.stop_name,
            'stop': h.stop_id,
            'trip_id': t.trip_id
            } for (h, t) in trips]
    head =['Heure', 'Ligne', 'Sens', 'Terminus', 'Arrêt']
    return {'head':head, 'data':data}
Пример #4
0
def load(feed_filename, db_filename=":memory:"):
    schedule = Schedule(db_filename)
    schedule.create_tables()

    fd = feed.Feed(feed_filename)

    for gtfs_class in (Agency,
                       Route,
                       Stop,
                       Trip,
                       StopTime,
                       ServicePeriod,
                       ServiceException,
                       Fare,
                       FareRule,
                       ShapePoint,
                       Frequency,
                       Transfer,
    ):

        try:
            for i, record in enumerate(fd.get_table(gtfs_class.TABLENAME + ".txt")):
                if i % 500 == 0:
                    schedule.session.commit()

                instance = gtfs_class(**record.to_dict())
                schedule.session.add(instance)
        except KeyError:
            # TODO: check if the table is required
            continue

    schedule.session.commit()

    return schedule
Пример #5
0
def form(request) :
    sched = Schedule(DBSession)
    stop_id = request.matchdict.get("stop_id", "").upper()
    stop = sched.getstop(stop_id)
    q = sched.stop_form(stop_id)
    ret = calc_form(q)
    return {'stop': stop, 'date': date.today(), 'routedirs': ret['sd'], 'stops': ret['ss']}
Пример #6
0
def json_stops(request):
    sched = Schedule(DBSession)
    term = request.GET.get("query")
    # minimum 2 caractères pour renvoyer
    if len(term) < 2 :
        return []
    else :
        return [{'id':s.stop_id, 'name':s.stop_name, 'commune':s.stop_desc} for s in sched.liste_stations(term)]
Пример #7
0
def json_form(request):
    sched = Schedule(DBSession)
    stop_id = request.GET.get("stop_id")
    q = sched.stop_form(stop_id)
    ret = calc_form(q)
    sd = ret['sd']
    return [{'route_id':s[0], 'direction_id':s[1], 'trip_headsign': s[2], 'route_short_name': s[3]}
            for s in sorted(sd, key=itemgetter(0,1))]
Пример #8
0
def accueil(request) :
    route = request.matched_route.name
    if route in ('index', 'accueil') :
        return {}
    else :
        sched = Schedule(DBSession)
        stop_id = request.matchdict.get("stop_id", "").upper()
        stop = sched.getstop(stop_id)
        return {'stop': stop}
Пример #9
0
Файл: sgs.py Проект: Artimi/ukko
 def get_schedule(self, activity_list):
     S = Schedule(self.problem)
     self.al_iter = activity_list.__iter__()
     for i in xrange(self.problem.num_activities):
         activity = self._select_activity()
         precedence_feasible_start = S.earliest_precedence_start(activity)
         real_start = self._compute_real_start(S, activity, precedence_feasible_start)
         S.add(activity, real_start, force=True)
     return S
Пример #10
0
 def test_exchange_column(self):
     """Tests the exchanging of columns in the schedule"""
     t = 10
     s = Schedule(t, t)
     self.assertTrue(s.c[0] == 0)
     self.assertTrue(s.c[1] == 1)
     s.exchange_column(0, 1)
     self.assertTrue(s.c[0] == 1)
     self.assertTrue(s.c[1] == 0)
Пример #11
0
def main():
    """
    The main function of the program that turns user input into a schedule and
    uses a genetic algorithm to find an optimal schedule.
    """
    # Container for user input.
    info = {}

    # Get the desired term and courses.
    if DEBUG:
        info["term"] = "FA16"
        info["courses"] = ["CSE 12", "CSE 15L", "DOC 1"]
    elif handleInput(info):
        return

    print("Finding schedule data...")

    # Get the schedule data for the given courses and term.
    schedule = Schedule()
    schedule.term = info["term"]
    schedule.courses = info["courses"]

    try:
        scheduleData = schedule.retrieve()
    except ClassParserError: 
        print("The Schedule of Classes data could not be loaded at this " \
              "or you have provided an invalid class.")

        return
    
    # Make sure all of the desired classes were found.
    for course in info["courses"]:
        if course not in scheduleData:
            print("'" + course + "' was not found in the Schedule of Classes!")

            return

    # Initiate the population.
    algorithm = Algorithm(scheduleData)
    algorithm.initiate(CAPACITY, CROSSOVER, MUTATE, ELITISM)

    # Run the algorithm through the desired number of generations.
    generation = 0
    highest = 0


    while generation < GENERATIONS:
        algorithm.evolve()
        generation += 1

        print("Generating... "
              + str(int((generation / GENERATIONS) * 100)) + "%", end="\r")

    print("\nDone!")

    algorithm.printFittest()
Пример #12
0
def main(args, app):
    if not args.rrule:
        msg = "Could not parse rrule specification: %s" % " ".join(sys.argv[3:])
        print "Error:", msg
        raise Exception(msg)
    new_schedule = Schedule(name=args.name, rrule=args.rrule, phases=" ".join([]))
    if not args.preview:
        new_schedule.store(app.config)
        app.config.save()
    print "added", new_schedule.format_url()
Пример #13
0
 def test_exhange_row(self):
     """Tests the exchanging of rows in the schedule"""
     t = 10
     s = Schedule(t, t)
     self.assertTrue(s.d[0] == 0)
     self.assertTrue(s.d[1] == 1)
     # Swap rows 0 and 1
     s.exchange_row(0, 1)
     self.assertTrue(s.d[0] == 1)
     self.assertTrue(s.d[1] == 0)
        def should_add_up(self):
            schedule = Schedule()
            schedule.add_lesson(RandomWeeklyLesson())
            schedule.add_lesson(RandomWeeklyLesson())

            b = Bins(schedule=schedule)
            b_ = b.bins()

            expect(b[0] + b[1] + b[2] + b[3] + b[4] + b[5]).to.equal(2)
            expect(b_[0] + b_[1] + b_[2] + b_[3] + b_[4] + b_[5]).to.equal(2)
        def should_delegate_to_df(self):

            l1_1 = WeeklyLesson(start_time=0, day_of_week=0)
            l1_2 = WeeklyLesson(start_time=1, day_of_week=0)
            l1_3 = WeeklyLesson(start_time=0.5, day_of_week=0)

            lessons_1 = [l1_1, l1_2, l1_3]

            s = Schedule(lessons=lessons_1, timezone=Timezone('Abu Dhabi'))
            expect(s.sum().sum()).to.equal(3)
        def should_return_the_timezone_object(self):
            timezone = Timezone('Abu Dhabi')
            l1_1 = WeeklyLesson(start_time=0, day_of_week=0)
            l1_2 = WeeklyLesson(start_time=1, day_of_week=0)
            l1_3 = WeeklyLesson(start_time=0.5, day_of_week=0)
            lessons = [l1_1, l1_2, l1_3]

            s = Schedule(lessons=lessons, timezone=timezone)

            expect(s.timezone()).to.equal(timezone)
Пример #17
0
def handleInput(info):
    """
    Handles prompting for user input and validating user input. The results of
    valid input are stored in the info dictionary.

    :param info: where user input is stored
    :returns: whether or not the program should close
    """
    term = None

    # Get which term will be used.
    try:
        term = input("Enter your desired term (example: FA16): ")
    except:
        print("")

        return True

    # Validate the format of the term.
    while not Schedule.validateTerm(term):
        term = input("You have entered an invalid term, try again: ")

    # Get all the desired courses.
    print("Enter all of your desired classes on a separate line.")
    print("To finish entering classes, input an empty line.")

    courses = []

    while True:
        try:
            course = input()

            if course:
                if Schedule.validateCourse(course):
                    courses.append(course.upper())
                else:
                    print("'" + course + "' is not a valid course code.")
            else:
                break
        except KeyboardInterrupt:
            return True
        except:
            break

    # Validate if any courses were entered.
    if len(courses) == 0:
        print("You did not enter any courses.")

        return True

    # Send the user input to the main function.
    info["term"] = term.upper()
    info["courses"] = courses

    return False
Пример #18
0
def json_map(request):
    sched = Schedule(DBSession)
    latl = request.GET.get("latl", -180)
    lath = request.GET.get("lath", 180)
    lonl = request.GET.get("lonl", -180)
    lonh = request.GET.get("lonh", +180)
    zoom = int(request.GET.get("zoom", -1))
    loc_type = 0 if zoom >= 18 else 1 ;
    stops = sched.stops_latlon(latl=latl, lath=lath, lonl=lonl, lonh=lonh, loc_type=loc_type)
    l = [{'lat': s.stop_lat, 'lon': s.stop_lon, 'id': s.stop_id, 'nom': s.stop_name, 'loc_type':s.location_type} for s in stops]
    return l
    def generate_sample_schedule(self, business_forecast):
        schedule = Schedule()

        for i in business_forecast:
            for j in range(0, int(i['frequency'] * i['schedule_type'])):
                schedule.add_lesson(\
                        RandomWeeklyLesson(\
                        start_time_range=self.start_time_range,
                        day_of_week_range=self.day_of_week_range))

        return schedule
Пример #20
0
 def loadScheduleBtn_clicked(self):
     """Loads a schedule from file"""
     schedule = Schedule()
     filename = QFileDialog.getOpenFileName(self, "Load Schedule", exportsPath, "Schedule Files (*.sched)")
     if filename is not None and filename != "":
         try:
             schedule.load(filename)
             dialog = ScheduleDialog(schedule=schedule)
             result = dialog.exec_()
             if result == True:
                 pass
         except Exception:
             QMessageBox.critical(self, "Error", "Failed to load schedule.", QMessageBox.Ok)
    def __init__(self, start_time_range=(0,23.75,), day_of_week_range=(0,6,)):
        self.start_time_range = start_time_range
        self.day_of_week_range = day_of_week_range

        schedule = Schedule()

        lower_limit_start_time, upper_limit_start_time = start_time_range
        lower_limit_day_of_week, upper_limit_day_of_week = day_of_week_range

        for i in np.linspace(lower_limit_start_time, upper_limit_start_time, 96):
            for j in range(lower_limit_day_of_week, upper_limit_day_of_week + 1):
                schedule.add_lesson( WeeklyLesson(start_time=i, day_of_week=j))

        self.bins = Bins(schedule=schedule).bins()
Пример #22
0
    def test_xor(self):
        """
        Tests the xoring of one row to another
        """
        t = 10
        s = Schedule(t, t)
        self.assertTrue(len(s.xors) == 0)

        # Test xoring row 1 into row 0
        s.xor(0, 1)
        self.assertTrue(len(s.xors) == 1)
        source_row, target_row = s.xors[0]
        self.assertTrue(source_row == 1)
        self.assertTrue(target_row == 0)
Пример #23
0
def json_stop(request):
    sched = Schedule(DBSession)
    stop_id = request.GET.get("stop_id")
    stop = sched.getstop(stop_id)
    if stop :
        return {'id':stop.stop_id, 'name':stop.stop_name, 'commune':stop.stop_desc,
                'location_type':stop.location_type, 'parent_station': stop.parent_station,
                'lat': stop.stop_lat, 'long': stop.stop_lon,
            }
    else :
        return {'id':None, 'name':None, 'commune':None,
                'location_type':None, 'parent_station': None,
                'lat': None, 'long': None,
            }
Пример #24
0
 def __init__(self, task_type_name):
     super(TaskLogFileSweeper,
           self).__init__(schedule=Schedule(frequency_in_seconds=3600))
     self._logs_dir = task_log_dir(task_type_name)
     self._archive_logs_dir = os.path.join(self._logs_dir, "ARCHIVE")
     ensure_dir(self._logs_dir)
     ensure_dir(self._archive_logs_dir)
Пример #25
0
    def setup(self):
        """Generic setup code."""

        # load standard config
        config = ConfigSectionKey('../conf', '../local')
        self.config = config
        config.load('bootstrap.ini', 'bootstrap')
        config.load('init.ini')
        config.load('connect.ini')

        # load project specific config
        self.config.load(self.project_file)
        self.project = self.config('project')

        # load project specific options from optional project specific environ var
        environ_var = just_file_stem(self.project_file).lower()
        self.option = Option(environ_var, options=config('project').options)

        # load project namespace
        self.namespace = self.config('namespace')

        # load project specific schedule
        self.schedule = Schedule(config('schedule'))

        # job specific folders
        self.state_folder = f'{self.session_folder}/{self.namespace.dataset}/state'
        self.work_folder = f'{self.session_folder}/{self.namespace.dataset}/work'
        self.publish_folder = f'{self.session_folder}/{self.namespace.dataset}/publish'
Пример #26
0
def test_players_do_not_play_the_same_game_in_multiple_sessions(games):
    players = [
        {
            'name': 'Alice',
            'owns': [],
            'interests': ['1817']
        },
        {
            'name': 'Bob',
            'owns': ['1817'],
            'interests': ['1817', '1849']
        },
        {
            'name': 'Charles',
            'owns': ['1830'],
            'interests': ['1830']
        },
    ]

    result = Schedule(games, players, [session(), session()]).solve()
    result = result[0] + result[1]

    assert len(result) == 2
    assert ('1817', [players[0], players[1], players[2]]) in result
    assert ('1830', [players[0], players[1], players[2]]) in result
Пример #27
0
	def __init__(self):
		threading.Thread.__init__(self)
		Object.__init__(self)
		
		# OBJECTS
		self.scheduler = Schedule() # The schedule object
		self.series = [] # List of series
Пример #28
0
 def gen_schedule_dict(self, interpreter, appts):
     """
     Modify self.schedule_dict to include appts that Interpreter can cover
     :param interpreter: An Interpreter object
     :param appts: A list of Appointment objects
     :return: None
     """
     self.schedule_dict = {}
     appts = copy.deepcopy(appts)
     sched = Schedule(appts, [interpreter])
     opt = Optimum(sched)
     opt.reset()
     opt_appts = opt.schedule.appts
     opt.update_valid_choices(interpreter.shift_start, opt_appts)
     temp_lst = [appt.idnum for appt in opt.valid_choices[interpreter]]
     temp_lst.sort()
     self.schedule_dict[0] = set(temp_lst)
     for appt in opt.valid_choices[interpreter]:
         opt.reset()
         opt.assign(interpreter, appt)
         appt.interpreter = ""
         opt.update_valid_choices(appt.finish, opt_appts)
         temp_lst = [appt.idnum for appt in opt.valid_choices[interpreter]]
         temp_lst.sort()
         self.schedule_dict[appt.idnum] = set(temp_lst)
Пример #29
0
 def gen_all_paths(self, tree_function, interpreter):
     """
     The DFS core function that generates all paths through tree,
     it modifies self.schedule_paths or self.best_paths
     :param tree_function: An adjacency list (idnum: [idnums])
     :param interpreter: An Interpreter object
     :return: None
     """
     list_of_paths = []
     appts = list(self.appts_to_assign)
     appt_ids = [appt.idnum for appt in appts]
     sched = Schedule(appts, [interpreter])
     opt = Optimum(sched)
     opt.gen_schedule_dict(interpreter, appts)
     tree = dict(opt.schedule_dict)
     nodes = [node for node in tree if node > 0]  # skip the root
     for node in nodes:
         # This lets gen_all_paths iteratively explore the tree,
         # visiting only nodes that are processed instead of all possible
         node_idx = appt_ids.index(node)
         appts_subset = appts[:node_idx + 1]
         opt.gen_schedule_dict(interpreter, appts_subset)
         subtree = dict(opt.schedule_dict)
         # To guard against index errors, tamp down endNode
         (startNode, endNode) = (min(subtree), min(node, max(subtree)))
         list_of_paths.append(
             list(tree_function(subtree, startNode, endNode, interpreter)))
     self.schedule_paths = []
     for row in list_of_paths:
         for appt in row:
             self.schedule_paths.append(appt)
     if interpreter in opt.best_paths:
         self.best_paths[interpreter] = opt.best_paths[interpreter]
Пример #30
0
def run(connections_file, coordinates_file, best_schedule_file, N, max_time,
        improve, depth, exclusion, method):
    """ Runs algorithm with specified heuristic and returns best schedule. """

    best = {"schedule": None, "K": 0, "All": []}

    print(f"{N}x {method.name}")

    for i in range(N):

        # Display progress
        if N >= 100 and i % (N // 100) == 0:
            print(f"{(i // (N // 100))}%", end="\r")

        method.schedule = Schedule(
            csvdata(connections_file, coordinates_file, exclusion), max_time)
        method.run()

        if improve:
            optimize = Optimize(method.schedule, depth)
            optimize.run()

        quality = method.schedule.quality()
        best["All"].append(quality)

        # Keep track of best schedule
        if quality["K"] > best["K"]:
            best["schedule"] = method.schedule
            best["K"] = quality["K"]

    dump(best["schedule"], best_schedule_file)
    best["schedule"].create_csv()
    visualisation(best["schedule"])
    def __init__(self, filename, auto=False):
        self.filename = filename
        self.auto = auto

        self.raw_date = ""
        self.raw_operations = []
        self.raw_notes = []

        self.year = 2000
        self.month = 1
        # self.operations = []
        # self.note_str = ""
        self.notes = {}
        self.notes_exist = False
        self.total_duration = 0
        self.schedule = Schedule()
async def handle_1_TV_raffle(type, raffleid, time_wait, time_limit, num,
                             real_roomid):
    Statistics().append_to_TVlist(raffleid, time_limit)
    if Schedule().scheduled_sleep:
        Printer().printer(f"定时休眠,跳过房间 {real_roomid} 广播道具抽奖 {raffleid}", "Info",
                          "green")
        return
    if bilibili().black_status:
        Printer().printer(f"黑屋休眠,跳过房间 {real_roomid} 广播道具抽奖 {raffleid}", "Info",
                          "green")
        return
    await asyncio.sleep(
        min(
            max(0, time_wait) + random.uniform(0, min(num, 30)),
            time_limit - 1))
    response2 = await bilibili().get_gift_of_TV(type, real_roomid, raffleid)
    # Printer().printer(f"参与了房间 {real_roomid} 的广播抽奖 {raffleid}", "Lottery", "cyan")
    json_response2 = await response2.json(content_type=None)
    # Printer().printer(f"参与房间 {real_roomid} 广播道具抽奖 {raffleid} 状态: {json_response2['msg']}", "Lottery", "cyan")
    if json_response2['code'] == 0:
        data = json_response2["data"]
        Printer().printer(
            f"房间 {real_roomid} 广播道具抽奖 {raffleid} 结果: {data['award_name']}X{data['award_num']}",
            "Lottery", "cyan")
        Statistics().add_to_result(data['award_name'], int(data['award_num']))
    else:
        # {"code":-403,"data":null,"message":"访问被拒绝","msg":"访问被拒绝"}
        # {'code': 503, 'data': None, 'message': '请求太多了!', 'msg': '请求太多了!'}
        # {'code': -509, 'message': '请求过于频繁,请稍后再试', 'ttl': 1}
        Printer().printer(
            f"房间 {real_roomid} 广播道具抽奖 {raffleid} 结果: {json_response2['message']}",
            "Lottery", "cyan")
        print(json_response2)
Пример #33
0
def test_short_sessions_restrict_games_with_static_playtimes(games):
    players = [
        {
            'name': 'Alice',
            'owns': ['1817'],
            'interests': ['1817']
        },
        {
            'name': 'Bob',
            'owns': ['1860'],
            'interests': ['1817']
        },
        {
            'name': 'Charles',
            'owns': [],
            'interests': ['1817']
        },
        {
            'name': 'Dick',
            'owns': [],
            'interests': ['1817']
        },
    ]

    result = Schedule(games, players, [session(length=300)]).solve()

    assert result == [
        [('1860', players)],
    ]
Пример #34
0
	def start(self):
		"""
		Override: Code called on initial start and subsequent restarts.

		Must set:
		- self.option = Option()
		- self.schedule = Schedule()

		Note: We don't load resources here; resources are loaded on demand.
		"""

		# load standard config
		config = ConfigSectionKey('../conf', '../local')
		self.config = config
		config.load('bootstrap.ini', 'bootstrap')
		config.load('init.ini')
		config.load('connect.ini')

		# load project specific config
		self.config.load(self.project_file)

		# load project specific options from optional project specific environ var
		environ_var = just_file_stem(self.project_file).lower()
		self.option = Option(environ_var, options=config('project').options)

		# load project specific schedule
		self.schedule = Schedule(config('schedule'))

		# diagnostics
		self.option.dump()
		self.config('project').dump(False)
		self.config('schedule').dump(False)
Пример #35
0
    def __init__(self, master, customers, payments, refresh):
        Toplevel.__init__(self,master)

        self.root = master
        self.refresh = refresh

        self.title("Check In")
        self.iconname = "Check In"

        self.name = StringVar() # variable for customer
        self.customers = customers # customers object
        self.payments = payments
        self.names = []
        self.workout = StringVar()
        self.workouts = []
        self.workouts_form = []
        self.date = StringVar()
        self.date.set(strftime("%m/%d/%Y"))
        self.refresh_time = 15 # in minutes
        self.output = '' # for the output label at the bottom
        self.schedule = Schedule()

        self.logger = Logger() #throws IOError if file is open

        inf = Frame(self)
        inf.pack(padx=10,pady=10,side='top')
        Label(inf, text="Name:").grid(row=0,column=0,sticky=E,ipady=2,pady=2,padx=10)
        Label(inf, text='Date:').grid(row=1,column=0,sticky=E,ipady=2,pady=2,padx=10)
        Label(inf, text="Workout:").grid(row=2,column=0,sticky=E,ipady=2,pady=2,padx=10)

        self.name_cb = Combobox(inf, textvariable=self.name, width=30,
                                values=self.names)
        self.name_cb.grid(row=0,column=1,sticky=W,columnspan=2)
        self.date_ent = Entry(inf, textvariable=self.date)
        self.date_ent.grid(row=1,column=1,sticky=W)
        self.date_ent.bind('<FocusOut>', self.update_workouts)
        Button(inf,text='Edit', command=self.enable_date_ent).grid(row=1,column=2,sticky=E)
        self.workout_cb = Combobox(inf, textvariable=self.workout, width=30,
                                   values=self.workouts_form,state='readonly')
        self.workout_cb.grid(row=2,column=1,sticky=W,columnspan=2)

        self.log_btn=Button(inf,text="Log Workout",command=self.log,width=12)
        self.log_btn.grid(row=3,column=1,columnspan=2,pady=4,sticky='ew')
        
        stf = Frame(self)
        stf.pack(padx=10,pady=10,fill='x',side='top')
        self.scrolled_text = ScrolledText(stf,height=15,width=50,wrap='word',state='disabled')
        self.scrolled_text.pack(expand=True,fill='both')

        self.update_workouts()
        self.update_names()

        self.bind('<Return>',self.log)
        self.name_cb.focus_set()  # set the focus here when created

        #disable the date field
        self.disable_date_ent()

        #start time caller
        self.time_caller()
Пример #36
0
 def __init__(self, vm_limit, azure_config, skip_setup, local):
     self.vm_limit = vm_limit # user input
     self.budget = 0
     self.timestamp = datetime.now()
     self.cost_pred = 0
     self.wf_end = None
     
     self.jobs_terminated = False
     self.last_resched = None
     
     self.workflow = Workflow()
     self.logwatcher = LogWatcher()
     
     self.schedule = Schedule()
     
     manager = Machine()
     manager.status = MachineStatus.manager
     manager.condor_slot = 'manager'
     self.machines = [manager]
     
     boot_entry = ScheduleEntry(Job('boot', None), manager, self.timestamp, self.timestamp)
     boot_entry.real_start = self.timestamp
     boot_entry.real_end = self.timestamp
     boot_entry.status = EntryStatus.completed
     self.schedule.add_entry_host(boot_entry, manager)
     
     self.local = local
     if azure_config and not local:
         hostname = socket.gethostname()
         self.exp = AzureExperiment(azure_config, skip_setup=skip_setup, name=hostname)
         self.master_addr = socket.gethostbyname(hostname)
         self.user = azure_config.admin_username
     else:
         self.exp = self.master_addr = self.user = None
Пример #37
0
	def GET(self):
		try:
			DELETE_DATE_THRESHOLD = date.today() - timedelta(3 * 30) #approx. 1 month
			db.delete(Schedule.gql("WHERE modified <= :1", DELETE_DATE_THRESHOLD))
			return 'Successfully deleted all schedules before %s' % DELETE_DATE_THRESHOLD
		except:
			return 'Problem deleting old schedules..'
Пример #38
0
def main():

    try:

        web_conf_path, task_dir = parse()

        #set task dir
        mkdir_needfile(task_dir)
        shutil.copy(web_conf_path, task_dir)

        #snappydata create table
        web_conf_dict = load_json(task_dir + '/web_config.json')
        config = atuocreatetable_config(web_conf_dict)
        for schema_db_tb in web_conf_dict['sync_tables']:
            schema, database, table = re.split('\.', schema_db_tb)
            print(schema, database, table, config)
            t = QuerypkOperation(schema, database, table, config)
            t.operate()

        #create offline sync service structure
        sdc_url = web_conf_dict["sdc_url"]
        taskID = web_conf_dict["taskID"]
        errorMessage_filepath = task_dir + '/log/errorMessage.txt'
        error_tb_filepath = task_dir + '/log/errorTable.txt'
        sync_newpipelineID_list, sync_df, sdc = create_structure(
            sdc_url, web_conf_dict, taskID, errorMessage_filepath,
            error_tb_filepath)

        #start schedule to control service
        s = Schedule(sdc, sdc_url)
        s.schedule(taskID, sync_newpipelineID_list, sync_df)

        #send mail to business for reporting sync errors
        receiver = web_conf_dict["email_receiver"]
        if os.path.getsize(errorMessage_filepath):
            send_mail(receiver, errorMessage_filepath)
        else:
            print("No error records appeared during sync")
        if os.path.getsize(error_tb_filepath):
            send_mail(receiver, error_tb_filepath)
        else:
            print("No table with lack of records during sync")

    except Exception as e:
        msg = traceback.format_exc()
        print(msg)
        print(e)
Пример #39
0
    def new_message(self, message):

        if message.upper() == self._COMMANDS[0]:
            return self._HELLO[randint(0, len(self._HELLO) - 1)]

        elif message.upper() == self._COMMANDS[1] or message.upper() == self._COMMANDS_SHORT[1]:
            return self._get_time()

        elif message.upper() == self._COMMANDS[2]:
            return self._BYE[randint(0, len(self._BYE) - 1)]

        elif message.upper().split(' ')[0] == self._COMMANDS[3] or message.upper().split(' ')[0] == self._COMMANDS_SHORT[3]:
            data = message.split(' ')
            db = Database()
            if(not db._check_if_user_exists(self._USER_ID)):
                return f"Пожалуйста сначала зарегистрируйтесь!"
            user_info = db._get_user_info(self._USER_ID)
            if len(data) == 2:
                if(data[1] not in self._GROUPS):
                    if(data[1] in self._GROUPS_ENG):
                        data[1] = self._GROUPS[self._GROUPS_ENG.index(data[1])]
                    else:
                        return "Ошибка группы!"
                sc = Schedule(data[1], user_info[1], user_info[2])
            else:
                sc = Schedule(user_info[0], user_info[1], user_info[2])
            return sc._get_schedule()

        elif message.upper() == self._COMMANDS[4] or message.upper() == self._COMMANDS_SHORT[4]:
            return "Всё что я понимаю это: \nПРИВЕТ - бесполезная опция, но если вам нечем больше заняться, можете также попробовать команду ПОКА\n\n\
            (В)РЕМЯ - скажу, который сейчас час\n\n(П)ОМОЩЬ - выведу вот это сообщение :)\n\n(Р)АСПИСАНИЕ [А-XX-18]- покажу расписание. Если группа не указана, расписание будет для вашей группы.\n\n\
            (З)АРЕГИСТРИРОВАТЬСЯ - если вы не зарегистрировались, для просмотра ваших оценок придётся это сделать, написав следующее:\n(З)АРЕГИСТРИРОВАТЬСЯ ваш_логин ваш_пароль А-XX-18 \n\n\
            (Б)АРС - просмотр оценок\n"

        elif message.split(' ')[0].upper() == self._COMMANDS[5] or message.split(' ')[0].upper() == self._COMMANDS_SHORT[5]:
            return self._register(message)

        elif message.upper() == self._COMMANDS[6] or message.upper() == self._COMMANDS_SHORT[6]:
            db = Database()
            if(not db._check_if_user_exists(self._USER_ID)):
                return f"Пожалуйста сначала зарегистрируйтесь!"
            user_info = db._get_user_info(self._USER_ID)
            bars = Bars(user_info[1], user_info[2])
            return bars._get_data()

        else:
            return self._DONT_KNOW[randint(0, len(self._DONT_KNOW) - 1)]
Пример #40
0
 def add_schedule(self, time, thing=None):
     if thing == None:  #thing==None时则是在time的位置其实是传入了一个schedule类了
         schedule = time
         self.insert_schedule(schedule)
     else:  #否则传入的就只是time和thing
         schedule = Schedule(time, thing)
         self.insert_schedule(schedule)
     return schedule
Пример #41
0
 def create_schedule(self):
     self.schedule = Schedule()
     if self.strategy == None:
         self._add_mandatory_actions()
         self.occupation.add_default_schedule(self, self.possession)
     else:
         self._add_mandatory_actions()
         self.strategy.create_schedule()
Пример #42
0
class Individual:
    def __init__(self, tag: int):
        self.tag = tag
        self.schedule = Schedule(tag)
        self.reqOffPeriods = 1

    def changeReqOff(self, newReq: int):
        self.reqOffPeriods = newReq

    def getReqOff(self) -> int:
        return self.reqOffPeriods

    def addSection(self, newSection: Section):
        self.schedule.addSection(newSection)

    def removeSection(self, section: Section):
        self.schedule.removeSection(section)

    def getSections(self):
        return self.schedule.getSections()

    def offDelta(self):
        """
        Positive when more scheduled off than required, negative when fewer scheduled off than required
        """
        return (len(self.schedule.getOpenPeriods()) - self.reqOffPeriods)

    def hasPotentialLunchSlot(self, lunchPeriods: list):
        for period in self.schedule.getOpenPeriods():
            if period in lunchPeriods:
                return True
        return False
Пример #43
0
def parse_scheduled(courses, start_date, course_start_date, calendar_dict):
    # pre-process to dataframe
    history = {}
    for course in courses:
        if course.start_date > start_date:
            continue
        history_df = pd.read_csv('Output/' + course.title + '_history_cleaned.csv')
        for index, row in history_df.iterrows():
            if '/' in row['Date']:
                cur_date_month, cur_date_day, cur_date_year = row['Date'].split('/')
            else:
                cur_date_year, cur_date_month, cur_date_day = row['Date'].split('-')
            history_df.loc[index, 'Date'] = date(int(cur_date_year), int(cur_date_month), int(cur_date_day))
        history[course] = history_df
    cur = course_start_date
    while cur < start_date:
        cur_schedule = Schedule(date=cur)
        for course, history_df in history.items():
            cur_history_df = history_df[history_df['Date'] == cur]

            if not cur_history_df.index.empty:
                cur_schedule.add_course(course=course, lesson=get_lesson(course=course, id=cur_history_df['Id'].item()),
                                        ins=get_ins_by_name(course=course, name=cur_history_df['Ins'].item()), point=0,
                                        calendar_dict=calendar_dict)

        if cur_schedule.is_valid():
            cur_schedule.schedule_today(calendar_dict=calendar_dict)
        cur += datetime.timedelta(days=1)
Пример #44
0
	def get(self):
		user = users.get_current_user()

		if user != None:
			user_name = user.nickname()
			access_link = users.create_logout_url('/')

			# Get query from database
			monday = Schedule.query(Schedule.user == user.user_id()).filter(Schedule.day == 'lunes')
			tuesday = Schedule.query(Schedule.user == user.user_id()).filter(Schedule.day == 'martes')
			wednesday = Schedule.query(Schedule.user == user.user_id()).filter(Schedule.day == 'miercoles')
			thursday = Schedule.query(Schedule.user == user.user_id()).filter(Schedule.day == 'jueves')
			friday = Schedule.query(Schedule.user == user.user_id()).filter(Schedule.day == 'viernes')
			saturday = Schedule.query(Schedule.user == user.user_id()).filter(Schedule.day == 'sabado')
			sunday = Schedule.query(Schedule.user == user.user_id()).filter(Schedule.day == 'domingo')

			template_values = {
				'user_name' : user_name,
				'access_link' : access_link,
				'monday' : monday,
				'tuesday' : tuesday,
				'wednesday' : wednesday,
				'thursday' : thursday,
				'friday' : friday,
				'saturday' : saturday,
				'sunday' : sunday
			}

			template = JINJA_ENVIRONMENT.get_template('showSchedule.html')
			self.response.write(template.render(template_values));
		else:
			self.redirect('/')
Пример #45
0
def main():

    #title of the online schedule (a Google Sheet)
    sheet_title = get_tomorrows_date()

    #the online schedule for the next day
    schedule = Schedule(sheet_title)

    #the content being sent to instructors
    group_text = TextMessage()

    people = schedule.get_scheduled_instructors()
    for person in people:
        to_add = Instructor(person, todays_schedule=schedule).get_human_time()
        group_text.append_to_msg_content(to_add)

    group_text.send_text()
    return
Пример #46
0
def fetchSchedules():
    cur.execute("SELECT id FROM schedules;")
    res = []
    i = 0
    results = cur.fetchall()
    for row in results:
        res.append(Schedule(row[0], cur))
        i = i + 1
    return res
Пример #47
0
    def __init__(self):
        self.__schedule = Schedule()

        self.__vk = vk_api.VkApi(token=token)
        self.__vk_api = self.__vk.get_api()

        self.__longpoll = VkLongPoll(self.__vk)
        self.__database = Database()
        self.__handler = Handler(self.__database, self.__schedule)
Пример #48
0
 def __init__(self, event):
     self.title = utils.fix(event.get("title"))
     self.description = utils.fix(event.get("shortdesc"))
     self.content = utils.fix(event.get("longdesc"))
     self.hint = None
     self.schedules = [
         Schedule(utils.fix(event.get("sname")),
                  event.get("begin_timestamp"), event.get("duration_sec"))
     ]
Пример #49
0
 def GetSchedule(self, polyline):
     """ Return a computed schedule to the user. 
     """
     if self.Directions is None:
         raise Exception("No Schedule Found!")
     chargers = [
         self.Environment.Route[c] for c, _ in self.ChargingPoints.items()
     ]
     return Schedule(self.Directions, polyline, chargers)
Пример #50
0
 def setUp(self):
     self.schedule = Schedule()
     self.schedule.insert({
         "enable": 1,
         "alias": "reboot",
         "command": "uptime && reboot",
         "schedule": "0 0 * * *",
         "executer": True
     })
Пример #51
0
def test_add_schedule_to_group():
    sadistix_group = Group("Sadistix Coders", "Invite_key")
    first_schedule = Schedule("SampleTitle", "Discription",
                              datetime.datetime.now())
    sadistix_group.add_schedule(first_schedule)
    assert sadistix_group.schedule_count == 1

    schedule = sadistix_group.urgent_schedule
    assert "SampleTitle" in str(schedule)
def main():

    schedule=Schedule()

    ts=[]
    ##存放电梯运行的线程

    t1=Thread(target=random_input,args=(schedule,ts),name='Thread-task')
    ##任务线程

    t2=Thread(target=show_status,args=(schedule,),name='Thread-monitoring')
    ##监控线程

  
    t1.start()
    t2.start()

    for elevator in schedule.elevators:

        name='Thread-elevator-%s'%(elevator.name)
        t=Thread(target=run_elevator,args=(elevator,),name=name)
        ts.append(t)


    

    while True:
        ##用于监听是否有运行中的电梯线程挂掉

        broken_list=[]
         ##用于存放挂掉的线程

        for t in ts:

            if t.is_alive():

                print u'%s is alive'%(t.name)

            else:
                print u'%s is broken'%(t.name)
                broken_list.append(t)

                ##线程结束了,对应的电梯就无法启动了,那么需要开辟一个新的线程运行该电梯
                for elevator in schedule.elevators:
                    name=u'Thread-elevator-%s'%elevator.name
                    if  name ==t.name:
                        add_elevator(elevator,ts)
                        print u'apppend broken Thread:%s back to ts'%(t.name)
                        break

        for t in broken_list:
            if t in ts:
                ts.remove(t)
                ##从ts中移除挂掉的线程

        sleep(10)
    def __schedule(self, itineraries, simulation, priority_list):
        self.__reset_itineraries(itineraries)
        predict_simulation = simulation.copy
        predict_simulation.airport.apply_schedule(Schedule(itineraries, 0, 0))
        tick_times = 5
        for i in range(tick_times):
            predict_simulation.pre_tick(self)
            self.__schedule_new_aircrafts(simulation, predict_simulation,
                                          itineraries, priority_list)
            predict_simulation.airport.apply_priority(priority_list)
            if i == tick_times - 1:
                # Done, conflicts are all handled, return the schedule
                self.__reset_itineraries(itineraries)
                return Schedule(itineraries, 0, 0), priority_list

            # After dealing with the conflicts in current state, tick to
            # next state
            predict_simulation.tick()
            predict_simulation.post_tick()
Пример #54
0
    def setup(self):
        nn = self.options['num_nodes']
        nv = self.options['num_vehicles']

        self.add_subsystem('schedule',
                           Schedule(num_nodes=nn, num_v=nv),
                           promotes=['*'])
        self.add_subsystem('vehicles',
                           Vehicles(num_nodes=nn, num_v=nv),
                           promotes=['*'])
Пример #55
0
    def _initialize(self):
        """
        Initialize the population of schedules.
        """
        for idx in range(self.parameters.population_size):
            self._population[idx] = Schedule(self.resources, self.parameters)
            self._population[idx].initialize()
            self._population[idx].calculate_fitness()

        self._track_best()
Пример #56
0
def sgs(project, alr):
    schedule = Schedule(project)
    for task_id in alr:
        task = schedule.tasks[task_id]
        schedule = greedily_schedule_task(task, project, schedule)
        # if greedy scheduling of task fails (i.e. misses max. time-lag)
        if schedule == 1:
            #            print('greedy scheduling has failed')
            return 1
    return schedule
Пример #57
0
    def init(self):
        self._updater = Updater(token=TOKEN, use_context=True)
        self._schedule = Schedule()
        self._database = BotDatabase()
        self._database.init()
        Logger.init()

        dispatcher = self._updater.dispatcher
        handler = CommandHandler('start', self.on_start_cmd)
        dispatcher.add_handler(handler)

        handler = MessageHandler(Filters.text, self.on_text)
        dispatcher.add_handler(handler)

        handler = CommandHandler('print', self.on_print_cmd)
        dispatcher.add_handler(handler)

        handler = CommandHandler('clear', self.on_clear_cmd)
        dispatcher.add_handler(handler)
Пример #58
0
def load(feed_filename, db_filename=":memory:", verbose=True):
    schedule = Schedule(db_filename)
    schedule.create_tables()

    fd = feed.Feed(feed_filename)

    for gtfs_class in (
            Agency,
            Route,
            Stop,
            Trip,
            StopTime,
            ServicePeriod,
            ServiceException,
            Fare,
            FareRule,
            ShapePoint,
            Frequency,
            Transfer,
    ):

        if verbose:
            print "loading %s" % gtfs_class

        try:
            for i, record in enumerate(
                    fd.get_table(gtfs_class.TABLENAME + ".txt")):
                if i % 500 == 0:
                    if verbose:
                        sys.stdout.write(".")
                        sys.stdout.flush()
                    schedule.session.commit()

                instance = gtfs_class(**record.to_dict())
                schedule.session.add(instance)
            print
        except KeyError:
            # TODO: check if the table is required
            continue

    schedule.session.commit()

    return schedule
def addSchedule(sheet, id_module_class) -> None:
    def parseDate(string) -> datetime:
        try:
            return datetime.strptime(string, "%d/%m/%Y")
        except:
            return None

    def parseInt(string) -> int:
        try:
            return int(string)
        except:
            return None

    i = 6

    while True:
        cell_str = sheet.cell(i, 2).value

        days = cell_str.split()
        start_day = parseDate(days[1])
        end_day = parseDate(days[3])

        while True:
            i += 1

            cell_str = sheet.cell(i, 2).value

            if cell_str == "":
                return

            cell_str_arr = cell_str.split()

            dow = cell_str_arr[1]

            if parseInt(dow) == None:
                break

            curr_day = start_day + timedelta(days=int(dow) - 2)

            shift = int(cell_str_arr[3].split(",")[1]) % 3 + 1
            room = cell_str.split(", ")[1].split()[0]

            while curr_day <= end_day:
                s = Schedule(
                    ID_Module_Class=id_module_class,
                    ID_Room=room,
                    Shift_Schedules=shift,
                    Day_Schedules=curr_day,
                )

                schedules_res.append(s)

                # print(s)

                curr_day = curr_day + timedelta(days=7)
Пример #60
0
    def test(self):
        pat1 = Patient(1, 'One', {'Spanish'}, 'Male')
        pat2 = Patient(2, 'Two', {'Spanish'}, 'Male')
        pat3 = Patient(3, 'Three', {'Spanish'}, 'Male')
        pat4 = Patient(4, 'Four', {'Spanish'}, 'Male')
        pat5 = Patient(5, 'Five', {'Spanish'}, 'Male')
        loc1 = Location(0, 0, "Building", "Clinic")
        a1 = Appointment(1, "8:00", 15, pat1, loc1, 1, "Dr.", "")
        a2 = Appointment(2, "8:10", 30, pat2, loc1, 2, "Dr.", "")
        a3 = Appointment(3, "8:30", 20, pat1, loc1, 3, "Dr.", "")
        a4 = Appointment(4, "8:45", 35, pat2, loc1, 4, "Dr.", "")
        a5 = Appointment(5, "9:30", 35, pat2, loc1, 5, "Dr.", "")
        a6 = Appointment(6, "9:00", 75, pat3, loc1, 6, "Dr.", "")
        a7 = Appointment(7, "8:35", 150, pat4, loc1, 7, "Dr.", "")
        a8 = Appointment(8, "8:30", 180, pat5, loc1, 8, "Dr.", "")
        appts = [a1, a2, a3, a4, a5, a6, a7, a8]
        sched = Schedule(appts, [
            Interpreter("Inter", {'Spanish', 'English'}, "Male", "8:00",
                        "17:00", {})
        ])
        inter = sched.interpreters[0]
        precalculated_p = {1: 0, 2: 0, 3: 1, 4: 2, 5: 4, 6: 3, 7: 1, 8: 1}
        precalculated_weights = {
            0: 0,
            1: 1,
            2: 2,
            3: 4,
            4: 6,
            5: 11,
            6: 11,
            7: 11,
            8: 11
        }

        global sched_test
        sched_test = appts
        cls = bfd(sched)
        p_dict = {}
        for appt in appts:
            prior = appt.calc_prior(appts)
            if prior is not None:
                p_dict[appt.idnum] = prior.idnum
            else:
                p_dict[appt.idnum] = 0
        # This tests whether calc_prior returns the correct indices
        self.assertEqual(p_dict, precalculated_p)
        self.assertEqual(cls.appt_weights, precalculated_weights)

        # test compute_optimal
        precalculated_co = [2, 4, 5]
        optimal = cls.compute_optimal(len(cls.appts_to_assign),
                                      cls.appts_to_assign)
        optimal = sorted([int(idx) for idx in optimal.split(', ')])
        optimal.pop(0)
        self.assertEqual(precalculated_co, optimal)