Ejemplo n.º 1
0
 def fetch_config(self):
     """
     This function is the main method where everything is governed on the manager.
     :return:
     :rtype:
     """
     math = WebUseMath()
     config = Config()
     newconfig = config.init_db_config()
     grouplist = newconfig.get_account().get_groups()
     path = newconfig.get_script_path()
     logging.info("Interval: " + str(newconfig.get_interval()))
     positiondict = {}
     while True:
         for i in grouplist:
             userconfig = self.interpreterServer.getUserConfig(i, "couchdb")
             ip = userconfig["ipaddress"]
             worklist = []
             worklist = [{
                 "ip": ip,
                 "sentance": userconfig["Sentance"],
                 "filepath": userconfig["filepath"],
                 "file": userconfig["file"],
                 "timestamp": time.time()
             }]
             groupdict = {}
             groupdict.update({i: worklist})
             logging.critical(str(i) + " " + str(worklist))
             newconfig.create_work_queue(newconfig.get_queue_name(),
                                         groupdict)
             worklist = []
         queue = Queues()
         queue.receive_one_message_from_q("purser_report_q",
                                          str(newconfig.get_interval()))
Ejemplo n.º 2
0
 def click_me(self):
     # Passing in the current class instance (self)
     bq.writeToScrol(self)
     sleep(2)
     htmlData = url.getHtml()
     print(htmlData)
     self.scr.insert(tk.INSERT, htmlData)
Ejemplo n.º 3
0
 def run_clerk(self):
     """
    This function deploys one test per user by creating an executable string which is sent to the RabbitMQ instance.
     :return:
     :rtype:
     """
     math = WebUseMath()
     config = Config()
     newconfig = config.init_db_config()
     grouplist = newconfig.get_account().get_groups()
     path = newconfig.get_script_path()
     logging.info("Interval: " + str(newconfig.get_interval()))
     positiondict = {}
     while True:
         for i in grouplist:
             userconfig = self.interpreterServer.getUserConfig(i, "couchdb")
             ip = userconfig["ipaddress"]
             worklist = []
             tenant_name = userconfig["tenant_name"]
             executable_string = "/root/uptime_challenge_master/testscript/clerk.pl -n " + tenant_name
             worklist.append(executable_string)
             groupdict = {}
             groupdict.update({i: worklist})
             logging.critical(str(i) + " " + str(worklist))
             newconfig.create_work_queue(newconfig.get_queue_name(), groupdict)
             worklist = []
         queue = Queues()
         queue.receive_one_message_from_q("clerk_reportq", str(newconfig.get_interval()))
Ejemplo n.º 4
0
 def fetch_config(self):
     """
     This function is the main method where everything is governed on the manager.
     :return:
     :rtype:
     """
     while True:
         config = Config()
         config.get_account()
         newconfig = config.init_db_config()
         userinfo = config.request_user_creation(newconfig)
         grouplist = newconfig.find_groupnames(
             newconfig.get_account().get_groups())
         self.interpreterServer.createAccounts(userinfo)
         path = newconfig.get_script_path()
         worklist = ["python " + path + "check_http.py db.no"]
         for i in grouplist:
             groupdict = {}
             groupdict.update({i: worklist})
             newconfig.create_work_queue(newconfig.get_queue_name(),
                                         groupdict)
             queue = Queues()
         timestart = time.time()
         while time.time() - timestart <= float(newconfig.get_interval()):
             queue.receive_one_message_from_q("reportq",
                                              time.time() - timestart,
                                              newconfig.get_interval())
Ejemplo n.º 5
0
 def run_leeshore(self):
     """
     This function deploys one leeshore-test per user every second hour. s
     :return:
     :rtype:
     """
     day = int(sys.argv[1])
     config = Config()
     newconfig = config.init_db_config()
     grouplist = newconfig.get_account().get_groups()
     path = newconfig.get_script_path()
     runinterval = int(newconfig.get_interval()) / len(grouplist)
     logging.info("Interval: " + str(newconfig.get_interval()))
     positiondict = {}
     while True:
         for i in grouplist:
             userconfig = self.interpreterServer.getUserConfig(i, "couchdb")
             if datetime.datetime.today().weekday() == day or userconfig["leeshore_enabled"] == 0:
                 logging.critical("Today is a day off for leeshore")
                 time.sleep(runinterval)
             else:
                 tenant_name = userconfig["tenant_name"]
                 ip = userconfig["ipaddress"]
                 executable_string = ""
                 executable_string = "/root/uptime_challenge_master/testscript/leeshore_short.pl -n " + tenant_name
                 worklist = []
                 worklist.append(executable_string)
                 groupdict = {}
                 groupdict.update({i: worklist})
                 newconfig.create_work_queue(newconfig.get_queue_name(), groupdict)
                 worklist = []
                 queue = Queues()
                 queue.receive_one_message_from_q("leeshore_reportq", str(runinterval))
Ejemplo n.º 6
0
 def run_clerk(self):
     """
    This function deploys one test per user by creating an executable string which is sent to the RabbitMQ instance.
     :return:
     :rtype:
     """
     math = WebUseMath()
     config = Config()
     newconfig = config.init_db_config()
     grouplist = newconfig.get_account().get_groups()
     path = newconfig.get_script_path()
     logging.info("Interval: " + str(newconfig.get_interval()))
     positiondict = {}
     while True:
         for i in grouplist:
             userconfig = self.interpreterServer.getUserConfig(i, "couchdb")
             ip = userconfig["ipaddress"]
             worklist = []
             tenant_name = userconfig["tenant_name"]
             executable_string = "/root/uptime_challenge_master/testscript/clerk.pl -n " + tenant_name
             worklist.append(executable_string)
             groupdict = {}
             groupdict.update({i: worklist})
             logging.critical(str(i) + " " + str(worklist))
             newconfig.create_work_queue(newconfig.get_queue_name(),
                                         groupdict)
             worklist = []
         queue = Queues()
         queue.receive_one_message_from_q("clerk_reportq",
                                          str(newconfig.get_interval()))
Ejemplo n.º 7
0
 def fetch_config(self):
     """
     This function is the main method where everything is governed on the manager.
     :return:
     :rtype:
     """
     math = WebUseMath()
     config = Config()
     newconfig = config.init_db_config()
     grouplist = newconfig.get_account().get_groups()
     path = newconfig.get_script_path()
     logging.info("Interval: " + str(newconfig.get_interval()))
     positiondict = {}
     while True:
         for i in grouplist:
             userconfig = self.interpreterServer.getUserConfig(i, "couchdb")
             ip = userconfig["ipaddress"]
             worklist = []
             worklist = [{"ip": ip, "sentance": userconfig["Sentance"], "filepath": userconfig["filepath"],
                          "file": userconfig["file"], "timestamp": time.time()}]
             groupdict = {}
             groupdict.update({i: worklist})
             logging.critical(str(i) + " " + str(worklist))
             newconfig.create_work_queue(newconfig.get_queue_name(), groupdict)
             worklist = []
         queue = Queues()
         queue.receive_one_message_from_q("purser_report_q", str(newconfig.get_interval()))
Ejemplo n.º 8
0
def find_primes(maximum, _primes_=None, _changes_=0, _recursions_=0):
    #if on the first call, there will be no recursion
    if _primes_ == None:
        pass
    else:
        _recursions_ = _recursions_ + 1

    #If the max is 2 or 3, the algorithm following this section will not work.
    if (maximum == 2):
        result = Queues.Queue(1)
        result.enqueue(2)
        return result.queue
    elif (maximum == 3):
        result = [2, 3]
        return result

    #create return queue
    _queue2_ = Queues.Queue(maximum - _changes_ - 1)

    #if this is the first call in the recursion cycle, populate the queue
    if _primes_ == None:
        _primes_ = Queues.Queue(maximum - 1)
        for x in range(2, maximum + 1):
            _primes_.enqueue(x)

    #grab the first item from the queue
    first_item = _primes_.dequeue()
    done = True

    #the primary loop
    while (True):
        next_item = _primes_.dequeue()
        if fact.is_factor(next_item, first_item) == True:
            done = False
            _changes_ = _changes_ + 1
        else:
            _queue2_.enqueue(next_item)

        if (_primes_.isEmpty() == True):
            break
        else:
            pass
    #if a change was made above
    if (done == False):
        value = find_primes(maximum, _queue2_, _changes_, _recursions_)
        value.enqueue(first_item)
        if _recursions_ == 0:
            result = sort.stack_sort(value.queue)
            return result
        else:
            return value
    else:
        if _recursions_ == 0:
            result = sort.stack_sort(_queue2_.queue)
            return result
        else:
            _queue2_.enqueue(first_item)
            unsorted = _queue2_
            return unsorted
Ejemplo n.º 9
0
 def clickMe(self):
     self.action.configure(text='Hello ' + self.name.get())
     # for idx in range(10):
     #     time.sleep(5)
     #     self.scr.insert(tk.INSERT, str(idx) + '\n')
     # self.createThread()
     print(self)
     bq.writeToScrol(self)
Ejemplo n.º 10
0
 def fetch_config(self):
     """
     This function is the main method where everything is governed on the manager.
     :return:
     :rtype:
     """
     math = WebUseMath()
     strengthlist = math.create_time_list()
     position = 0
     config = Config()
     newconfig = config.initDbConfig()
     grouplist = newconfig.getAccount().get_groups()
     path = newconfig.get_script_path()
     index = 0
     logging.info("Interval" + str(newconfig.get_interval()))
     positiondict = {}
     ip = ""
     for i in grouplist:
         userconfig = self.interpreterServer.getFileAndOffsetFromUser(i)
         ipconfig = self.interpreterServer.getIpFromUser(i)
         ip = ""
         ip = ipconfig["ipaddress"]
         executable_string = path + "webuse.pl -U " + ip + " -r '10:10:10:10'"
         logging.info(str(userconfig))
         index = int(userconfig["offset"])
         logging.info("INDEX " + str(index))
         content = math.decideEntry(strengthlist, index)
         worklist = []
         listvalues = math.convertToList(content)
         position = int(listvalues[0])
         strength_number = math.calculateList(listvalues)
         worklist = math.create_number_of_scripts(strength_number, executable_string)
         groupdict = {}
         groupdict.update({i: worklist})
         newconfig.createWorkQ(newconfig.get_queue_name(), groupdict)
         worklist = []
         positiondict.update({i: position})
     while True:
         for i, position in positiondict.iteritems():
             worklist = []
             ip = ""
             ipconfig = self.interpreterServer.getIpFromUser(i)
             ip = ipconfig["ipaddress"]
             executable_string = path + "webuse.pl -U " + ip + " -r '10:10:10:10'"
             logging.info("USER: "******" POSITION: " + str(position))
             strength_value_as_string = math.jumpToNextEntry(strengthlist, int(position))
             values_in_value_string = math.convertToList(strength_value_as_string)
             strength_number = math.calculateList(values_in_value_string)
             worklist = math.create_number_of_scripts(strength_number, executable_string)
             groupdict = {}
             groupdict.update({i: worklist})
             if position == 288:
                 positiondict[i] = 0
             else:
                 positiondict[i] = position + 1
             newconfig.createWorkQ(newconfig.get_queue_name(), groupdict)
             queue = Queues()
         queue.receive_one_message_from_q("webusereportq", newconfig.get_interval())
Ejemplo n.º 11
0
    def run_httperf(self):
        """
        This function uses workload-profiles to generate a set of tests per deployment. This manager needs the file
        transsine.dat to successfully execute.
        :return:
        :rtype:
        """
        math = WebUseMath()
        strengthlist = math.create_time_list()
        position = 0
        config = Config()
        newconfig = config.init_db_config()
        grouplist = newconfig.get_account().get_groups()
        path = newconfig.get_script_path()
        executable_string = path + "traffic.sh"

        index = 0
        logging.info("Interval: " + str(newconfig.get_interval()))
        positiondict = {}
        for i in grouplist:
            ip = ""
            userconfig = self.interpreterServer.getFileAndOffsetFromUser(i)
            ipconfig = self.interpreterServer.getIpFromUser(i)
            ip = ipconfig["ipaddress"]
            index = int(userconfig["offset"])
            logging.info("INDEX: " + str(index))
            content = math.decide_entry(strengthlist, index)
            worklist = []
            listvalues = math.convert_to_list(content)
            position = int(listvalues[0])
            logging.info("USER: "******" POSITION: " + str(position))
            strength_number = math.calculatelist(listvalues)
            worklist = math.create_httperf_string(ip, strength_number, executable_string)
            groupdict = {}
            groupdict.update({i: worklist})
            newconfig.create_work_queue(newconfig.get_queue_name(), groupdict)
            worklist = []
            positiondict.update({i: position})
        while True:
            for i, position in positiondict.iteritems():
                logging.info("USER: "******" POSITION: " + str(position))
                ip = ""
                ipconfig = self.interpreterServer.getIpFromUser(i)
                ip = ipconfig["ipaddress"]
                strength_value_as_string = math.jump_to_next_entry(strengthlist, int(position))
                values_in_value_string = math.convert_to_list(strength_value_as_string)
                strength_number = math.calculatelist(values_in_value_string)
                worklist = math.create_httperf_string(ip, strength_number, executable_string)
                groupdict = {}
                groupdict.update({i: worklist})
                if position == 288:
                    positiondict[i] = 0
                else:
                    positiondict[i] = position + 1
                newconfig.create_work_queue(newconfig.get_queue_name(), groupdict)
                queue = Queues()
            queue.receive_one_message_from_q("httperfreportq", newconfig.get_interval())
 def clickMe(self):
     #self.action.configure(text='Hello ' + self.name.get()+ ' ' + self.numberChosen.get())
     # aLabel.configure(foreground='red')
     # self.createThread(8)
     qs.writeToScrol(self)
     time.sleep(2)
     htmlData = url.getHtml()
     print(htmlData)
     self.scr.insert(tk.INSERT, htmlData)
Ejemplo n.º 13
0
 def click_me(self):
     self.action.configure(text='Hello ' + self.name.get())
     #print(self)
     # self.create_thread()                # now called from imported module
     bq.write_to_scrol(self)
     sleep(2)
     html_data = url.get_html()
     print(html_data)
     self.scrol.insert(tk.INSERT, html_data)
Ejemplo n.º 14
0
 def send_users_to_queue(self, accountlist):
     """
     OUTDATED- This function converts the accountlist to a string that can be sent over a queue.
     :param accountlist:
     :type accountlist:
     :return:
     :rtype:
     """
     listtostring = accountlist
     queue = Queues()
     queue.create_queue("createuserq", str(listtostring))
Ejemplo n.º 15
0
 def send_users_to_queue(self, accountlist):
     """
     OUTDATED- This function converts the accountlist to a string that can be sent over a queue.
     :param accountlist:
     :type accountlist:
     :return:
     :rtype:
     """
     listtostring = accountlist
     queue = Queues()
     queue.create_queue("createuserq", str(listtostring))
Ejemplo n.º 16
0
 def create_report_queue(self, queuename, content):
     """
     Create the report queue
     :param queuename:
     :type queuename:
     :param content:
     :type content:
     :return:
     :rtype:
     """
     queue = Queues()
     queue.create_queue(queuename, content)
Ejemplo n.º 17
0
 def create_report_queue(self, queuename, content):
     """
     Create the report queue
     :param queuename:
     :type queuename:
     :param content:
     :type content:
     :return:
     :rtype:
     """
     queue = Queues()
     queue.create_queue(queuename, content)
Ejemplo n.º 18
0
 def create_work_queue(self, queuename, joblist):
     """
     Function to create a workqueue that is used to put jobs on
     :param queuename:
     :type String:
     :param joblist:
     :type list:
     :return:
     :rtype:
     """
     queue = Queues()
     for group, job in joblist.iteritems():
         for j in job:
             jobdict = {}
             jobdict.update({group: j})
             queue.create_queue(queuename, jobdict)
Ejemplo n.º 19
0
 def create_work_queue(self, queuename, joblist):
     """
     Function to create a workqueue that is used to put jobs on
     :param queuename:
     :type String:
     :param joblist:
     :type list:
     :return:
     :rtype:
     """
     queue = Queues()
     for group, job in joblist.iteritems():
         for j in job:
             jobdict = {}
             jobdict.update({group: j})
             queue.create_queue(queuename, jobdict)
Ejemplo n.º 20
0
    def clickMe(self):
        self.action.configure(text='Hello ' + self.name.get())
#         # Non-threaded code with sleep freezes the GUI
#         for idx in range(10):
#             sleep(5)
#             self.scr.insert(tk.INSERT, str(idx) + '\n')

#         # Threaded method does not freeze our GUI
#         self.createThread()

        # Passing in the current class instance (self)
        print(self)
        bq.writeToScrol(self)
        sleep(2)
        htmlData = url.getHtml()
        print(htmlData)
        self.scr.insert(tk.INSERT, htmlData)
Ejemplo n.º 21
0
 def run_manager(self):
     """
     This function is the main method where everything is governed on the manager.
     :return:
     :rtype:
     """
     interval = 0
     intervaltime = 900
     time_of_day = random.uniform(-12, 12)
     while True:
         if time_of_day > 12:
             time_of_day -= 24
         config = Config()
         config.get_account()
         newconfig = config.init_db_config()
         interval = newconfig.get_interval()
         userinfo = config.request_user_creation(newconfig)
         grouplist = newconfig.find_groupnames(newconfig.get_account().get_groups())
         self.interpreterServer.createAccounts(userinfo)
         path = newconfig.get_script_path()
         hour = 0
         fetchload = []
         while hour < 3600:
             fetchload = newconfig.return_load(time_of_day)
             currentload = float(fetchload[0])
             loadincrease = float(fetchload[1]) / 10
             time_elapsed = 0
             worklist = [path + "traffic.sh " + str(int(currentload) * 5) + " " + str(int(currentload))]
             while time_elapsed < 900:
                 for i in grouplist:
                     groupdict = {}
                     groupdict.update({i: worklist})
                     newconfig.create_work_queue(newconfig.get_queue_name(), groupdict)
                     queue = Queues()
                 # queue.listen_continously_to_queue("reportq")
                 timestart = time.time()
                 while time.time() - timestart <= float(newconfig.get_interval()):
                     queue.receive_one_message_from_q("reportq", time.time() - timestart, newconfig.get_interval())
                 if currentload + loadincrease < 0:
                     loadincrease *= -1
                 currentload += loadincrease
                 worklist = [path + "traffic.sh " + str(int(currentload) * 5) + " " + str(int(currentload))]
                 time_elapsed += float(interval)
                 hour += float(interval)
             time_of_day += 24. / 96
Ejemplo n.º 22
0
    def __init__(self, name):
        # Fila de processos requisitando este recurso
        self.queue = Queues.Queue()

        # Processo usando o recurso atualmente
        self.process = None

        # Nome do recurso
        self.name = name
Ejemplo n.º 23
0
def solvePrefix(expression):
    alphabet = [
        "a", "b", "c", "d", "e", "f", "g", "h", 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    ]
    numerals = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
    signQ = qz.Queue(len(expression))
    letters = stk.stack(len(expression))

    x = 0
    while (x < len(expression)):
        if (expression[x] == "*" or expression[x] == "-"
                or expression[x] == "+" or expression[x] == "/"
                or expression[x] == "^"):
            signQ.enqueue(expression[x])
        else:
            pass
        x = x + 1
    temp = ''
    for x in expression:
        #print("x = " + str(x))
        if (x.lower() in alphabet):
            letters.push(x)
        elif (x in numerals):
            temp = temp + str(x)
        else:
            if (temp != ''):
                letters.push(temp)
            if (x != ' '):
                v1 = letters.pop()
                v2 = letters.pop()

                sign = signQ.dequeue()
                try:
                    if (sign == "+"):
                        answer = int(v2) + int(v1)
                    elif (sign == "-"):
                        answer = int(v2) - int(v1)
                    elif (sign == "*"):
                        answer = int(v2) * int(v1)
                    elif (sign == "/"):
                        answer = int(v2) / int(v1)
                    elif (sign == "^"):
                        answer = int(v2)**int(v1)
                    else:
                        pass
                    letters.push(answer)
                except:
                    if (sign == "+" or sign == "-" or sign == "/"
                            or sign == "^"):
                        answer = str(v2) + ' ' + str(v1) + sign
                    elif (sign == "*"):
                        answer = str(v2) + ' ' + str(v1) + sign
                    letters.push(answer)

            temp = ''
    return letters.pop()
Ejemplo n.º 24
0
def Circles(item, num):
    q = Queues.Queue()
    for i in item:
        q.enqueue(i)
        # print(q.dequeue())
    while q.size() > 1:
        for i in range(num):
            q.enqueue(q.dequeue())
        q.dequeue()
    return q.dequeue()
Ejemplo n.º 25
0
def main(configFile, param):
    cleanResDirectory()
    config = decodeConfigJson(configFile)

    #caudalURL = config["Caudal"]
    serviceLogURL = "http://localhost:8080/logs"

    print("Sending events to: {}".format(serviceLogURL))

    models = M.buildModels(config["Models"])
    queues = Q.buildQueues(config["Queues"])
    predictors = P.buildPredictors(models, queues, config["Predictors"])
    print("creating cameras")
    cameras = VCS.buildCameras(queues, config["Cameras"])

    withImg = True if param == "manual" else False
    print("mostrando imagenes ?" + str(withImg))

    outQ = queues["qr_out"]
    lastDataMatrixSent = ""
    n = 0
    while 1:
        print("Sacando elemento {}".format(n))
        component, cam, pred, img, ok = outQ.get()

        n += 1
        objects = pred["objects"]
        dataMatrix = pred["dataMatrix"]
        plate = getWithDefault(pred, "plate", "unknown")
        height, width, channels = img.shape
        if ok and (dataMatrix !=
                   "unknown") and lastDataMatrixSent != dataMatrix:
            lastDataMatrixSent = dataMatrix
            info = {"cameraId": cam, "aITime": getMillis(), "data": dataMatrix}

            print("Sending: {}".format(info))
            # try:
            #     requests.post(
            #         serviceLogURL,
            #         headers=JSON_HEADERS,
            #         data=json.dumps(info))
            # except:
            #     print("Unexpected error:", sys.exc_info()[0])

        if withImg:
            showPrediction(img, pred, scale=2)
            cmdK = cv2.waitKey(10) & 0xFF
            if cmdK == ord("q"):
                print("Quiting...1")
                streamCams.stopAll()
                cv2.destroyAllWindows()
                print("Quiting...2")
                exit()
Ejemplo n.º 26
0
 def fetch_config(self):
     """
     This function is the main method where everything is governed on the manager.
     :return:
     :rtype:
     """
     while True:
         config = Config()
         config.get_account()
         newconfig = config.init_db_config()
         userinfo = config.request_user_creation(newconfig)
         grouplist = newconfig.find_groupnames(newconfig.get_account().get_groups())
         self.interpreterServer.createAccounts(userinfo)
         path = newconfig.get_script_path()
         worklist = ["python " + path + "check_http.py db.no"]
         for i in grouplist:
             groupdict = {}
             groupdict.update({i: worklist})
             newconfig.create_work_queue(newconfig.get_queue_name(), groupdict)
             queue = Queues()
         timestart = time.time()
         while time.time() - timestart <= float(newconfig.get_interval()):
             queue.receive_one_message_from_q("reportq", time.time() - timestart, newconfig.get_interval())
Ejemplo n.º 27
0
 def run_leeshore(self):
     """
     This function deploys one leeshore-test per user every second hour. s
     :return:
     :rtype:
     """
     day = int(sys.argv[1])
     config = Config()
     newconfig = config.init_db_config()
     grouplist = newconfig.get_account().get_groups()
     path = newconfig.get_script_path()
     runinterval = int(newconfig.get_interval()) / len(grouplist)
     logging.info("Interval: " + str(newconfig.get_interval()))
     positiondict = {}
     while True:
         for i in grouplist:
             userconfig = self.interpreterServer.getUserConfig(i, "couchdb")
             if datetime.datetime.today().weekday(
             ) == day or userconfig["leeshore_enabled"] == 0:
                 logging.critical("Today is a day off for leeshore")
                 time.sleep(runinterval)
             else:
                 tenant_name = userconfig["tenant_name"]
                 ip = userconfig["ipaddress"]
                 executable_string = ""
                 executable_string = "/root/uptime_challenge_master/testscript/leeshore_short.pl -n " + tenant_name
                 worklist = []
                 worklist.append(executable_string)
                 groupdict = {}
                 groupdict.update({i: worklist})
                 newconfig.create_work_queue(newconfig.get_queue_name(),
                                             groupdict)
                 worklist = []
                 queue = Queues()
                 queue.receive_one_message_from_q("leeshore_reportq",
                                                  str(runinterval))
Ejemplo n.º 28
0
def main():
    frontier = Queues.Queue()
    cameFrom = {}
    start = Node(0)
    frontier.enqueue(start)
    cameFrom[start] = None

    while frontier.length() is not 0:
        current = frontier.dequeue()
        for next in graph.neighbors(current):
            if next not in cameFrom:
                cameFrom[next] = current
                frontier.enqueue(next)
    
    goal = Node(1)
    generatePath(goal,cameFrom, start)
def simulation(num_seconds, pages_per_minute):
    lab_printer = Printer.Printer(pages_per_minute)
    print_queue = Queues.Queue()
    waiting_times = []
    for current_second in range(num_seconds):
        if new_print_task():
            task = Task.Task(current_second)
            print_queue.enqueue(task)
        if (not lab_printer.busy()) and (not print_queue.is_empty()):
            next_task = print_queue.dequeue()
            waiting_times.append(next_task.wait_time(current_second))
            lab_printer.start_next(next_task)
        lab_printer.task()
    average_wait = sum(waiting_times) / len(waiting_times)
    print("Average Wait %6.2f secs %3d tasks remaining." %
          (average_wait, print_queue.size()))
Ejemplo n.º 30
0
    def BuscaEmLargura(self, inicial, metas):
        fronteira = Queues.Queue()
        fronteira.put(inicial)
        veio_de = {}
        veio_de[inicial] = None

        while not fronteira.empty():
            self.explorados += 1
            atual = fronteira.get()

            if atual in metas:
                break

            for prox in self.g.grafo[atual]:
                if prox not in veio_de:
                    fronteira.put(prox)
                    veio_de[prox] = atual
        return atual, veio_de
def main():
    frontier = Queues.Queue()
    visited = {}
    start = Node(0)
    frontier.enqueue(start)
    visited[start] = True
    goal = Node(2)

    while frontier.length() is not 0:
        current = frontier.dequeue()
    
        # We can stop expanding the frontier as soon as we’ve found our goal. 
        if current == goal:
            break

        for next in graph.neighbors(current):
            if next not in visited:
                visited[next] = True
                frontier.enqueue(next)
Ejemplo n.º 32
0
def load_crash_report_events():
    queue = 'crash_report'
    mapper = lambda payload: (payload['user_id'], payload['timestamp'], payload['message'])
    connection, channel = Queues.get_queue(queue)
    conn, curs = DB.get_db()
    try:
        data = unpack_data(channel, queue, mapper)
        payloads = [d['payload'] for d in data]
        args_str = b','.join(curs.mogrify("(%s,%s,%s)", x) for x in payloads)

        if args_str:
            curs.execute(b"INSERT INTO crash_report(user_id, timestamp, message) VALUES " + args_str)
            conn.commit()
    except Exception as e:
        print("ERROR:", e.args)
    else:
        for d in data:
            channel.basic_ack(d['method_frame'].delivery_tag)
    finally:
        connection.close()
Ejemplo n.º 33
0
	def Aestrela(self, inicial, metas):
		fronteira = Queues.PriorityQueue()
		fronteira.put(inicial, 0)
		veio_de = {}
		veio_de[inicial] = None
		custo_ate_agora = {}
		custo_ate_agora[inicial] = 0

		while not fronteira.empty():
			self.explorados += 1
			atual = fronteira.get()

			if atual in metas:
				break

			for prox in self.g.grafo[atual]:
				custo_novo = custo_ate_agora[atual] + 1
				if prox not in custo_ate_agora or custo_novo < custo_ate_agora[prox]:
					custo_ate_agora[prox] = custo_novo
					prio = custo_novo + self.hx(prox, metas)
					fronteira.put(prox, prio)
					veio_de[prox] = atual
		return atual,veio_de
Ejemplo n.º 34
0
    def __init__(self, processes, disk, memory, resources):

        # Lista ordenada de processos agendados por tempo de inicialização e prioridade
        self.processesByInitTime = sorted(processes,
                                          key=lambda x:
                                          (x.initTime, x.priority))

        # Define o tempo inicial como o tempo do primeiro processo agendado
        self.time = self.processesByInitTime[0].initTime if len(
            self.processesByInitTime) > 0 else 0

        # Mantém variações de tempo
        self.timeVariation = 0

        # Instancia a fila de prontos
        self.readyQueue = Queues.ReadyQueue()

        # Salva elementos como variaveis internas
        self.memory = memory
        self.disk = disk
        self.resources = resources

        # Define um processo na CPU
        self.currentProcess = None
 def click_me(self):
     self.action.configure(text='Hello ' + self.name.get() + ' ' +
                           self.number_chosen.get())
     # self.create_thread()
     bq.write_to_scrol(self)
Ejemplo n.º 36
0
def solvePrefix(expression):
    alphabet = [
        "a", "b", "c", "d", "e", "f", "g", "h", 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    ]
    numerals = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
    signQ = qz.Queue(len(expression))
    letters = qz.Queue(len(expression))

    x = 0
    while (x < len(expression)):
        if (expression[x] == "*" or expression[x] == "-"
                or expression[x] == "+" or expression[x] == "/"
                or expression[x] == "^"):
            signQ.enqueue(expression[x])
        else:
            pass
        x = x + 1
    temp = ''
    for x in expression:
        print(letters.queue)
        print("x = " + str(x))
        if (x.lower() in alphabet):
            letters.enqueue(x)
        elif (x in numerals):
            temp = temp + str(x)
        else:
            if (temp != ''):
                letters.enqueue(temp)
            if (x != ' '):
                store = qz.Queue(letters.getLength() + 1)
                print(store.queue)
                for z in letters.queue:
                    if (z != None):
                        store.enqueue(z)
                value = len(letters.queue) - 1
                for y in range(0, letters.getLength()):
                    if (y != 0 and y != 1):
                        letters.dequeue()
                v1 = letters.dequeue()
                v2 = letters.dequeue()
                sign = signQ.dequeue()

                try:
                    print("AHGHDHGSJGH")
                    print("AHGJSFKHGJKLSF = " + str(x))
                    if (sign == "+"):
                        print("v1 = " + str(v1))
                        print("v2 = " + str(v2))
                        answer = int(v2) + int(v1)
                        print("answer = " + str(answer))
                        print("+")
                    elif (sign == "-"):
                        answer = int(v2) - int(v1)
                        print("-")
                    elif (sign == "*"):
                        answer = int(v2) * int(v1)
                        print("*")
                    elif (sign == "/"):
                        answer = int(v2) / int(v1)
                        print("/")
                    elif (sign == "^"):
                        answer = int(v2)**int(v1)
                        print("^")
                    else:
                        pass
                    print(store.queue)
                    for t in store.queue:
                        if (t != None):
                            print("OOF = " + str(t))
                            letters.enqueue(x)
                    letters.enqueue(answer)
                except:
                    if (sign == "+" or sign == "-" or sign == "/"
                            or sign == "^"):
                        answer = str(v2) + ' ' + str(v1) + sign
                    elif (sign == "*"):
                        answer = str(v2) + ' ' + str(v1) + sign
                    else:
                        pass
                    for x in store.queue:
                        if (x != None):
                            letters.enqueue(x)
                    letters.enqueue(answer)

            temp = ''
    return letters.dequeue()
Ejemplo n.º 37
0
 def click_me(self):
     # Passing in the current class instance (self)
     print(self)
     bq.writeToScrol(self)
Ejemplo n.º 38
0
 def click_me(self):
     # self.action.configure(text = 'Hello' + self.name.get())
     # self.create_thread()
     print(self)
     bq.write_to_scrol(self)
 def click_me(self):
     self.action.configure(text="Hello " + self.name.get() + ' ' + self.number_chosen.get())
     #self.create_thread()
     # Passing the current class instance (self)
     print(self)
     bq.write_to_scrol(self)