1. C++ / Говнокод #14610

    +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
    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
    95. 95
    96. 96
    97. 97
    void KateQuickOpen::update () {
      // пропущено
      QModelIndex idxToSelect;
      int linecount = 0;
      QMapIterator<qint64, KTextEditor::View *> i2(sortedViews);
      while (i2.hasNext()) {
            i2.next();
    
            KTextEditor::Document *doc = i2.value()->document();
    
            if (alreadySeenDocs.contains(doc))
              continue;
    
            alreadySeenDocs.insert (doc);
    
            QStandardItem *itemName = new QStandardItem(doc->documentName());
    
            itemName->setData(qVariantFromValue(QPointer<KTextEditor::Document> (doc)), DocumentRole);
            itemName->setData(QString("%1: %2").arg(doc->documentName()).arg(doc->url().pathOrUrl()), SortFilterRole);
            itemName->setEditable(false);
            QFont font = itemName->font();
            font.setBold(true);
            itemName->setFont(font);
    
            QStandardItem *itemUrl = new QStandardItem(doc->url().pathOrUrl());
            itemUrl->setEditable(false);
            base_model->setItem(linecount, 0, itemName);
            base_model->setItem(linecount, 1, itemUrl);
            linecount++;
    
            if (!doc->url().isEmpty() && doc->url().isLocalFile())
              alreadySeenFiles.insert (doc->url().toLocalFile());
    
            // select second document, that is the last used (beside the active one)
            if (linecount == 2)
              idxToSelect = itemName->index();
        }
    
      // get all open documents
      QList<KTextEditor::Document*> docs = Kate::application()->documentManager()->documents();
        foreach(KTextEditor::Document *doc, docs) {
            // skip docs already open
            if (alreadySeenDocs.contains (doc))
              continue;
    
            QStandardItem *itemName = new QStandardItem(doc->documentName());
    
            itemName->setData(qVariantFromValue(QPointer<KTextEditor::Document> (doc)), DocumentRole);
            itemName->setData(QString("%1: %2").arg(doc->documentName()).arg(doc->url().pathOrUrl()), SortFilterRole);
            itemName->setEditable(false);
            QFont font = itemName->font();
            font.setBold(true);
            itemName->setFont(font);
    
            QStandardItem *itemUrl = new QStandardItem(doc->url().pathOrUrl());
            itemUrl->setEditable(false);
            base_model->setItem(linecount, 0, itemName);
            base_model->setItem(linecount, 1, itemUrl);
            linecount++;
    
            if (!doc->url().isEmpty() && doc->url().isLocalFile())
              alreadySeenFiles.insert (doc->url().toLocalFile());
        }
    
        // insert all project files, if any project around
        if (Kate::PluginView *projectView = m_mainWindow->mainWindow()->pluginView ("kateprojectplugin")) {
          QStringList projectFiles = projectView->property ("projectFiles").toStringList();
          foreach (const QString &file, projectFiles) {
            // skip files already open
            if (alreadySeenFiles.contains (file))
              continue;
    
            QFileInfo fi (file);
            QStandardItem *itemName = new QStandardItem(fi.fileName());
    
            itemName->setData(qVariantFromValue(KUrl::fromPath (file)), UrlRole);
            itemName->setData(QString("%1: %2").arg(fi.fileName()).arg(file), SortFilterRole);
            itemName->setEditable(false);
            QFont font = itemName->font();
            font.setBold(true);
            itemName->setFont(font);
    
            QStandardItem *itemUrl = new QStandardItem(file);
            itemUrl->setEditable(false);
            base_model->setItem(linecount, 0, itemName);
            base_model->setItem(linecount, 1, itemUrl);
            linecount++;
          }
        }
    
        // swap models and kill old one
        m_model->setSourceModel (base_model);
        delete m_base_model;
        m_base_model = base_model;
    
        // пропущено
    }

    Адская копипаста. У меня мозг сегфолтится при попытке ее формализировать.

    https://projects.kde.org/projects/kde/applications/kate/repository/revisions/master/entry/kate/app/katequickopen.cpp#L135

    Elvenfighter, 16 Февраля 2014

    Комментарии (63)
  2. VisualBasic / Говнокод #14597

    −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
    Option Explicit
    
    Dim HTMLCode As String 'переменная для хранения кода страницы
    
    Private Sub Command1_Click()
        Winsock1.RemotePort = 80                'устанавливаем порт сервера 80
        Winsock1.RemoteHost = "ippages.com"     'Хост
        Winsock1.Connect                        'Подключаемся
        Label4.Caption = Winsock2.LocalIP
    End Sub
    
    Function CutIP(HTML As String) As String
    Dim p1 As Integer
        p1 = InStr(HTML, "Content-Type: text/html")
        CutIP = Trim(Mid(HTML, p1 + 27, Len(HTML) - p1 - 23))
    End Function
    
    Private Sub Label1_Click()
    
    End Sub
    
    Private Sub Winsock1_Close()        'Событие генерируется при закрытии Канала связи
        Form1.Caption = "Не подключен" 'Просто сообщаем о том что не подключены
        Winsock1.Close
    End Sub
    
    Private Sub Winsock1_Connect()      'Событие генерируется при подключении
       Form1.Caption = "Подключение"      'Подключены
       'Посылаем запрос на сервер  выдающему наш IP
      Winsock1.SendData "GET " + "/simple/" + " HTTP/1.0" + Chr(10) + Chr(10)
    End Sub
    
    'Событие генерируется когда нам приходят данные
    Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
    Dim Temp As String
      Winsock1.GetData HTMLCode
      Label1.Caption = CutIP(HTMLCode)
    End Sub
    
    Получение ай-пи адреса посредством отправки на сайт запроса через компонент WinSock.
    http://vbbook.ru/visual-basic/polychenie-svoego-ip/
    Строго говоря, это не лажа кодера, просто используется (по незнанию?) очень глючный и непредсказуемый компонент.

    Fixed by me:

    Function GetCurrentIP() As String
    Dim txt As String
    Dim i, j As Integer
    Dim mshttp As New XMLHTTP 'по умолчанию сервер всегда зареган.
    mshttp.open "GET", "http://checkip.dyndns.org/", False ' синхронный get
    mshttp.send
    txt = mshttp.responseText
    i = InStr(1, txt, ":")

    If i > 0 Then
    i = i + 1
    Else
    GetCurrentIP = "" ' удобно было бы, если по присваиванию, подобному этому, происходило покидание процедуры. Ан, нет.
    Exit Function
    End If

    j = InStr(i, txt, "</")
    If j < 1 Then
    GetCurrentIP = ""
    Exit Function
    End If

    GetCurrentIP = Trim(Mid(txt, i, j - i))
    End Function

    Stertor, 15 Февраля 2014

    Комментарии (203)
  3. Objective C / Говнокод #14594

    −184

    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
    - (Pt) menuItemPos: (int) i colRef: (int *) colr
    {
        int rowBeg [6] = { 1, 8, 15, 22, 28, 100 };
        float rowNum [6] =  { 7, 7, 7, 6.0, 5.0 };// { 7.03, 6.72, 7, 5.65, 4.43 };
        int col = -5;
        int row = -5;
        for(int j = 1; j < 6; ++j)
            if(i < rowBeg[j] && i >= rowBeg[j - 1])
            {
                row = j - 1;
                col = i - rowBeg[row];
                *colr = col;
                break;
            }
        
        float S = _large ? 80 : 30;
        float W = _large ? 1474/2 : 320;
        float w = W - 2 * S;
        float dx = w / (rowNum[row] - 1);
        
       // float scX = _large ? 2.1 : 1.0;
        float scY = _large ? 2.0 : 1.0;
        float aX = _large ? 18 : 0;
        return ccp( (S + col * dx) + aX,  (210 - row * 56.0) * scY);
    }

    Хардкодинг 90 уровня. Все константы подобраны вручную, с заботой и любовью.

    tirinox, 15 Февраля 2014

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

    +70

    1. 1
    2. 2
    .
    																		buffer.put(Transaction.getTransaction((JSONObject)transactionsData.get(j)).getBytes());

    Вложенность, например. Но это нужно видеть целиком.
    https://bitbucket.org/JeanLucPicard/nxt-public/src/

    rat4, 15 Февраля 2014

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

    −157

    1. 1
    2. 2
    3. 3
    4. 4
    SELECT ...
    FROM ...
    WHERE (CASE WHEN big_part = 1 AND blk_flag = 2 THEN -1 ELSE 0 END) <> -1 
    ;

    slbsomeone, 15 Февраля 2014

    Комментарии (2)
  6. C# / Говнокод #14585

    +139

    1. 1
    var date = (DateTime.UtcNow.Date > DateTime.UtcNow ? DateTime.UtcNow.AddSeconds(1) : (DateTime.UtcNow.Date < DateTime.UtcNow ? DateTime.UtcNow.Date.AddSeconds(1) : DateTime.UtcNow));

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

    aleksandr_kesha, 14 Февраля 2014

    Комментарии (23)
  7. Java / Говнокод #14583

    +73

    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
    final double[][] matrix = new double[companies.size() + 1][(sampleSizeTo - sampleSizeFrom) / sampleSizeStep + 2];
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[0].length; j++) {
            if (i == 0 && j == 0) {
                continue;
            }
            if (i == 0) {
                matrix[i][j] = sampleSizeFrom + (j - 1) * sampleSizeStep;
                continue;
            }
            if (j == 0) {
                matrix[i][j] = companies.get(i-1);
                continue;
            }
        }
    }

    Название функции getSmartDistibution (именно так) какбэ намекает, что дальше будет весело

    roman-kashitsyn, 14 Февраля 2014

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

    +136

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    public static string CreateBrowserCacheExtension(object key)
    {
        //...Остальной код опущен для ясности
        return "Cache=" + Math.Abs(key.GetHashCode());
    }

    Legacy code из проекта над которым я работаю.
    Косяк в том, что GetHashCode() иногда возвращает значение, равное System.Int32.MinValue.
    А это в свою очередь приводит к OverflowException, в случае с Math.Abs(...);

    pikowatt, 14 Февраля 2014

    Комментарии (27)
  9. C++ / Говнокод #14581

    +58

    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
    template <typename T>
    class MySharedPtr{
    public:
      explicit MySharedPtr(T* obj) : _obj(obj){}
      // --> я дописал
      MySharedPtr(const MySharedPtr& other) : _obj(other._obj){ inc_ref_count(_obj);}
      // <-- я дописал
      MySharedPtr& operator=(const MySharedPtr& other) {
        // --> я дописал
        if (this == &other)
          return *this;
        // <-- я дописал
        _obj = other._obj;
        inc_ref_count(_obj);
      }
      ~MySharedPtr(){
        dec_ref_count(_obj);
      }
    
    private:
      static void inc_ref_count(T* obj){
        std::lock_guard<std::mutex> lock(_mutex);
        _ref_count[obj] ++ ;
      }
    
      static void dec_ref_count(T* obj){
        std::lock_guard<std::mutex> lock(_mutex);
        if (--_ref_count[obj]){
          delete obj;
          _ref_count.erase(_ref_count.find(obj));
        }
      }
    
      T* _obj;
    
      static std::mutex MySharedPtr<T>::_mutex;
      static std::map<T*,int> MySharedPtr<T>::_ref_count;
    };
    
    
    template <typename T>
    std::map<T*,int> MySharedPtr<T>::_ref_count;
    
    
    template <typename T>
    std::mutex MySharedPtr<T>::_mutex;

    сегодня приходил чел-выпускник, написал на листочке shared_ptr, какое ваше мнение?

    LispGovno, 14 Февраля 2014

    Комментарии (63)
  10. PHP / Говнокод #14577

    +146

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    $synonyms = array(
        1 => 'once',
        2 => 'twice',
        3 => 'three times',
        4 => 'four times',
        5 => 'five times',
        6 => 'six times',
        7 => 'seven times',
        8 => 'eight times',
        9 => 'nine times',
        10 => 'ten times',
    );

    Dima, ты лучший!;)

    valllllera, 14 Февраля 2014

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