コード例 #1
0
    def addExp(self, enemyLevel, boss):
        nextLevel = self.Level + 1
        A = (enemyLevel * 2) + 10
        C = (enemyLevel + self.Level + 10)
        if not boss:
            B = (randint(35, 75) * enemyLevel) / 5
        else:
            B = (randint(150, 250) * enemyLevel) / 5 * 1.5
        gain = floor(floor(sqrt(A) * (A * A)) * B / floor(sqrt(C) *
                                                          (C * C))) + 1
        self.exp += gain
        lvlup = floor(1.2 * nextLevel**3 - 15 * nextLevel**2 +
                      100 * nextLevel - 140)  # (player[name][1]+1)**3
        if self.Level < 100:
            Popup('You gained ' + str(gain) + ' exp')
        while self.exp > lvlup:
            if self.Level == 100:
                break
            if self.Level < 100:
                if self.exp > lvlup:
                    print('You gained a level!')
                    hpGain = randint(2, 7)
                    atkGain = randint(1, 4)
                    defGain = int(floor(randint(1, 4) * 0.5))
                    spdGain = int(floor(randint(1, 4) * 1.5))
                    manaGain = randint(5, 10)

                    Popup(
                        'You gained a level!', 'HP: ' + str(self.Hp) + " + " +
                        str(hpGain) + " = " + str(self.Hp + hpGain),
                        'Attack: ' + str(self.Atk) + " + " + str(atkGain) +
                        " = " + str(self.Atk + atkGain),
                        'Defense: ' + str(self.Def) + " + " + str(defGain) +
                        " = " + str(self.Def + defGain),
                        'Speed: ' + str(self.Spd) + " + " + str(spdGain) +
                        " = " + str(self.Spd + spdGain),
                        'Mana: ' + str(self.mana) + " + " + str(manaGain) +
                        " = " + str(self.mana + manaGain))

                    self.Level += 1
                    self.Hp += hpGain
                    self.Atk += atkGain
                    self.Def += defGain
                    self.Spd += spdGain
                    self.mana += manaGain
                    nextLevel = self.Level + 1
                    lvlup = floor(1.2 * nextLevel**3 - 15 * nextLevel**2 +
                                  100 * nextLevel - 140)
                    self.currHp += hpGain
                    self.currMana += manaGain
コード例 #2
0
ファイル: main_2.py プロジェクト: raghavg123/Xpnsit
    def Add_Trans(self, particulars: str, _type: str, amount: float, date: str):
        cursor = conn.cursor()

        try:
            cursor.execute(f"""
            INSERT INTO transactions (
                user_id,
                username,
                particulars,
                exp_type,
                amount,
                exp_date
            )
            VALUES (
                {self.user.user_id},
                '{self.user.uname}',
                '{particulars}',
                '{_type}',
                {amount},
                "{date}"
                );
            """)

            conn.commit()

            Popup("Transaction successfully added.")
            self.win.Refresh()

        except SQLErrors.ProgrammingError:
            PopupError("ERROR: Invalid details.\nRectify and try again.")

        cursor.close()
コード例 #3
0
ファイル: main_2.py プロジェクト: raghavg123/Xpnsit
def create_account(u: Union[str, int], p: Union[str, int], e: Union[str, int], f: str, l: str) -> None:
    cursor = conn.cursor()

    e = 'NULL' if e in (None, '') else e

    try:
        '''
        Creates a new entry in the db.
        Required two cases as the email field is optional
        '''
        if e != 'NULL':
            cursor.execute(f"""
                INSERT INTO users (username,passwd,email_id,first_name,last_name)
                VALUES ('{u}','{p}','{e}','{f}','{l}');
                """)
        else:
            cursor.execute(f"""
            INSERT INTO users (username,passwd,email_id,first_name,last_name)
            VALUES ('{u}','{p}',{e},'{f}','{l}');
            """)

        conn.commit()

    except ConnectionError:
        Popup("Error Connecting to Database.",
              "Please try again or restart the program")

    cursor.close()
コード例 #4
0
ファイル: main.py プロジェクト: Riki432/3HD
def findNamesFromFolder(name: str, folder: str, matchWhole: bool, cache):
    from Cache import storeCacheData
    '''
    Takes a name or basically keywords that are matched by text from the Images.
    If matchWhole is true, the entire word is matched at once.
    If matchWhole is false, the words are split by spaces and searched.
    Returns a list of all the files that have the text in them.
    '''
    os.chdir(folder)
    res = []
    if len(name.strip()) == 0:
        raise Exception("Invalid Argument")
    words = name.split(" ")
    counter = 0
    dirs = os.listdir()
    count = len(dirs)

    for f in dirs:
        Popup(
            "Searching.. {}/{} files".format(counter, count),
            auto_close=True,
            auto_close_duration=1,
            non_blocking=True,
            no_titlebar=True,
            # title="Searching..",
            button_type=None)
        print("Searched {}/{} files".format(counter, count))
        counter = counter + 1
        if not os.stat(os.path.join(folder, f)).st_size / 1024 > 10:
            continue
        if isImage(f):
            if cache is not None:
                _text = cache.get(f, None)
                if _text == None:
                    text = getText(f)  # This function takes a lot of time
                    cache[f] = (os.stat(f).st_mtime, text)
                else:
                    text = _text[1]

            # if len(text) < len(name):
            #     continue
            if matchWhole:
                if (text.lower().find(name.lower()) != -1):
                    res.append(f)
            else:
                if all(text.lower().find(word.lower()) != -1
                       for word in words):
                    res.append(f)

        if f == dirs[-1]:
            storeCacheData(cache)

    return res
コード例 #5
0
def healing(currHP, hp):
    rand = random()
    if rand <= 0.1:
        Popup("You ate a Super Julie Starch Mango! HP fully restored!")
        currHp += hp
    elif 0.10 < rand <= 0.30:
        Popup("You ate a Julie Starch Mango! Gained " + str(round(hp * 0.75)) +
              " HP!")
        currHP += round(hp * 0.75)
    elif 0.30 < rand <= 0.65:
        Popup("You ate a Julie Mango! Gained " + str(round(hp * 0.50)) +
              " HP!")
        currHP += round(hp * 0.50)
    elif rand > 0.65:
        Popup("You ate a Starch Mango! Gained " + str(round(hp * 0.25)) +
              " HP!")
        currHP += round(hp * 0.25)

    if currHP > hp:
        currHP = hp
    return currHP
コード例 #6
0
def manaRestore(currMana, mana):
    rand = random()
    if rand <= 0.1:
        Popup("You ate a Big Sweet Chenette! Mana fully restored!")
        currMana += mana
    elif 0.10 < rand <= 0.30:
        Popup("You ate a Sweet Chenette! Gained " + str(round(mana * 0.75)) +
              " Mana!")
        currMana += round(mana * 0.75)
    elif 0.30 < rand <= 0.65:
        Popup("You ate a Chenette! Gained " + str(round(mana * 0.50)) +
              " Mana!")
        currMana += round(mana * 0.50)
    elif rand > 0.65:
        Popup("You ate an Ok Chenette! Gained " + str(round(mana * 0.25)) +
              " Mana!")
        currMana += round(mana * 0.25)

    if currMana > mana:
        currMana = mana
    return currMana
コード例 #7
0
ファイル: modules.py プロジェクト: Romulogss/Loans-management
def exlcuir_emprestimo(nome):
    """
    Funcionará em auxílio com o função busca, caso a pessoa deseje excluir o empréstimo que buscou.
    :param emprestimo: receberá um dicionário, contento o emprestimo que deseja excluir
    :return: 0, para testes
    """
    for emprestimo in EMPRESTIMOS:
        if nome == emprestimo['nome']:
            EMPRESTIMOS.remove(emprestimo)
            gravar_dados()
            Popup("Apagado com sucesso!",
                  button_color=('white', 'springgreen4'))
    return 0
コード例 #8
0
ファイル: modules.py プロジェクト: Romulogss/Loans-management
def cadastrar(informacoes):
    """
    Esta função irá passar os dados de uma lista para um dicionário,
    e passará ele para a lista contendo todos emprestimos.
    :param informacoes: a função receberá uma lista de strings
    :return: 0 para testes.
    """
    try:
        nome = informacoes[0]
        telefone = informacoes[1]
        celular = informacoes[2]
        email = informacoes[3]
        vivencia = informacoes[4]
        data = informacoes[5]
        item = informacoes[6]
        data = datetime.strptime(data, '%d/%m/%Y').date()
        emprestimo = {
            'nome': nome,
            'telefone': telefone,
            'celular': celular,
            'email': email,
            'vivencia': vivencia,
            'item': item,
            'data': data
        }

        EMPRESTIMOS.append(emprestimo)
        EMPRESTIMOS.sort(key=itemgetter('data'))
        gravar_dados()
        Popup("Cadastro realizado com sucesso",
              button_color=('white', 'springgreen4'))
        return 0
    except ValueError:
        Popup("Erro no cadastro ou cadastro vazio!",
              button_color=('white', 'springgreen4'))
        return -1
コード例 #9
0
def from_eid(eid):
    corp_ftax = []
    for i in master_df.index:
        if master_df[3][i] == eid.upper():
            a = str(int(master_df[2][i])) + ' - ' + master_df[4][i].strip()
            corp_ftax.append(a)

    if corp_ftax:
        PopupScrolled(
            f'Following corp/ftax combinations have EID: {eid.upper()}\n\n{fmtcols(corp_ftax, 5)}',
            size=(100, 20),
            title=f'{eid.upper()}')

    else:
        Popup(
            f'{eid.upper()} not available or invalid, please check and try again!',
            title='Error')
コード例 #10
0
ファイル: main_2.py プロジェクト: raghavg123/Xpnsit
    def Signup(self):
        signup_active = True

        layout = [
            [T("Signup for Xpnsit", **heading_format), ],
            [T("First Name:"), Input(size=(15, 1), key="f_name"), T(
                " "), T("Last Name:"), Input(size=(15, 1), key="l_name")],
            [T("Username:"******"user")],
            [T("Password:"******"pass", password_char="*")],
            [],
            [T(' '*40), Submit()]
        ]

        signup_win = Window("Xpnsit - Signup", layout=layout)

        while signup_active:  # <------------ Event Loop -----------------> #
            event, values = signup_win.Read()

            if event in (None, 'Exit'):
                signup_active = False
                login_active = True

            if event == 'Submit':
                self.vals = [values["user"], values["pass"],
                             values["mail"], values["f_name"], values["l_name"]]
                if not username_used(self.vals[0]):
                    create_account(*self.vals)

                    # <------------------- Confirmation of Insertion ------------------> #
                    success = check_login_info(values["user"], values["pass"])

                    if success == True:
                        print("Signup Successful.")
                        Popup(
                            "Signup Successful!",
                            "Exit this popup to return to the login page"
                        )
                        signup_win.close()
                        signup_active = False
                        login_active = True
                else:
                    PopupError("ERROR: Username already in usage",
                               title="Username already taken")
コード例 #11
0
def get_corp_ftax(corp, offer_id, df):
    corpftax_altice = set()
    corpftax_legacy = set()
    smb = set()

    offer_eid = {df[1][i] for i in df.index if df[2][i] == offer_id}
    for j in master_df.index:
        if master_df[1][j] in corp:
            if master_df[5][j] == 'Y' and master_df[3][j] in offer_eid:
                corpftax_altice.add(
                    str(master_df[2][j])[:-2] + ' - ' +
                    master_df[4][j].strip() + ' - ' + master_df[3][j].strip())

            elif master_df[5][j] == 'N' and master_df[3][j] in offer_eid:
                corpftax_legacy.add(
                    str(master_df[2][j])[:-2] + ' - ' +
                    master_df[4][j].strip() + ' - ' + master_df[3][j].strip())

            elif master_df[3][j] in offer_eid:
                smb.add(
                    str(master_df[2][j])[:-2] + ' - ' +
                    master_df[4][j].strip() + ' - ' + master_df[3][j].strip())

    if corpftax_legacy or corpftax_altice:
        PopupScrolled(
            f"Offer ID {offer_id} available in following corp/ftax combinations \n\nAltice One Combinations\n\n{fmtcols(sorted(corpftax_altice), 3)}\n\nLegacy Combinations\n\n{fmtcols(sorted(corpftax_legacy), 3)}",
            size=(100, 20),
            title=f'{offer_id}')

    elif smb:
        PopupScrolled(
            f"<SMB> Offer ID {offer_id} available in following corp/ftax combinations \n\nCombinations for SMB\n\n{fmtcols(sorted(smb), 3)}",
            size=(100, 20),
            title=f'{offer_id}')

    else:
        Popup(
            f'Offer {offer_id} not available in {corp} or is invalid!\n\nPlease check offer ID or change corp and try again!',
            title='Error')
コード例 #12
0
ファイル: main_2.py プロジェクト: raghavg123/Xpnsit
def check_login_info(User: str, Pass: str) -> bool:
    cursor = conn.cursor()

    try:
        cursor.execute(f"""
        SELECT username, passwd
        FROM users
        WHERE username = '******' AND passwd = '{Pass}';
        """)

        result = cursor.fetchone()
        if result not in [[], None, [()]]:
            return True

        else:
            return False

    except ConnectionError:
        Popup("Error Connecting to Database.",
              "Please try again or restart the program")
    except SQLErrors.ProgrammingError:
        PopupError("ERROR: Invalid credentials.", "Try again")
    cursor.close()
コード例 #13
0
ファイル: modules.py プロジェクト: Romulogss/Loans-management
def editar_emprestimo(identificador, novas_informarcoes):
    """
    Função que atualizará dados de um emprestimo já realizado
    :param identificador: recebe o nome em forma de string
    :param novas_informarcoes: recebe uma lista, das novas informações do emprestimo
    :return: 0, para testes
    """
    try:
        for emprestimo in EMPRESTIMOS:
            if identificador == emprestimo['nome']:
                emprestimo['nome'] = novas_informarcoes[0]
                emprestimo['telefone'] = novas_informarcoes[1]
                emprestimo['celular'] = novas_informarcoes[2]
                emprestimo['email'] = novas_informarcoes[3]
                emprestimo['vivencia'] = novas_informarcoes[4]
                data = novas_informarcoes[5]
                emprestimo['data'] = datetime.strptime(data, '%d/%m/%Y').date()
                emprestimo['item'] = novas_informarcoes[6]
                gravar_dados()
                Popup("Atulizado com sucesso",
                      button_color=('white', 'springgreen4'))
                return 0
    except:
        return -2
コード例 #14
0
 janela.FindElement('email').Update('')
 janela.FindElement('vivencia').Update('')
 janela.FindElement('Edit').Update(visible=False)
 botao_busca = tela_escolha_busca()
 try:
     if botao_busca == "Nome":
         nome_busca = tela_busca(botao_busca)
         if len(nome_busca) != 0:
             NOMES = get_informacoes(nome=nome_busca)
             if len(NOMES) != 0:
                 txt_busca = "Buscando por " + nome_busca
                 janela.FindElement('buscas').Update(txt_busca)
                 janela.FindElement('botao_busca').Update(text='Cancelar busca', visible=True)
                 janela.FindElement('lista').Update(NOMES)
             else:
                 Popup("Nome não encontrado!", button_color=('white', 'springgreen4'))
     elif botao_busca == 'Item':
         item_busca = tela_busca(botao_busca)
         if len(item_busca) != 0:
             NOMES = get_informacoes(item=item_busca)
             if len(NOMES) != 0:
                 txt_busca = "Buscando pelo item " + item_busca
                 janela.FindElement('buscas').Update(txt_busca)
                 janela.FindElement('botao_busca').Update(text='Cancelar busca', visible=True)
                 janela.FindElement('lista').Update(NOMES)
             else:
                 Popup("Item não encontrado!", button_color=('white', 'springgreen4'))
     elif botao_busca == 'Ano':
         ano_busca = tela_busca(botao_busca)
         if type(ano_busca) != str:
             NOMES = get_informacoes(ano=ano_busca)
コード例 #15
0
        offer_id = values['-ID-']
        if values['-QA2-']:
            corp = [7712, 7709]
        elif values['-QAINT-']:
            corp = [7702, 7704, 7710, 7715]
        elif values['-QA1-']:
            corp = [7708, 7711]
        elif values['-QA3-']:
            corp = [7707, 7714]
        else:
            corp = [7701, 7703, 7705, 7706, 7713]

        try:
            offer_id = int(offer_id)
        except:
            Popup('Enter numerical value')
        else:
            get_corp_ftax(corp, offer_id, eid_df)

    if event == '-ANOTHER-':
        upload_flag = True
        window['-COL1-'].update(visible=True)
        window['-COL2-'].update(visible=False)

    if event == '-TYPESUBMIT-' and values['-SEID-']:
        window['-COL1-'].update(visible=False)
        window['-COL2-'].update(visible=False)
        window['-COL3-'].update(visible=True)

    if event == '-SUBMIT1-':
        eid = values['-EID-']
コード例 #16
0
    if (event is 'next1'):
        RunTool = False
        window.Close()

        SUM_FROM_COL = 7

        clec = queryFrame.select_dtypes(np.number).columns
        queryFrame[clec] = queryFrame[clec].fillna(0)
        queryFrame = queryFrame.fillna("")
        #drop all rows that meet criteria
        sumList = list(i for i in queryFrame.itertuples()
                       if str(getattr(i, colname)) in list(values.values()))
        for tupl in sumList:
            rowTupl = tupl[0]
            sumTupl = 0
            for i in range(SUM_FROM_COL, len(tupl)):
                try:
                    sumTupl += tupl[i]
                except:
                    sumTupl += 0
            print(sumTupl)
            queryFrame.loc[rowTupl, colsum] = sumTupl
        #write results to output
        writer = ExcelWriter(PATH[:-5] + " OUTPUT.xlsx", engine='xlsxwriter')
        queryFrame.to_excel(writer, sheet_name='Output', index=False)
        writer.save()
        writer.close()

        #Let user know we're finished
        Popup('Successful Execution!')
コード例 #17
0
def tela_busca(botao):
    """
    tela na qual será informado o que o usuário deseja pesquisar.
    :param botao: uma string, que informará qual o método de busca.
    :return: retorna dado informado pelo usuário, que será usado em uma função de busca.
    """
    if botao == 'Nome':
        layout_nome = [[T("Qual nome deseja buscar?", size=(30, 1))],
                       [In(size=(30, 1)), Button("Buscar")]]
        janela_nome = Window("Busca Nome",
                             size=(370, 100),
                             icon=('C:\\Loans-management\\Icon\\icon-logo.ico'
                                   )).Layout(layout_nome)
        buscar, nome = janela_nome.Read()
        janela_nome.Close()
        return nome[0]
    if botao == 'Item':
        layout_item = [[T("Qual item deseja buscar?", size=(30, 1))],
                       [In(size=(30, 1)), Button("Buscar")]]
        janela_item = Window("Busca Item",
                             size=(370, 100),
                             icon=('C:\\Loans-management\\Icon\\icon-logo.ico'
                                   )).Layout(layout_item)
        buscar, item = janela_item.Read()
        janela_item.Close()
        return item[0]
    if botao == 'Ano':
        layout_mes = [[T("Qual ano deseja buscar?", size=(30, 1))],
                      [In(size=(30, 1)), Button("Buscar")]]
        janela_mes = Window("Busca Ano",
                            size=(370, 100),
                            icon=('C:\\Loans-management\\Icon\\icon-logo.ico'
                                  )).Layout(layout_mes)
        buscar, mes = janela_mes.Read()
        try:
            mes = datetime.strptime(mes[0], '%Y').date().year
        except TypeError and ValueError:
            janela_mes.Close()
            return Popup("Erro na Busca",
                         button_color=('white', 'springgreen4'))
        janela_mes.Close()
        return mes
    if botao == 'Mes + Ano':
        layout_mes_ano = [[T("Qual mes e ano deseja buscar?", size=(30, 1))],
                          [In("Ex: 10/2018", size=(30, 1)),
                           Button("Buscar")]]
        janela_mes_ano = Window(
            "Busca Mes",
            size=(370, 100),
            icon=('C:\\Loans-management\\Icon\\icon-logo.ico'
                  )).Layout(layout_mes_ano)
        buscar, mes_ano = janela_mes_ano.Read()
        try:
            mes_ano = datetime.strptime(mes_ano[0], '%m/%Y').date()
        except TypeError and ValueError:
            janela_mes_ano.Close()
            return Popup("Erro na Busca",
                         button_color=('white', 'springgreen4'))
        janela_mes_ano.Close()
        return mes_ano
    if botao == 'Cancelar':
        return 0
コード例 #18
0
ファイル: UI.py プロジェクト: irineos1995/ULint
    def present_errors(self, errors, rules_filename=None, star_depth_threshold=None):
        layout = []

        counter = 0
        for pln, lst in errors.items():
            initial_line = 'Error in line {} ---|\n'.format(pln)
            layout.append([Text(initial_line)])
            for err in lst:
                parent_cls, child_cls, depth = self.error_decode(err)
                self.global_dict[counter] = {
                    'parent_cls': parent_cls,
                    'child_cls': child_cls,
                    'depth': depth
                }
                counter += 1
                layout.append([Checkbox(err)])
            # layout.append([Checkbox('Error in line: {}'.format(pln))])


        layout.append([OK()])

        window = sg.Window('Linting Errors', resizable=True).Layout([[sg.Column(layout, size=(1200,1000), scrollable=True)]])
        button, values = window.Read()


        popup_string = ''
        if rules_filename:
            with open(rules_filename) as json_file:
                rules = json.load(json_file)
        for i, value in enumerate(values):
            if value:
                parent_cls = self.global_dict[i]['parent_cls']
                child_cls = self.global_dict[i]['child_cls']
                depth = int(self.global_dict[i]['depth'])

                string = 'Parent: {} is allowed to have a relation to child: {} at depth: {}'.format(
                    parent_cls,
                    child_cls,
                    depth
                )
                popup_string += string + '\n'
                print(string)

                if rules_filename:
                    child_relation = rules.get(parent_cls, {}).get(child_cls, {})
                    if child_relation:
                        if star_depth_threshold:
                            if len(child_relation) + 1 >= star_depth_threshold:
                                rules[parent_cls][child_cls] = '*'
                            else:
                                rules[parent_cls][child_cls].append(depth)
                    else:
                        if rules.get(parent_cls, {}):
                            rules[parent_cls][child_cls] = [depth]
                        else:
                            rules[parent_cls] = {
                                child_cls: [depth]
                            }
        if rules_filename:
            with open(rules_filename, 'w') as fp:
                json.dump(rules, fp, indent=4)



        Popup('The GUI returned:', button, popup_string)
コード例 #19
0
                    Input('Indicator Name', size=(25, 0))
                ])
            layout2.append([
                Column(column,
                       scrollable=True,
                       vertical_scroll_only=True,
                       size=(450, 400))
            ])
            layout2.append([
                Button('Next', key='toLayout3'),
                Button('Cancel', key='exit')
            ])
            window.Close()
            window = Window('CompyrisonTool').Layout(layout2)
        except:
            Popup('Please enter a interger value')

    if (event == 'toLayout3'):
        fileList = list()
        fileItem = list()
        for i in range(0, len(values)):
            fileItem.append(values[i])
            if len(fileItem) == 3:
                fileList.append(fileItem)
                fileItem = []

        dataINframes = list()
        dataINlist = list()
        try:
            for arg in fileList:
                dataINframes.append(read_excel(arg[0], sheet_name=arg[1]))