1. Лучший говнокод

    В номинации:
    За время:
  2. Assembler / Говнокод #20234

    +70

    1. 1
    https://youtu.be/hB6eY73sLV0?t=241

    Исполнение произвольного кода(в данном случае Flappy Bird) в Super Mario World. Запись инструкций в память происходит посредством прыжков в нужных координатах.

    j123123, 20 Июня 2016

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

    +70

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    List<Integer> positionList = new ArrayList<Integer>(positions.keySet());
    Collections.sort(positionList, new Comparator<Integer>() {
        @Override
        public int compare(Integer lhs, Integer rhs) {
            if (lhs > rhs) {
                return 1;
            } else if (lhs < rhs) {
                return -1;
            }
            return 0;
        }
    });

    Видать разработчику за кол-во написанных строк платили...

    tony777, 13 Июля 2015

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

    +70

    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
    public class ConcurrentStringStatsProvider implements StringStatsProvider {
        private final ExecutorService executor;
        private final ExecutorCompletionService<CharCounter> service;
        private final int threadNum;
    
        public ConcurrentStringStatsProvider() {
            //http://stackoverflow.com/questions/13834692/threads-configuration-based-on-no-of-cpu-cores
            threadNum = Runtime.getRuntime().availableProcessors() + 1;
            executor = Executors.newFixedThreadPool(threadNum);
            this.service = new ExecutorCompletionService<CharCounter>(executor);
        }
    
        @Override
        public synchronized CharCounter countChars(String str) {
            int length = str.length();
            if (length == 0)
                return new CharCounter();
    
            int chunk = length / threadNum;
            if (chunk == 0)
                chunk = length;
    
            for (int i = 0; i < threadNum; i++) {
                int start = i * chunk;
                int end = (i + 1) * chunk - 1;
                if (end > length) {
                    end = length - 1;
                }
                service.submit(new SubstringTask(start, end, str));
                if (end == length - 1)
                    break; //break early
            }
    
            CharCounter result = null;
            while (true) {
                Future<CharCounter> future = service.poll();
                if (future == null) {
                    if (result != null && result.getTotalCount() == length)
                        break;
                    else
                        continue;
                }
                CharCounter subResult = null;
                try {
                    subResult = future.get();
                } catch (InterruptedException e) {
                    log.error("Failed to calculate. Interrupted: ", e);
                    Thread.currentThread().interrupt();
                } catch (ExecutionException e) {
                    log.error("Calculation error", e);
                    throw new IllegalStateException("Calculation error: ", e);
                }
                if (result == null) {
                    result = subResult;
                } else if (result.equals(subResult)) {
                    break; //!!
                } else {
                    service.submit(new MergeTask(result, subResult));
                    result = null;
                }
            }
            return result;
        }
    
        private class SubstringTask implements Callable<CharCounter> {
            private final int start;
            private final int end;
            private final String str;
    
            public SubstringTask(int start, int end, String str) {
                this.start = start;
                this.end = end;
                this.str = Objects.requireNonNull(str);
            }
    
           @Override
            public CharCounter call() throws Exception {
                return doJob();
            }
    
            private CharCounter doJob() {
                CharCounter charCounter = new CharCounter(end - start + 1);
                for (int i = start; i <= end; i++) {
                    charCounter.increment(str.charAt(i));
                }
                return charCounter;
            }
        }
    
        private class MergeTask implements Callable<CharCounter> {
            private final CharCounter cc1, cc2;
    
            public MergeTask(CharCounter cc1, CharCounter cc2) {
                this.cc1 = Objects.requireNonNull(cc1);
                this.cc2 = Objects.requireNonNull(cc2);
            }
    
            @Override
            public CharCounter call() throws Exception {
                return CharCounter.merge(cc1, cc2);

    Первое знакомство с ExecutorCompletionService, решал задачку подсчета количества символов в строке в несколько потоков.

    nitrogen, 05 Февраля 2015

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

    +70

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    public static List<Defaulter> getDefaulterList() {
    	List<Defaulter> defaulters = new ArrayList<Defaulter>();
    
    	for (Map.Entry<Class<?>, Defaulter> defaulterEntry : hash.entrySet()) {
    		Defaulter def = defaulterEntry.getValue();
    		defaulters.add(def);
    	}
    
    	return defaulters;
    }

    Всё заменилось одной строкой:

    return new ArrayList<Defaulter>(hash.values());

    someone, 12 Декабря 2014

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

    +70

    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
    QString windoliz_path(QString str)
    {
    /*
    функция "виндолизирует" QTшные пути, для передачи в неQTшные части проги
    (в QT-шные, кстати тоже можно, ибо QT вроде бы понимает и те и другие ;)
    если вызвать вне винды ничо страшного, предпроцессор сделает всё за вас
    и функция вернёт ту же строку что и получила. После вызова в виндах не
    помешает сделать .toLocal8Bit()
    //*/
    #ifdef _WIN32                      //если венда
        char s = '\\';                 //символ для замены
        char t = '/';                  //шаблон поиска
        for (int i = str.size();i;i--) //повторить столько раз сколько символов в строке
        {
            if (str[i-1] == t)           //если символ соответствует образцу поиска
            {
                str[i-1] = s;            //меняем на образец замены
            }
        }
    #endif                             //директива отметы условия "если венда"
        return str;
    }

    Этот проект не перестаёт удивлять... апи не смотри, велосипеды пиши. Коммент сохранен авторский.

    kin63camapa, 28 Ноября 2014

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

    +70

    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
    *  Calculates the minimum number of bits necessary to represent the given number.  The
         *      number should be given in its unsigned form with the starting bits equal to 1 if it is
         *      signed.  Repeatedly compares number to another unsigned int called x.
         *      x is initialized to 1.  The value of x is shifted left i times until x is greater
         *      than number.  Now i is equal to the number of bits the UNSIGNED value of number needs.
         *      The signed value will need one more bit for the sign so i+1 is returned if the number
         *      is signed, and i is returned if the number is unsigned.
     * @param number the number to compute the size of
     * @param bits 1 if number is signed, 0 if unsigned
     */
        public static int minBits(int number, int bits)
        {
        int val = 1;
        for (int x = 1; val <= number && !(bits > 32); x <<= 1) 
        {
            val = val | x;
            bits++;
        }
    
        if (bits > 32)
                {
                        assert false : ("minBits " + bits + " must not exceed 32");
                }
        return bits;
    }

    Адоб, как обычно, порадовал (условие окончания цикла).
    [color=blue]https://git-wip-us.apache.org/repos/asf/flex-sdk/repo?p=flex-sdk.git;a=blob;f=modules/swfutils/src/java/flash/swf/SwfEncoder.java;h=03a100dda92989d537b00b 96033d614c73c47801;hb=HEAD#l320[/code]

    wvxvw, 17 Августа 2014

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

    +70

    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
    public void testTranlateScript() throws Exception {
    		// Инициализируем бесконечный цикл переводов. Должен переводить пока не
    		// кончатся тексты, ну или пока не зависнет. Потом кинет Exception.
    		int i = 1;
    		while (true) {
    			int j = 1;
    			// Фильтруем по непереведенному на какой-то язык и нажимаем первую
    			// ссылку "Перевести". Нужно указывать алиас языка на который
    			// переводим в фильтре.
    			driver.findElement(By.id("content_filter_header")).click();
    			System.out.println(i
    					+ "."
    					+ j
    					+ "  "
    					+ "начинаем настройку фильтра "
    					+ driver.findElement(By.id("content_filter_header"))
    							.toString());
    			j++;
    			new Select(driver.findElement(By.id("filter-lang-type")))
    					.selectByVisibleText("Не переведено на язык(и)");
    			driver.findElement(By.id("filter-lang-alias-en")).click();
    			System.out.println(i
    					+ "."
    					+ j
    					+ "  "
    					+ "заканчиваем настройку фильтра "
    					+ driver.findElement(By.id("filter-lang-alias-en"))
    							.toString());
    			j++;
    			driver.findElement(By.name("btn_filter")).click();
    			System.out.println(i + "." + j + "  "
    					+ "нажимаем на кнопку Применить "
    					+ driver.findElement(By.name("btn_filter")).toString());
    			j++;
    			driver.findElements(By.linkText("Перевести")).get(0).click();
    			System.out.println(i
    					+ "."
    					+ j
    					+ "  "
    					+ "нажимаем на первую ссылку Перевести "
    					+ driver.findElements(By.linkText("Перевести")).get(0)
    							.toString());
    			j++;
    			// Ищем оригинальный текст и присваеваем его переменной
    			for (int second = 0;; second++) {
    				if (second >= 60)
    					fail("timeout");
    				try {
    					if (isElementPresent(By.id("original-text")))
    						break;
    				} catch (Exception e) {
    				}
    				Thread.sleep(1000);
    			}
    			// driver.findElement(By.id("original-text")).isDisplayed();
    			String text_to_translate = driver.findElement(
    					By.id("original-text")).getText();
    			System.out.println(i + "." + j + "  " + "текст получен: '"
    					+ text_to_translate + "'     "
    					+ driver.findElement(By.id("original-text")).toString());
    			j++;
    			if ((text_to_translate == null) || (text_to_translate.equals(""))) {
    				System.out.println(i + "." + j + "  "
    						+ "Выход по break (пустой текст):"+ "'" + text_to_translate + "'");
    				j++;
    				break;
    			}
    			// Вот это по идее должно не допускать, пустые стринги в тех
    			// случаях, если не сработал локатор.
    
    			// Идем в гугл и переводим текст из переменной. Тут нужно
    			// указывать
    			// алиасы языков с которого и на который переводим.
    			driver.get("https://translate.google.com/#ru/en/"
    					+ text_to_translate);
    			// Ждем элемент с переведенным текстом и присваиваем его новой
    			// переменной.
    			driver.findElement(By.id("source")).isDisplayed();
    			String text_translated = driver.findElement(By.id("result_box"))
    					.getText();
    			// Возвращаемся на сайт и снова точно также фильтруем.
    			driver.get(baseUrl + "/admin/translate");
    			driver.findElement(By.id("content_filter_header")).click();
    			System.out.println(i
    					+ "."
    					+ j
    					+ "  "
    					+ "снова начинаем настройку фильтра "
    					+ driver.findElement(By.id("content_filter_header"))
    							.toString());
    			j++;
    			new Select(driver.findElement(By.id("filter-lang-type")))
    					.selectByVisibleText("Не переведено на язык(и)");
    			driver.findElement(By.id("filter-lang-alias-en")).click();
    			System.out.println(i
    					+ "."
    					+ j
    					+ "  "
    					+ "снова заканчиваем настройку фильтра "
    					+ driver.findElement(By.id("filter-lang-alias-en"))

    http://pastebin.com/hQdwHepm

    jkhne4pijgberg, 15 Августа 2014

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

    +70

    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
    public class MyFancyException extends Exception {
        
        public MyFancyException(Throwable cause) {
            super(cause);
        }
        
        static public <X extends Throwable> void foo() throws X {
            try {
                throw new MyFancyException(new Exception());
            }
            catch (MyFancyException ex) {
                throw (X) ex.getCause();
            }
        }
        
        
        public static void main(String[] args) throws IOException {
            MyFancyException.<IOException>foo();
        }
    }

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

    aspid812, 27 Июня 2014

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

    +70

    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
    {
    	final int p = page;
    	final boolean current = p == 1;
    	this.pagercell(writer, current, 1, "<<");
    }
    for (int p = page - this.size; p < page; p++) {
    	if (p >= 1) {
    		final boolean current = p == 1;
    		this.pagercell(writer, current, p);
    	}
    }
    {
    	final int p = page;
    	final boolean current = (p - this.size) < 1;
    	this.pagercell(writer, current, p - this.size, "<");
    }
    {
    	final int p = page;
    	final boolean current = p == page;
    	this.pagercell(writer, current, p);
    }
    {
    	final int p = page;
    	final boolean current = (p + this.size) > pages;
    	this.pagercell(writer, current, p + this.size, ">");
    }
    for (int p = page + 1; p <= (page + this.size); p++) {
    	if (p <= pages) {
    		final boolean current = p == pages;
    		this.pagercell(writer, current, p);
    	}
    }
    {
    	final int p = page;
    	final boolean current = p == pages;
    	this.pagercell(writer, current, pages, ">>");
    }

    веселый вывод постраничной навигации (кусок метода)

    Lure Of Chaos, 22 Апреля 2014

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

    +70

    1. 1
    qDebug() << QString("%1-%2").arg("%1").arg("foo");

    LispGovno, 19 Апреля 2014

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