1. Python / Говнокод #27244

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    86. 86
    87. 87
    88. 88
    89. 89
    90. 90
    91. 91
    92. 92
    93. 93
    94. 94
    import datetime, random, time, os, vk_api
    import sqlite3 as sl
    from vk_api.exceptions import Captcha
    from vk_api.longpoll import VkEventType, VkLongPoll
    from functions import *
    from settings import *
    vk_session = vk_api.VkApi(token=token, api_version=5.126)
    longpoll = VkLongPoll(vk_session)
    vk = vk_session.get_api()
    now = datetime.datetime.now()
    
    for event in longpoll.listen():
        try:
            def send_msg(msg='', chat=False, prefix=True, attach=''):
                if chat:
                    vk.messages.send(chat_id=event.chat_id,message=msg,attachment=attach)
                else:
                    vk.messages.send(user_id=event.user_id,message=msg,attachment=attach)
        except Captcha:
            time.sleep(1)
            send_msg('Ошибка. Слишком частые запросы.')
        except Exception as e:
            time.sleep(1)
            send_msg(f'Неизвестная ошибка при отправке сообщения.\n{e}')
        try:
            if event.type == VkEventType.MESSAGE_NEW and event.to_me:
                user_get = vk.users.get(user_ids=event.user_id)
                first_name = user_get[0]['first_name']
                last_name = user_get[0]['last_name']
                if event.from_chat and event.chat_id and (event.message == '!meme' or event.message == '!мем'):
                    meme_create()
                    upload = vk_api.VkUpload(vk_session)
                    try:
                        a = upload.photo_messages(photos=os.path.dirname(__file__) + '/random_meme.jpg', peer_id=event.user_id)
                        send_msg(attach=f'photo{a[0]["owner_id"]}_{a[0]["id"]}',chat=True, prefix=False)
                    except:
                        send_msg("Ошибка. Попробуйте снова.")
                elif event.from_chat and event.chat_id and (event.message == '!info' or event.message == '!инфо'):
                    response = requests.get(f'https://vk.com/foaf.php?id={event.user_id}')
                    soup = BeautifulSoup(response.text, 'lxml')
                    created = soup.find('ya:created').get('dc:date')
                    created1 = datetime.datetime.strptime(created, '%Y-%m-%dT%H:%M:%S%z').replace(tzinfo=None)
                    diff = datetime.datetime.now()-created1
                    modified = soup.find('ya:modified').get('dc:date')
                    modified1 = datetime.datetime.strptime(modified, '%Y-%m-%dT%H:%M:%S%z').replace(tzinfo=None)
                    send_msg(f'''https://vk.com/id{event.user_id}\nИмя пользователя: {first_name} {last_name}\nАккаунт существует {diff.days} дней.\nДата регистрации: {created1.month} {months[created1.month-1]} {created1.year} в {created1.time()}\nПоследнее обновление информации: {modified1.month} {months[modified1.month-1]} {modified1.year} в {modified1.time()}''', chat=True)
                elif event.from_user and event.user_id and (event.message == '!info' or event.message == '!инфо'):
                    response = requests.get(f'https://vk.com/foaf.php?id={event.user_id}')
                    soup = BeautifulSoup(response.text, 'lxml')
                    created = soup.find('ya:created').get('dc:date')
                    created1 = datetime.datetime.strptime(created, '%Y-%m-%dT%H:%M:%S%z').replace(tzinfo=None)
                    diff = datetime.datetime.now()-created1
                    modified = soup.find('ya:modified').get('dc:date')
                    modified1 = datetime.datetime.strptime(modified, '%Y-%m-%dT%H:%M:%S%z').replace(tzinfo=None)
                    send_msg(f'''https://vk.com/id{event.user_id}\nИмя пользователя: {first_name} {last_name}\nАккаунт существует {diff.days} дней.\nДата регистрации: {created1.month} {months[created1.month-1]} {created1.year} в {created1.time()}\nПоследнее обновление информации: {modified1.month} {months[modified1.month-1]} {modified1.year} в {modified1.time()}''')
                elif event.from_user and event.user_id and event.message == '!coin':
                    coin = 'Орёл' if random.randint(0, 1) == 1 else 'Решка'
                    send_msg(f'{coin}')
                elif event.from_user and event.user_id and (event.message == '!anek' or event.message == '!анек'):
                    send_msg(f'{get_anek()}', prefix=False)
                elif event.from_user and event.user_id:
                    con = sl.connect(os.path.dirname(__file__) + '/users.db')
                    count = 0
                    with con:
                                con.execute("""
                                    CREATE TABLE IF NOT EXISTS USER (
                                        user_id INTEGER NOT NULL PRIMARY KEY,
                                        name TEXT,
                                        permission_lvl INTEGER
                                    );
                                """)
                    with con:
                        data = con.execute("SELECT * FROM USER")
                        for row in data:
                            if event.user_id in row:
                                count += 1
                        if count == 0:
                            send_msg(f'''Привет, это сообщение отправлено автоматически.\nПока я добавляю информацию о тебе в базу данных, ты можешь ознакомиться с командами написав !help\nКоманд не так много, но в будущем их станет больше ;)''')
                            sql = 'INSERT INTO USER (user_id, name, permission_lvl) values(?, ?, ?)'
                            data = [(event.user_id, f'{first_name} {last_name}', 1)]
                            with con:
                                con.executemany(sql, data)
                if event.attachments:
                    print(
                        f"{now}\nuser_id: {event.user_id} | {first_name} {last_name}\nmessage: {event.message}\nattach: {event.attachments}\n")
                else:
                    print(
                        f"{now}\nuser_id: {event.user_id} | {first_name} {last_name}\nmessage: {event.text}\n")
        except Captcha:
            time.sleep(1)
            send_msg('Ошибка. Слишком частые запросы.')
        except Exception as e:
            time.sleep(1)
            send_msg(f'Упс. Произошла неизвестная ошибка.\n{e}')

    Каким образом можно улучшить этот ссаный говнокод?

    TupoyChel, 09 Февраля 2021

    Комментарии (97)
  2. Python / Говнокод #27226

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    def filter_goods(items, date_registered_from=0, date_registered_to=99999999999, from_finished_entries=0, to_finished_entries=99999, views_from=0, views_to=999999, activeGoodsFrom=0, activeGoodsTo=999999, delete_no_delivery=False, delete_comapnies=False, delete_duplicates=False, published_later_then=0):
        ids = []
        q = Queue()
        for i in items:
            if i[0]['date_created'] >= published_later_then:
                if i[1]['date_registered'] >= date_registered_from:
                    if i[1]['date_registered'] <= date_registered_to:
                        if i[1]['prods_sold_cnt'] >= from_finished_entries:
                            if i[1]['prods_sold_cnt'] <= to_finished_entries:
                                if i[0]['views'] >= views_from:
                                    if i[0]['views'] <= views_to:
                                        if i[1]['prods_active_cnt'] >= activeGoodsFrom:
                                            if i[1]['prods_active_cnt'] <= activeGoodsTo:
                                                if delete_no_delivery:
                                                    if i[0]['delivery_enabled'] or delete_no_delivery == False:
                                                        if not (delete_comapnies and i[1]['type'] == 'person'):
                                                            if delete_comapnies == False:
                                                                if delete_duplicates:
                                                                    if i[0]['owner']['id'] not in ids:
                                                                        ids.append(i[0]['owner']['id'])
                                                                        q.put(i[0]['id'])
                                                                else:
                                                                    q.put(i[0]['id'])
                                                        return q

    Стояла задача написать самый длинный if? Человек не знает про and? Этого мы никогда не узнаем.

    katant, 30 Января 2021

    Комментарии (3)
  3. Python / Говнокод #27206

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    import fnmatch,os,datetime,time,re,shutil,sys 
    	
    def find(pattern, startdir=os.curdir): 
    		for (thisDir, subsHere, filesHere) in os.walk(startdir): # 
    			for name in subsHere + filesHere:
    				if fnmatch.fnmatch(name,pattern): 
    					fullpath = os.path.join(thisDir,name)
    					yield fullpath 
    
    def timeconvert(x):
    	convert  = time.strftime("%Y-%m-%d",time.localtime(os.path.getctime(x)))   
    	return   convert
    
    print("select action: delete: delete files: copy: copy files: view: view files")
    action = input(" ")
    
    if action == "copy":
        print("inter path")
        dest = input(" ") 
    
    else:
        print ("inter date")
        cursive = input("")
        optime  = re.search('20[0-12]\d{1,2}.\d{1,2}',cursive)
    
    if optime == None:
        print ('error')
    else:    
    	if __name__== '__main__':
    		import sys 
    		namepattern,startdir, = sys.argv[1],sys.argv[2]
            for name in find(namepattern,startdir): 
            
    		
              
    		  if not  str(cursive) <= timeconvert(name):   
                if action == 'copy':
                    shutil.copy(name, dest)
                
    			elif action == 'delete':
                    os.remove(name)
    			  
                elif  action == "view":
                   print(name + timeconvert(name))
                
    			else:
                    print ('error')

    Я по сусекам метён,
    По коробам скребён,
    На сыром масле мешен,
    На окошке стужен;
    Я от дедушки ушёл,
    Я от бабушки ушёл,
    И от тебя убегу.

    Madhouse_camomile, 11 Января 2021

    Комментарии (0)
  4. Python / Говнокод #27192

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    board = [" ", " ", " "], \
            [" ", " ", " "], \
            [" ", " ", " "]
    
    i = 1
    win = True
    place_chek = True
    
    
    def show():
        print("---------")
        print("|" + board[0][0] + "  " + board[0][1] + "  " + board[0][2] + "|")
        print("|" + board[1][0] + "  " + board[1][1] + "  " + board[1][2] + "|")
        print("|" + board[2][0] + "  " + board[2][1] + "  " + board[2][2] + "|")
        print("---------")
    
    
    def move(i):
        if i % 2 == 0:
            return "X"
        else:
            return "0"
    
    
    def choise(x, y):
        board[x][y] = move(i)
    
    
    def repeat(x, y):
        global i
        global place_chek
        if board[x][y] == "0":
            print()
            print("Choose another location")
            print()
            place_chek = False
    
        elif board[x][y] == "X":
            print()
            print("Choose another location")
            print()
            place_chek = False
    
        elif board[x][y] == " ":
            i = i + 1
            place_chek = True
    
    
    def win_check():
        global win
        if board[0][0] == board[0][1] == board[0][2] == "X" or \
                board[1][0] == board[1][1] == board[1][2] == "X" or \
                board[2][0] == board[2][1] == board[2][2] == "X" or \
                board[0][0] == board[1][0] == board[2][0] == "X" or \
                board[0][1] == board[1][1] == board[2][1] == "X" or \
                board[0][2] == board[1][2] == board[2][2] == "X" or \
                board[0][0] == board[1][1] == board[2][2] == "X" or \
                board[0][2] == board[1][1] == board[2][0] == "X":
            print("X won")
            win = False
    
        elif board[0][0] == board[0][1] == board[0][2] == "0" or \
                board[1][0] == board[1][1] == board[1][2] == "0" or \
                board[2][0] == board[2][1] == board[2][2] == "0" or \
                board[0][0] == board[1][0] == board[2][0] == "0" or \
                board[0][1] == board[1][1] == board[2][1] == "0" or \
                board[0][2] == board[1][2] == board[2][2] == "0" or \
                board[0][0] == board[1][1] == board[2][2] == "0" or \
                board[0][2] == board[1][1] == board[2][0] == "0":
            print("0 won")
            win = False
    
    
    show()  # first time show
    
    while win:
        x, y = input("Enter the coordinates: ").split()
        repeat(int(x) - 1, int(y) - 1)
        if place_chek:
            choise(int(x) - 1, int(y) - 1)
        show()
        win_check()

    Крестики нолики на питоне. Самый большой позор это способ определение победы, не смог ничего придумать и сделал такой позор

    warzon131, 03 Января 2021

    Комментарии (63)
  5. Python / Говнокод #27167

    +3

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    class Metapetuh(type):
        def __subclasscheck__(cls, C):
            return True
        def __instancecheck__(self, other):
            return True
    
    
    class Petuh(metaclass=Metapetuh):
        pass
    
    
    issubclass(object, Petuh)  # True
    isinstance(42, Petuh)      # True

    Мы зашкварили весь «Питон», и теперь все классы в нём — петухи.

    По просьбам трудящихся: https://govnokod.ru/27166#comment602776.

    gost, 19 Декабря 2020

    Комментарии (10)
  6. Python / Говнокод #27161

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    from playsound import *
    import tkinter
    from tkinter import *
    import tkinter as tk
    from tkinter import ttk
    import getpass
    import sys
    import os
    import os.path
    import pyautogui
    from time import sleep

    https://habr.com/post/532684/
    > Написание WinLocker'а на Python
    > И всем привет братва, с вами я, Геймер Дисклеймер. Как вы думаете, чем я занимался 2 дня подряд? Нет, я не в доту рубился (и вам не советую, раз уж вы себя программистами называете). Я подготавливал материал для Хабра. А точнее, создавал винлокер. И нет, я его не скоммуниздил украл у кого-то, а сам создавал его с нуля. И сегодня я научу вас его создавать. И да, если вы дисклеймер так и не прочитали, то ни в коем случае не используйте этот код во вред другим! Ну ладно, без лишних слов, погнали!

    gost, 12 Декабря 2020

    Комментарии (111)
  7. Python / Говнокод #27150

    −12

    1. 1
    print('HELLO')

    ОЧЕНЬ СЛОЖНЫЙ КОД

    Atom, 04 Декабря 2020

    Комментарии (56)
  8. Python / Говнокод #27147

    −2

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    #Ide для япа
    
    
    code = input('Ваш код: ')
    
    if code = "print('text')
          print('text')

    Atom, 03 Декабря 2020

    Комментарии (13)
  9. Python / Говнокод #27117

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    86. 86
    87. 87
    88. 88
    #Я новичок в питоне, учусь буквально 2 недели. Это моя первая программа - типа банкомат, 
    #которую показал для примера учитель в очень упрощенном варианте, а я уже заинтересовался этим и стал улучшать её. 
    
    x=input('Чтобы зарегистрироваться, введите логин.\n' )
    y=input('Придумайте пароль.\n')
    login=x
    password=y
    print('Вы успешно зарегистрировались!')
    print('__________________________________________________________________________________________________________________')
    print('__________________________________________________________________________________________________________________')
    print('Войдите в систему, чтобы получить доступ ко всем функциям.')
    log=(input("Введите логин:\n"))
    pas=(input("Введите пароль:\n"))
    if((log==login)and(pas == password)):
    	balance=0
    	print('__________________________________________________________________________________________________________________')
    	print('__________________________________________________________________________________________________________________')
    	print("Вход выполнен успешно! У вас на счету",balance,"р.")
    	while 1:
    		print('__________________________________________________________________________________________________________________')
    		print('__________________________________________________________________________________________________________________')
    		print("Введите 1, чтобы пополнить счет, 2, чтобы снять, 3, чтобы выйти из аккаунта, и 4, чтобы узнать состояние счета.")
    		s=int(input('(Далее - Enter.)\n'))
    		if(s==1):
    			sum=int(input("На сколько вы хотите пополнить счет? (Далее - Enter.)\n"))
    			balance=balance+sum
    			print("Операция проведена успешно! На Вашем счету",balance,'р.')
    		if(s==2):
    			print("Сколько вы желаете снять со счета?")
    			sum=int(input('(Далее - Enter.)\n'))
    			if (sum>balance):
    				print('__________________________________________________________________________________________________________________')
    				print('__________________________________________________________________________________________________________________')
    				print("На счете недостаточно средств. Попробуйте ввести меньшее значение.")
    			else:
    				balance=balance-sum
    				print("Средства сняты со счета. Остаток:",balance,"р.")
    		if(s==3):
    			print('__________________________________________________________________________________________________________________')
    			print('__________________________________________________________________________________________________________________')
    			print('Вы вышли из аккаунта.') 
    			raise SystemExit
    		if(s==4):
    			print('__________________________________________________________________________________________________________________')
    			print('__________________________________________________________________________________________________________________')
    			print('На вашем счету',balance,'р.')
    if((log!= login)or(pas!= password)):
    	count=4
    	while ((log!=login)or(pas!=password)):
    		count=count-1
    		print("Неправильно введён логин или пароль. Осталось попыток входа:", count)
    		log=(input("Введите логин:\n"))
    		pas=(input("Введите пароль:\n"))	
    		if ((count < 2)and((log!=login)or(pas!=password))):
    			print('Вход заблокирован в связи с ошибкой при входе.')
    			break
    if ((log ==login)and(pas==password)):
    	
    	balance=0
    	print('__________________________________________________________________________________________________________________')
    	print('__________________________________________________________________________________________________________________')
    	print("Вход выполнен успешно! У вас на счету",balance,"р.")
    	while ((balance > -1)):
    		print('__________________________________________________________________________________________________________________')
    		print('__________________________________________________________________________________________________________________')
    		print('Введите 1, чтобы пополнить счет, 2, чтобы снять, 3, чтобы выйти из аккаунта, и 4, для того чтобы узнать состояние счета.')
    		s=int(input('(Далее - Enter.)\n'))
    		if(s==1):
    			sum=int(input("На сколько вы хотите пополнить счет?\n"))
    			balance=balance+sum
    			print("Операция проведена успешно! На Вашем счету",balance,'р.')
    		if(s==2):
    			print("Сколько вы желаете снять со счета?")
    			sum=int(input('(Далее - Enter.)\n'))
    			if (sum>balance):
    				print("На счете недостаточно средств. Попробуйте ввести меньшее значение.")
    			else:
    				balance=balance-sum
    				print("Средства сняты со счета. Остаток:",balance,"р.")
    		if(s==3):
    			print('__________________________________________________________________________________________________________________')
    			print('__________________________________________________________________________________________________________________')
    			print('Вы вышли из аккаунта.')
    			raise SystemExit
    		if(s==4):
    			print('__________________________________________________________________________________________________________________')
    			print('__________________________________________________________________________________________________________________')
    			print('На вашем счету',balance,'р.')

    govnokoder7, 18 Ноября 2020

    Комментарии (36)
  10. Python / Говнокод #27113

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    In order to fund the development work on speeding CPython by a factor of five, something like $2M will be required.
    This seems like a sizeable sum, but compared to the amount of money spent on Python development and the 
    cost of running Python applications, it is quite a modest sum.
    
    ---
    
    The overall aim is to speed up CPython by a factor of (approximately) five. We aim to do this in four distinct stages, 
    each stage increasing the speed of CPython by (approximately) 50%.
    
    1.5**4 ≈ 5
    
    ---
    
    The interpreter will adapt to types and values during execution, exploiting [b]type stability[/b] in the program
    
    ---
    
    Improved performance for [b]integers of less than one machine word[/b].
    Improved peformance for [b]binary operators[/b].
    
    ---
    
    Simple "JIT" compiler for small regions. Compile small regions of specialized code, using a relatively simple, fast compiler.
    Extend regions for compilation. Enhance compiler to generate [b]superior machine code[/b].

    питонисты готовят новую версию интерпретатора с революционной фичей - возможностью отъема денег у населения. Ожидается, что нововведение позволит языку быстро заработать очки на рынке пускания пыли в глаза.

    https://github.com/markshannon/faster-cpython

    Fike, 13 Ноября 2020

    Комментарии (65)