Exemplo n.º 1
0
def generateui(state, number):
    global last_state
    if (last_state == state):
        winsound.PlaySound(None, winsound.SND_ASYNC)
        return
    elif (last_state == "Incoming"
          or last_state == "Outgoing" and state == "Idle"):
        winsound.PlaySound("nlla.mp3", winsound.SND_ASYNC)
        ms.alert(number, state, "Call Disconnected", None, 5000)
    else:
        if (state == "Incoming"):
            actiontxt = "Go Answer!"
            winsound.PlaySound(None, winsound.SND_ASYNC)
            winsound.PlaySound("BuildItUp1.wav",
                               winsound.SND_ASYNC | winsound.SND_ALIAS)
        if (state == "Outgoing"):
            actiontxt = "call picked"
            winsound.PlaySound(None, winsound.SND_ASYNC)
            winsound.PlaySound("outgoing.wav",
                               winsound.SND_ASYNC | winsound.SND_ALIAS)
        if (state == "answering"):
            actiontxt = "You are Talking To " + number
            winsound.PlaySound(None, winsound.SND_ASYNC)

        global actiontxt
        ms.alert(number, state, actiontxt, None, 30000)

    last_state = state
Exemplo n.º 2
0
    def update_robot(self, unused_addr, args):
        print("update robot")
        self.robot.run()
        score = Robot.count("Soja")
        self.playerListBox.delete(0, tk.END)
        #self.playerListBox.insert(tk.END, player_name + " " + str(score))
        print(self.players_list)
        for p in self.players_list:
            self.playerListBox.insert(tk.END, p + " " + str(self.players_list[p]))

        msg = osc_message_builder.OscMessageBuilder(address="/player")
        msg.add_arg(player_name)
        msg.add_arg(score) #
        msg = msg.build()
        self.to_client_client.send(msg)

        if self.robot.win:
            # I am the winner
            # lets tel that to ohters
            msg = osc_message_builder.OscMessageBuilder(address="/winner")
            msg.add_arg(player_name)
            msg.add_arg(score)
            msg = msg.build()
            #self.to_client_client.send(msg)
            self.to_server_client.send(msg)
            alert(text = "Vous avez gagné la partie !")
Exemplo n.º 3
0
def PlotBar(fileName, inpString=''):

    try:
        df = pd.read_excel(fileName)
    except:
        pymsgbox.alert('You have entered invalid file name!', 'Alert')
        return
    if (inpString != ''):
        df = df[df[inpString] == 'Yes']
    departmentsNames = list(set(df['Department']))
    departmentValues = [0] * len(departmentsNames)

    for j, i in enumerate(departmentsNames):
        departmentValues[j] = (list(df.Department).count(i))

    print(departmentsNames, departmentValues)
    data1 = {
        'departmentsNames': departmentsNames,
        'departmentValues': departmentValues
    }
    df1 = DataFrame(data1, columns=['departmentsNames', 'departmentValues'])

    root = tk.Tk()

    figure1 = plt.Figure(figsize=(5, 5), dpi=100)
    ax1 = figure1.add_subplot(111)
    bar1 = FigureCanvasTkAgg(figure1, root)
    bar1.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
    df1 = df1[['departmentsNames',
               'departmentValues']].groupby('departmentsNames').sum()
    df1.plot(kind='bar', legend=True, ax=ax1)
    ax1.set_title('Department Names Vs. {}'.format(inpString))

    root.mainloop()
Exemplo n.º 4
0
def signup():
    if request.method == 'POST':
        fname = request.form['fname']
        mname = request.form['mname']
        lname = request.form['lname']
        email = request.form['email']
        phoneno = request.form['phoneno']
        pswd = request.form['pswd']
        DOB = request.form['DOB']
        gender = request.form['gender']
        question = request.form['question']
        answer = request.form['answer']
        uid = id_generator()
        cur = mysql.connection.cursor()
        cur.execute("select EXISTS(select email from user where email=%s)",
                    [email])
        res = cur.fetchone()
        if res[0] == 0:
            cur.execute("insert into user values(%s,%s,%s)",
                        [uid, email, pswd])
            cur.connection.commit()
            cur.execute(
                "insert into client values(%s,%s,%s,%s,%s,%s,%s,%s,%s)", [
                    fname, lname, mname, gender, question, answer, phoneno,
                    DOB, uid
                ])
            cur.connection.commit()
            cur.close()
            return redirect(url_for("login"))
        else:
            pymsgbox.alert('Email id already Registered')
            return redirect(url_for("login"))
    return render_template('signup.html')
Exemplo n.º 5
0
    def matchFile(self, filename, userInput=True):
        try:
            title, artist, score = self._topresult(filename)
            print("")
            print("AcoustID Name: %s" % title)
            print("AcoustID Artist: %s" % artist)
            print("")
            self.spotifysearch.search(
                "%s - %s" % (title, artist)
            )  # Plug back in our acoustID results into spotify search

            return self.spotifysearch.selectResult(
                0)  # Return the resulting spotify track

        except TypeError:  # Again, If we could not identify a match
            # TODO: Work on the userInput exception handling... e.g. skip None Songs
            if userInput == True:
                pymsgbox.alert(text='Could not identify song automatically',
                               title='Song ID Error',
                               button='OK')
                userSongName = pymsgbox.prompt(text='Song Name',
                                               title='Enter Song Name')
                userSongArtist = pymsgbox.prompt(text='Artist',
                                                 title='Enter Artist Name')

                self.spotifysearch.search(
                    "%s - %s" % (userSongName, userSongArtist)
                )  # Search spotify with user entered values
                return self.spotifysearch.selectResult(
                    0)  # Return the resulting spotify track
            else:
                return None
Exemplo n.º 6
0
def fetch(url):
    print(f"Url being requested: {url}")
    # First try to fetch request without using proxy rotation
    try:
        req = requests.get(url)
        return req
    except:
        proxy_list = get_proxy_list()
        for proxy in proxy_list:
            try:
                print(f'Trying proxy: {proxy}')
                req = requests.get(url, proxies={'https': proxy}, timeout=5)
                return req
            except ConnectTimeout:
                print('Connection time out error. Trying next one')
            except ProxyError:
                print('Proxy Error. Trying next one')
            except SSLError:
                print(
                    'SSL Error. Maximum retries exceeded with url. Trying next one'
                )

    # If nothing is returned, send error message to user
    pymsgbox.alert(
        f"Couldn't obtain a valid proxy. Please change api key for web scraping."
    )
    exit()
Exemplo n.º 7
0
def editprofile():
    if request.method == 'POST':
        fname = request.form['fname']
        mname = request.form['mname']
        lname = request.form['lname']
        email = request.form['email']
        phoneno = request.form['phoneno']
        pswd = request.form['pswd']
        DOB = request.form['DOB']
        gender = request.form['gender']
        question = request.form['question']
        answer = request.form['answer']
        cur = mysql.connection.cursor()
        uid = session['uid']
        cur.execute("update user set email=%s,pswd=%s where uid=%s",
                    [email, pswd, uid])
        cur.connection.commit()
        cur.execute(
            "update client set fname=%s,lname=%s,mname=%s,gender=%s,security_question=%s,answer=%s,phone_number=%s,dob=%s where uid=%s",
            [fname, lname, mname, gender, question, answer, phoneno, DOB, uid])
        cur.connection.commit()
        cur.close()
        pymsgbox.alert('Profile Updated Successfully', 'Title')
        return redirect(url_for("homepage"))
    return render_template('editprofile.html')
Exemplo n.º 8
0
    def _do_work(self):
        """
        Activated the first model on the recording from the queue
        if there is detection of keyword start the second model to identify the speaker
        :return:
        """
        num = Queue.get()

        model = load_model('model.h5', compile=False)
        model.load_weights('model_weight.h5')

        reader = csv.reader(open('speech.csv', 'r'))
        labels_dict2 = {}
        for row in reader:
            k, v = row
            labels_dict2[k] = v

        file = audio2vector('temp/output' + str(num) + '.wav')
        file = file.reshape(1, 10, 4, 1)

        item_prediction = model.predict_classes(file)
        for i, j in labels_dict2.items():
            if j == str(item_prediction[0]):
                pred = i
                print('keyword: {}'.format(i))
        with open('Files/ID_Name.txt') as fp:
            for line in enumerate(fp):
                if (pred == line[1].strip()):
                    model2 = load_model('model2.h5', compile=False)
                    model2.load_weights('model_weight2.h5')
                    file_name = 'temp/output' + str(num) + '.wav'
                    audio2Image('temp', file_name, 0)
                    train_datagen = ImageDataGenerator(rescale=1. / 255,
                                                       shear_range=0.2,
                                                       zoom_range=0.2,
                                                       horizontal_flip=True)
                    training_set = train_datagen.flow_from_directory(
                        './data/test',
                        target_size=(64, 64),
                        batch_size=32,
                        class_mode='categorical',
                        shuffle=False)

                    pred = model2.predict_generator(training_set,
                                                    steps=10,
                                                    verbose=1)
                    filenames = training_set.filenames
                    predicted_class_indices = np.argmax(pred, axis=1)
                    labels = (training_set.class_indices)
                    labels = dict((v, k) for k, v in labels.items())
                    predictions = [labels[k] for k in predicted_class_indices]
                    predictions = predictions[:len(filenames)]
                    print('speaker: {}'.format(predictions[0]))
                    #Utils.lower_sound(1)
                    pymsgbox.alert(
                        ' {} is calling you.'.format(predictions[0]),
                        'Recognition')
                    #Utils.lower_sound(0)
                    self.flag = True
        self.sleep(1)
Exemplo n.º 9
0
 def get_color(self):
     boolean = True
     while boolean:
         try:
             red = int(
                 prompt(text='Введите значение Red (от 0 до 255)',
                        title='Ввод'))
             green = int(
                 prompt(text='Введите значение Green (от 0 до 255)',
                        title='Ввод'))
             blue = int(
                 prompt(text='Введите значение Blue (от 0 до 255)',
                        title='Ввод'))
             if (0 <= red <= 255 and 0 <= green <= 255
                     and 0 <= blue <= 255):
                 boolean = False
                 color = (red, green, blue)
                 return color
             else:
                 alert(text='Введите численное значение от 0 до 255',
                       title='Ошибка ввода')
         except ValueError:
             alert(text='Введите численное значение от 0 до 255',
                   title='Ошибка ввода')
         except TypeError:
             boolean = False
Exemplo n.º 10
0
    def b():
        print(lista)
        nome_Funcionario = ui.leFuncionario.text()
        # string = ''
        # for i in lista:
        #     string += f'{i}\n\n'
        # ui.lResultado.setText(string)
        numDate = date(year=datetime.now().year,
                       month=datetime.now().month,
                       day=datetime.now().day)
        weekday_name = ["Seg", "Ter", "Qua", "Qui", "Sex", "Sab", "Dom"]
        wkday = numDate.weekday()

        try:

            if lista:

                total = get_total(lista)
                write_banco(
                    f'{nome_Funcionario}  |  {numDate.strftime("%d/%m/%Y")} {weekday_name[wkday]}  |  Adicional Noturno: {total}'
                )
                lista.clear()
                ui.lResultado2.setText(
                    f'{nome_Funcionario}  |  {numDate.strftime("%d/%m/%Y")} {weekday_name[wkday]}  |  Adicional Noturno: {total}'
                )
                ui.leFuncionario.setText('')
                ui.label_3.setText('')

            else:
                raise

        except Exception:
            alert(text='Nada para calcular', title="ERRO", button="OK")
Exemplo n.º 11
0
    def update_robot(self, unused_addr, args):
        print("update robot")
        self.robot.run()
        score = Robot.count("Soja")
        self.playerListBox.delete(0, tk.END)
        #self.playerListBox.insert(tk.END, player_name + " " + str(score))
        print(self.players_list)
        for p in self.players_list:
            self.playerListBox.insert(tk.END,
                                      p + " " + str(self.players_list[p]))

        msg = osc_message_builder.OscMessageBuilder(address="/player")
        msg.add_arg(player_name)
        msg.add_arg(score)  #
        msg = msg.build()
        self.to_client_client.send(msg)

        if self.robot.win:
            # I am the winner
            # lets tel that to ohters
            msg = osc_message_builder.OscMessageBuilder(address="/winner")
            msg.add_arg(player_name)
            msg.add_arg(score)
            msg = msg.build()
            #self.to_client_client.send(msg)
            self.to_server_client.send(msg)
            alert(text="Vous avez gagné la partie !")
Exemplo n.º 12
0
 def clean(NoMedia=False):
     try:
         subprocess.call(rmCommand + TempPath + '"', shell=True)
     except FileNotFoundError:
         # 如果删除失败,就打开临时文件夹让用户自己删除
         alert(
             error('ErrorOnRemoveTemp') + ' "' + str(TempPath) + '" ' +
             error('ErrorOnRemoveManual'), error('ErrorOnRemoveTitle'))
         with open(str(TempPath + separator + error('ErrorOnRemoveTip')),
                   'w'):
             pass
         # subprocess.Popen('explorer "' + TempPath + '"', shell=False)
     if NoMedia:
         try:
             subprocess.call(rmCommand + StorePath + '"', shell=True)
         except FileNotFoundError:
             alert(
                 error('ErrorOnRemoveEmpty') + ' "' + str(StorePath) +
                 '" ' + error('ErrorOnRemoveManual'),
                 error('ErrorOnRemoveEmptyTitle'))
             with open(
                     str(TempPath + separator + error('ErrorOnRemoveTip')),
                     'w'):
                 pass
             openinexplorer(StorePath)
Exemplo n.º 13
0
    def test_alert(self):
        # no text
        t = KeyPresses(['enter'])
        t.start()
        print(('Line', inspect.currentframe().f_lineno)); self.assertEqual(pymsgbox.alert(), 'OK')

        # text
        t = KeyPresses(['enter'])
        t.start()
        print(('Line', inspect.currentframe().f_lineno)); self.assertEqual(pymsgbox.alert('Hello'), 'OK')

        # text and title
        t = KeyPresses(['enter'])
        t.start()
        print(('Line', inspect.currentframe().f_lineno)); self.assertEqual(pymsgbox.alert('Hello', 'Title'), 'OK')

        # text, title, and custom button
        t = KeyPresses(['enter'])
        t.start()
        print(('Line', inspect.currentframe().f_lineno)); self.assertEqual(pymsgbox.alert('Hello', 'Title', 'Button'), 'Button')

        # using keyword arguments
        t = KeyPresses(['enter'])
        t.start()
        print(('Line', inspect.currentframe().f_lineno)); self.assertEqual(pymsgbox.alert(text='Hello', title='Title', button='Button'), 'Button')
Exemplo n.º 14
0
    def get_phone_number(self, group_name):
        # Navigate to whatsapp webpage
        self.driver.get(self.url)

        try:
            element_present = EC.presence_of_element_located((By.ID, 'app'))
            WebDriverWait(self.driver, self.timeout).until(element_present)
            time.sleep(2)
        except:
            print("Timed out waiting for page to load")

        try:
            if not self.driver.find_element_by_xpath("//*[@id='app']/div/div/div[2]/div[1]/div/div[2]/div/canvas") is None:
                pymsgbox.alert('Por favor active su whatsapp en la computadora y después haz clic Ok!', 'Atención!')
        except:
            logging.info("Whastapp was already logged!")

        try:
            numbers = self.search_group(group_name)
            time.sleep(3)
        except:
            numbers = None
            logging.info("Problem accessing whatsapp group.")
        
        return numbers
Exemplo n.º 15
0
 def add_team(self):
     query = "insert into team values (default, %s, NULL, NULL, 'Нет', %s)"
     data = (self.lineEdit.text(), self.lineEdit_5.text())
     cursor.execute(query, data)
     cnx.commit()
     pymsgbox.alert("Экипаж добавлен", "Инфо")
     self.setupAdminUi()
Exemplo n.º 16
0
 def delete_team(id):
     query = "delete from team where idteam = %s"
     data = (id, )
     cursor.execute(query, data)
     cnx.commit()
     pymsgbox.alert("Экипаж удален", "Инфо")
     self.setupAdminUi()
Exemplo n.º 17
0
def addNewUser(newUs, newPw, cityOne, stateTwo):
    global userData

    inputOne = str(newUs)
    inputTwo = str(newPw)
    inputThree = str(cityOne)
    inputFour = str(stateTwo)
    inDb = checkUser(inputOne)

    # checks if user already exists
    if (inDb == -1):
        # creates the new user with info
        new_row = {
            'username': inputOne,
            'password': inputTwo,
            'city': inputThree,
            'state_or_prov': inputFour
        }
        # adds new user
        userData = userData.append(new_row, ignore_index=True)
        userData.to_csv('chatbot_spreadsheet.csv',
                        encoding='utf-8',
                        index=False)
        pymsgbox.alert('The account has been added!')
    else:
        pymsgbox.alert('Username already exists try new name!')
Exemplo n.º 18
0
    def update_backend_excel(self):
        # Get backend dictionary
        self.get_backend_dict()

        # Extract the data related to the selected ticker
        self.get_ticker_selection()

        ticker_data = None
        if self.ticker in self.bk_dict:
            ticker_data = self.bk_dict[self.ticker]
        else:
            pymsgbox.alert(
                f"Backend storage file doesn't yet contain data about {self.ticker}. Please update sheet first",
                "No data to be used")
            exit()

        # Get an iss translation list for the backend sheet
        result_dict = handler.translate_dict_keys(ticker_data['Value'],
                                                  'Backend')

        # initialize xlwings worksheet
        self.initialize_worksheet(sheet_type="backend")

        # Enter all required data using a for loop based on the named ranges
        for key, value in result_dict.items():
            self.ws.Range(key).Value = value
Exemplo n.º 19
0
    def enroll_user(self):
        mycursor = self.mydb.cursor()
        erp = self.erp_ip.text()
        name = self.name_ip.text()
        pa = self.password_ip.text()
        cpa = self.cpassword_ip.text()
        #ip = socket.gethostbyname(socket.gethostname())

        if (erp.isalnum()   and pa.isalnum() and cpa.isalnum()):
            if (len(pa) <= 8 and len(cpa)<=8 ):
                if pa == cpa:
                    inputs = (erp,name,"NA","NULL",pa)
                    query = "insert into library values(%s,%s,%s,%s,%s)"
                    mycursor.execute(query,inputs)
                    self.mydb.commit()
                    successfull_function(self)
                    mycursor.close()
                    self.mydb.close()
                else:
                    error_function(self)
            else:
                pymsgbox.alert('Enter 8 alphanumeric characters only!')
                self.password_ip.clear()
                self.cpassword_ip.clear()
        else:
            pymsgbox.alert('Provide Alphanumeric Inputs Only!')
            return
Exemplo n.º 20
0
    def test_model(self):
        print('Starting Testing the Model ...')
        pymsgbox.alert('Starting Testing the Model ...',
                       'Message',
                       timeout=1000)
        test_images = self.__get_dumped_model('test_images')
        test_labels = self.__get_dumped_model('test_labels')

        x_dimension, y_dimension = self.__get_image_dimensions()

        test_images = np.reshape(
            test_images, (test_images.shape[0], x_dimension, y_dimension, 1))

        self.model = load_model(cnf.KERAS_PATH)  # Loading the keras model
        pred_labels = []

        pred_probabs = self.model.predict(
            test_images)  # Predicitng the probabilities

        for pred_probab in pred_probabs:
            pred_labels.append(list(pred_probab).index(max(pred_probab)))

        # cm = confusion_matrix(test_labels, np.array(pred_labels))

        classification_report = cfr(test_labels, np.array(pred_labels))

        accuracy = accuracy_score(
            test_labels, np.array(pred_labels))  # getting the model score

        print('\n\nClassification Report')
        print('---------------------------')
        print(classification_report)
        pymsgbox.alert(classification_report, 'Classification Report')
        return accuracy * 100
Exemplo n.º 21
0
def main():
    enable = enableSystem()
    if enable:
        plateNumberRecognition()
    else:
        pymsgbox.alert('No Guard On Duty!', 'Alert!', timeout=5000)
        main()
Exemplo n.º 22
0
    def test_alert(self):
        # no text
        t = KeyPresses(['enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.alert(), 'OK')

        # text
        t = KeyPresses(['enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.alert('Hello'), 'OK')

        # text and title
        t = KeyPresses(['enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.alert('Hello', 'Title'), 'OK')

        # text, title, and custom button
        t = KeyPresses(['enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.alert('Hello', 'Title', 'Button'), 'Button')

        # using keyword arguments
        t = KeyPresses(['enter'])
        t.start()
        print('Line', inspect.currentframe().f_lineno); self.assertEqual(pymsgbox.alert(text='Hello', title='Title', button='Button'), 'Button')
Exemplo n.º 23
0
def PlotPie(fileName, inpString=""):
    try:
        df = pd.read_excel(fileName)
    except:
        pymsgbox.alert('You have entered invalid file name!', 'Alert')
        return
    if (inpString != ''):
        df = df[df[inpString] == 'Yes']
    labels = list(set(df['Department']))
    departmentValues = [0] * len(labels)

    for j, i in enumerate(labels):
        departmentValues[j] = (list(df.Department).count(i))
    values = departmentValues

    explode = list()
    for k in labels:
        explode.append(0.1)

    root = tk.Tk()
    actualFigure = plt.figure(figsize=(5, 5), dpi=100)
    actualFigure.suptitle("Participation Stats", fontsize=22)
    pie = plt.pie(values,
                  labels=labels,
                  explode=explode,
                  shadow=True,
                  autopct='%1.1f%%')
    plt.legend(pie[0], labels, loc="upper corner")
    canvas = FigureCanvasTkAgg(actualFigure, root)
    canvas.get_tk_widget().pack()
    root.mainloop()
Exemplo n.º 24
0
def run(ticker, bool_batch=False):
    # Let user choose the solution for getting the data: Either scraping or using API
    if not bool_batch:
        scraping_method = pymsgbox.confirm(
            f'What method do you want to use to get the financial data from {ticker}?',
            'Select Option',
            buttons=['API', 'Web Scraping'])
    else:
        scraping_method = 'API'

    # Output folders
    work_directory = pathlib.Path(__file__).parent.absolute()
    excel_output_folder = os.path.join(work_directory, '../financial_files',
                                       'excel')
    json_output_folder = os.path.join(work_directory, '../financial_files',
                                      'json')
    excel_output_path = os.path.join(excel_output_folder, ticker + '.xlsx')
    json_output_path = os.path.join(json_output_folder, ticker + '.json')

    if scraping_method == 'Web Scraping':
        pymsgbox.alert(
            "Be aware that this option my not work due to possible scraping restrictions from website."
        )

        if not check_validity_output_file(excel_output_path) \
                or not excel_sheet_exists(excel_output_path, source=scraping_method):
            links = links_constructor(ticker)
            df_fs = scrape_tables(links)
        else:
            df_fs = excel_to_dataframe(excel_output_path,
                                       source=scraping_method)

    else:
        if not check_validity_output_file(json_output_path) \
                or not excel_sheet_exists(excel_output_path, source=scraping_method):
            json_file = get_api_request(ticker, bool_batch=bool_batch)
            save_json_request_to_file(json_file, json_output_path)
        else:
            with open(json_output_path, 'r') as file:
                json_file = json.load(file)

        df_fs = create_dataframe_from_api(json_file)

    # Get all the calculated ratios and relevant stock data
    results_df = get_rule_number1_ratios(df_fs, ticker)

    # Output all the financial data into an excel file
    dataframe_to_excel(excel_output_path,
                       df_fs,
                       ticker,
                       source=scraping_method,
                       bool_batch=True)

    # Output all the Rule #1 results into the excel file
    dataframe_to_excel(excel_output_path,
                       results_df,
                       ticker,
                       source='filter_fs_data',
                       bool_batch=bool_batch)
Exemplo n.º 25
0
def calculate():
        # asks the user to input the amount of the purchase
        price = float(pymsgbox.prompt('Please input the amount of the purchase to calculate the total cost for the item after taxes:', 'Price of Item'))
        total = float(price * s * c + price)
        #calculates full price with taxes and outputs it
        pymsgbox.alert("Your new price is: $" + str(total))
        "OK"
        return again()
def valid_email_addr(email_addr: str) -> bool:
    regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'

    if (re.search(regex, email_addr)):
        return True
    else:
        pgbox.alert('Invalid Email Address %s' % email_addr, 'Alert');
        return False
Exemplo n.º 27
0
def alertMeNegInt():
    pymsgbox.alert("Process Failed! No Internet Connection. Please Try Again.")
    response = pymsgbox.password('Please enter password to confirm')
    print response
    if response == "None":
        alertMeNegInt()
    if not response:
        alertMeNegInt()
Exemplo n.º 28
0
 def __init__(self):
     self.mydb = mysql.connector.connect(
         host="localhost",
         username="******",
         passwd="",
         database="pccoe"
     )
     pymsgbox.alert('Connected to Library Database!')
Exemplo n.º 29
0
def alertMeNegK():
    pymsgbox.alert("Process Failed! Web and net is up, but there is no secure K drive Connection. Please Try Again.")
    response = pymsgbox.password('Please enter password to confirm')
    print response
    if response == "None":
        alertMeNegK()
    if not response:
        alertMeNegK()
Exemplo n.º 30
0
def alertMePos():
    pymsgbox.alert("Success! Photo Roster Data from Canvas has been UPDATED for today!")
    response = pymsgbox.password('Please enter password to confirm')
    print response
    if response == "None":
        alertMePos()
    if not response:
        alertMePos()
Exemplo n.º 31
0
def messageTest():
    if msg.confirm(text='CONFIRM_TEXT',
                   title='CONFIRM_TITLE',
                   buttons=['OK', 'Cancel']) == 'OK':
        msg.alert(text='u r pressed OK', title='ALERT_TITLE', button='OK')
    else:
        msg.alert(text='u r pressed CANCEL', title='ALERT_TITLE', button='OK')
    msg.password(text='', title='', default='', mask='*')
Exemplo n.º 32
0
def hi():
    CLIENT_SECRET_FILE = ''  #download and insert your own secret file of google calender
    API_NAME = 'calendar'
    API_VERSION = 'v3'
    SCOPES = ['https://www.googleapis.com/auth/calendar']

    service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)

    syear = sy.get()
    smon = sm.get()
    sdate = sd.get()
    eyear = ey.get()
    emon = em.get()
    edate = ed.get()
    stime = sh.get()
    smin = smi.get()
    etime = eh.get()
    emin = emi.get()
    event_name = en.get()
    edes = ed1.get()

    stime, smin = time(stime, smin)
    etime, emin = time(etime, emin)

    #Create

    calendar_id_party = ''  ##insert your own id

    event_request_body = {
        'start': {
            'dateTime':
            convert_to_RFC_datetime(int(syear), int(smon), int(sdate),
                                    int(stime), int(smin)),
            'timeZone':
            'Asia/Kolkata',
        },
        'end': {
            'dateTime':
            convert_to_RFC_datetime(int(eyear), int(emon), int(edate),
                                    int(etime), int(emin)),
            'timeZone':
            'Asia/Kolkata',
        },
        'summary': event_name,
        'description': edes,
        'colorId': 5,
        'status': 'confirmed',
        'transparency': 'opaque',
        'visibility': 'public'
    }

    response = service.events().insert(calendarId=calendar_id_party,
                                       body=event_request_body).execute()
    eventId = response['id']

    pymsgbox.alert(text='Your event is created successfully',
                   title='Confirmation',
                   button='OK')
Exemplo n.º 33
0
			self.BookButton.setIconSize(QSize(40,20))
			self.list.removeItem(idx)
		else:
			bookmarks.append(url)
			b = open("bookmarks.txt","wb")
			pickle.dump(bookmarks,b)
			b.close()
			self.BookButton.setIcon(QIcon('icons/bookmark.png'))
			self.BookButton.setIconSize(QSize(40,20))
			self.list.addItem(url)

	def handle_bookmarks(self, choice):
		global url

		url = choice
		self.url_input.setText(url)
		self.Enter()

if(__name__ == '__main__'):
	network_available = False

	while(network_available == False):
		network_available = check_connection()
		if(network_available == False):
			pymsgbox.alert(text = "No Internet Connection found !", title = "Alert", button = "Retry")

	app = QApplication(sys.argv)
	window = Main()
	window.showMaximized()

	sys.exit(app.exec_())
Exemplo n.º 34
0
 def pop_message():
     pymsgbox.alert(text=u"Found %s, go get it" % pokename, title=u"Super Rare Mon")
Exemplo n.º 35
0
    drama_and_episode = line.split(",")
    drama_dict[drama_and_episode[0]] = int(drama_and_episode[1])
file.close()       

filedata = None
with open('dramaList.txt', 'r') as file :
   filedata = file.read()
  
for div_class in site.findAll('div',{'class':'col-md-3 item-list-lager sub'}):  #sorts out the subbed drama from the raws
    for part in div_class.findAll('span'):  #looks for the drama in the webpage 
          for dramaOnline in part.strings:  #tags are currently 1 char; have to convert to strings (part.strings)
              for drama_entries in drama_dict:  #drama_entries; looks the drama in the dictionary/dramaList
                    if drama_entries in dramaOnline: #dramaOnline is the drama online; format is DRAMA NAME EPISODE #
                        try:
                            curr_episode = int(dramaOnline[-2:]) #looks for last two digits of dramaOnline for the episode #
                        except TypeError:           #in case the episode # isn't double digits (ie. 1, 2, 3...)
                            curr_episode = int(dramaOnline[-1:])
                        if int(drama_dict[drama_entries]) < curr_episode: #if recorded drama episode is less than the one on the site
                            drama_dict[drama_entries] = str(drama_dict[drama_entries])
                            curr_episode = str(curr_episode)
                            filedata = filedata.replace(drama_dict[drama_entries], curr_episode)
                            pymsgbox.alert(drama_entries + " episode " + curr_episode + " is now available.")
                                #pop-up code goes here

with open('dramaList.txt', 'w') as file:
    file.write(filedata)

#print("Finished!")

                        
Exemplo n.º 36
0
 def test_timeout(self):
     # Note: If these test's fail, the unit tests will hang.
     self.assertEqual(pymsgbox.alert('timeout test', timeout=1000), pymsgbox.TIMEOUT_TEXT)
     self.assertEqual(pymsgbox.confirm('timeout test', timeout=1000), pymsgbox.TIMEOUT_TEXT)
     self.assertEqual(pymsgbox.prompt('timeout test', timeout=1000), pymsgbox.TIMEOUT_TEXT)
     self.assertEqual(pymsgbox.password('timeout test', timeout=1000), pymsgbox.TIMEOUT_TEXT)
Exemplo n.º 37
0
def event_func(msg):
	#print "Current Time:",time.time(),'msg:',msg	

	#httpHandler = urllib2.HTTPHandler(debuglevel=1)  
	#httpsHandler = urllib2.HTTPSHandler(debuglevel=1)  
	#opener = urllib2.build_opener(httpHandler, httpsHandler)  
	#urllib2.install_opener(opener)

	header = {'User-agent': 'Mozilla/5.0'}
	#header = {"User-Agent":"Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36(KHTML, like Gecko) Ubuntu Chromium/31.0.1650.63 Chrome/31.0.1650.63 Safari/537.36"}

	url_str = 'http://outlet.lenovo.com/outlet_us/laptops'
	content = open_url(url_str, None, header, 10)
	if content == '':
		return

	category_id = re.findall(r"facetParams\[\"category-id\"\] = \"(.+?)\"", content, re.S)
	if len(category_id) == 0:
		#items are gone!
		print "category_id empty!"
		return

	#POST message obtained via wireshark
	postdata = {
		'category-id':category_id[0],  
		'sort-criteria':'0',  
		'FacetDropDownOrientation':'vertical',  
		'page-index':'1',
		'page-size':'100',  
		'facet-3':'14', #T series
		'facet-3':'18', #W series
		'facet-3':'21', #Y series
		'facet-6':'1', #CPU i7
		#'facet-6':'2', #CPU i5
		#'facet-6':'3', #CPU i3
		#'facet-9':'4', #memory 4GB-5.99GB
		#'facet-9':'5', #memory 6GB-7.99GB
		'facet-9':'6', #memory 8GB-9.9GB
		'keyword-facet':'',
		'update-facet-id':'1'
	}
	data = urllib.urlencode(postdata)

	url_str = 'http://outlet.lenovo.com/SEUILibrary/controller/e/outlet_us/LenovoPortal/en_US/catalog.workflow:GetCategoryFacetResults?q=1&catalog-type='
	content = open_url(url_str, data, header, 10)
	if content == '':
		print "Searching condition does not match."
		return

	#get the category part of the url
	item_url = re.findall(r"url:\'//(.+?)\',", content)
	list_length = len(item_url)
	if list_length == 0:
		print 'error: no valid url.'
		raise SystemExit

	url_head = 'http://' + item_url[0] +'&page=1&itemid=';
	#log_write(url_head)	
	#print url_head

	#get the item part of the url
	item_id_str = re.findall(r"var fitems = \[(.+?)\];", content, re.S);
	list_length = len(item_id_str)
	if list_length == 0:
		print 'error: no items.'
		#log_write('error: no items.')
	else:
		item_list = re.findall(r"'(.+?)',", item_id_str[0], re.S);	
		indicator = 0

		if len(item_list) == 0:
			print "no item found, check the browser response."
			#log_write("no item found or request blocked")
		#k = 0;

		for idx in item_list:
			item_url_full = url_head + idx
			#print item_url_full
			#log_write(item_url_full)
			content = open_url(item_url_full, None, header, 10)
			if content == '':
				print "Item list is empty."
				return

			#dump_file('item'+str(k), content)
			#k += 1
			
			flag_found = filter_item(content)
			if flag_found != 0:
				#print item_url_full
								
				#leads to the webpage for adding to shopping cart
				content = open_url(item_url_full, None, header, 10)
				key_words = re.findall('Sold out', content, re.S);

				if content == '':
					#print "The loaded webpage is lost..."
					return
				elif len(key_words) != 0:
					#print "The item was sold out..."
					continue

				#webbrowser.open(item_url_full)
				
				#find the item url				
				#tmp_found = re.findall(r"<div class=\"fbr-detailslink\">(.+?)Model details</a>", content, re.S)
				#
				#if len(tmp_found) != 0:
				#	new_url = re.findall(r"<a href=\"/(.+?)\">", tmp_found[0], re.S)
				#	
				#	new_full_url = 'http://outlet.lenovo.com/'+new_url[0]				
				#	print new_full_url
				#	webbrowser.open(new_full_url)

				#add to shopping cart
				tmp_found = re.findall(r"<div class=\"action\">(.+?)Add to cart</span>", content, re.S)
				if len(tmp_found) != 0:
					new_url = re.findall(r"<a href=\"(.+?)\" class=", tmp_found[0], re.S)
					new_addtocart_url = 'http:'+new_url[0]
					#print new_full_url
					#web_controller = webbrowser.get('firefox')
					#web_controller.open(new_addtocart_url)	
					webbrowser.open(new_addtocart_url)
				else:
					print "The deal was found but lost before adding to shopping cart..."

			indicator = indicator | flag_found
		#end of for

		if indicator != 0:
			#print "Item Found!"
	
			if indicator & 0b000001:
				print "Y510 Found in Lenovo Outlet!"
				log_write('Y510 Found in Lenovo Outlet')
			if indicator & 0b000010:
				print "T540 Found in Lenovo Outlet!"
				log_write('T540 Found in Lenovo Outlet')
			if indicator & 0b000100:
				print "Y50 Found in Lenovo Outlet!"	
				log_write('Y50 Found in Lenovo Outlet')		
			if indicator & 0b001000:
				print "T440 Found in Lenovo Outlet!"
				log_write('T440 Found in Lenovo Outlet')	
			if indicator & 0b010000:
				print "W540 Found in Lenovo Outlet!"
				log_write('W5X0 Found in Lenovo Outlet')
			if indicator & 0b100000:
				print "P400 Found in Lenovo Outlet!"
				log_write('P400 Found in Lenovo Outlet')

			pymsgbox.alert('Items are now in store in Lenovo Outlet!', 'Warning')