1. Си / Говнокод #24208

    +1

    1. 1
    x & (x-1);

    Написавший это утверждает, что меняется содержимое памяти, но как происходят эти мистические изменения он объяснить не может.

    Ioann_Zid, 01 Мая 2018

    Комментарии (13)
  2. PHP / Говнокод #24204

    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
    <!DOCTYPE html>
    <html>
    <head>
    	<title>Change login</title>
    </head>
    <body>
    <form method="POST">
    <p>Input your new e-mail</p>
    <input type="text" name="email" type="e-mail" placeholder="[email protected]"><br><br>
    <button>Sumbit</button>
    </form>
    <?php
    session_start();
    if(isset($_POST['email'])) {
    	require_once 'connection.php';
        //подключение БД
    	 $link = mysqli_connect($host,$user,$password,$database)
         or die("Error with connection to DB".mysqli_error($link));
         //записываем в переменную для удобства
         $email = $_POST['email'];
         if($email != '') {
         	$select = "SELECT mail from users";
            $query = "UPDATE users SET mail = '$email' WHERE username = '{$_SESSION['username']}'"
            or die("Update error!".mysqli_error($link));
                    //записать все логины,для проверки одинаковых данных
            $check = mysqli_query($link,$select);
            //количество записей в запросе на выбор
            $rows = mysqli_num_rows($check);
            $bool = true;
            for($i = 0; $i < $rows; $i++) {
                //извлекаем отдельную строку
                $row = mysqli_fetch_row($check);
                //перебор по ячейкам текущей строки
                for($j = 0; $j < 1; $j++) {
                //если такой пользователь уже есть,то выводим ошибку и завершаем цикл
                if($email == $row[$j]) {
                    echo "e-mail is already exist";
                    $bool = false;
                    break;
                }
            }
            }
            //если такого пользователя нет,то заносим запись в БД
            if($bool) {
            $result = mysqli_query($link,$query) or die("Ошибка " . mysqli_error($link));
                    if($result) {
                echo "e-mail changed";
                mail($email,"Смена адреса","Вы успешно сменили e-mail адрес!");
            }
             }
            //закрываем подключение
            mysqli_close($link);
         }
    }
    ?>
    </body>
    </html>

    Собственно говоря смена адреса электронной почты на PHP,как бы исправить этот говнокод,чтобы он выглядел чуточку элегантней?

    Mark96, 28 Апреля 2018

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

    +4

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    var net = require("net");
    Array.from({ length: 1000 }, (x, i) => i).map(id => makeClient(id));
    function makeClient(id) {
      var client = net.createConnection({ host: "46.101.246.194", port: 80 }, () =>
        console.log(`[${id}] connected`)
      );
      client.on("end", () => console.log(`[${id}] disconnect`));
      return client;
    }

    govnokod dudos script

    ec80dbca-8f52-4517, 28 Апреля 2018

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

    +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
    /**
    * Вхождения слова "питушня" в говнокодах по языкам
    */
    
    {
         "C++": 124,
         "PHP": 56,
         "Куча": 54,
         "C": 41,
         "JavaScript": 39,
         "C#": 25,
         "Python": 11,
         "Java": 10,
         "Pascal": 8,
         "SQL": 7,
         "VisualBasic": 2,
         "Swift": 2,
         "ActionScript": 1,
         "Assembler": 1,
         "Perl": 1,
         "Haskell": 1,
         "Ruby": 1,
         "1C": 0,
         "Lua": 0,
         "Objective C": 0,
         "bash": 0
    }

    mazhuravlev, 28 Апреля 2018

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

    −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
    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
    from itertools import *
    
    lines = tuple ( chain ( ( tuple ( product ( *g ( range ( 3 ) , ( i , ) ) ) ) for g in ( lambda i , j : ( i , j ) , lambda i , j : ( j , i ) ) for i in range ( 3 ) ) , ( ( ( 0 , 0 ) , ( 1 , 1 ) , ( 2 , 2 ) ) , ( ( 2 , 0 ) , ( 1 , 1 ) , ( 0 , 2 ) ) ) ) )
    
    def aimove ( table , i , j ) :
        from random import choice
        possiblewin = ( lambda x : ( lambda f : ( lambda x : len ( x ) and x [ 0 ] ) ( tuple ( filter ( lambda x : x , map ( f , lines ) ) ) ) ) ( lambda k : 2 == sum ( table.get ( i ) == x for i in k ) and ( lambda e : len ( e ) == 1 and e [ 0 ] ) ( tuple ( i for i in k if not table.get ( i ) ) ) ) )
        return ( ( 1 , 1 ) if ( 1 , 1 ) not in table.keys() else possiblewin ( -1 ) or possiblewin ( 1 ) or ( lambda : ( lambda x : x if table.get ( x ) == None else ( lambda x : len ( x ) and x [ 0 ] ) ( tuple ( filter ( lambda x : not table.get ( x ) , permutations ( ( 0 , 2 ) ) ) ) ) ) ( ( 2 * ( i == 0 ) , 2 * ( j == 0 ) ) ) ) () or ( lambda : choice ( tuple ( filter ( lambda x : x not in table.keys() , product ( *tee ( range ( 3 ) ) ) ) ) ) ) () )
    
    iseog = lambda table : ( lambda x : len ( x ) and x [ 0 ] ) ( tuple ( filter ( lambda x : abs ( x ) == 3 , ( sum ( table [ ij ] for ij in keys if table.get ( ij ) ) for keys in lines ) ) ) ) or len ( table ) >= 9
    
    table = {}
    eog = 0
    
    while not eog :
        i , j = map ( int , input ( "введите координаты: " ) .split() )
        if ( i , j ) in table.keys() :
            print ( "эта клетка занята" )
            continue
        if i not in range ( 3 ) or j not in range ( 3 ) :
            print ( "неправильные координаты" )
            continue
        table [ i , j ] = 1
        eog = iseog ( table )
        if not eog :
            table [ aimove ( table , i , j ) ] = -1
            eog = iseog ( table )
        for ij in product ( *tee ( range ( 3 ) ) ) :
            print ( ( " " , "x" , "o" ) [ table.get ( ij ) or 0 ] , end = ( " | " , " | " , "\n" ) [ ij [ 1 ] ] )
            if ij [ 0 ] < 2 and ij [ 1 ] == 2 :
                print ( "--+---+--" )
    
    print ( ( "ничья. тебе везёт ( пока что )" , "ты победил. ах ты жульник!" , "ты продул, а я победил. бе-бе-бе!" ) [ eog // 3 ] )

    Лямбда. Лямбда. Хуямбда.

    yet_another_one_shit, 27 Апреля 2018

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

    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
    /**
     * Peetushna
     * Node.js 10
     * node index.js > report.csv
     */
    
    const { get } = require("axios");
    const { load } = require("cheerio");
    
    Promise.resolve().then(async () => {
      const responses = reqGen(1, 25000);
      const peetushna = /питушня/g;
      for await (const resp of responses) {
        if (resp.status != 200) break;
        const wordCount = resp.data.match(peetushna);
        const count = wordCount ? wordCount.length : 0;
        const html = load(resp.data);
        const lang = html('a[rel="chapter"]')
          .text()
          .replace("Си", "C");
        console.log(`"${lang}", ${count}`);
      }
    });
    
    async function* reqGen(first, max) {
      while (first <= max) {
        try {
          const resp = await get("http://govnokod.ru/" + first++);
          yield resp;
        } catch (e) {
          //
        }
      }
    }

    mazhuravlev, 27 Апреля 2018

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

    +2

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    struct Bar {};
    
    class Foo {
    public:
        Bar& bar() const { return *bp; }
    
    private:
        Bar b;
        Bar * const bp = &b;
    };

    https://wandbox.org/permlink/7JPzrvslrUwbvREb

    Как называется данный говнопаттерн?

    Elvenfighter, 27 Апреля 2018

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

    −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
    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
    function running(html, clear) {
    	var	id, brk = true;
    	if(clear)
    		html.className = "";
    	if(html.className != "Ready") {
    		if(html.children.length > 0) {
    			if(!clear) {
    				for(id = 1; id < html.childNodes.length; ++ id) {
    					var	active = findActive(html.childNodes[id]);
    					if(active == null) {
    						brk = true;
    						break;
    					}
    					brk = active.className != "Ready" ? false : brk;
    				}
    			}
    			if(!brk && html.childNodes[0].value && html.childNodes[0].max) {
    				if(clear)
    					html.childNodes[0].value = 1;
    				else
    				if(html.childNodes[0].value <= html.childNodes[0].max) {
    					++ html.childNodes[0].value;
    					if(brk) {
    						for(id = 1; id < html.childNodes.length; ++ id)
    							findActive(html.childNodes[id], true);
    						html.parentNode.className = "";
    					}
    					return null;
    				} else {
    					html.parentNode.className = "Ready";
    					html.className = "";
    					return html;
    				}
    			}
    			if(!clear)
    				html.className = html.className != "Active" ? "Active" : "Ready";
    			return null;
    		} else {
    			if(!clear)
    				html.className = html.className != "Active" ? "Active" : "Ready";
    			return html;
    		}
    	}
    	return html;
    }

    Должен бегать по вложенным элементам и анимировать их.

    Alikberov, 27 Апреля 2018

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

    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
    using (var stream = File.Open(inFile, FileMode.Open))
    using (var reader = new StreamReader(stream))
    using (var csvReader = new CsvReader(reader, new Configuration
    {
    HeaderValidated = HeaderValidated,
    MissingFieldFound = null,
    PrepareHeaderForMatch = header =>
        CultureInfo.CurrentCulture.TextInfo.ToTitleCase(header)
    }))
    using (var outStream = File.Open(outFile, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
    using (var writer = new StreamWriter(outStream))
    using (var csvWriter = new CsvWriter(writer))

    mazhuravlev, 26 Апреля 2018

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

    −6

    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
    /* Q: Can someone recommend a more elegant way to achieve these compile-time constants? */
    template <int> struct Map;
    template <> struct Map<0> {static const int value = 4;};
    template <> struct Map<1> {static const int value = 8;};
    template <> struct Map<2> {static const int value = 15;};
    
    template <int> struct MapInverse;
    template <> struct MapInverse<4> {static const int value = 0;};
    template <> struct MapInverse<8> {static const int value = 1;};
    template <> struct MapInverse<15> {static const int value = 2;};
    
    
    /* A: Another TMP approach for a linear search using C++11: */
    #include <type_traits>
    
    // === Types:
    // Usage:
    //    Function<Map<x1,y1>,Map<x2,y2>,...>
    template<int D, int R> struct Map { enum { domain=D, range=R }; };
    template<typename ...A> struct Function {};
    
    // === Metafunctions:
    // Usage:
    //    ApplyFunction<x,F>::value
    template<int I, typename M> struct ApplyFunction;
    // Usage:
    //    ApplyFunctionInverse<x,F>::value
    template<int I, typename M> struct ApplyFunctionInverse;
    
    // ==== Example:
    // Define function M to the mapping in your original post.
    typedef Function<Map<0,4>,Map<1,8>,Map<2,15>> M;
    
    // ==== Implementation details
    template<typename T> struct Identity { typedef T type; };
    template<int I, typename A, typename ...B> struct ApplyFunction<I, Function<A,B...> > {
       typedef typename
          std::conditional <I==A::domain
                           , Identity<A>
                           , ApplyFunction<I,Function<B...>> >::type meta;
       typedef typename meta::type type;
       enum { value = type::range };
    };
    template<int I, typename A> struct ApplyFunction<I, Function<A>> {
       typedef typename
           std::conditional <I==A::domain
                            , Identity<A>
                            , void>::type meta;
       typedef typename meta::type type;
       enum { value = type::range };
    };
    // Linear search by range
    template<int I, typename A> struct ApplyFunctionInverse<I, Function<A>> {
       typedef typename
           std::conditional <I==A::range
                            , Identity<A>
                            , void>::type meta;
       typedef typename meta::type type;
       enum { value = type::domain };
    };
    template<int I, typename A, typename ...B> struct ApplyFunctionInverse<I, Function<A,B...> > {
       typedef typename
           std::conditional <I==A::range
                            , Identity<A>
                            , ApplyFunctionInverse<I,Function<B...>> >::type meta;
       typedef typename meta::type type;
       enum { value = type::domain };
    };
    
    // ==============================
    // Demonstration
    #include <iostream>
    int main()
    {
       // Applying function M
       std::cout << ApplyFunction<0,M>::value << std::endl;
       std::cout << ApplyFunction<1,M>::value << std::endl;
       std::cout << ApplyFunction<2,M>::value << std::endl;
    
       // Applying function inverse M
       std::cout << ApplyFunctionInverse<4,M>::value << std::endl;
       std::cout << ApplyFunctionInverse<8,M>::value << std::endl;
       std::cout << ApplyFunctionInverse<15,M>::value << std::endl;
    }

    Элегантненько.
    s: https://stackoverflow.com/questions/26075969/compile-time-map-and-inverse-map-values

    gost, 25 Апреля 2018

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