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

    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
    u_long thisIp = htonl(this->sockaddr.sin_addr.S_un.S_addr);
        u_long otherIp = htonl(other.sockaddr.sin_addr.S_un.S_addr);
        u_short thisPort = htons(this->sockaddr.sin_port);
        u_short otherPort = htons(other.sockaddr.sin_port);
    
        // ip1 + port1 < ip2 + port2
        if (thisIp < otherIp)
        {
            if (thisPort <= otherPort)
            {
                return true;
            }
            else
            {
                return ((unsigned)(thisPort - otherPort) < (unsigned)(otherIp - thisIp));
            }
        }
        else
        {
            if (thisPort >= otherPort)
            {
                return false;
            }
            else
            {
                return ((unsigned)(thisIp - otherIp) < (unsigned)(otherPort - thisPort));
            }
        }

    Сравнить IPv4 адрес + порт. Т.е., по сути, (thisIP + thisPort) < (otherIP + otherPort).
    unsigned long long, приди!

    gost, 21 Мая 2016

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

    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
    // jquery required
    
    function trim(str){
    	return str.replace(/^\s+/, "").replace(/\s+$/, "");
    }
    
    function round1000(val){
    	return Math.round(parseInt(val)/1000)*1000;
    }
    function floor1000(val){
    	return Math.floor(parseInt(val)/1000)*1000;
    }
    function ceil1000(val){
    	return Math.ceil(parseInt(val)/1000)*1000;
    }
    
    function setCookie(c_name,value,expiredays){
    	var exdate=new Date();
    	exdate.setDate(exdate.getDate()+expiredays);
    	document.cookie=c_name+'='+escape(value)+((expiredays==null)?'':';expires='+exdate.toGMTString())+';path=/';
    }
    
    function resetCookie(c_name){
      var exdate=new Date(0);
    	document.cookie = c_name + '=0;expires=' + exdate.toUTCString() + ';path=/';
    }
    
    function getCookie(name){
    	var cookies=document.cookie.split(";");
    	for(var i=0;i<cookies.length;i++){
    		var params=cookies[i].split("=");
    		if(trim(params[0])==name){
    			return unescape(params[1]);
    		}
    	}
    	return false;
    }
    
    function asyncScriptLoader(scriptUrl){
    	var d=document,
    	h=d.getElementsByTagName('head')[0],
    	s=d.createElement('script');
    	s.type='text/javascript';
    	s.async=true;
    	s.src=scriptUrl;
    	h.appendChild(s);
    }

    http://www.morton.ru/images/js/main.js

    >> // jquery required
    >> function asyncScriptLoader(scriptUrl){

    nik757, 20 Мая 2016

    Комментарии (13)
  3. C++ / Говнокод #20047

    +3

    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
    bool  Object::DeleteDouble(void* data)
        {
            Element* rc = Head;
            BANKCLIENT* asd = (BANKCLIENT*)rc->Data;
            int dbl;
            Element* rc1 = Head;
            BANKCLIENT* asd1 = (BANKCLIENT*)rc1->Data;
            while ((rc != NULL) && (rc->Data != data))
            {
                asd = (BANKCLIENT*)rc->Data;
                dbl = asd->NumScore;
                while ((rc1 != NULL) && (rc1->Data != data))
                {
                    asd1 = (BANKCLIENT*)rc1->Data;
                    if (dbl == asd1->NumScore)
                    {
                        std::cout << "Дублирующийся элемент удалён" << std::endl;
                        Delete(rc1);
                        goto flag;
                    }
                }
            }
        flag:
            system("pause");
            return rc;
        }

    Некая svetlana.kotik раскрывает секреты односвязных списков.

    Fluttie, 20 Мая 2016

    Комментарии (71)
  4. PHP / Говнокод #20045

    −3

    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
    98. 98
    99. 99
    <?php
    namespace AppBundle\Command;
    
    use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
    use Symfony\Component\Console\Input\InputArgument;
    use Symfony\Component\Console\Input\InputOption;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class InterpolationLabsCommand extends ContainerAwareCommand
    {
    
        /**
         * nodes for interpolation polynomial
         */
        protected $_nodes;
    
    
        protected function configure()
        {
            $this
                ->setName('app:interpolation:labs')
                ->setDescription('interpolation')
                ->addOption('nodes-count', null, InputOption::VALUE_REQUIRED, 
                    'Sets the number of nodes for interpolation.', null);
        }
    
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $intervalStart = -3;
            $intervalEnd  = 3;
    
            $nodesCount = $input->getOption('nodes-count');
            
            $this->generateSeries($nodesCount, $intervalStart, $intervalEnd, function($x) {
                return sin($x);
            });
    
            foreach (range($intervalStart, $intervalEnd, 0.1) as $value) {
    
                $result = $this->getLagrangeValue($value);
                $output->writeln("$value $result");
            }
        }
    
        /**
         * Find value for lagrange interpolation polynomial at n nodes
         * @throw \Exception
         * 
         * @return 
         */
        protected function getLagrangeValue($x)
        {
    
            $w = function($nodeKey) use ($x) {
    
                if (!array_key_exists($nodeKey, $this->_nodes)) {
                    throw new \Exception("The key is not exists to the array nodes");
                }
    
                $return = 1;
                foreach ($this->_nodes as $key => $node) {
                    if ($key == $nodeKey) {
                        continue;
                    }
    
                    $return *= ($x - $node->x)/($this->getNode($nodeKey)->x - $node->x);
                }
                return $return;
            };
    
            $result = 0;
            foreach ($this->_nodes as $nodeKey => $node) {
                $a = $w($nodeKey);
    
                $result += $w($nodeKey) * $node->fx;
            }
    
            return $result;
    
        }
    
        protected function getNode($i)
        {
            return $this->_nodes[$i];
        }
    
    
        private function generateSeries($num,  $intervalStart, $intervalEnd,  $fun)
        {
            for ($i=0; $i < $num; $i++) { 
    
                $x  = $intervalStart + ($intervalEnd - $intervalStart)/($num-1) * $i;
                $this->_nodes[] = (object) array('x' => $x, 
                    'fx' => $fun($x)); 
            }
        }
    }

    Лаба по методам численного анализа

    konmado, 19 Мая 2016

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

    +6

    1. 1
    2. 2
    Что вообще за херня, почему для каждого язычка(рантайма) делают свой пакетный менеджер? pip, npm, cabal, Quicklisp, opam, nuget, NPMчо там еще?
    И притом все они считают что для языка %LanguageName% всенепременно надо писать пакетный менеджер на нем самом.

    Вот например когда я что-то устанавливл через pip, какая-то там херня требует openssl-devel. И узнаю я это только по ошибкам компиляции, ну т.е. там какая-то поебень криптографическая вызывается из питона, оно при установке компилирует через GCC некое говно которое инклудит какое-то .h говно от openssl, но поскольку этого .h нет, оно обламывается на этапе компиляции. Какого хера я про это должен узнавать только на этапе компиляции блядь? Какого хера я должен вручную разруливать эти говнозависимости? А если например будет программа на руби которая использует программу на лиспе, которая использует программу на хаскеле использующую программу на окамле, то что мне, всю эту поеботу тоже руками разруливать по цепочке?

    https://blog.versioneye.com/2014/01/15/which-programming-language-has-the-best-package-manager/

    какие-то уебни еще сравнивают, какой язык имеет лучший пакетный менеджер... Мудачье! Кто вам сказал что делать для каждого ёбаного языка свой пакетный менеждер это хорошая идея и что среди них может быть "лучший"? Они все говно по определению. Нужно или некое стандартное API для общения между разными пакетными менеджеры разных языков, или один единый пакетный менеджер для всего и под все ОС(а не только Gentoo).

    j123123, 19 Мая 2016

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

    0

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    var languageCodes = locales
                    .GroupBy(l => l.Key.Substring(0, 2))
                    .Select(group => group.First())
                    .Select(l => new KeyValuePair<string, string>(l.Key.Substring(0, 2), l.Value))
                    .OrderBy(l => l.Value);

    Прислала боевая подруга из Канады. Да, это продакшен. Но на этот раз код не падавана, а её собственный.

    kerman, 19 Мая 2016

    Комментарии (34)
  7. PHP / Говнокод #20039

    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
    require_once ('./main/config.php');
    class user 
    {
        /* 
        private login;
        private password;
        private username;
        private about;
        */
        
        function registerUser($login, $password, $username, $about)
        {
            $db = MysqliDb::getInstance();
            $data = Array ("login" => $login,
                   "password" => $password,
                   "username" => $username,
                   "about" => $about,
            );
            $id = $db->insert ('users', $data);
            if($id)
                echo 'user was created. Id=' . $id;
        }
        
        function authorizeUser($login, $password)
        {
            $db->where ("id", 1);
            $user = $db->getOne ("users");
            echo $user['id'];
            /*
            $logins = $db->getValue ("users", "login", null);
            // select login from users
            // select login from users limit 5
            foreach ($logins as $login)
            echo $login;
            */
        }
        
        
    }

    Ну как вам? Класс юзера для регистрации и авторизации (недоделан)

    Folsky, 18 Мая 2016

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

    +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
    public function generate_hash($options = null) {
            $string_length  = (isset($options["length"])) ? $options["length"] : 10;
            $use_lowercase  = (isset($options["lowercase"])) ? $options["lowercase"] : true;
            $use_uppercase  = (isset($options["uppercase"])) ? $options["uppercase"] : true;
            $lowercase      = array(
                "a",
                "b",
                "c",
                "d",
                "e",
                "f",
                "g",
                "h",
                "i",
                "j",
                "l",
                "m",
                "n",
                "o",
                "p",
                "q",
                "r",
                "s",
                "t",
                "u",
                "v",
                "w",
                "x",
                "y",
                "z"
            );
            $uppercase      = array(
                "A",
                "B",
                "C",
                "D",
                "E",
                "F",
                "G",
                "H",
                "I",
                "J",
                "L",
                "M",
                "N",
                "O",
                "P",
                "Q",
                "R",
                "S",
                "T",
                "U",
                "V",
                "W",
                "X",
                "Y",
                "Z"
            );
            $digits         = array(
                0,
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                8,
                9
            );
            $arrays         = array_merge($lowercase, $uppercase);
            $final_string   = array();
            $final_string[] = $arrays[array_rand($arrays)];
            // чтобы первым символом не была цифра
            $arrays         = array_merge($arrays, $digits);
            for ($i = 0; $i < ($string_length - 1); $i++) {
                $final_string[] = $arrays[array_rand($arrays)];
            }
            $final_string = implode("", $final_string);
            return $final_string;
    }

    dgkj, 18 Мая 2016

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

    +1

    1. 1
    http://pastebin.com/xww1EKP1

    http://map.vmr.gov.ua/scripts/__RasPil.js - было тут

    j123123, 18 Мая 2016

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

    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
    function * getTreePost(postsInfo, id) {
      var parent = _.filter(postsInfo, function (item) {
        return Boolean(item._id == id);
      });
    
      var children = _.filter(postsInfo, function (item) {
        return Boolean(item.parentId);
      });
    
      return _.union(parent, findChildren(id, children));
    
      function findChildren(parentId) {
        if (parentId) {
          var data = _.where(children, {parentId: parentId});
          var ret = [];
          if (data.length) {
            _.each(data, function (item, index) {
              var data_r = findChildren(item._id);
              if (data_r.length) {
                ret = _.union(data_r, ret);
              }
            });
            return _.union(data, ret);
          } else
            return [];
        } else return [];
      }
    }

    обычная рекурсия

    volodymyrkoval, 18 Мая 2016

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