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

    −126

    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
    def price_request(self, response):
        # ебануцо
        t = TakeFirst()
        magic_data = {'__ASYNCPOST': 'true'}
    
        # --- забираю зашитые данные из форм
        keys = [
            '__BOOKMARKERbmTabs',
            '__VIEWSTATE',
            '__VIEWSTATEGENERATOR',
            '__EVENTVALIDATION',
            'HiddenField'
        ]
        for k in keys:
            val = response.xpath('//input[contains(@id, "%s")]/@value' % k).extract()
            key = response.xpath('//input[contains(@id, "%s")]/@name' % k).extract()
            if key:
                magic_data[t(key)] = t(val) or ''
    
        val = response.xpath('//input[contains(@value, "btnGetPrice")]/@value').extract()
        key = response.xpath('//input[contains(@value, "btnGetPrice")]/@name').extract()
        if key:
            magic_data[t(key)] = t(val) or ''
    
        # --- неведомая херня из js
        # вызов получения цены
        js = response.xpath(u'//script[contains(text(), "$(document).ready(function ()")][contains(text(), "__doPostBack")]').re(
            "__doPostBack\('([^']+)','([^']*)'\)")
        # [\$\w0]+btnGetPrice
        magic_data['__EVENTTARGET'] = js[0]
        # обычно ''
        magic_data['__EVENTARGUMENT'] = js[1]
    
        # ключ от сервера, скорее всего он связан с сессией
        js = response.xpath(u'//script[contains(text(), "Sys.Application.setServerId")]').re('\("([^"]+)", "([^"]*)"\)')
        super_magic_key = js[1]
    
        # --- опять данные из формы которые туда должны при ините странице соваться
        js = response.xpath(u'//script[contains(text(), "Sys.WebForms.PageRequestManager._initialize")]').re("'form1', \[([^\]]+)\]")[0]
        super_magic_values = re.findall("'([^']+)'", js)
        super_magic_value_1 = super_magic_values[0]
    
        for m in super_magic_values[1:len(super_magic_values)]:
            if m:
                magic_data[m] = ''
    
        # хер его знает почему, но первую букву надо откусить, обычно это t
        super_magic_value1 = super_magic_value_1[1:len(super_magic_value_1)]
    
        # составное значение вида [\$\w0]+=[\$\w0]+$updPrice|[\$\w0]+btnGetPrice
        magic_data[super_magic_key] = super_magic_value1 + '|' + magic_data['__EVENTTARGET']
    
        return FormRequest(url=response.url,
                           formdata=magic_data,
                           dont_filter=True,
                           meta=response.meta,
                           callback=self.parse_price,
                           method='post',
                           headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                                    'X-Requested-With': 'XMLHttpRequest',
                                    'X-MicrosoftAjax': 'Delta=true',
                                    'Origin': 'http://www.exist.ru',
                                    'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate',
                                    'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; en-gb) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27'
                           })

    То что случается если жалко ресурсов на запуск js при парсинге )

    kyzi007, 09 Июня 2015

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

    −267

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    import execjs
    
    js = '{"1": "2", "3": [4,5]}'
    
    default = execjs.get()
    print default.eval(js)

    Раз уже астрологи объявили неделю ебанутого парсенья json.

    3_14dar, 02 Июня 2015

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

    −120

    1. 1
    sqlalchemy.orm.relationship(argument, secondary=None, primaryjoin=None, secondaryjoin=None, foreign_keys=None, uselist=None, order_by=False, backref=None, back_populates=None, post_update=False, cascade=False, extension=None, viewonly=False, lazy=True, collection_class=None, passive_deletes=False, passive_updates=True, remote_side=None, enable_typechecks=True, join_depth=None, comparator_factory=None, single_parent=False, innerjoin=False, distinct_target_key=None, doc=None, active_history=False, cascade_backrefs=True, load_on_pending=False, strategy_class=None, _local_remote_pairs=None, query_class=None, info=None)

    Охуенный АПИ: прочитал и сразу запомнил.

    wvxvw, 27 Мая 2015

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

    −123

    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
    def run(code):
        
        def func(operator):
            from functools import reduce
            
            add    = lambda a, b: float(a) + float(b)
            mul    = lambda a, b: float(a) * float(b)
            div    = lambda a, b: float(a) / float(b)
            deduct = lambda a, b: float(a) - float(b)
            
            d = {
                '+': lambda arr: reduce(add,    arr),
                '*': lambda arr: reduce(mul,    arr),
                '/': lambda arr: reduce(div,    arr),
                '-': lambda arr: reduce(deduct, arr)
            }
            
            return d[operator]
        
        def lex(token):
            if token in ('+', '-', '/', '*', '%'):
                return "operator"
            elif token == '(':
                return "lbracket"
            elif token == ')':
                return "rbracket"
            elif token[0].isalpha():
                return "name"
            elif token[0] == token[-1] and token[0] in ('"', "'"):
                return "string"
            else:
                try:
                    float(token)
                    return "number"
                except:
                    raise ValueError
                
        def getArgs(words):
            args = []
            arg = []
            i = 0
            for word in words[2:]:
                if word == '(':
                    i += 1
                    arg.append(word)
                elif word == ')':
                    i -= 1
                    arg.append(word)
                    if i == 0:
                        args.append(arg)
                        arg = []
                elif i == 0:
                    arg.append(word)
                    args.append(arg)
                    arg = []
                else:
                    arg.append(word)
            return args
        
        def expr(words):
            args = getArgs(words)
            args_ = []
            for arg in args:
                if len(arg) == 1:
                    args_.append(arg)
                else:
                    args_.append(expr(arg))
            
            if lex(words[1]) == "operator":
                return func(words[1])(list(map(lambda a: (type(a) in (list, tuple) and a[0]) or a, args_)))
    
        lines = code.split("\n")
        for line in lines:
            word = ''
            words = []
            chars = tuple(line)
            
            for i in tuple(line):
                
                if i in ('(', ')'):
                    if word: words.append((word, lex(word)))
                    words.append((i, lex(i)))
                    word = ''
                
                elif i == ' ':
                    if word: words.append((word, lex(word)))
                    word = ''
                    
                else:
                    word += i
                    
            if word: words.append((word, lex(word)))
        words_ = list(map(lambda arr: arr[0], words))
        print(expr(words_))

    функция считает лиспоподобные арифметические выражения, например так:

    run("(+ 2 (* 3 4))") # 14

    в своё оправдание могу лишь сказать, что писал это в электричке на планшете

    KolesnichenkoDS, 27 Мая 2015

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

    −129

    1. 1
    2. 2
    except Exception:
        raise

    3_14dar, 25 Мая 2015

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

    −119

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    import inspect
    
    def phpformat(fmt):
        return fmt.format(**inspect.getouterframes(inspect.currentframe())[1][0].f_locals)
    
    surname = "Бонд"
    name = "Джеймс"
    num = 7
    print(phpformat("{surname}. {name} {surname}. Агент {num:03d}."))

    PHP'шная интерполяция строк теперь и в питоне.

    Родилось в http://govnokod.ru/18147#comment285697

    bormand, 11 Мая 2015

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

    −94

    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
    # Мы хотели бы подключиться к базе данных. Мы не знаем, верны ли логин и пароль
    # Если соединение с базой будет неуспешно, то
    # Он бросит исключение. Обратите внимание, что MyDatabase и DatabaseException
    # НЕ являются реальными классами, мы просто используем их в качестве примеров.
    
    try:
        database = MyDatabase(db_host, db_user, db_password, db_database)
        database_connection = database.connect()
    except DatabaseException:
        pass
    
    if database_connection is None:
        print('The database could not connect')
    else:
        print('The database could connect')

    Часто вы хотите выполнить действие, которое может работать либо завершиться неудачно. Используя None, вы можете проверить успех действия. Вот пример:

    3_14dar, 09 Мая 2015

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

    −118

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    def get_a():
        print("Hello goblin")
        return get_a
    
    get_a()()()()()()()()()()()()()

    Осталось понять зачем

    greenx, 30 Апреля 2015

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

    −180

    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
    try:
        ip_port = sys.argv[1].split(':')
        ip = ip_port[0]
     
        if len(ip_port) == 2:
            port = ip_port[1]
        elif len(ip_port) == 1:
            port = "80"
        else:
            raise IndexError
    except IndexError:
        print "Usage: %s <target ip:port>" % sys.argv[0]
        sys.exit(1)

    Эксплоиты. Неиссякаемый источник ГК.

    Я бы сделал так:

    try:
    ip_port = sys.argv[1].split(':')
    ip = ip_port[0]
    try:
    port = ip_port[1]
    except IndexError:
    port = 80
    except IndexError:
    print "Usage: %s <target ip:port>" % sys.argv[0]
    sys.exit(1)

    3_14dar, 25 Апреля 2015

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

    −120

    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
    class Column(object):
        """
            Элемент конфигурации
        """
        def __init__(self, *args, **kwargs):
    
            hid = False
            filters = []
            sorters = []
    
            if len(args) == 3:
                inner_name, verbose_name, width = args
            elif len(args) == 2:
                inner_name, verbose_name = args
                width = 20
            elif len(args) == 4:
                inner_name, verbose_name, width, hid = args
            elif len(args) == 5:
                inner_name, verbose_name, width, hid, filters = args
            elif len(args) == 6:
                inner_name, verbose_name, width, hid, filters, sorters = args
    
            special_attrs = ['locked', 'editable']
    
            self.code = inner_name
            self.name = verbose_name
            self.width = width
            self.hidden = hid
            self.idx = 0
            if sorters:
                sorters.column = self
            if filters:
                filters.column = self
                filters.code = self.code
    
            #здесь хранятся экземпляры фильтров для колонок
            self.filters = filters
            #здесь хранятся экземпляры сортировщиков для колонок
            self.sorters = sorters
    
        def get_config(self):
            ''' ?
            '''
            config = dict()
            config['data_index'] = self.code
            config['header'] = self.name
            config['width'] = self.width
            config['hidden'] = self.hidden
    
            return config

    Разбор параметров

    pycz, 23 Апреля 2015

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