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

    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
    class Cell:
        def __init__(self, row_id, column_id):
            """Описание ячейки в матрице"""
            """Определение первой буквы в ячейке"""
            if row_id == 0:
                self.cell_letter_1 = 'A'
            elif row_id == 1:
                self.cell_letter_1 = 'K'
            elif row_id == 2:
                self.cell_letter_1 = 'Q'
            elif row_id == 3:
                self.cell_letter_1 = 'J'
            elif row_id == 4:
                self.cell_letter_1 = 'T'
            elif row_id == 5:
                self.cell_letter_1 = '9'
            elif row_id == 6:
                self.cell_letter_1 = '8'
            elif row_id == 7:
                self.cell_letter_1 = '7'
            elif row_id == 8:
                self.cell_letter_1 = '6'
            elif row_id == 9:
                self.cell_letter_1 = '5'
            elif row_id == 10:
                self.cell_letter_1 = '4'
            elif row_id == 11:
                self.cell_letter_1 = '3'
            elif row_id == 12:
                self.cell_letter_1 = '2'
            """Определение второй буквы в ячейке"""
            if column_id == 0:
                self.cell_letter_2 = 'A'
            elif column_id == 1:
                self.cell_letter_2 = 'K'
            elif column_id == 2:
                self.cell_letter_2 = 'Q'
            elif column_id == 3:
                self.cell_letter_2 = 'J'
            elif column_id == 4:
                self.cell_letter_2 = 'T'
            elif column_id == 5:
                self.cell_letter_2 = '9'
            elif column_id == 6:
                self.cell_letter_2 = '8'
            elif column_id == 7:
                self.cell_letter_2 = '7'
            elif column_id == 8:
                self.cell_letter_2 = '6'
            elif column_id == 9:
                self.cell_letter_2 = '5'
            elif column_id == 10:
                self.cell_letter_2 = '4'
            elif column_id == 11:
                self.cell_letter_2 = '3'
            elif column_id == 12:
                self.cell_letter_2 = '2'
            """Установка порядка отойбражения 1-й и 2-й буквы в ячейке"""
            if row_id == 0:
                self.cell_text = self.cell_letter_1 + self.cell_letter_2
            elif row_id == 1 and column_id >= 2:
                self.cell_text = self.cell_letter_1 + self.cell_letter_2
            elif row_id == 2 and column_id >= 3:
                self.cell_text = self.cell_letter_1 + self.cell_letter_2
            elif row_id == 3 and column_id >= 4:
                self.cell_text = self.cell_letter_1 + self.cell_letter_2
            elif row_id == 4 and column_id >= 5:
                self.cell_text = self.cell_letter_1 + self.cell_letter_2
            elif row_id == 5 and column_id >= 6:
                self.cell_text = self.cell_letter_1 + self.cell_letter_2
            elif row_id == 6 and column_id >= 7:
                self.cell_text = self.cell_letter_1 + self.cell_letter_2
            elif row_id == 7 and column_id >= 8:
                self.cell_text = self.cell_letter_1 + self.cell_letter_2
            elif row_id == 8 and column_id >= 9:
                self.cell_text = self.cell_letter_1 + self.cell_letter_2
            elif row_id == 9 and column_id >= 10:
                self.cell_text = self.cell_letter_1 + self.cell_letter_2
            elif row_id == 10 and column_id >= 11:
                self.cell_text = self.cell_letter_1 + self.cell_letter_2
            elif row_id == 11 and column_id == 12:
                self.cell_text = self.cell_letter_1 + self.cell_letter_2
            else:
                self.cell_text = self.cell_letter_2 + self.cell_letter_1

    http://python.su/forum/topic/33195/?page=1#post-181430

    FishHook, 17 Июля 2017

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

    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
    import csv
    import json
    
    import requests
    
    from io import StringIO
    
    from lxml import etree
    
    
    class DayPicParser(object):
        url = 'урл_до_сайта'
    
        def get_info(self):
            handler = open('daypic.csv', 'w+')
            page = 1
            rows = []
            tags = set()
            while page <= 1077:
                response = requests.get('{}/page/{}'.format(self.url, page))
                response.connection.close()
                parser = etree.HTMLParser()
                tree = etree.parse(StringIO(response.text), parser)
                posts = tree.xpath('//div[@class="posts"]/div[@class="post"]')
                for i, post in enumerate(posts):
                    title = post.find('./h2/a')
                    link_to_fulltext = title.attrib['href']
    
                    short_text = post.find('./div[@class="text"]//p[1]')
                    response = requests.get(link_to_fulltext)
                    full_parser = etree.HTMLParser()
                    full_tree = etree.parse(StringIO(response.text), full_parser)
                    full_post = full_tree.xpath('//div[@class="text"]//p')
    
                    main_image = None
                    full_text = []
                    for inner in full_post:
                        if inner.find('.//noindex') is not None:
                            continue
                        if inner.find('.//img') is not None:
                            src = inner.find('.//img').attrib['src']
                            if not main_image:
                                main_image = src
                            full_text.append({'image': src})
                        for paragraph in etree.tostring(inner, method="text", encoding='utf-8').decode('utf-8').strip().split("\n"):
                            if paragraph:
                                full_text.append({'text': paragraph})
                    rows.append({'title': title.text.strip(),
                                 'preview': main_image if main_image else '',
                                 'short_text': short_text.text.strip(),
                                 'full_text': full_text})
                    print('Post {} of {}'.format(i, len(posts)))
                page += 1
                print(page)
            handler.write(json.dumps(rows))
            handler.close()
            print(tags)
    
    
    DayPicParser().get_info()

    storvus, 10 Июля 2017

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

    +2

    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
    class StreamRailBase:
        __metaclass__ = ABCMeta
    
        def __init__(self): pass
    
        # @abstractmethod
        # def create_connection(self): pass
        #
        # @abstractmethod
        # def send_to_sr(self, method, path, params=None): pass
    
        # @abstractmethod
        # def get_advertisers(self): pass
        #
        # @abstractmethod
        # def get_targeting_conditions(self, env, geos, os, size, white_list, black_list): pass
        #
        # @abstractmethod
        # def create_ad_source(self, name, price, partner, tag_url, env, geos, os, size, req_cap, imp_cap, white_list=None, black_list=None): pass
        #
        # @abstractmethod
        # def create_sr_tag(self, tag_instance): pass
        #
        # @abstractmethod
        # def create_domain_list(self, f, list_type, adsource_name): pass
        #
        # @abstractmethod
        # def activate_adsource(self, adsource_id): pass
        #
        # @abstractmethod
        # def deactivate_adsource(self, adsource_id): pass
        #
        # @abstractmethod
        # def set_caps(self, params, new_req_cap, new_imp_cap): pass
        #
        # @abstractmethod
        # def set_geos(self, params, new_geos): pass
        #
        # @abstractmethod
        # def edit_domain_list(self, f, list_id): pass
        #
        # @abstractmethod
        # def set_list(self, params, new_list, list_type): pass
        #
        # @abstractmethod
        # def set_size(self, params, size): pass
        #
        # @abstractmethod
        # def edit_adsource(self, tag_instance, form_data): pass
        #
        # @abstractmethod
        # def create_new_partner(self, name): pass
        #
        # @abstractmethod
        # def sync_tag(self, tag_instance): pass
        #
        # @abstractmethod
        # def add_new_tag_to_template(self, tag_name, price, tag_id, adv_id): pass

    В человеке умер рахитектор, и в отчаянии, он закомитил эту хуйню в мастер.

    wvxvw, 09 Июля 2017

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

    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
    # returns yesterday reports
        def get_yesterday_reports(self):
            pass
    
        def get_waterfall_sources(self, wf_id, active_only=False):
            # TODO: check if meta property is equal to the number of items in the array
            # return test.mock_waterfall_sources.get_sources()
            status = '1' if active_only else urllib.quote('0,1')  # '0%2C1&'
            self.get_auth_token()
            encoded = urllib.urlencode({'authorization': self.token})
            url = BASE_URL + "/waterfall-ad-sources?advertiser=&itemsPerPage=9999&name=&page=1&sortAsc=true&sortBy=tier&status={}&tier=&waterfall={}&{}" \
                .format(status, wf_id, encoded)
    
            retries = 1
            while retries <= 3:
                response = requests.get(url)
                if response.status_code == 200:
                    break
                else:
                    logging.error('Failed GET request to StreamRail, status code {}, {} retries'
                                  .format(response.status_code, retries))
                retries += 1
    
            assert response.status_code == 200
            try:
                data = simplejson.loads(response.content)
                waterfall_sources = data['waterfallAdSources']
                assert int(data['meta']['total']) == len(waterfall_sources)
                return waterfall_sources
            except:
                logging.exception("Could not load ad sources for waterfall {} from StreamRail:\n"
                                  "{}".format(wf_id, response.headers))
                raise

    Хотя, с другой стороны, все эти рекламораспространители так выглядят. Но тут просто кучно так получилось.

    wvxvw, 06 Июля 2017

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

    +3

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    def do_creaprim(self, mesh, objname, addondir):
    	
    	global message
    	
    	objname = objname.replace(".", "")
    	objname = objname.replace(" ", "_")
    	bm = bmesh.new()
    	bm.from_mesh(mesh)	  
    	
    	
    	try:
    		txt = bpy.data.texts[str.lower("add_mesh_" + objname) + ".py"]
    		txt.clear()
    	except:
    		txt = bpy.data.texts.new("add_mesh_" + str.lower(objname) + ".py")
    	
    	strlist = []
    	strlist.append("bl_info = {\n")
    	strlist.append("\"name\": \"" + objname + "\", \n")
    	strlist.append("\"author\": \"Gert De Roost\",\n")
    	strlist.append("\"version\": (1, 0, 0),\n")
    	strlist.append("\"blender\": (2, 65, 0),\n")
    	strlist.append("\"location\": \"Add > Mesh\",\n")
    	strlist.append("\"description\": \"Create " + objname + " primitive.\",\n")
    	strlist.append("\"warning\": \"\",\n")
    	strlist.append("\"wiki_url\": \"\",\n")
    	strlist.append("\"tracker_url\": \"\",\n")
    	strlist.append("\"category\": \"Add Mesh\"}\n")
    	strlist.append("\n")
    	strlist.append("\n") 
    	strlist.append("if \"bpy\" in locals():\n")
    	strlist.append("	   import imp\n")
    	strlist.append("\n")
    	strlist.append("\n")
    	strlist.append("import bpy\n")
    	strlist.append("import bmesh\n")
    	strlist.append("import math\n")
    	strlist.append("from mathutils import *\n")
    	strlist.append("\n")
    	strlist.append("\n")
    	strlist.append("\n")
    	strlist.append("\n")
    	strlist.append("class " + objname + "(bpy.types.Operator):\n")
    	strlist.append("	bl_idname = \"mesh." + str.lower(objname) + "\"\n")
    	strlist.append("	bl_label = \"" + objname + "\"\n")
    	strlist.append("	bl_options = {\'REGISTER\', \'UNDO\'}\n")
    	strlist.append("	bl_description = \"add " + objname + " primitive\"\n")
    	strlist.append("\n")
    	strlist.append("	def invoke(self, context, event):\n")
    	strlist.append("\n")
    	strlist.append("		mesh = bpy.data.meshes.new(name=\"" + objname + "\")\n")
    	strlist.append("		obj = bpy.data.objects.new(name=\"" + objname + "\", object_data=mesh)\n")
    	strlist.append("		scene = bpy.context.scene\n")
    	strlist.append("		scene.objects.link(obj)\n")
    	strlist.append("		obj.location = scene.cursor_location\n")
    	strlist.append("		bm = bmesh.new()\n")
    	strlist.append("		bm.from_mesh(mesh)\n")
    	strlist.append("\n")
    	strlist.append("		idxlist = []\n")
    	posn = 0
    	strlist.append("		vertlist = [")
    	for v in bm.verts:
    		if posn > 0:
    			strlist.append(", ")
    		posn += 1
    		strlist.append(str(v.co[:]))
    	strlist.append("]\n")	 
    	strlist.append("		for co in vertlist:\n")
    	strlist.append("			v = bm.verts.new(co)\n")
    	strlist.append("			bm.verts.index_update()\n")
    	strlist.append("			idxlist.append(v.index)\n")
    	posn = 0
    	strlist.append("		edgelist = [")
    	for e in bm.edges:
    		if posn > 0:
    			strlist.append(", ")
    		posn += 1
    		strlist.append("[" + str(e.verts[0].index) + ", " + str(e.verts[1].index) + "]")
    	strlist.append("]\n")	 
    	strlist.append("		for verts in edgelist:\n")
    	strlist.append("			try:\n")
    	strlist.append("				bm.edges.new((bm.verts[verts[0]], bm.verts[verts[1]]))\n")
    	strlist.append("			except:\n")
    	strlist.append("				pass\n")
    	posn1 = 0
    	strlist.append("		facelist = [(")
    	for f in bm.faces:
    		if posn1 > 0:
    			strlist.append(", (")
    		posn1 += 1
    		posn2 = 0
    		for v in f.verts:
    			if posn2 > 0:
    				strlist.append(", ")
    			strlist.append(str(v.index))
    			posn2 += 1
    		strlist.append(")")
    	strlist.append("]\n")	 
    	strlist.append("		bm.verts.ensure_lookup_table()\n")
    	strlist.append("		for verts in facelist:\n")

    Залил вам отборного

    Skarn, 30 Июня 2017

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

    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
    if hasattr(query, "items"):
            query = query.items()
        else:
            # It's a bother at times that strings and string-like objects are
            # sequences.
            try:
                # non-sequence items should not work with len()
                # non-empty strings will fail this
                if len(query) and not isinstance(query[0], tuple):
                    raise TypeError
                # Zero-length sequences of all types will get here and succeed,
                # but that's a minor nit.  Since the original implementation
                # allowed empty dicts that type of behavior probably should be
                # preserved for consistency
            except TypeError:
                ty, va, tb = sys.exc_info()
                raise TypeError("not a valid non-string sequence "
                                "or mapping object").with_traceback(tb)

    https://github.com/python/cpython/blob/master/Lib/urllib/parse.py#L848

    Зачем генерировать TypeError, а потом ее ловить и снова кидать?

    Admina_mamu_ebal, 23 Июня 2017

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

    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
    primary_list = tuple([line.strip() for line in open('file1.txt', 'r')])
    secondary_list = tuple([line.strip() for line in open('file2.txt', 'r')])
    f = open('test.txt', 'w')
    
    users_unique = []
    
    def isUnique(value):
      if value not in users_unique:
        users_unique.append(value)
        return True
      else:
        return False
    
    def common():
      for item in primary_list:
        if item is None:
          continue
        elif item in secondary_list and isUnique(item):
          f.write(str(item)+'\r\n')
      print 'Complete'

    Masha-Rostova, 07 Июня 2017

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

    −2

    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
    from threading import Thread 
    from time import sleep
    
    for i in range(4):
        print(type(i))
        def f(i):
            if int(i) == 1:
                print('i=',i)
            
            elif i == 2:
                print('i=',i)
            
            elif i == 3:
                print('i=', i)
            
        t = Thread(target=f, args=(i,))
        t.start()
        sleep(1)
        print(i)

    dmitriiweb, 01 Июня 2017

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

    0

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    class Stream(object):
        def __init__(self, generator):
            object.__init__(self)
            self.data = ''
            self.generator = generator
            self.closed = False
            
            generator.subscribe(self)
            
        def update(self, data):
            self.data += data
            
        def read(self):
            if self.closed: return None
            data = self.data
            self.data = ''
            return data
            
        def close(self):
            self.generator.unsubscribe(self)
            self.closed = True
            self.data = ''
    
    class Server(dispatcher, dict):
        writable = lambda x: False
        
        def __init__(self, host = None, port = 0xB00B):
            dispatcher.__init__(self)
            
            self.create_socket(AF_INET, SOCK_STREAM)
            dict.__init__(self, {self.fileno(): self})
            
            self.set_reuse_addr()
            self.bind((host, port))
            self.listen(0xA)
            
            self.dataSource = PiGenerator()
            
        def removeClient(self, client):
            del self[client.fileno()]
            
        def handle_accept(self):
            sock, (host, port) = self.accept()
            print 'new client from %s:%d' % (host, port)
            
            stream = Stream(self.dataSource)        
            self[sock.fileno()] = Client(sock, self, stream)
            
        def handle_error(self):
            print 'Server error: %s' % sys.exc_value
            sys.exit(1)
        
    class Client(dispatcher):
        readable = lambda x: False    
        
        def __init__(self, sock, server, stream):
            dispatcher.__init__(self, sock)
            self.server = server
            self.stream = stream
            self.buffer = ''
            
        def handle_error(self):
            print 'Client error: %s' % sys.exc_value
            import traceback
            print traceback.format_exc(1000)
            sys.exit(1)        
            
        def handle_write(self):                
            sent = self.send(self.buffer)
            self.buffer = self.buffer[sent:]
            
        def handle_expt(self):
            print 'client dropped connection'        
            self.close()
            
        def close(self):
            self.server.removeClient(self)
            self.stream.close()
            self.buffer = ''
            dispatcher.close(self)
            
        def writable(self):
            data = self.stream.read()
            if data == None:
                print 'client finished reading'
                self.close()
                return False
            
            self.buffer += data
            return len(self.buffer) > 0
    
    def main():
        try:
            asyncore.loop(0.1, True, Server('127.0.0.1'))
        except KeyboardInterrupt:
            print '\nBye :-*'
            sys.exit(0)
    
    if __name__ == '__main__':
        main()

    start http://govnokod.ru/23059

    Lis, 23 Мая 2017

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

    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
    #!/usr/bin/python
    #encoding: utf-8
    
    import sys
    import time
    import socket
    import asyncore
    import exceptions
    
    from socket import AF_INET, SOCK_STREAM
    from asyncore import dispatcher
    from threading import Thread, RLock
    
    class PiCalcThread(Thread):
        def __init__(self, buffer, lock):
            Thread.__init__(self)
            self.buffer = buffer
            self.lock = lock
            
        def run(self):
            """ See http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/spigot.pdf """
            q,r,t,k,n,l = 1,0,1,1,3,3
            
            while True:
                if 4*q+r-t < n*t:
                    self.lock.acquire()
                    self.buffer.newDigits(str(n))
                    self.lock.release()
                    
                    q,r,t,k,n,l = (10*q,10*(r-n*t),t,k,(10*(3*q+r))/t-10*n,l)
                else:
                    q,r,t,k,n,l = (q*k,(2*q+r)*l,t*l,k+1,(q*(7*k+2)+r*l)/(t*l),l+2)
                
                time.sleep(0.001)
    
    class PiGenerator(list):
        def __init__(self):
            list.__init__(self)
            self.calculator = None
            self.lock = RLock()
            self.digits = ''
        
        def subscribe(self, obj):  
            self.lock.acquire()
            try:     
                self.append(obj)
                self._notify(obj=obj)
            finally:
                self.lock.release()            
                
            if not self.calculator:
                self.calculator = PiCalcThread(self, self.lock)
                self.calculator.start()
            else:
                if len(self) > 0:
                    self._resumeCalculator()
                    
        def unsubscribe(self, obj):
            self.lock.acquire()
            self.remove(obj)   
            self.lock.release()
                 
            if len(self) <= 0:
                self._pauseCalulator()
                
        def _pauseCalulator(self):
            self.lock.acquire()
        
        def _resumeCalculator(self):
            try: self.lock.release()
            except exceptions.AssertionError: pass
                
        def _notify(self, digits = None, obj = None):
            objs = [obj] if obj else self
            digits = digits or self.digits
            
            for obj in objs:
                obj.update(digits)
            
        def newDigits(self, digits):
            self.digits += digits
            self._notify(digits)

    Lis, 23 Мая 2017

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