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

    +8

    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
    #include <pthread.h>
    template<class T = long long>
    class AtomicCounter
    {
        public:
            explicit AtomicCounter( T value = 0 ): _count( value ) { pthread_spin_init( &_lock, PTHREAD_PROCESS_PRIVATE );};
            ~AtomicCounter()  { pthread_spin_destroy( &_lock );    };
    
            T operator++(int) volatile {  return interlockFetchAndAdd( 1 );      };
            T operator--(int) volatile {  return interlockFetchAndAdd( -1 );     };
            T operator() ()   volatile {  return interlockFetchAndAdd( 0 );      }
    
        private:
            volatile T    _count;
            pthread_spinlock_t _lock;
    
            T interlockFetchAndAdd( int delta ) volatile
            {
                T x = 0;
                pthread_spin_lock( &_lock );
                x = _count;
                _count += delta;
                pthread_spin_unlock(&_lock);
                return x;
            }
    };

    Принцип наименьшего удивления, говорите

    roman-kashitsyn, 26 Июля 2013

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

    +14

    1. 1
    2. 2
    3. 3
    4. 4
    std::string buf_str = str;
    buf_str.erase( 0, strBlobFsParam.size() + 1 );
    buf_str.erase( buf_str.begin(), find_if(buf_str.begin(), buf_str.end(), not1( ptr_fun<int, int>(isspace) ) ) );
    buf_str.erase( find_if( buf_str.rbegin(), buf_str.rend(), not1( ptr_fun<int, int>(isspace) ) ).base(), buf_str.end() );

    trim головного мозга

    roman-kashitsyn, 26 Июля 2013

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

    +111

    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
    public class PmsUtil {
    	
    	public static boolean allowViewFolder(IFolder folder) {
    		return isIntersected(folder.getPermissions(), getUserPms());
    	}
    
    	private static Set<Permission> getUserPms() {
    		return LoginController.get().getUser().getRole().getPermissions();
    	}
    
    	private static boolean isIntersected(Set<Permission> pmsSetA, Set<Permission> pmsSetB) {
    		for(Permission pms : pmsSetB) {
    			if(pmsSetA.contains(pms)) {
    				return true;
    			}
    		}
    		return false;
    	}
    
    	
    }

    К слову об именах переменных... любил мой предшественник делать нестандартные сокращения.

    someone, 26 Июля 2013

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

    +69

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    SOAPMessage msg = ctx.getMessage();
    
    //msg.writeTo(System.out);
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    msg.writeTo(baos);
    logger.trace(baos);

    где у хвалёного log4j метод для передачи его как аргументом java.io.OutputStream???

    defecate-plusplus, 26 Июля 2013

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

    +110

    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
    private void Save(string ThreadID, string Board)
            {
                string pathL;
                if (cbGIF.Checked)
                {
                    pathL = String.Format(path, Board, ThreadID, "-gif");
                }
                else
                {
                    pathL = String.Format(path, Board, ThreadID, "");
                }
                string htmlPath = String.Format(threadPath, Board, ThreadID);
    
                WebClient wcli = new GZipWebClient();
                string cThread = wcli.DownloadString(htmlPath);
                
                var rx = new Regex(cbGIF.Checked ? regExGif : regEx);
                var ms = rx.Matches(cThread);
                imgSaved = 0;
                imgCount = ms.Count;
                saveProgress.Minimum = 0;
                saveProgress.Maximum = imgCount;
                saveProgress.Value = 0;
                if (!Directory.Exists(pathL))
                {
                    Directory.CreateDirectory(pathL);
                }
                try
                {
                    foreach (Match m in ms)
                    {
                        WebClient ccl = new WebClient();
                        ccl.DownloadFileCompleted += new AsyncCompletedEventHandler(ccl_DownloadFileCompleted);
                        string[] v = m.Value.Split('"');
                        string sd = v[1].Split('/').Last();
                        string a = url + v[1];
                        string b = pathL + sd;
                        if (File.Exists(b))
                        {
                            imgSaved++;
                            saveProgress.Value = imgSaved;
                            lblSaveProgress.Text = imgSaved.ToString() + "/" + imgCount.ToString();
                            if (imgSaved == imgCount)
                            {
                                btnSave.Enabled = true;
                                lblSaveProgress.Text = "FUKKEN SAVED!";
                            }
                        }
                        else ccl.DownloadFileAsync(new Uri(a),b);
                    }
                }
                catch (WebException e)
                {
                    MessageBox.Show(e.Message + e.StackTrace);
                }          
            }

    В пределах одного метода бросаемся из крайности в крайность в именовании переменных.

    A1mighty, 26 Июля 2013

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

    +153

    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
    function showAddForm(node)
    { 
          if(node.attr('e_control') == 1)
          var strOK = "addProduct(\""+node.attr('e_id')+"\",\""+node.attr('e_control')+"\",\""+node.attr('e_name')+"\",\""+node.attr('e_size')+"\", $(\"#count_product_form\")[0].value, $(\"#control_product_form\")[0].checked, \"" + node.attr('e_code') + "\");";
        else
          var strOK = "addProduct(\""+node.attr('e_id')+"\",\""+node.attr('e_control')+"\",\""+node.attr('e_name')+"\",\""+node.attr('e_size')+"\", $(\"#count_product_form\")[0].value, 0, \"" + node.attr('e_code') + "\");";
      
      $('#product_add_window')[0].innerHTML = "<div style='width:100%;text-align:right;font:10px Tahoma;color:blue;'><a href='#' onclick='$(\"#product_add_window\").hide(); return false;'>закрыть</a></div>";
      $('#product_add_window')[0].innerHTML += "<div style='padding:5px;width:100%'><u>Наименование:</u><span style='padding-left:5px;'>"+node.attr('e_name')+"&nbsp;</span></div>";
      
          $('#product_add_window')[0].innerHTML += "<div style='padding:5px;width:100%'><u>Типоразмер:</u><span style='padding-left:5px;'>"+node.attr('e_size')+"&nbsp;</span></div>";
      
          if(node.attr('e_control') == 1)
          $('#product_add_window')[0].innerHTML += "<div style='padding:5px;width:100%'><u>Ободная лента:</u><span style='padding-left:5px;'><input id='control_product_form' type='checkbox' value='"+node.attr('e_control')+"' checked /></span></div>";
      
        
      $('#product_add_window')[0].innerHTML += "<div style='padding:5px;width:100%'><u>Количество:</u><span style='padding-left:5px;'><input id='count_product_form' type='text' value='' checked style='background-color:#f6f6f7; border:1px solid #455064;' onkeydown='if(event.keyCode==13) {sstop=true; $(\"#focusOK\")[0].onclick();} event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true);' onkeyup='this.value = this.value.replace(/[^0-9]/g,\"\");' onclick='event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true);' />&nbsp;</span></div>";
    
      $('#product_add_window')[0].innerHTML += "<div style='padding-top:5px;text-align:right'><input type='button' value='ok' id='focusOK' style='width:50px;height:20px;font-size:11px;' size=5 onclick='"+strOK+"$(\"#product_add_window\").hide();'>&nbsp;<input type='button' value='Отмена' style='width:70px;height:20px;font-size:11px;' onclick='$(\"#product_add_window\").hide();event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true);'></div>";
    	  
      $('#product_add_window').show();
      setTimeout("$('#count_product_form')[0].focus();",200);
      
    }

    clauclauclau, 26 Июля 2013

    Комментарии (12)
  7. Куча / Говнокод #13477

    +124

    1. 1
    "(\{\{([#%$])([^:\}]+)(:([^\}]+))?\}\})"

    Регуляркоговно.
    Заменено на

    "(\{\{([#%$])(.+?)(:(.+))?\}\})"

    vistefan, 25 Июля 2013

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

    +9

    1. 1
    2. 2
    3. 3
    HRESULT hr = ReadGenericXMLFile(srcStorage, pagePath, result);
      if (hr == S_FALSE) return STG_E_FILENOTFOUND;  // File must exist
      if (FAILED(hr)) return hr;

    Могу понять, обратное, когда вызывающая функция просто возвращает "false" при любом неудачном вызове внутренней функции: нет файла / нет доступа / runtime error и т.д. Здесь же наоборот, при "общем" неудачном вызове внутренней функции возвращается "конкретное" сообщение об ошибке.

    Fogbit, 25 Июля 2013

    Комментарии (36)
  9. Java / Говнокод #13475

    +69

    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
    protected String getException (final Exception exception) throws IOException
    {
            final ByteArrayOutputStream bos = new ByteArrayOutputStream ();
            try
            {
                final PrintStream ps = new PrintStream (bos);
                exception.printStackTrace (ps);
            }
            finally
            {
                bos.close ();
            }
    
            return bos.toString ();
    }

    john812, 25 Июля 2013

    Комментарии (0)
  10. C++ / Говнокод #13474

    +17

    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
    struct c_log
    {
      template<typename T> const c_log& operator << (const T& value)
      {
          //...
      }
    };
    
    template<> const c_log& c_log::operator << <p_wstr> (const p_wstr& value)
    {
      fwrite(value, sizeof(wchar_t), wcslen(value), log_file);
      return *this;
    }

    LispGovno, 25 Июля 2013

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