1. Куча / Говнокод #27868

    0

    1. 1
    https://250bpm.com/blog:36/

    > At that point every semi-decent programmer curses spaghetti code in general and the author of the function in particular and embarks on the task of breaking it into managable chunks, trying to decompose the problem into orthogonal issues, layer the design properly, move the common functionality into base classes, create convenient and sufficiently generic extension points et c.

    <…>

    It turns out that the 1500-line function was parsing a network protocol. It is a 30-year old, complex and convoluted Behemoth of a protocol, defined by many parties fighting over the specification, full of compromises and special cases, dragged through multiple standardisation bodies and then anyway slightly customised by each vendor.

    <...>

    Unfortunately, it turns out that the tweak intersects the boundary between two well-defined components in the implementation. The right thing to do would be to re-think the architecture of the parser and to re-factor the codebase accordingly. <

    Вот так вот. Не стоит спешить любую портянку из 100+ строк кода называть "спагетти-кодом". Код может быть функцией микроконтроллера в котором вызов функции достаточно дорогой по памяти/времени, сложным алгоритмом и пр. Спагетти - это про организацию кода. Монолитный (но хорошо мапящийся на домен) код понять проще, чем солянку из функций, классов и пр. которые решают непонятно какую задачу (это и есть спагетти-код). Алсо https://en.wikipedia.org/wiki/Wikipedia:Chesterton%27s_fence

    JaneBurt, 12 Декабря 2021

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

    −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
    #!/usr/bin/python
      
      import sys
      
      cache = {}
      
      def count(start, end):
          if start < end:
              if start not in cache:
                  cache[start] = count(start + 1, end) + count(start * 2, end) + count(start ** 2, end)
              return cache[start]
          elif start == end:
              return 1
          else:
              return 0
    
      print(count(int(sys.argv[1]), int(sys.argv[2])))

    Подсчитать количество путей из a в b с помощью прибавления единицы, умножения на 2 и возведения в квадрат

    Чем формально ограничены возможности преобразовать рекурсию в хвостовую? Вот такое ведь не преобразовать?

    vistefan, 11 Декабря 2021

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

    +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
    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
    def export_to_csv(model, fields=None, related_models=[]):
        def export(request):
            meta = model._meta
            queryset = model.objects.all()
            
            if fields is not None:
                field_names = fields
            elif 'Shops' in related_models and 'Spots' in related_models:
                field_names = [field.name for field in Shops._meta.fields] +\
                    [field.name for field in Spots._meta.fields]
            elif 'Products' in related_models and 'Spots' in related_models:
                field_names = [field.name for field in Products._meta.fields] +\
                    [field.name for field in Spots._meta.fields]
            else:
                field_names = []
                for field in meta.fields:
                    if not field.name in FORBIDDEN_FIELDS:
                        field_names.append(field.name)
    
            response = HttpResponse(content_type='text/csv')
            response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)
            response.write(u'\ufeff'.encode('utf8'))
    
            writer = csv.writer(response, delimiter=',', lineterminator='\n', quoting=csv.QUOTE_ALL, dialect='excel')
            writer.writerow(field_names)
    
            if len(related_models) == 0:
                for obj in queryset:
                    row = writer.writerow([getattr(obj, field) for field in field_names])
    
            elif 'Shops' in related_models and 'Spots' in related_models:
                shops_fields = [field.name for field in Shops._meta.fields]
                contact_fields = [field.name for field in Spots._meta.fields]
    
                for obj in queryset:
                    row = []
    
                    if obj.Shops is not None:
                        row += [getattr(obj.Shops, field) for field in shops_fields]
                    else:
                        row += ['' for field in shops_fields]
    
                    if obj.Contact is not None:
                        row += [getattr(obj.Contact, field) for field in contact_fields]
                    else:
                        row += ['' for field in contact_fields]
    
                    writer.writerow(row)
                
            elif 'Products' in related_models and 'Spots' in related_models:
                products_fields = [field.name for field in Products._meta.fields]
                contact_fields = [field.name for field in Spots._meta.fields]
                
                for obj in queryset:
                    row = []
                    
                    if obj.Products is not None:
                        row += [getattr(obj.Products, field) for field in products_fields]
                    else:
                        row += ['' for field in products_fields]
    
                    if obj.Contact is not None:
                        row += [getattr(obj.Contact, field) for field in contact_fields]
                    else:
                        row += ['' for field in contact_fields]
                    
                    writer.writerow(row)
    
            return response
    
        return export

    В юности нагородила вот такую портянку для экспорта в csv связных между собой таблиц. Связка данных на уровне DAO-шки (в терминологии Джанго - Managers)? Пфф... Только инжект if-else с копипастой связки данных, только хардкор!

    JaneBurt, 11 Декабря 2021

    Комментарии (331)
  4. JavaScript / Говнокод #27863

    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
    type NetworkLoadingState = {
      state: "loading";
    };
    
    type NetworkFailedState = {
      state: "failed";
      code: number;
    };
    
    type NetworkSuccessState = {
      state: "success";
      response: {
        title: string;
        duration: number;
        summary: string;
      };
    };
    
    type NetworkState =
      | NetworkLoadingState
      | NetworkFailedState
      | NetworkSuccessState;
    
    
    function logger(state: NetworkState): string {
      switch (state.state) {
        case "loading":
          return "Downloading...";
        case "failed":
          // The type must be NetworkFailedState here,
          // so accessing the `code` field is safe
          return `Error ${state.code} downloading`;
        case "success":
          return `Downloaded ${state.response.title} - ${state.response.summary}`;
        default:
          return "<error>";
      }
    }
    
    function main() {
        print(logger({ state: "loading" }));
        print(logger({ state: "failed", code: 1.0 }));
        print(logger({ state: "success", response: { title: "title", duration: 10.0, summary: "summary" } }));
        print(logger({ state: "???" }));
        print("done.");
    }

    Ура... радуйтесь.... я вам еще говнокодца поднадкинул... ну и перекопал же говна в коде что бы это сделать. Дампик тут.. https://pastebin.com/u7XZ00LV Прикольно получается если скомпилить с оптимизацией то нихрена от кода не остается. и результат работы

    C:\temp\MLIR_to_exe>1.exe
    Downloading...
    Error 1 downloading
    Downloaded title - summary
    <error>
    done.

    ASD_77, 10 Декабря 2021

    Комментарии (62)
  5. Куча / Говнокод #27861

    +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
    RUN apt install -y apache2
    RUN apt install -y php
    RUN apt install -y php-mysql
    RUN apt install -y libapache2-mod-php
    RUN apt install -y curl
    RUN apt install -y php-mbstring
    RUN apt install -y php-mysql
    RUN apt install -y php7.4-sqlite3
    RUN apt install -y php-gd
    RUN apt install -y php-intl
    RUN apt install -y php-xml
    RUN apt install -y php-curl
    
    #RUN apt install -y php7.0-ffmpeg
    
    RUN sed -i "s/short_open_tag = Off/short_open_tag = On/" /etc/php/7.4/apache2/php.ini
    RUN sed -i "s/short_open_tag = Off/short_open_tag = On/" /etc/php/7.4/cli/php.ini
    
    RUN echo "ServerName localhost" >> /etc/apache2/apache2.conf
    RUN echo "IncludeOptional /var/www/*.conf" >> /etc/apache2/apache2.conf
    #RUN sed -i "s/<\/VirtualHost>/Проверка\n<\/VirtualHost>" /etc/apache2/apache2.conf
    RUN sed -i "s/<\/VirtualHost>/\n\t<Directory \/var\/www\/html>\n\t<\/Directory>\n<\/VirtualHost>/g" /etc/apache2/sites-available/000-default.conf
    RUN sed -i "s/<\/Directory>/\tOptions Indexes FollowSymLinks MultiViews\n\t<\/Directory>/g" /etc/apache2/sites-available/000-default.conf
    RUN sed -i "s/<\/Directory>/\tAllowOverride All\n\t<\/Directory>/g" /etc/apache2/sites-available/000-default.conf
    RUN sed -i "s/<\/Directory>/\tOrder allow,deny\n\t<\/Directory>/g" /etc/apache2/sites-available/000-default.conf
    RUN sed -i "s/<\/Directory>/\tAllow from all\n\t<\/Directory>/g" /etc/apache2/sites-available/000-default.conf
    RUN sed -i "s/<\/Directory>/\tRequire all granted\n\t<\/Directory>/g" /etc/apache2/sites-available/000-default.conf
    RUN mv /etc/apache2/sites-enabled/000-default.conf /tmp
    RUN cd /etc/apache2/sites-enabled/; ln -s ../sites-available/000-default.conf 000-default.conf
    RUN a2enmod php7.4
    RUN a2enmod rewrite
    #RUM apt install -y certbot
    #RUN a2enmod python-certbot-apache
    #RUN a2enmod ssl
    EXPOSE 80
    EXPOSE 22
    
    #        <Directory /var/www/html>
    #                Options Indexes FollowSymLinks MultiViews
    #                AllowOverride All
    #                Order allow,deny
    #                Allow from all
    #                Require all granted
    #        </Directory>
    
    RUN wget -O /var/www/html/index.phar https://github.com/mpak2/mpak.su/raw/master/phar/index.phar
    RUN wget -O /var/www/html/.htaccess https://github.com/mpak2/mpak.su/raw/master/.htaccess
    RUN wget -O /var/www/html/.htdb https://github.com/mpak2/mpak.su/raw/master/.htdb
    RUN chown www-data /var/www/html/.htdb
    RUN chown www-data /var/www/html
    RUN mkdir /var/www/html/include
    RUN mkdir /var/www/html/include/images
    RUN chmod 0777 /var/www/html/include/images
    RUN rm /var/www/html/index.html

    https://github.com/mpak2/mpak.su/blob/654b7daf0b7d4f3c83385c0ca35fcab6a1ec45f7/phar/docker/www/Dockerfile

    ISO, 07 Декабря 2021

    Комментарии (21)
  6. Куча / Говнокод #27860

    +1

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    Можно ли считать говнокодом (говноAPI) правильно работающую, но незадокументированную особенность API?
    Например у вьюхи есть свойство isOpen, которое может быть задано (true/false) а может быть не задано (undefined). 
    Первое нужно для управления видимостью в реактивном стиле, второе предполагает что разработчик будет
    управлять видимостью через хендлы вьюхи. И оно так и работает - если isOpen=undefined, то этот проп просто игнорируется
    при обновлении вьюхи (чтобы не допустить конфликта source truth). Но этого нет в документации, отчего неосторожное 
    использование булеана и значения которое может быть undefined в качестве значения isOpen, приводит к забавному
    косяку - вьюха должна исчезнуть, но она не исчезает! И тут по-началу грешишь на забагованное API. Но в нем нет бага!

    JaneBurt, 06 Декабря 2021

    Комментарии (26)
  7. Си / Говнокод #27859

    +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
    #include <conio.h>
    
    void activateAlarm(int channelID) {
    
        int key = 0;
    
        while(temperatureChannel[channelID].currentTemperature > temperatureChannel[channelID].highLimit
            ||temperatureChannel[channelID].currentTemperature < temperatureChannel[channelID].lowLimit) {
    
            beep(350,100);
    
            if (_kbhit()) {
                key = _getch();
                if(key == 'P');
                    break;
            }    
        }
    }

    3_dar, 06 Декабря 2021

    Комментарии (24)
  8. PHP / Говнокод #27858

    0

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    public function renderJSON()
        {
            $this->checkError();
    
            return serialize($this);
        }

    Чтобы враг не догадался!

    zoorg, 06 Декабря 2021

    Комментарии (20)
  9. 1C / Говнокод #27856

    −1

    1. 1
    2. 2
    Для ТекИндекс = 0 По Объект.Товары.Количество() -1 Цикл       									   
    			Стр = Объект.Товары[ТекИндекс];

    //Интересе, а чем не устроило?:

    Для каждого Стр из Объект.Товары Цикл

    timofeysin, 06 Декабря 2021

    Комментарии (8)
  10. JavaScript / Говнокод #27855

    +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
    function main() {
        let a: number | string;
    
        a = "Hello";
    
        if (typeof(a) == "string")
        {
    	print("str val:", a);
        }
    
        a = 10.0;
    
        if (typeof(a) == "number")
        {
    	print("num val:", a);
        }
    
        print("done")
    }

    Аллилуйя братья... я вам принес "union"-s . Возрадуйтесь новой фиче. (А ты можешь так в с/c++?)

    дампик https://pastebin.com/QNmKFfT7

    C:\temp>C:\dev\TypeScriptCompiler\__build\tsc\bin\tsc.exe --emit=jit --opt --shared-libs=C:\dev\TypeScriptCompiler\__build\tsc\bin\TypeScriptRuntime.dll C:\temp\1.ts 
    str val: Hello
    num val: 10
    done

    ASD_77, 06 Декабря 2021

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