Example #1
0
def main(args):
    filename = args.name
    print("Processing filelist: ", filename)
    name_list = get_all_file_names_from_txt(filename)

    mrf_exe = 'C:/Program Files/MRFTools/MRFSurface.exe'
    print("Check MRFSurface installation path at line 20")
    print(mrf_exe)

    if args.part == "Full":
        base_path = os.path.split(args.surfacepath)[0] + "/LAA_decoupling/"
        if not os.path.exists(base_path):
            os.mkdir(base_path)
        target_sdf_dir = base_path + "/distance_fields/"
        name_list = get_all_file_names_from_txt(filename)
        if not os.path.exists(target_sdf_dir):
            os.makedirs(target_sdf_dir)
    elif args.part == "LAA":
        base_path = os.path.split(args.surfacepath)[0]
        if not os.path.exists(base_path):
            os.mkdir(base_path)
        target_sdf_dir = base_path + "/distance_fields/"
        name_list = get_all_file_names_from_txt(filename)
        if not os.path.exists(target_sdf_dir):
            os.makedirs(target_sdf_dir)
    else:
        print("Provide either 'Full' or 'LAA' for input part")
        sys.exit()

    target_surfaces_dir = args.surfacepath
    N = len(name_list)
    args = list(
        zip(name_list, [target_surfaces_dir] * N, [target_sdf_dir] * N,
            [mrf_exe] * N))
    Methods.imap_unordered_bar(Methods.DistanceField, args, 12)
Example #2
0
 def __init__(self, account):
     self.thread_num = 3  #爬取的目标qq数
     self.account = account  #提供cookie的账号
     self.cookie = Methods.getCookie(account)
     self.gtk = Methods.get_Gtk(self.cookie)
     self.target_list = []
     #电脑和手机的请求头
     self.headers = {
         'computer': {
             'user-agent':
             'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'
         },
         'phone': {
             'user-agent':
             'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Mobile Safari/537.36'
         }
     }
     #电脑版的会话和手机版的会话
     self.s_com = requests.session()
     self.s_com.cookies.update(self.cookie)
     self.s_com.headers.update(self.headers['computer'])
     self.s_pho = requests.session()
     self.s_pho.cookies.update(self.cookie)
     self.s_pho.headers.update(self.headers['phone'])
     with open('./targetQQ.txt', 'r') as f:
         for str in f.readlines():
             str = str.strip()
             if str:
                 self.target_list.append(str)  #待爬的qq列表
     if len(self.target_list) > self.thread_num:
         Methods.writeQQ(self.target_list[self.thread_num:],
                         './targetQQ.txt')
         self.target_list = self.target_list[0:self.thread_num]
     else:
         self.thread_num_information = len(self.target_list)
Example #3
0
def getAbstract():
    print("===============================================================")
    print("Query a person's driver abstract given a name...")
    registered = False
    while registered == False:
        fname = getInput(AGENTSUBSCREEN, "First name: ")
        lname = getInput(AGENTSUBSCREEN, "Last name: ")
        registered = m.checkregName(fname, lname)
        if registered == False:
            print("No tickets for this person")

    validResponse = False
    ordering = ""
    while validResponse == False:
        ordering = getInput(AGENTSUBSCREEN,
                            "Order from latest to oldest (yes,no)? ")
        if ordering == "yes" or ordering == "no":
            validResponse = True
        else:
            print("Please enter a response of either 'yes' or 'no'.")
    # TODO Aryan : Query the database and report the results DONE
    m.getDriverAbstract(fname, lname, ordering)
    getall = getInput(AGENTSCREEN, "get all ? (yes, no): ")
    if getall == "yes":
        m.getDriverAbstractB(fname, lname, ordering)
    elif getall == "no":
        print("-------------------------------------------------------------")
    print("===============================================================")
    return
Example #4
0
def processPayment():
    print("===============================================================")
    print("Enter details about the ticket payment:")
    tno = ""
    tnoValid = False
    while tnoValid == False:
        tno = getInput(AGENTSUBSCREEN, "Ticket number: ")
        # TODO Aryan : Verify it's a valid tno DONE
        tnoValid = m.verifyTno(tno)
        if tnoValid == False:
            print(
                "Ticket number invalid! Please enter a valid ticket number...")
    maxAmount = m.maxAmount(tno)
    # TODO Aryan : Calculate the max payment amount using queries DONE
    # maxAmount = {database.tickets.fine} - sum{{database.payments.amount}} DONE
    amount = 0
    amountValid = False
    while amountValid == False:
        amount = int(getInput(AGENTSUBSCREEN, "Amount: "))
        amountValid = amount <= maxAmount
        if amountValid == False:
            print("Amount being paid cannot exceed $" + str(maxAmount) +
                  ", please re-enter...")
    m.processPayment(tno, amount)
    print("The payment has been recorded.")
    print("===============================================================")
    return
Example #5
0
	def wiiMode(self):
		"""
		Gére le mode "Wii" de l'application. Le mode "Wii" réalise les actions via la manette nunchuk.
		"""
		buttons = self.nunchuk.getButtons()
		button_c = buttons[0]
		button_z = buttons[1]

		if button_z:
			self.laser.ON()
		else:
			self.laser.OFF()

		if button_c:
			axis = self.nunchuk.getAccelerometerAxis()
			hAngle = int(axis[0]*1.8-216.0)# Min=70 ; Max=170
			vAngle = int(axis[1]*-1.8+225.0)# Min=175 ; Max=75
		else:
			position = self.nunchuk.getJoystickPosition()
			hAngle = int(position[0]*0.93-123.58)# Min=36 ; Max=229
			vAngle = int(position[1]*0.95-120.48)# Min=32 ; Max=221

		self.horizontalServo.setPosition(hAngle)
		self.verticalServo.setPosition(vAngle)
		Methods.sendData(self.uart, self.horizontalServo.getPosition(), self.verticalServo.getPosition(), self.laser.getState())
		sleep(0.01)
Example #6
0
def registerBirth():
    print("===============================================================")
    print("Enter birth details:")
    fname = getInput(AGENTSUBSCREEN, "First name: ")
    lname = getInput(AGENTSUBSCREEN, "Last name: ")
    # TODO Aryan : Check if the name already exists DONE
    existsAlready = m.nameExists(fname, lname)
    if existsAlready == True:
        print("This person already exists, cannot register.")
        print(
            "===============================================================")
        return
    gender = getInput(AGENTSUBSCREEN, "Gender: ")
    bday = getInput(AGENTSCREEN, "Birth Date: ")
    bplace = getInput(AGENTSUBSCREEN, "Birth place: ")
    m_fname = getInput(AGENTSUBSCREEN, "Mother's first name: ")
    m_lname = getInput(AGENTSUBSCREEN, "Mother's last name: ")
    f_fname = getInput(AGENTSUBSCREEN, "Father's first name: ")
    f_lname = getInput(AGENTSUBSCREEN, "Father's last name: ")
    # TODO Aryan : Check if both parents are in the database DONE
    pB = [m_fname, m_lname]
    pA = [f_fname, f_lname]
    intable = m.checkParents(pA, pB)
    motherFound = intable[1]
    fatherFound = intable[0]

    if motherFound == False:
        registerPerson(AGENTSUBSCREEN, "Mother")
    if fatherFound == False:
        registerPerson(AGENTSUBSCREEN, "Father")
    # TODO Aryan : Register the birth DONE
    m.registerBirth(uid, fname, lname, gender, pA, pB, bday, bplace)
    print("The birth has been recorded. Congratulations to the parents.")
    print("===============================================================")
    return
Example #7
0
	def initServos(self):
		"""
		Initialise les servomoteurs à la position 0,0 et éteint le laser.
		"""
		self.horizontalServo.setPosition(0)
		self.verticalServo.setPosition(0)
		Methods.sendData(self.uart, 0, 0, self.laser.getState())
Example #8
0
	def manualMode(self):
		"""
		Gére le mode "Manuel" de l'application. Le mode "Manuel" réalise les mouvements simples via l'IHM (Déplacement vert le Haut, la droite, allumer le laser...).
		"""
		for i in range(100):
			self.reading = self.uart.read()
			hPos = self.horizontalServo.getPosition()
			vPos = self.verticalServo.getPosition()
			if self.reading != "":
				if self.reading == "Up":
					vPos+=2
				elif self.reading == "Left":
					hPos-=2
				elif self.reading == "Right":
					hPos+=2
				elif self.reading == "Down":
					vPos-=2
				elif self.reading == "Center":
					hPos = 0
					vPos = 0
				elif self.reading == "Laser":
					if self.laser.getState() == "0":
						self.laser.ON()
					else:
						self.laser.OFF()
				else:
					break
				
				self.horizontalServo.setPosition(hPos)
				self.verticalServo.setPosition(vPos)
				
			Methods.sendData(self.uart, self.horizontalServo.getPosition(), self.verticalServo.getPosition(), self.laser.getState())
			sleep(0.01)
Example #9
0
def test_efficiency(points,
                    number_of_clusters,
                    solution=None,
                    max_iterations=100,
                    times=100,
                    method=Methods.method_heuristic_initial_clusters_max_dist):
    error_list = []

    time_start = time()

    for i in range(times):
        iteration_result = Methods.clustering(points, number_of_clusters,
                                              max_iterations, method)

        if solution is not None:

            clusters = iteration_result.clusters

            errors = Methods.compare_results(clusters, solution)

            error_list.append(errors)

    time_end = time()

    time_range = time_end - time_start

    print("-----------------------------")
    print("Method used: " + get_method_name(method))
    print("Total time: " + str(time_range) + " s")
    if solution is not None:
        print("Results after " + str(times) + "runs and " +
              str(max_iterations) + " iterations each:")
        print("Max error: " + str(max([item[1] for item in error_list])))
        print("Min error: " + str(min([item[2] for item in error_list])))
        print("Median error: " + str(mean([item[0] for item in error_list])))
Example #10
0
    def __is_session_alive(data: Data, browser: Browser):
        """
        This function checks if the session of the browser is still alive.

        @param data: The data object of the program.
        @type data: Classes.Data
        @param browser: Chrome driver object.
        @type browser: webdriver.Chrome
        @return: True - session still alive, False - session has logged out.
        @rtype: bool
        """
        same_content = 0
        different_content = 0
        for session_page in [page for page in data.pages if page.is_session]:
            if session_page.cookies != browser.get_cookies():
                # Does not have the same cookies of the other session pages.
                return False
            browser.get(session_page.url)
            browser.refresh()
            if Methods.remove_forms(
                    browser.page_source) != Methods.remove_forms(
                        session_page.content):
                # Does not have the same content.
                different_content += 1
            else:
                # Have the same content.
                same_content += 1
        # If there are more same-content pages than different-content pages.
        return different_content <= same_content
Example #11
0
    def __set_cookies(self, data: Data, browser: Browser):
        """
        This function sets the specified cookies to the browser.

        @param data: The data object of the program.
        @type data: Classes.Data
        @param browser: The webdriver browser.
        @type browser: Browser
        @return: None
        """
        if data.cookies:
            # If user specified cookies.
            if Methods.enter_cookies(data, browser, data.url):
                # Success.
                self.__non_session_browser[0] = Methods.new_browser(
                    data)  # setting up secondary browser object.
                print(
                    f"\t[{COLOR_MANAGER.YELLOW}!{COLOR_MANAGER.ENDC}] {COLOR_MANAGER.YELLOW}"
                    f"Cookies were added to the session.{COLOR_MANAGER.ENDC}")
            else:
                # Failure.
                print(
                    f"\t[{COLOR_MANAGER.YELLOW}!{COLOR_MANAGER.ENDC}] {COLOR_MANAGER.YELLOW}"
                    f"Invalid cookies, check your syntax and try again. {COLOR_MANAGER.ENDC}"
                )
                data.cookies = None  # There is no need to use them again.
Example #12
0
	def setState(self, state):
		"""
		Permet d'e changer l'état du laser (allumé ou éteint).

		Args:
			state (str): État du laser. "0" pour éteint, "1" pour allumé.
		"""
		self.state = state
		Methods.writeFile("/sys/class/gpio/gpio"+str(self.nb)+"/value", self.state, "w")
Example #13
0
def hamming_distance(s1, s2):
    if len(s1) == len(s2):
        #Convert string to bits
        b1 = Methods.byteToBin(s1)
        b2 = Methods.byteToBin(s2)
        #Sum each matching bit
        return sum([int(b1[i]) ^ int(b2[i]) for i in range(len(b1))])
    else:
        assert ("String not same size")
Example #14
0
def kmeans_hsv(df, method=None, k=1):
    """输入一个包含HSV信息的DataFrame,可选不同方法估计K值或指定k值,再对其进行K-means聚类,默认k = 1,输出四个关键DataFrame"""

    # 增加极坐标hx, hy
    df['hx'] = df.s * np.sin(df.h * 2 * np.pi)
    df['hy'] = df.s * np.cos(df.h * 2 * np.pi)

    def kmeans_session(df, k):
        # # 对df[['h', 's', 'v']]kmeans
        # kmeansHSV = KMeans(n_clusters=k, random_state=0, n_init=10).fit(df[['h', 's', 'v']])
        # 对df[['hx', 'hy', 'v']]kmeans
        kmeansHSV2 = KMeans(n_clusters=k, random_state=0,
                            n_init=10).fit(df[['hx', 'hy', 'v']])

        # 为df添加kcenter列,内容为kmeansHSV2的labels
        df['kcenter'] = kmeansHSV2.labels_

        # weighted_cluster_centers2空矩阵,k行3列
        weighted_cluster_centers2 = np.zeros((kmeansHSV2.n_clusters, 3))
        # 选择df中kcenter为c的行,以['pixels']为权重求['h', 's', 'v']每列均值,填入第c行
        # for c in range(kmeansHSV.n_clusters):
        for c in range(kmeansHSV2.n_clusters):
            weighted_cluster_centers2[c] = np.average(
                df[df['kcenter'] == c][['h', 's', 'v']],
                weights=df[df['kcenter'] == c]['pixels'],
                axis=0)

        # weighted_cluster_center_colors2空矩阵,k行3列
        weighted_cluster_center_colors2 = np.zeros((kmeansHSV2.n_clusters, 3))
        # 把kmeansHSV2的k个中心分别填入weighted_cluster_center_colors2的每行
        for i in range(kmeansHSV2.n_clusters):
            weighted_cluster_center_colors2[i] = colorsys.hsv_to_rgb(
                h=weighted_cluster_centers2[i, 0],
                s=weighted_cluster_centers2[i, 1],
                v=weighted_cluster_centers2[i, 2])
        weighted_cluster_center_colors2 *= 255

        return df, kmeansHSV2, weighted_cluster_centers2, weighted_cluster_center_colors2

    if method == 'GS':
        k = Methods.gs(df[['hx', 'hy', 'v']].values)
        print('Gap Statistic: the best k is', k)
    elif method == 'SC':
        k = Methods.sc(df[['hx', 'hy', 'v']].values)
        print('Silhouette Coefficient: the best k is ', k)
    elif method == 'CH':
        k = Methods.ch(df[['hx', 'hy', 'v']].values)
        print('Calinski-Harabasz Index: the best k is ', k)
    else:
        print('The chosen k is', k)

    kmeans_result = kmeans_session(df, k)

    return kmeans_result
Example #15
0
	def __init__(self, nb):
		"""
		Initialise le laser

		Args:
			nb (int): Numéro de la GPIO utilisé.
		"""
		self.nb = nb

		self.state = "0"
		Methods.writeFile("/sys/class/gpio/gpio"+str(self.nb)+"/direction", "high", "w")
		self.OFF()
Example #16
0
def solve_block(block):
    score = 0
    key = bytes([0])
    #loop every possible key¨¨
    for i in range(256):
        #xor cipher w possible key and generate a string
        s = ''.join([chr(ord(c) ^ i) if c not in b'' else '' for c in block])
        #Store highest score
        if Methods.score(s) > score:
            score = Methods.score(s)
            key = bytes([i])
    return key
Example #17
0
def CalcI(Theta_Hwp, PositivePol, Q_IP=0, U_IP=0):

    M_Hwp = Mt.ApplyRotation(Mt.ComMatrix(0, np.pi), Theta_Hwp)
    M_Pol = Mt.Polarizer(PositivePol)
    M_IP = np.zeros((4, 4))
    M_IP[1, 0] = Q_IP
    M_IP[2, 0] = U_IP
    M_IP[0, 0] = 1
    M_IP[1, 1] = 1
    M_IP[2, 2] = 1
    M_IP[3, 3] = 1

    return np.linalg.multi_dot([M_Pol, M_IP, M_Hwp])
Example #18
0
	def __init__(self, led1, led2):
		"""
		Initialise les GPIO des LEDs

		Args:
			led1 (int): Numéro de la GPIO de la LED 1.
			led2 (int): Numéro de la GPIO de la LED 2.
		"""
		self.led1 = led1
		self.led2 = led2
		self.mode = ""
		self.shutdownThread = threading.Event()

		Methods.writeFile("/sys/class/gpio/gpio"+str(self.led1)+"/direction", "high", "w")
		Methods.writeFile("/sys/class/gpio/gpio"+str(self.led2)+"/direction", "high", "w")
Example #19
0
def renewRegistration():
    print("===============================================================")
    print("Enter the registrations's details:")
    regnoValid = False
    while regnoValid == False:
        regno = getInput(AGENTSUBSCREEN, "Registration number: ")
        # TODO Aryan : Verify if it's a valid registration number  DONE
        valid = m.checkregno(regno)
        if not (valid):
            print("Registration number invalid, please try again...")
        else:
            break
    m.renewRegistration(regno)
    # TODO Aryan : Set the new expiry data for the registration DONE
    print("The registration has been renewed.")
    return
def return_hardcall(C,L,cutoff,barcode,Ind=False,hmm=False):

    bchunk, bcall = Methods.best_chunk( C, L )
    ichunk, icall = Methods.ind_consensus( C, L, cutoff )
    #hchunk, hcall = Methods.hmm_consensus()

    if Ind:
        if barcode == icall:
            return 1
        else:
            return 0
    else:
        if barcode == bcall:
            return 1
        else:
            return 0
Example #21
0
def fill_temp_form(form):
    """
    This function fill the temp form text inputs with the CHANGING_SIGN.

    @param form: The temp form.
    @type form: dict
    @return: None
    """
    if len(Methods.get_text_inputs(form["inputs"])) < 3:
        return
    for input_tag in form["inputs"]:
        if input_tag in Methods.get_text_inputs(form["inputs"]):
            # If it is a text input.
            if "value" in input_tag.keys() and not input_tag["value"]:
                # There is no value to the text input.
                input_tag["value"] = Methods.CHANGING_SIGN
def CheckFeedrate(vs,ve,length):
    v=np.abs(vs-ve)
    v1=min(vs,ve)
    t1=Acc/Jerk
    t2=v/Acc-t1
    if t2<0:
        t2=0
        t1=np.sqrt(v/Jerk)
    
    length1=v1*(2*t1+t2)+0.5*Jerk*t1*(2*t1+t2)*(t1+t2)
    if length1<=length:
        return ve
    else:
        args=(Jerk,0,2*v1,-length)
        ans=Methods.CubicEquation(args)
        flag=0
        for i in ans:
           if i.imag ==0 and i.real>=0:
               t1=i
               flag=1
        if flag==0:
            return vs
        else:
            if ve>vs:
                return vs+Jerk*t1**2
            else:
                return vs-Jerk*t1**2 
Example #23
0
 def analysis_response(self, response):
     response_list = []
     star_response = 0
     end_response = 0
     while True:  # 解析一个评论集的每条回复的结构
         res = {}
         star_response = end_response
         star_response = response.find('{"abledel"', star_response)
         if star_response < 0:
             break
         end_response = Methods.braket_wife(response, star_response,
                                            '{') + 1
         response_one = response[star_response:end_response]
         target = {}
         tmp = re.findall('"content":"(.*?)"', response_one)[0]
         #有些神奇的存在明明@了某个人,源码却未显示
         try:
             target_content = re.findall('@{uin.*?:1}', tmp)[0]
             target['name'] = re.findall('nick:(.*?),who',
                                         target_content)[0]
             target['qq'] = re.findall('uin:(\d+),nick', target_content)[0]
         except:
             target_content = ''
             target['name'] = ''
             target['qq'] = ''
         res['content'] = tmp.replace(target_content, '')
         res['time'] = re.findall('"createTime2":"(.*?)"', response_one)[0]
         res['name'] = re.findall('"name":"(.*?)"', response_one)[0]
         res['qq'] = re.findall('"uin":(\d+)', response_one)[0]
         res['target'] = target
         response_list.append(res)
     return response_list
Example #24
0
    def spider(self, target_qq):
        for page in range(0, 10):
            url = 'https://user.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6?uin=%s&ftype=0&sort=0&' \
                  'pos=%d&num=20&replynum=100&g_tk=%s&callback=_preloadCallback&code_version=1&' \
                  'format=jsonp&need_private_comment=1&g_tk=%s'%(target_qq,page*20,self.msg.gtk,self.msg.gtk)
            r = self.msg.s_com.get(url)
            text = r.text
            if len(text) < 1000:  #少于1000个字符,说明这一页没有说说
                break
            self.sem.acquire()
            with open('./爬虫.html', 'a', encoding='utf-8') as f:
                f.write('QQ:%s   page:%d' % (target_qq, page))
                f.write(text)
                f.write(
                    '------------------------end--------------------------\n\n\n\n\n\n\n\n\n'
                )
            self.sem.release()

            star = text.find('"msglist":[')
            end = Methods.braket_wife(text, star, '[') + 1
            page_source = text[star:end]  #一页的内容

            #解析每条说说的内容
            moods = []
            for mood_text in self.get_mood(page_source):
                mood = self.analysis_mood(mood_text, target_qq)
                moods.append(mood)
                self.sem_mood.acquire()
                self.write_mood(mood)  #可视化写入本地
                self.sem_mood.release()

            self.sem_mood_json.acquire()
            with open('./mood_json.txt', 'a') as f:
                json.dump(moods, f)  #以json形式写入本地
            self.sem_mood_json.release()
Example #25
0
def submitProfile():
    #--------------------------------------------------------------------------------
    #   When user submits their profile, create a profile with the username_profile.txt
    #       store all of the acquired data in the profile
    #------------------------------------------------------------------------
    profileContent = []
    profileContent.append(FnameEntry.get())
    profileContent.append(LnameEntry.get())
    profileContent.append(usernameEntry.get())
    profileContent.append(passwordEntry.get())
    profileContent.append(confirmPasswordEntry.get())
    profileContent.append(securityQuestion1Entry.get())
    profileContent.append(securityQuestion2Entry.get())
    #Check for completed fields
    submitNow = True
    for field in profileContent:
        if (Methods.isEmpty(field) == True):
            submitNow = False
            error = proErrorInput + "*"
            Label(createProfileWindow, text=error).grid(row=10, column=2)
            break
    #check if user profile does not exist
    if (submitNow):
        saveProfile = usernameEntry.get() + "_profile.txt"
        if (os.path.isfile(saveProfile) == False):
            with open(saveProfile, "w") as file:
                for content in profileContent:
                    file.write(content + ",")
            #close profile window
            createProfileWindow.destroy()
Example #26
0
def checkLogin():
    #---------------------------------------------------------------
    #   Open up the username_profile.txt and verify the user credentials
    #       if the credentials match what is in file, upload user progress
    #        from file and go to main home screen
    #
    #---------------------------------------------------------------
    profileName = loginUsernameEntry.get() + "_profile.txt"
    #Check if the username profile exist
    if os.path.isfile(profileName):
        existingProfile = Methods.fileSplitter(profileName)
        searchedUsername = existingProfile[2]
        searchedPassword = existingProfile[3]
        #Check if the username and passwrod match
        if (searchedUsername == loginUsernameEntry.get()
                and searchedPassword == loginPasswordEntry.get()):
            # Send user to homePage
            Label(frame, text="Successful Login").grid(row=2, column=2)
            #Go to the home Screen module
            Home.main(root, frame)
        else:
            Label(frame, text="incorrect password/username").grid(row=2,
                                                                  column=2)
    else:
        Label(frame, text="incorrect password/username").grid(
            row=3, column=2)  # remove the hard code
Example #27
0
def SIR_Model(S, I, R, D, reproduction_number, dailyDeathRate, rLen, IR,
              interactions, pop):
    pop = [Person(i, 'S') for i in range(int(totalpop))]
    pop[len(pop) - 1].type = 'I'
    for i in t:
        S[i] = sum([p.type == 'S' for p in pop])
        I[i] = sum([p.type == 'I' for p in pop])
        R[i] = sum([p.type == 'R' for p in pop])
        D[i] = sum([p.type == 'D' for p in pop])
        pop = M.addDay(pop.copy())
        pop = M.dailyInfect(I[i], pop.copy(), IR, interactions, totalpop)
        pop = M.removed(pop.copy(), dailyDeathRate, rLen)
        l = M.daily_reproduction_number([p for p in pop if p.type == "I"],
                                        rLen)
        reproduction_number[i] = np.average(l)
    return S, I, R, D, reproduction_number, pop
Example #28
0
def registerPerson(parentScreen, personStr):
    print("---------------------------------------------------------------")
    print("The " + personStr + "'s details were not found in the database!")
    print("Please enter the " + personStr + "'s details:")
    details = dict()
    while True:
        details = getPersonDetails(parentScreen)
        if details["fname"] == "" or details["lname"] == "":
            print(
                "First name or last name cannot be blank! Re-enter details...")
        else:
            break
    # TODO Aryan : Store these values in the database DONE
    m.registerPerson(details['fname'], details['lname'], details['birthdate'],
                     details['birthplace'], details['address'],
                     details['phone'])
    print("---------------------------------------------------------------")
Example #29
0
def test(points,
         number_of_clusters,
         solution=None,
         max_iterations=100,
         method=Methods.method_heuristic_initial_clusters_max_dist):
    win = GraphWin("Results", 800, 600)
    displacement = 20

    time_start = time()

    for point in points:
        p = GPoint(point.x * displacement, point.y * displacement)
        p.draw(win)

    iteration_result = Methods.clustering(points, number_of_clusters,
                                          max_iterations, method)

    clusters = iteration_result.clusters

    for c in clusters:
        c = Circle(
            GPoint(c.center.x * displacement, c.center.y * displacement),
            c.radius * displacement)
        c.draw(win)

    time_end = time()

    time_range = time_end - time_start

    print("-----------------------------")
    print("Method used: " + get_method_name(method))
    print("Total time: " + str(time_range) + " s")
    print("Results after " + str(max_iterations) + " iterations:")
    print(str(clusters))
    if solution is not None:
        errors = Methods.compare_results(clusters, solution)
        print("Max error: " + str(errors[1]))
        print("Min error: " + str(errors[2]))
        print("Median error: " + str(errors[0]))

    try:
        win.getMouse()
        win.close()
    except:
        return 0
Example #30
0
 def FindUsers(self, UserData, finallist):
     instance = Methods.MethodRepository()
     EvolveRes = instance.EvolveForUser(finallist, UserData, self.T)
     Total = len(self.Tset) - 1
     POfClasses = instance.findClassP(Total, self.D)
     # ZeroFrequency =Instance.ZeroFreProblem(EvolveRes)
     Prediction = instance.Predict(EvolveRes, POfClasses)
     Result = instance.GivePrediction(Prediction)
     return Result
Example #31
0
def filter_forms(page):
    """
    This function filters the pages that has an action form.

    @param page: The current page
    @type page: Classes.Page
    @return: List of forms
    @rtype: list
    """
    filtered_forms = list()
    if "html" in page.type.lower():
        # We can check only html files.
        forms = Methods.get_forms(page.content)  # Getting page forms.
        for form in forms:
            if len(Methods.get_text_inputs(form["inputs"])) != 0:
                # If there are no text inputs, it can't be command injection.
                filtered_forms.append(form)
    return filtered_forms
Example #32
0
	def blink(self):
		"""
		Fait clignoter les LEDs alternativement.
		"""
		while not self.shutdownThread.is_set():
			Methods.writeFile("/sys/class/gpio/gpio"+str(self.led1)+"/value", "0", "w")
			Methods.writeFile("/sys/class/gpio/gpio"+str(self.led2)+"/value", "1", "w")
			sleep(0.3)
			Methods.writeFile("/sys/class/gpio/gpio"+str(self.led1)+"/value", "1", "w")
			Methods.writeFile("/sys/class/gpio/gpio"+str(self.led2)+"/value", "0", "w")
			sleep(0.3)
Example #33
0
def main(root, frame):
    frame.destroy()
    root.title("FunSmart Home Screen")
    frame = Frame(root, )
    frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1)
    photo3 = PhotoImage(file="funsmart.png")
    w = Label(frame, image=photo3)
    w.pack()

    subjects = Methods.fileSplitter("subjectSelector.txt")

    btn = Button(frame,
                 font=("Arial", 14, "italic"),
                 foreground='white',
                 text=subjects[0],
                 height=80,
                 padx=100,
                 pady=50,
                 bg='#82E0AA',
                 command=lambda: PreTest.main(root, frame, subjects[0]))
    # btn = Button(frame,font=("Arial", 14, "italic"),foreground = 'white',  text = subjects[0], height=60,pady=20, bg='#28C275', command = lambda: PreTest.main(root, frame, subjects[0]))
    btn.pack()

    btn1 = Button(frame,
                  font=("Arial", 14, "italic"),
                  foreground='white',
                  text=subjects[1],
                  height=80,
                  padx=100,
                  pady=50,
                  bg="#82E0AA",
                  command=lambda: PreTest.main(root, frame, subjects[1]))
    btn1.pack()

    btn2 = Button(frame,
                  font=("Arial", 14, "italic"),
                  foreground='white',
                  text=subjects[2],
                  height=80,
                  padx=100,
                  pady=50,
                  bg="#82E0AA",
                  command=lambda: PreTest.main(root, frame, subjects[2]))
    btn2.pack()

    # btn3 = Button(frame, text = subjects[3], padx = 100, pady=50, height=20, bg="lightgreen", command = lambda: PreTest.main(root, frame, subjects[3]))
    btn3 = Button(frame,
                  font=("Arial", 14, "italic"),
                  foreground='white',
                  text=subjects[3],
                  height=80,
                  padx=100,
                  pady=50,
                  bg="#82E0AA",
                  command=lambda: PreTest.main(root, frame, subjects[3]))
    btn3.pack()
Example #34
0
	def setPosition(self, position):
		"""
		Met à jour la position du servo selon la position donné en degrés.

		Args:
			position (int): Position en degré
		"""
		if position > 90:
			position = 90
		elif position < -90:
			position = -90

		self.position = position

		if self.invert:
			position*=-1
		duty = (50000/9)*position+1500000

		Methods.writeFile("/sys/devices/ocp.3/pwm_test_"+self.name+"."+self.nb+"/duty", str(duty), "w")
    def FileRead(self):
        file = 'csv/DataForDT.csv'
        #Getting reccords from CSV file
        lines = csv.reader(open(file))
        #Making a list of reccords
        lisst = list(lines)
        Instance = Methods.MethodRepository()
        TraininD, TestD = Instance.MadeChunks(lisst)

        return [TraininD, TestD]
Example #36
0
	def __init__(self, name, nb, invert):
		"""
		Initialise le PWM et positionne le servomoteur à 0 degrès.

		Args:
			name (str): Nom du PWM ("P9_14", "P9_22"...).
			nb (str): Nombre après le nom du PWM.
			invert (bool): Défini si l'axe du servomoteur est inversé.
		"""
		self.name = name
		self.nb = nb
		self.invert = invert

		try:
			Methods.writeFile("/sys/devices/bone_capemgr.8/slots", "bone_pwm_"+name, "a")
			sleep(2)
			Methods.writeFile("/sys/devices/ocp.3/pwm_test_"+name+"."+nb+"/period", "20000000", "w")
			self.setPosition(0)
		except IOError:
			print "La configuration des servos a déjà été faites"
Example #37
0
def run(args, batch=False, ask_user=False, remove_existent_db=True):

    start = time.time()

    check_if_dbfile_exists(args, batch, ask_user, remove_existent_db)

    gene_white_list, gene_black_list = build_white_and_black_gene_lists(args)

    db = SQLiteDB.DB(args.output_file)

    genes_total = 0
    genes_passed = 0

    # files to iterate over
    if args.input_file:
        eqtl_files = [args.input_file]
    elif args.input_folder:
        eqtl_files = [
            os.path.join(args.input_folder, x)
            for x in os.listdir(args.input_folder)
        ]
    else:
        logging.error(
            "You must provide exactly one of the followings arguments: --input_folder or --input_file."
        )
        exit("Aborting...")

    if args.snpid_format != "rsid":
        snpid_regex = re.compile(args.snpid_format)
    else:
        snpid_regex = None

    # Each chunk corresponds to all SNPs associated to the expression of a given gene
    for eqtl_file in eqtl_files:
        logging.info("Processing %s" % eqtl_file)
        for i, chunk in enumerate(
                DFS.read_eQTL_file(eqtl_file, args, snpid_regex)):
            chunk = Methods.generate_weights(
                chunk, args)  # convert to a Pandas data frame
            if len(chunk.index) != 0:
                genes_passed += 1
                gene_name = chunk.iloc[0][
                    Constants.GENENAME]  # extract gene name
                db("INSERT INTO extra VALUES(\"%s\", \"%s\", \"%s\", NULL, NULL, NULL)"
                   % (gene_name, gene_name, len(chunk)))
            Utilities.write_df_into_db(chunk, db)
            genes_total += 1

    print "DB %s created, with %d/%d genes." % (args.output_file, genes_passed,
                                                genes_total)
    print "--- %s seconds ---" % (time.time() - start)

    db.create_indexes()
    db.close()
Example #38
0
	def initPeriph(self):
		"""
		Initialise tout les périphériques servant à l'application (Laser, Servos, Manette nunchuk...) et instancie les objets globals.
		"""
		try:
			# GPIOs
			Methods.writeFile("/sys/class/gpio/export", "66", "a")
			Methods.writeFile("/sys/class/gpio/export", "69", "a")
			Methods.writeFile("/sys/class/gpio/export", "45", "a")

			# PWMs
			Methods.writeFile("/sys/devices/bone_capemgr.8/slots", "am33xx_pwm", "a")

			# UART
			Methods.writeFile("/sys/devices/bone_capemgr.8/slots", "BB-UART1", "a")

			sleep(2)

		except IOError:
			print "La configuration des périphériques a déjà été faites"

		# Création du laser
		self.laser = Laser(45)

		# Création de la gestion d'indication des modes
		self.modeObj = Mode(66, 69)

		# Création des servos
		self.verticalServo = Servo("P9_14", "10", False)
		self.horizontalServo = Servo("P9_22", "11", True)

		# Création de l'UART
		self.uart = UART()

		# Création du Nunchuk
		try:
			self.nunchuk = Nunchuk()
			self.nunchukIsConnected = True
		except IOError:
			print "Erreur de connexion avec la manette \"Nunchuk\""
			self.nunchukIsConnected = False
Example #39
0
 def get_comment(self, comments):
     star = 0
     end = 0
     comment_list = []
     while True:
         star = end
         star = comments.find('{"IsPasswordLuckyMoneyCmtRight"', star)
         if star < 0:
             break
         end = Methods.braket_wife(comments, star, '{') + 1
         comment_list.append(comments[star:end])
     return comment_list
Example #40
0
	def start(self, horizontalPositionTable, verticalPositionTable, laserStateTable):
		"""
		Dessine une forme personnalisé.

		Args:
			horizontalPositionTable (int[]): Tableau de toutes les positions du servomoteur qui gére l'axe horizontal.
			verticalPositionTable (int[]): Tableau de toutes les positions du servomoteur qui gére l'axe vertical.
			laserStateTable (str[]): Tableau de tout les états du laser.
			
		Les trois tableaux doivent être de même longueur !
		"""
		if len(horizontalPositionTable) != len(verticalPositionTable):
			print "Erreur (Shape): Les tableau des 2 servos ne sont pas de même longueur !!!"
			return

		for i in range(0,len(horizontalPositionTable)):
			self.horizontalServo.setPosition(horizontalPositionTable[i])
			self.verticalServo.setPosition(verticalPositionTable[i])
			self.laser.setState(laserStateTable[i])
			Methods.sendData(self.uart, horizontalPositionTable[i], verticalPositionTable[i], self.laser.getState())
			sleep(0.01)
Example #41
0
 def get_mood(self, text):
     mood_list = []
     star = 0
     end = 0
     while True:
         star = end
         star = text.find('{"certified"', star)
         if star < 0:
             break
         end = Methods.braket_wife(text, star, '{') + 1
         mood_list.append(text[star:end])
     return mood_list
Example #42
0
def Predict( arguments = None, data = None, colNames = None, target = None,
             adjustArgs = True ):
    '''
    Interface for Predict() in Methods
    
    updateArgs allows the caller to decide whether the arguments object
    should be updated by AdjustArgs() in GetArgs().
    '''
    args = GetArgs( arguments, adjustArgs )
    
    D = Methods.Predict( args, data, colNames, target, Methods.Source.Jupyter )
    return D # Dictionary { rho, RMSE, MAE, header, prediction, S-map }
Example #43
0
def listcourses():
	html = ""
	html += startCode()
	p1 = request.form['priority1']
	p2 = request.form['priority2']
	p3 = request.form['priority3']
	if p1 == "None":
		html += "Please select a 1st priority. " + \
		    "<a href=\"choose_course\">Go back</a>" + "</br>"
		return html
	courses_taken = Methods.courseList(request.form['coursestaken'])
	s = Methods.rankedCoursesMultiple(request.form.getlist('dept1'), \
		p1,p2,p3,courses_taken)
	top_courses = Methods.getSubset(s, 10)
	html += "Here are your top " + str(len(top_courses)) + " recommendations:"
	html += "\n\t\t<br><br>"
	html += "\n\t\t<center><table>"
	html += "\n\t\t\t<tr>"
	html += "\n\t\t\t\t<td width=200><b>Course Name</b></td>"
	html += "\n\t\t\t\t<td width=200><b>Overall Score</b></td>"
	html += "\n\t\t\t\t<td width=200><b>" + Methods.key(p1) + "</b></td>"
	if p2 != "None":
		html += "\n\t\t\t\t<td width=200><b>" + Methods.key(p2) + "</b></td>"
	if p3 != "None":
		html += "\n\t\t\t\t<td width=200><b>" + Methods.key(p3) + "</b></td>"
	html += "\n\t\t\t</tr>"
	for course in top_courses:
		html += "\n\t\t\t<tr>"
		html += "\n\t\t\t\t<td>"
		for i in range(0,len(course[0])-1):
			html += Methods.link(course[0][i]) + ", "
		html += Methods.link(course[0][len(course[0])-1]) + "</td>"
		html += "\n\t\t\t\t<td>" + str(course[1][0]) + "</td>"
		html += "\n\t\t\t\t<td>" + str(course[1][1]) + "</td>"
		if p2 != "None":
			html += "\n\t\t\t\t<td>" + str(course[1][2]) + "</td>"
		if p3 != "None":
			html += "\n\t\t\t\t<td>" + str(course[1][3]) + "</td>"
		html += "\n\t\t\t</tr>"
	html += "\n\t\t</table></center>"
	html += endCode()
	return html
    def run_methods(bins, count, cscore):
    
        count[cscore] += 1
        
        ## Single Read Methods
        fchunk, fcall = Methods.first_chunk( contexts, labels, cscore )
        lchunk, lcall = Methods.last_chunk( contexts, labels, cscore )
        rchunk, rcall = Methods.random_chunk( contexts, labels, cscore )

        ## Multi-Read Methods
        bchunk, bcall = Methods.best_chunk( contexts, labels )
        ichunk, icall = Methods.ind_consensus( contexts, labels, cscore )
        hchunk, hcall = Methods.hmm_consensus( indices, ems, len(means), chunk_vector )
     
        
        # First Chunk
        if barcode == fcall:
            bins['f'].append( 1 )
        else:
            bins['f'].append( 0 )

        # Last Chunk
        if barcode == lcall:
            bins['l'].append( 1 )
        else:
            bins['l'].append( 0 )

        # Random Chunk
        if barcode == rcall:
            bins['r'].append( 1 )
        else:
            bins['r'].append( 0 )

        # Best Chunk
        if barcode == bcall:
            bins['b'].append( 1 )
        else:
            bins['b'].append( 0 )

        #HMM Consensus
        if barcode == hcall:
            bins['h'].append( 1 )
        else:
            bins['h'].append( 0 )
            
        # Ind Consensus
        if barcode == icall:
            bins['i'].append( 1 )
        else:
            bins['i'].append( 0 )
        def run_methods(bins, cm, cm_counter ):
        
            ## Single Read Methods
            fchunk, fcall = Methods.first_chunk( contexts, labels, cscore )
            lchunk, lcall = Methods.last_chunk( contexts, labels, cscore )
            rchunk, rcall = Methods.random_chunk( contexts, labels, cscore )

            ## Multi-Read Methods
            bchunk, bcall = Methods.best_chunk( contexts, labels )
            ichunk, icall = Methods.ind_consensus( contexts, labels, cscore )
            hchunk, hcall = Methods.hmm_consensus( indices, ems, len(means), chunk_vector )
         
            
            # First Chunk
            #soft_calls['f'].append( fchunk )
            if barcode == fcall:
                bins['f'] += 1

            # Last Chunk
            #soft_calls['l'].append( lchunk )
            if barcode == lcall:
                bins['l'] += 1

            # Random Chunk
            #soft_calls['r'].append( rchunk )
            if barcode == rcall:
                bins['r'] += 1

            # Best Chunk
            #soft_calls['b'].append( bchunk )
            if barcode == bcall:
                bins['b'] += 1

            #HMM Consensus
            #soft_calls['h'].append( hchunk )
            if barcode == hcall:
                bins['h'] += 1
                
            # Ind Consensus
            #soft_calls['i'].append( ichunk )
            if barcode == icall:
                bins['i'] += 1
            
            ## Confusion Matrix

            cm_counter[ cm_choice.index( barcode) ] += 1 # Update appropriate counter
            cm[ cm_choice.index( barcode ), cm_choice.index( icall ) ] += 1 # Updates correct row given bar code
Example #46
0
 def buttonOff_onClick(self, event):
     Methods.testeDoBotaoOff()
Example #47
0
 def buttonOn_onClick(self, event):
     Methods.testeDoBotaoOn()
Example #48
0
 def btnMenuWebSite_onClick(self, event):
     Methods.openWebPageFromGitHub()
Example #49
0
 def btnMenuSobre_onClick(self, event):
     Methods.aboutDialogMessage(self)
from datetime import datetime

initialY=2013
initialM=8 #Aug
initialD=1
initialT=0
finalY=2013
finalM=12 #Dec
finalD=31
finalT=23


from datetime import timedelta
lapse = 5
d=timedelta(0,60*lapse)
initialdate=datetime(initialY,initialM,initialD)
finaldate=datetime(finalY,finalM,finalD,finalT,59)



monthdict={1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'}
current=initialdate
g=open('NewComersVsStaying.csv','a')
while(current<=finaldate):
        n,o,t= Methods.countNewVsStayingAtTime(monthdict[current.month],str(current.day),str(current.hour),str(current.minute))
        g.write(str(current)+", "+str(n)+", "+str(o)+", "+str(t)+"\n")
        current+=timedelta(0,60*lapse)
g.close()


initialY=2013
initialM=8 #Aug
initialD=1
initialT=0
finalY=2013
finalM=12 #Dec
finalD=31
finalT=23


lapse = 5
from datetime import timedelta
d=timedelta(0,60*lapse)
initialdate=datetime(initialY,initialM,initialD)
finaldate=datetime(finalY,finalM,finalD,finalT,59)



monthdict={1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'}
current=initialdate
g=open('StarbucksCountsFall.csv','a')
while(current<=finaldate):
	c= Methods.countAtTime(monthdict[current.month],str(current.day),str(current.hour),str(current.minute))
	g.write(str(current)+", "+str(c)+"\n")
	current+=timedelta(0,60*lapse)
g.close()



Example #52
0
	def setMode(self, mode):
		"""
		Change le mode de l'application

		Args:
			mode (str): Nom du mode ("Manual", "Semi-auto", "Wii", "Auto" ou "Stop").
		"""
		self.mode = mode
		if mode == "Manual" or mode == "Semi-auto":
			print "Mode manuel"
			self.shutdownThread.set()
			sleep(0.7)
			Methods.writeFile("/sys/class/gpio/gpio"+str(self.led1)+"/value", "1", "w")
			Methods.writeFile("/sys/class/gpio/gpio"+str(self.led2)+"/value", "0", "w")
		elif mode == "Wii":
			print "Mode Wii"
			self.shutdownThread.set()
			sleep(0.7)
			Methods.writeFile("/sys/class/gpio/gpio"+str(self.led1)+"/value", "1", "w")
			Methods.writeFile("/sys/class/gpio/gpio"+str(self.led2)+"/value", "1", "w")
		elif mode == "Auto":
			print "Mode automatique"
			self.shutdownThread.clear()
			threading.Thread(target=self.blink).start()
		elif mode == "Stop":
			self.shutdownThread.set()
			sleep(0.7)
			Methods.writeFile("/sys/class/gpio/gpio"+str(self.led1)+"/value", "0", "w")
			Methods.writeFile("/sys/class/gpio/gpio"+str(self.led2)+"/value", "0", "w")
		else:
			print "Mode inconnu !"
	print "File attributes_parsed.csv has been created"
	
	#These are the months that we have available:
try:
	months={'Jan':31, 'Feb':28, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30}
	hours=range(0,24)
	minutes=['00','05','10','15','20','25','30','35','40','45','50','55']
	

	g=open('StarbucksCountsJantoJun.csv','a')
	for m in sorted(months):
		d=1
		while d < months[m]:
			for h in hours:
				for min in minutes:
					count=Methods.countAtTime(m,str(d),str(h),str(min))
					g.write(m+', '+str(d)+', '+str(h)+', '+str(min)+', '+str(count)+"\n")
			d+=1
		print "finished month:"+ m
		
try:	
	for m in sorted(months):
		d=1
		while d < months[m]:
			Methods.StatsAtTime(m,str(d),'00:00:00','23:30:00',15)					
			os.system('cat Stats_'+m+str(d)+'_00:00:00_23:30:00.tsv >> Aux')
			os.system('rm Stats_'+m+str(d)+'_00:00:00_23:30:00.tsv')
			d+=1
except:
	print "Problem doing DB"
	
Example #54
0
 def buttonVerdeOff_onClick(self, event):
     Methods.testeDoBotaoVerdeOff()
Example #55
0
def chooseSchedule():
	if request.method == 'GET':
		html = startCode()
		html += "\n\t\t<br><br><form name=\"myform\" action=\"chooseSchedule\""
		html += " method=\"POST\">"
		return html
	html = startCode()
	taken = [i[0]+i[1] for i in Methods.courseList(request.form['coursestaken'])]
	try:
		year = int(request.form['year'])
		if year < 2015:
			raise Exception
	except:
		html += "<br>" + "Please enter a valid year 2015 or beyond. " + \
			"<a href=\"complete_schedule\">Go back</a>" + "</br>"
		return html
	if request.form['priority1'] == "None":
		html += "<br>" + "Please enter a first priority. " + \
					"<a href=\"complete_schedule\">Go back</a>" + "</br>"
		return html
	schedule = Methods.getMajorCourses(request.form['major'],taken, \
		request.form['priority1'],request.form['priority2'], \
		request.form['priority3'],year)
	#schedule = Methods.printSchedule(courses, taken, year)
	if schedule == "graduated":
		html += "You've graduated. You have no more semesters to take classes."
	elif schedule == "Not enough time":
		html += "Your schedule has too many prequesites to take in " 
		html += str((year - 2014) * 2) + " semesters"
	else:
		html += "\n\t\tLet's see what we came up with for you...<br><br>"
		html += "\n\t\t<center><table width=300>"
		overloaded = False
		# Print courses for each semester
		for i in range(0,len(schedule)/2):
			if len(schedule[2*i]) > 6 or len(schedule[2*i+1]) > 6:
				overloaded = True
			html += "\n\t\t\t<tr>"
			for j in range(2):
				html += "\n\t\t\t\t<td>"
				html += "\n\t\t\t\t\t<center><table>"
				html += "<b>Semester " + str(schedule.index(schedule[2*i+j]) + 1)
				html += "</b>"
				for course in schedule[2*i+j]:
					html += "\n\t\t\t<tr>"
					html += "\n\t\t\t\t<td>"
					html += Methods.link(str(course))
					html += "\n\t\t\t\t</td>"
					html += "\n\t\t\t</tr>"
				html += "\n\t\t\t\t\t</table></center>"
				html += "\n\t\t\t\t\t<br>"
				html += "\n\t\t\t\t</td>"
			html += "\n\t\t\t</tr>"
		html += "\n\t\t</table></center>"
		html += "<br>" + "Don't forget to allot time for sector requirements: "
		html += "Our <a href=\"choose_course\">decide on a course</a> module can help!" + "</br>"
		if overloaded:
			html += "<br>" + "Even without sectors, you're overloaded. You "
			html += "may need more years" + "</br>"
	html += endCode()
	return html
Example #56
0
 def buttonBuzzer_onClick(self, event):
     Methods.testeBuzzer()
Example #57
0
def main():
    
    #Initialisation
    
    nb_cust_time = Methods.fill_arg(Globals.DISTRIBUTION_CUSTOMERS, 60) # This list know each minute how many customers arrive
    customers = []                                                      # This is the future list of customers
    for i in range(Globals.NB_CUSTOMERS):
        customers.append(Classes.Customer())                            # This is how the list is filled
    cust_index = []               # This list stores the indexes of the customers who are present
    offers_index = []             # This list stores the indexes of the offers who are presentes
    offers_completed = 0          # This counter increases everytime an offer is completed    
    offers_refused = 0            # This counter increases everytime an offer is refused and a customer leaves
    first_loop_counter = 0        # This counter counts the number of times all the customers go throught the loop change of wish
    second_loop_counter = 0       # This counter counts the number of times all the customers go throught the loop booking unavailable
    satisfaction_temp = []        # This list stores the utility of the customers who are present (with the offers they have)
    satisfaction_temp_split = []  # This list stores the split of the previous utility (destination, week, time and price)
    satisfaction_finale = [0 for i in range(len(customers))]       # This list stores the utility the customers leave the agency with
    satisfaction_finale_split = [0 for i in range(len(customers))] # Same for the split
    step_cust = 0  # This step allows us to know which is the next customer from the customer list to show up
    time = 0       # This is just a timer
    
    while time < (len(nb_cust_time) + 10) or cust_index != []:  # While there are customers remaining in the shop or outside
        
        
        if time < len(nb_cust_time):       # If there are still new customers to come
            new_custs = nb_cust_time[time] # The new number of customers arriving in the agency is givent by the list
        else:
            new_custs = 0
            
        if new_custs != 0:                                                 # For every new customer
            for i in range(new_custs):
                customers[step_cust].time_proc = time                      # We intialize their time_proc to the actual time
                cust_index.append(step_cust)                               # We store their index in the appropriate list
                [k, u, v] = Methods.best_offer_index(customers[step_cust]) # We give them the best offer
                offers_index.append(k)                                     # and store the characteristics
                satisfaction_temp.append(u)                                # of this offer in the
                satisfaction_temp_split.append(v)                          # corresponding lists
                step_cust += 1                                             # Then we increment the customer index for the next one
                
        if cust_index != []:          # If there are people in the store
            pop_list = []             # This will be explained later
            for i in range(len(cust_index)):  # For every customer in the store
                wait = time - customers[cust_index[i]].time_pro  # We calculate how long they have been waited
                if wait >= Globals.PROCESS_TIME:                 # If that time is greater than the process time they are processed
# We then check the satisfaction of the customers to be processed to determine the rest of the process
                    if satisfaction_temp[i] > Globals.THRESHOLD_2: # If the utility is too big they will leave                                     
                        satisfaction_finale[cust_index[i]] = satisfaction_temp[i]             # We store their final utility
                        satisfaction_finale_split[cust_index[i]] = satisfaction_temp_split[i] # and the split
                        pop_list.append(i)  # We add to the pop list their number
                        offers_refused += 1 # We increase the number of offers refused
                    elif satisfaction_temp[i] > Globals.THRESHOLD_1: # The elif means we are between the two thresholds
                        first_loop_counter += 1                                        # We are into the first loop
                        customers[cust_index[i]].modif(time)                           # We change the wishes (see Classes)
                        [k, u, v] = Methods.best_offer_index(customers[cust_index[i]]) # We change the stored values with a new offer
                        offers_index[i] = k
                        satisfaction_temp[i] = u
                        satisfaction_temp_split[i] = v 
                    else: # The only remaining possibility is we are below the smallest threshold
                        if Globals.OFFERS[offers_index[i]][6]: # If the offer is available
                            Methods.booking(offers_index[i])   # We book the corresponding offer
                            offers_completed += 1              # We have one more offer completed
                            satisfaction_finale[cust_index[i]] = satisfaction_temp[i]             # We can store the final utility
                            satisfaction_finale_split[cust_index[i]] = satisfaction_temp_split[i] # and the split
                            pop_list.append(i) # We add to the pop list the number of the customer
                        else: # If the offer is no longer available
                            customers[cust_index[i]].reject_loop += 1 # We go through the reject loop but don't change the wishes
                            [k, u, v] = Methods.best_offer_index(customers[cust_index[i]]) # The customer gets a new best offer
                            offers_index[i] = k                        # We store the new values corresponding to this customer
                            satisfaction_temp[i] = u
                            satisfaction_temp_split[i] = v
                            customers[cust_index[i]].time_proc = time  # and reset the waiting time                    
                            second_loop_counter += 1                   # Finally we increase the second loop counter
            if pop_list != []:                         # The pop list is more of a technical Python issue actually
                p = 0                                  # The only purpose of it is to remove the customers who are leaving the
                for i in pop_list:                     # agency (whether they leave with an offer or not) from the temporary lists
                    cust_index.pop(i - p)              # that represent the characteristics of the cutomers who are present
                    offers_index.pop(i - p)
                    satisfaction_temp.pop(i - p)
                    satisfaction_temp_split.pop(i - p)
                    p += 1
                pop_list = []
        time += 1                                      # Once everything is treated, the timer increases and the loop begins once more

    # From here the simulation is actually over
        
    loops = []  # Used as a check to control if the code works : not actually used here       
    first_loop_nb = 0    # We will count the number of people who went through the changing loop
    second_loop_nb = 0   # And the number of those who went through the reject loop
    for i in range(len(customers)):
        loops.append(customers[i].store)
        if customers[i].other_loop != 0:
            first_loop_nb += 1
        if customers[i].reject_loop != 0:
            second_loop_nb += 1
            
    # We print the results we are interested in to be able to copy them for future use        
    print("Number of potential offers : "+str(len(Globals.OFFERS)))
    print("Number of customers : "+str(Globals.NB_CUSTOMERS))
    print("Offers completed : "+str(offers_completed))
    print("Customers not served : "+str(offers_refused))
    av_ut = sum(satisfaction_finale) // len(satisfaction_finale)
    print("Average utility : "+str(av_ut))
    print("Number of first loops : "+str(first_loop_counter))
    print("Number of customers through first loop : "+str(first_loop_nb))
    print("Number of second loops : "+str(second_loop_counter))
    print("Number of customers through second loop : "+str(second_loop_nb))
Example #58
0
import Classes
import Methods

kanaM, kanaF = Methods.getKana()
Methods.chooseNum(kanaM, kanaF)
    ## For a given cscore, group and iterate through.
    event_sum = 0
    for i in xrange(9, int(cscore*10-1), -1):
        event_sum += len(ranked_events[i])
        for event in ranked_events[i]:
            # Unpack Variables
            event_name = event[0]
            contexts = event[1]
            labels = event[2]
            ems = event[3]
            means = event[4]
            barcode = event_name.split('-')[0]
            # Counter for keeping track of number of events
            counter += 1
            ## Single Read Methods
            fchunk, fcall = Methods.first_chunk( contexts, labels, cscore )
            lchunk, lcall = Methods.last_chunk( contexts, labels, cscore )
            rchunk, rcall = Methods.random_chunk( contexts, labels, cscore )
            
            ## Multi-Read Methods
            bchunk, bcall = Methods.best_chunk( contexts, labels )
            ichunk, icall = Methods.ind_consensus( contexts, labels, cscore )
            hchunk, hcall = Methods.hmm_consensus( indices, ems, len(means), chunk_vector )

            #-=Single Read Methods=-
            # First Chunk
            soft_calls['f'].append( fchunk )
            if fcall[0] == barcode:
                bins['f'] += 1

            # Last Chunk