Exemplo n.º 1
0
    def __init__(self, main):

        self.__main = main
        self.__main.geometry("%dx%d+%d+%d" % (1, 1, 1, 1))
        self.__main.overrideredirect(True)
        self.__main.resizable(False, False)

        self.__opened = False
        self.__modified = False
        self.__saved = False
        self.__configChanged = False
        self.__path = ""

        import pyglet
        pyglet.font.add_file('Hammerfat.ttf')
        self.__setFont(1)

        self.__dicts = Dictionaries()
        __monitor = Monitor()
        __loading_Screen = DisplayLoading(__monitor.get_screensize())
        self.__Config = Config(self.__dicts)
        if self.__Config.get_Element("StaticSize") == "0":
            s = self.__GetWindowSize(__monitor.get_screensize())
        else:
            s = int(self.__Config.get_Element("StaticSize"))

        self.__size_Num = self.__Create_Main_Window_By_Screen_Size(
            s, __monitor.get_screensize(),
            self.__Config.get_Element("Language"))
    def __init__(self):

        global bandwidthBytes, packetBuffer, TCPBuffer, SYNBuffer, NULLBuffer, XMASBuffer, FINBuffer, UDPBuffer, ICMPBuffer, userInterfaceData, logList, timer

        # initialise global variables and lists
        userInterfaceData = [None, None, None, None, None, None]
        packetBuffer = []
        TCPBuffer = []

        SYNBuffer = []
        NULLBuffer = []
        XMASBuffer = []
        FINBuffer = []
        UDPBuffer = []
        ICMPBuffer = []

        # instantiate monitor object to capture network traffic
        global monitor
        monitor = Monitor()
        monitor.startMonitoringConnection()

        currentDateTime = datetime.datetime.now(
        )  # calculate current system time
        timer = time.time()
        logDateTime = 'Event logs for ' + (
            currentDateTime.strftime('%c')
        )  # start log entry in human readable format
        logList = [logDateTime, '-----------------']
Exemplo n.º 3
0
def Login():
    uName = raw_input("Enter user name:")
    uPass = raw_input("Enter password:"******"127.0.0.1", "root", "password", "srmudb")
    mycursor = db.cursor()
    mycursor.execute("select * from employee")
    for row in mycursor:
        dbUser = row[0]
        dbPass = row[1]
        dbStatus = row[6]
        if uName == dbUser:
            if uPass == dbPass:
                dbtype = row[2]
                if dbStatus == "activated":
                    if dbtype == "admin":
                        Admin.final()
                        break
                    else:
                        Monitor.final(uName)
                        break

    else:
        print("Login Authentication Failed")
    db.commit()
    db.close()
Exemplo n.º 4
0
def get_filepath_inode_map(mountpoint, dir):
    paths = Monitor.get_all_paths(mountpoint, dir)

    df = dataframe.DataFrame()
    df.header = ['filepath', 'inode_number']
    for path in paths:
        inode_number = Monitor.stat_a_file(os.path.join(mountpoint, path))['inode_number']
        df.addRowByList([path, inode_number])

    return df
def process1(process, monitor):
    print("processo 1 start")
    first = True
    while True:
        if not first:
            monitor.wait(process.id)
        else:
            first = False
        print(process)
        monitor.signal(process.id)
Exemplo n.º 6
0
def get_filepath_inode_map(mountpoint, dir):
    paths = Monitor.get_all_paths(mountpoint, dir)

    df = dataframe.DataFrame()
    df.header = ['filepath', 'inode_number']
    for path in paths:
        inode_number = Monitor.stat_a_file(os.path.join(mountpoint,
                                                        path))['inode_number']
        df.addRowByList([path, inode_number])

    return df
def main():
    p1 = monitor.Process(1)
    p2 = monitor.Process(2)
    p3 = monitor.Process(3)
    pm = monitor.process_manager()
    pm.add_Process(p1)
    pm.add_Process(p2)
    pm.add_Process(p3)
    Monitor = monitor.Monitor(pm)

    t1 = threading.Thread(target= process1, args = (p1,Monitor))
    t2 = threading.Thread(target= process2, args = (p2,Monitor))
    t3 = threading.Thread(target= process3, args = (p3,Monitor))

        t1.start()
Exemplo n.º 8
0
def pipeline(path, start, end):
    moni = Monitor.Monitor(path)
    moni.creat_json_file()
    anchor = start
    while anchor < end:
        # print(anchor, end)
        if anchor == 0:
            GeoOPt.geo_opt(path, moni)
        elif anchor == 1:
            if start == 1:
                HF1.hf1_start(path, moni)
            else:
                HF1.hf1(path, moni)
        elif anchor == 2:
            Localization.localization(path, moni)
        elif anchor == 3:
            HF2.hf2(path, moni)
        elif anchor == 4:
            LMP2.lmp2(path, moni)
            if if_skip_rpa() == 1:
                anchor += 1
        elif anchor == 5:
            RPA.rpa(path, moni)
        elif anchor == 6:
            Cluster.cluster(path)
        elif anchor == 7:
            Correction.correction(path, moni)
        elif anchor == 8:
            Results.results(path)
        anchor += 1
    end_programm(path)
Exemplo n.º 9
0
    def show_cpu(self):
        key = ["用户空间", "内核空间", "空闲"]

        # 666:数据库查询,结果为str显示到文本框
        lab = Utils.get_arg("Lab")
        flag1, password = dbutils.find_value("LabIP", lab, "Password")
        flag2, ip = dbutils.find_value("LabIP", lab, "IP")
        flag3, user = dbutils.find_value("LabIP", lab, "User")
        # print(password,ip,flag1,flag2)
        if flag1 and flag2 and flag3:
            # CPU信息
            cpu_info = Monitor.os_cpu(ip, user, password)
            if cpu_info == False:
                messagebox.showinfo(title='提示', message="网络连接超时")
            else:
                root = Tk()
                tree = ttk.Treeview(root, show="headings")

                root.title("%s实验室cpu" % lab)

                tree["columns"] = (key[0], key[1], key[2])
                tree.column(key[0], width=100)  # 表示列,不显示
                tree.column(key[1], width=100)
                tree.column(key[2], width=100)

                tree.heading(key[0], text=key[0])  # 显示表头
                tree.heading(key[1], text=key[1])
                tree.heading(key[2], text=key[2])

                # 写入数据
                tree.insert('', 0, values=cpu_info)
                tree.pack(side=LEFT, fill=BOTH)
        else:
            messagebox.showinfo(title='提示', message="数据库查找不到%s实验室的ip或口令" % lab)
Exemplo n.º 10
0
def run(interval, command):
    Log.info("*" * 51)
    #log.print_ts("Command %s"%command)
    Log.info("Run every %s seconds." % interval)
    Log.info("*" * 51)
    main = Func.Func()
    monitor = Monitor.Monitor()
    while True:
        try:
            # sleep for the remaining seconds of interval
            time_remaining = interval - time.time() % interval
            Log.info("Sleeping until %s(%.3f seconds).." % (time.strftime(
                "%Y-%m-%d %H:%M:%S",
                time.localtime(
                    (time.time() + time_remaining))), time_remaining))
            time.sleep(time_remaining)
            Log.info("-" * 51)
            #log.print_ts("Starting command.")
            Log.info("Starting Run...")
            # execute the command
            main.Run()
            monitor.Run()
            Log.info("Stop...")
            #status = os.system(command)
            Log.info("-" * 51)
            #log.print_ts("Command status = %s."%status)
        except Exception as e:
            Log.error("LogtextArchived.run() error code: %s" % (str(e)))
Exemplo n.º 11
0
def schedule_lectures(ics_path, func):
    '''read ICS from @ics_path and schedule @func at given time'''
    utils.log('INFO', 'Starting scheduling capturing...')
    gcal = utils.get_cal(ics_path)
    utils.print_cal_events(gcal)
    Monitor.FUNC = func

    # initialize scheduler for events
    Monitor.SCHED = sched.scheduler(time.time, time.sleep)

    for component in gcal.walk():
        if component.name == "VEVENT":
            summary = component.get('summary')
            start_time = component.get('dtstart').dt
            end_time = component.get('dtend').dt
            time_delta = end_time - start_time
            seconds = time_delta.total_seconds()
            args = summary.split(' ')
            args.append(seconds)

            # create new Monitor
            if start_time < utils.utc_now():
                continue
            job = Monitor.Monitor(Monitor.SCHED, func, args, start_time)
            Monitor.MONITORS.append(job)

    # Schedule all events
    for mo in Monitor.MONITORS:
        mo.schedule_task()
    utils.log('INFO', 'Finished scheduling capturing...')

    cal_receiver.start_server()

    while 1:
        pass
Exemplo n.º 12
0
def msg_receive(msg):
    if itchat.search_friends(
            userName=msg['FromUserName'])['NickName'] == '**':  #** 为你的微信昵称
        list = msg['Content'].split()
        price = None
        clock = int(5)
        if len(list) > 0:
            id = list[0][3:]
        else:
            id = None
        if len(list) == 3:
            price = list[1][6:]
            clock = int(list[2][6:])
        elif len(list) == 2:
            if list[1][:5] == 'price':
                price = list[1][6:]
            elif list[1][:4] == 'clock':
                clock = int(list[2][6:])
        if len(list) > 0 and list[0][:2] == 'id' and id != None:
            monitor = Monitor.Monitor(sess=requests.Session(),
                                      stock_id=id,
                                      price=price,
                                      area_id='2_2830_51800_0',
                                      clock=clock)
            monitor.good_detail_loop()
Exemplo n.º 13
0
    def show_result(self):
        # 666:数据库查询,结果为str显示到文本框
        lab = Utils.get_arg("Lab")
        flag1, password = dbutils.find_value("LabIP", lab, "Password")
        flag2, ip = dbutils.find_value("LabIP", lab, "IP")
        flag3, user = dbutils.find_value("LabIP", lab, "User")
        # print(password,ip,flag1,flag2)
        if flag1 and flag2 and flag3:

            # 进程信息
            login_success = Monitor.login_success(ip, user, password)
            if login_success == False:
                messagebox.showinfo(title='提示', message="网络连接超时")
            else:
                root = Tk()
                tree = ttk.Treeview(root, show="headings")

                root.title("%s实验室登录记录" % lab)
                key = ["登录IP", "工作日", "登入时间", "登出时间"]
                tree["columns"] = ("登录IP", "工作日", "登入时间", "登出时间")
                tree.column(key[0], width=150)  # 表示列,不显示
                tree.column(key[1], width=50)
                tree.column(key[2], width=200)
                tree.column(key[3], width=200)

                tree.heading(key[0], text=key[0])  # 显示表头
                tree.heading(key[1], text=key[1])
                tree.heading(key[2], text=key[2])
                tree.heading(key[3], text=key[3])

                for i in range((len(login_success))):  # 写入数据
                    tree.insert('', i, values=login_success[i])
                tree.pack(side=LEFT, fill=BOTH)
        else:
            messagebox.showinfo(title='提示', message="数据库查找不到%s实验室的ip或口令" % lab)
Exemplo n.º 14
0
 def CleanUpFile(self, fileName):
     import os
     ctime = os.path.getctime(fileName)
     import Monitor
     monitor = Monitor.Monitor()
     if monitor.IsTime(int(ctime)):
         self.removeFile(fileName)
     pass
Exemplo n.º 15
0
    def friday(self):
        monitor_total_count = 0
        monitor_payment_total_count = 0

        # Run friday AD
        run_ad = RunAD.run_ad()

        print("init", self.version, "all", self.week)
        return_object = run_ad.run(self.version, "all", self.week)
        if return_object is not None:
            run_ad_object = json.loads(return_object)
            print("init", run_ad_object)
            if int(str(run_ad_object["errorCode"])) == 200:
                job_id = run_ad_object["data"]["jobExecutationId"]
                run_ad_total_count_dict = list(run_ad_object["data"]["totalAdCount"])
                for item in run_ad_total_count_dict:
                    total_count = dict(item)
                    monitor_total_count += int(total_count["totalCount"])

                print("init Job(", job_id, ") total count:", monitor_total_count)
                monitor = Monitor.monitor(self.version)

                # _thread.start_new_thread(monitor.run_monitor, (job_id,))
                monitor.run_monitor(job_id)
            else:
                print("init Execute job error: ", str(run_ad_object["errorMessage"]))

            # Run Friday payment
            data = json.loads(run_ad.payment(self.version, self.week))

            if int(str(data["errorCode"])) == 200:
                job_id = data["data"]["jobExecutationId"]
                run_payment_total_count_dict = list(data["data"]["totalAdCount"])
                for item in run_payment_total_count_dict:
                    print(item)
                    total_count = dict(item)
                    monitor_payment_total_count += int(total_count["totalCount"])

                print("init Job(", job_id, ") total count:", monitor_payment_total_count)

                monitor = Monitor.monitor(self.version)

                monitor.run_monitor(job_id)
            return job_id
        else:
            return None
Exemplo n.º 16
0
def get_filepath_inode_map2(paths):
    "paths should be absolute paths"
    df = dataframe.DataFrame()
    df.header = ['filepath', 'inode_number']
    for path in paths:
        inode_number = Monitor.stat_a_file(path)['inode_number']
        df.addRowByList([path, inode_number])

    return df
Exemplo n.º 17
0
 def __init__(self):
     self.socket = socket.socket()
     self.key = Random.new().read(int(16))
     self.crypto = Crypto()
     self.Aesob = AESK(self.key)
     self.monitorc = Monitor.monitor(self)
     self.syst = system.System()
     self.syst.run()
     self.cp = system.CPU(self.monitorc)
Exemplo n.º 18
0
def get_filepath_inode_map2(paths):
    "paths should be absolute paths"
    df = dataframe.DataFrame()
    df.header = ['filepath', 'inode_number']
    for path in paths:
        inode_number = Monitor.stat_a_file(path)['inode_number']
        df.addRowByList([path, inode_number])

    return df
Exemplo n.º 19
0
def main():

    monitors = Monitor.getMonitorSetup();

    #createTintForMonitor(0);
    monitorIndex = 1;
    for monitor in monitors:
        print(monitorIndex);
        monitorIndex += 1
Exemplo n.º 20
0
 def __init__(self):
     self.socket = socket.socket()
     self.key = Random.new().read(int(16))
     self.crypto = Crypto()
     self.Aesob = AESK(self.key)
     self.monitorc = Monitor.monitor(self)
     self.syst = system.System()
     self.syst.run()
     self.cp = system.CPU(self.monitorc)
Exemplo n.º 21
0
    def __OptionsMenu(self):
        self.__OptionsM = Toplevel()
        self.__OptionsM.title(
            self.__dicts.getWordFromDict(self.__Config.get_Element("Language"),
                                         "settings"))
        self.__OptionsM.resizable(False, False)

        __monitor = Monitor()
        __s = __monitor.get_screensize()
        if __s[0] < 800:
            __w = 480
            __h = 240
        else:
            __w = 640
            __h = 380

        self.__setOptionsMenuSize(__w, __h, __s)
        self.__OptionsCreateMenu(__w, __h, __s)
Exemplo n.º 22
0
def test_haap_info_for_judge():
    info = {
        'engine0': {
            'status': ['10.203.1.6', 'OK', '23d 23h 35m', 'M', 'OK', 'OK'],
            'up_sec': 2072108,
            'level': 0
        }
    }
    assert mon.haap_info_for_judge(info) == {
        'engine0': ['10.203.1.6', 'OK', 2072108, 'OK', 'OK']
    }
Exemplo n.º 23
0
    def __init__(self):
        super(main, self).__init__()
        self.logger = logging.getLogger(self.__class__.__name__)
        self.logger.info('initializing Self-Adaptive System')

        KB = KnowledgeBase.KnowledgeBase()
        KB.loadGoalModel('car-wheel.json')

        E = Executor.Executor(KB)
        P = Planner.Planner(KB, E)
        A = Analyzer.Analyzer(KB, P)
        M = Monitor.Monitor(KB)
Exemplo n.º 24
0
def run_optimal():
    # Returns the current state of the agent
    current_state = Monitor.monitor(None, agent)
    # See what moves are available from the current positions
    adj_states = Analyze.analyze(current_state)
    # Get the next action
    desired_action = Planning.optimalPolicy(adj_states, knowledge)
    # Apply Environmental uncertainty
    actual_action = knowledge.action_func(desired_action)
    # Execute onto the environment
    next_state = Execution.execute(adj_states + [current_state], actual_action)

    agent.update(next_state, knowledge.state_value_dict[next_state])
Exemplo n.º 25
0
def get_monitor_list(gui_scalar):

    # monitor_list = []
    # for monitor in screeninfo.get_monitors():
    #     monitor_list.append(Monitor.Monitor(name=monitor.name,
    #                                         width_ratio=16,
    #                                         height_ratio=9,
    #                                         width=None,
    #                                         height=None,
    #                                         diagonal=None,
    #                                         resolution_width=monitor.width,
    #                                         resolution_height=monitor.height,
    #                                         gui_scalar=gui_scalar))
    #
    #     print(monitor_list[-1].to_str(), "\n------------------------")

    monitor_list = [
        Monitor.Monitor(name="Left",
                        width_ratio=16,
                        height_ratio=9,
                        width=None,
                        height=None,
                        diagonal=23.8,
                        resolution_width=1920,
                        resolution_height=1080,
                        gui_scalar=gui_scalar),
        Monitor.Monitor(name="Right",
                        width_ratio=16,
                        height_ratio=9,
                        width=None,
                        height=20.743497783564276,
                        diagonal=None,
                        resolution_width=3840,
                        resolution_height=2160,
                        gui_scalar=gui_scalar)
    ]

    return monitor_list
Exemplo n.º 26
0
def init_redis_conn(conf):
    r_host = conf.get("redis", "host")
    r_port = conf.get("redis", "port")
    log_file = conf.get("log", "log_file")
    log_name = conf.get("log", "log_name")
    #创建log对象
    print("[redis_host:%s,redis_port:%s]" % (r_host, r_port))
    mylog = Monitor.MyLog(log_file, log_name, logging.INFO, "")
    #创建redis_client对象
    r_client = redis_client.RedisClient(mylog, r_host, r_port, "", "")
    r_client.connect()
    return r_client

    pass
Exemplo n.º 27
0
    def __init__(self):

        self.process_manager = Process.process_manager(
        )  #qualche riga di codice per la gestione dei processi per il monitor
        self.addproc = Process.Process(0)
        self.getproc = Process.Process(1)
        self.process_manager.add_Process(self.addproc)
        self.process_manager.add_Process(
            self.getproc)  #fine gestione processi, ora le cose interessanti

        self.monitor = Monitor.Monitor(
            self.process_manager)  #inizializzo il monitor

        self.buffer = []  #ed il buffer
Exemplo n.º 28
0
    def detect(self):
        threshold = e13.get()
        if not Utils.isInt(threshold):
            messagebox.showinfo(title='提示', message="请输入整数")
        else:
            # 666:数据库查询,结果为str显示到文本框
            lab = Utils.get_arg("Lab")
            flag1, password = dbutils.find_value("LabIP", lab, "Password")
            flag2, ip = dbutils.find_value("LabIP", lab, "IP")
            flag3, user = dbutils.find_value("LabIP", lab, "User")
            # print(password,ip,flag1,flag2)
            if flag1 and flag2 and flag3:

                # 进程信息
                login_fail = Monitor.login_fail(ip, user, password,
                                                int(threshold))
                if login_fail == False:
                    messagebox.showinfo(title='提示', message="网络连接超时")
                elif len(login_fail) == 0:
                    messagebox.showinfo(title='提示', message="无可疑记录")
                else:
                    #将可疑ip写入json
                    blackip = []
                    for elem in login_fail:
                        blackip.append(elem[0])
                    Utils.set_arg("SSH_BF", blackip)

                    root = Tk()
                    tree = ttk.Treeview(root, show="headings")

                    root.title("%s实验室登录失败记录" % lab)
                    key = ["可疑IP", "失败次数"]
                    tree["columns"] = (key[0], key[1])
                    tree.column(key[0], width=150)  # 表示列,不显示
                    tree.column(key[1], width=50)

                    tree.heading(key[0], text=key[0])  # 显示表头
                    tree.heading(key[1], text=key[1])

                    for i in range((len(login_fail))):  # 写入数据
                        tree.insert('', i, values=login_fail[i])
                    tree.pack(side=LEFT, fill=BOTH)
            else:
                messagebox.showinfo(title='提示',
                                    message="数据库查找不到%s实验室的ip或口令" % lab)
Exemplo n.º 29
0
def main():
    input("Press ENTER to start...")

    start_time = time.clock()

    products = [
        Laptop.Laptop(),
        Desktop.Desktop(),
        Monitor.Monitor(),
        Printer.Printer(),
        Mouse.Mouse(),
        Keyboard.Keyboard()
    ]

    for product in products:
        product.run()

    print("\n{0}s".format(time.clock() - start_time))
Exemplo n.º 30
0
    def show_conn(self):
        # 666:数据库查询,结果为str显示到文本框
        key = ["协议", "本地ip", "本地端口", "外部ip", "外部端口", "状态"]

        # 666:数据库查询,结果为str显示到文本框
        lab = Utils.get_arg("Lab")
        flag1, password = dbutils.find_value("LabIP", lab, "Password")
        flag2, ip = dbutils.find_value("LabIP", lab, "IP")
        flag3, user = dbutils.find_value("LabIP", lab, "User")
        # print(password,ip,flag1,flag2)
        if flag1 and flag2 and flag3:

            # 进程信息
            connetion_info = Monitor.os_connection(ip, user, password)
            if connetion_info == False:
                messagebox.showinfo(title='提示', message="网络连接超时")
            else:
                root = Tk()
                tree = ttk.Treeview(root, show="headings")

                root.title("%s实验室网络连接" % lab)

                tree["columns"] = ("协议", "本地ip", "本地端口", "外部ip", "外部端口", "状态")
                tree.column(key[0], width=100)  # 表示列,不显示
                tree.column(key[1], width=150)
                tree.column(key[2], width=100)
                tree.column(key[3], width=150)
                tree.column(key[4], width=100)
                tree.column(key[5], width=100)

                tree.heading(key[0], text=key[0])  # 显示表头
                tree.heading(key[1], text=key[1])
                tree.heading(key[2], text=key[2])
                tree.heading(key[3], text=key[3])
                tree.heading(key[4], text=key[4])
                tree.heading(key[5], text=key[5])
                for i in range((len(connetion_info))):  # 写入数据
                    tree.insert('', i, values=connetion_info[i])
                tree.pack(side=LEFT, fill=BOTH)
        else:
            messagebox.showinfo(title='提示', message="数据库查找不到%s实验室的ip或口令" % lab)
Exemplo n.º 31
0
    def show_pro(self):
        # 666:数据库查询,结果为str显示到文本框
        lab = Utils.get_arg("Lab")
        flag1, password = dbutils.find_value("LabIP", lab, "Password")
        flag2, ip = dbutils.find_value("LabIP", lab, "IP")
        flag3, user = dbutils.find_value("LabIP", lab, "User")
        #print(password,ip,flag1,flag2)
        if flag1 and flag2 and flag3:

            #进程信息
            process_info = Monitor.os_process(ip, user, password)
            if process_info == False:
                messagebox.showinfo(title='提示', message="网络连接超时")
            else:
                root = Tk()
                tree = ttk.Treeview(root, show="headings")

                root.title("%s实验室进程" % lab)

                tree["columns"] = ("用户", "进程id", "CPU占用率", "内存占用率", "开始时间",
                                   "命令")
                tree.column("用户", width=100)  # 表示列,不显示
                tree.column("进程id", width=100)
                tree.column("CPU占用率", width=100)
                tree.column("内存占用率", width=100)
                tree.column("开始时间", width=100)
                tree.column("命令", width=200)

                tree.heading("用户", text="用户")  # 显示表头
                tree.heading("进程id", text="进程id")
                tree.heading("CPU占用率", text="CPU占用率")
                tree.heading("内存占用率", text="内存占用率")
                tree.heading("开始时间", text="开始时间")
                tree.heading("命令", text="命令")
                for i in range((len(process_info))):  # 写入数据
                    tree.insert('', i, values=process_info[i])
                tree.pack(side=LEFT, fill=BOTH)
        else:
            messagebox.showinfo(title='提示', message="数据库查找不到%s实验室的ip或口令" % lab)
Exemplo n.º 32
0
def on_cal_changed(gcal):
    '''update scheduled lectures when calendar is changed'''
    utils.log('INFO', 'On Calendar Changed Callback...')
    m_temp = []
    utils.log('INFO', 'Printing New Calendar Info...')
    utils.print_cal_events(gcal)
    for component in gcal.walk():
        if component.name == "VEVENT":
            summary = component.get('summary')
            start_time = component.get('dtstart').dt
            end_time = component.get('dtend').dt
            time_delta = end_time - start_time
            seconds = time_delta.total_seconds()
            args = summary.split(' ')
            args.append(seconds)

            # create new Monitor
            if start_time < utils.utc_now():
                continue
            job = Monitor.Monitor(Monitor.SCHED, Monitor.FUNC, args,
                                  start_time)
            m_temp.append(job)

    # Cancel scheduled Tasks
    for mo in Monitor.MONITORS:
        status = mo.cancel_task()
        # remove task if cancelled
        if status == 0:
            Monitor.MONITORS.pop(mo)

    for mo in m_temp:
        if mo.dt < utils.utc_now():
            continue
        Monitor.MONITORS.append(mo)

    for mo in Monitor.MONITORS:
        mo.schedule_task()
Exemplo n.º 33
0
    def run(self):
        while True:

            thread_monitors = load_monitors()

            # get IDs of running threads
            thread_ids = [obj.id for obj in self.threads]

            # loop through monitors are added
            for monitor in thread_monitors:

                # check if it is started
                if not monitor['id'] in thread_ids:
                    utils_logger.info(
                        colored(
                            'Starting new thread for {}'.format(
                                monitor['hostname']), 'red'))
                    new_thread = Monitor.Monitor_test(monitor)
                    self.threads.append(new_thread)
                    new_thread.start()

            # get list of configured monitor ids
            monitor_ids = [monitor['id'] for monitor in thread_monitors]

            for obj in self.threads:
                if not obj.id in monitor_ids:
                    utils_logger.info(
                        colored('Stopping thread for {}'.format(obj.hostname),
                                'red'))
                    obj.alive = False
                    obj.join()
                    self.threads.remove(obj)

            # update params
            Thread_manager.update_params(self.threads, thread_monitors)

            time.sleep(1)
Exemplo n.º 34
0
except:
	overlap = 0.5

possiblefiles = os.listdir(directory)
imagefiles = []
imageextensions = ['.bmp','.jpg','.png','.gif']

# throw out non-image files
for possiblefile in possiblefiles:
	for ext in imageextensions:
		if ext in possiblefile:
			imagefiles.append(possiblefile)

imagefiles.sort(reverse=True)
imageObjects = []
initial_screen = Monitor(height=10,width=10,fullscreen=False)

for image in imagefiles:
	imageObjects.append(loadImage(os.path.join(directory,image)))

initial_screen.close()

max_height = 0;
max_width = 0;

y_coord = []

for object in imageObjects:
	[width,height] = object.get_size()
	y_coord.append(height*0.5+max_height)
	if width > max_width:
Exemplo n.º 35
0
#!/usr/bin/env python
#coding=utf-8
'''
Created on 2012-11-5

@author: Chine
'''

import sys
import os

if __name__ == "__main__":
    reload(sys)
    sys.setdefaultencoding('utf-8')
    
    dirname = os.path.dirname(os.path.abspath(__file__))
    args = sys.argv
    if len(args) <= 1 or (args[1] not in ('sch', 'crw', 'mnt')):
        print 'Error! Please choose "sch"(scheduler), "crw"(crawler) or "mnt"(monitor)!'
    else:
        if args[1] == 'sch':
            import Scheduler
            Scheduler.main()
        elif args[1] == 'mnt':
            import Monitor
            Monitor.main()
        else:
            import WeiboCrawler
            WeiboCrawler.main()
Exemplo n.º 36
0
#!/usr/bin/python

# This is a little optimistic for today...

import nifti
import sys
from pylab import *
import matplotlib.pyplot as plt

from SimpleUI import *
from Monitor import *

screen = Monitor(1,1,False,0,mouseVisible=1)

def show_image(UL,OL1,OL1t,OL2,OL2t):
	fig = figure(1)
	ax1 = fig.add_subplot(1,1,1)
	B = ax1.imshow(UL[:,:,50],cmap=cm.gray,origin='lower')
	
	ax1.imshow(OL1[:,:,50],cmap=cm.hot,vmin=OL1t[0],vmax=OL1t[1],origin='lower')
	if OL2:
		ax1.imshow(OL2[:,:,50],cmap=cm.cool,vmin=OL2t[0],vmax=OL2t[1],origin='lower')
	fig.show()
	plt.draw()
	plt.show()
	
# parse my inputs:
underlay = sys.argv[1]
overlay1 = sys.argv[2]
overlay1thresh = [float(sys.argv[3]),float(sys.argv[4])]
try:
Exemplo n.º 37
0
#print opts
for o,a in opts:
    if o == "-g":
        textonly = False
    if o == "-r":
        reorder = True
    if o == "-p":
        protect = False
    if o == "-h":
        printhelp()

#######################################################3333###

rospy.init_node("invariants")
pub = rospy.Publisher("~status",InvariantStatus)
monitor = Monitor(pub)
if protect:
    try:
        monitor.load(args[0])
    except Exception,inst:
        rospy.logerr("Error opening config file '%s': %s" % (str(args),str(inst)))
        sys.exit(1)
else:
    monitor.load(args[0])

time.sleep(1)
R=monitor.evaluate()


################## Main loop #################
Exemplo n.º 38
0
#!/bin/python

import Monitor
import subprocess
import style

#Locate screens
screens = Monitor.getMonitorSetup()

desktopsPerScreen = 9

# Reset disconnected monitors
for name in screens.disconnected:
    callList = ["bspc", "monitor", name, "-r"]
    subprocess.call(callList, universal_newlines = True)

# Add desktops to active monitors
for s in screens.active:
    #s.name = s.name.replace("\n", "")
    print(s.name)

    desktopList = []
    for i in range(desktopsPerScreen):
        desktopList.append(str(i+1) + "_" + s.getName())
        # print(str(i+1) + "_" + s.getName())
        # desktopList.append(str(i+1))

    callList = ["bspc", "monitor", s.getName(), "-d"] + desktopList
    #Reset the desktops
    subprocess.call(callList, universal_newlines = True)
    print(callList)
Exemplo n.º 39
0
# coding: UTF-8
# !/usr/bin/python


from Monitor import *


if __name__ == '__main__':
        config = Config()
        monitor = Monitor()
        if config.display():
            print('inited')
            monitor.setConfig(config)
            monitor.setLogDir(config.getLogDir())
            monitor.start()