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

    +32

    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
    #include <iostream>
    #include <vector>
    #include <map>
    #include <algorithm>
    #include <iterator>
    #include <iomanip>
    using namespace std;
    
    vector<string> bracesExpressionExamples = {
    	"({[{}]{}[]})",
    	"({}}{[{}]{}[]})",
    	"({[{}]{}[]}",
    	"({[{}]{}]})",
    	"({[{}{}[]})",
    	"",
    	"{}"
    };
    
    string openBrace = "({[";
    string closeBrace = ")}]";
    
    typedef map<char, char> otc;
    const otc& openToCloseBrace(){
    	static const otc o2c([](){
    		otc o2c;
    		transform(
    			openBrace.begin(), openBrace.end(),
    			closeBrace.begin(),
    			inserter(o2c, o2c.begin()),
    			[](const char open, const char close){return make_pair(open, close);}
    		);
    		return o2c;
    	}());
    	return o2c; 
    }
    
    bool checkBraces (const string& e){
    	vector<char> s;
    	for(const char b: e)
    		if(string::npos!=openBrace.find(b))
    			s.push_back(openToCloseBrace().at(b));
    		else if(string::npos!=closeBrace.find(b) && (!s.empty()) && b==s.back())
    			s.pop_back();
    		else return false;
    	return s.empty();
    }
    
    int main() {
    	cout<<boolalpha;
    	transform(
    		bracesExpressionExamples.begin(),
    		bracesExpressionExamples.end(),
    		ostream_iterator<bool>(cout, "\n"),
    		checkBraces);
    	return 0;
    }

    http://ideone.com/AbO4tw
    Кот с собеседований.
    Проверка правильности расстановки скобок для каждого выражения из bracesExpressionExamples.

    USB, 05 Марта 2014

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

    +127

    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
    import Data.List
    import Data.Maybe
    checkBraces "" = True
    checkBraces e = checkBrace e [] where
    	openBraces = "({["
    	closeBraces = ")}]"
    	braceToBrace fromBraces toBraces brace = toBraces!!(fromJust $ elemIndex brace fromBraces)
    	otcBrace = braceToBrace openBraces closeBraces
    	checkBrace (c:e) s | elem c openBraces = checkBrace e ((otcBrace c):s)
    	checkBrace (c:e) (h:s) | (elem c closeBraces) && (h==c) = checkBrace e s
    	checkBrace (_:e) _ = False
    	checkBrace [] [] = True
    	checkBrace [] _ = False
    main = mapM_ (print . checkBraces) bracesExpressionExamples where
    	bracesExpressionExamples = 
    		[
    			"({[{}]{}[]})",
    			"({}}{[{}]{}[]})",
    			"({[{}]{}[]}",
    			"({[{}]{}]})",
    			"({[{}{}[]})",
    			"",
    			"{}"
    		]

    http://ideone.com/sZ9tiN
    Кот с собеседований.
    Проверка правильности расстановки скобок для каждого выражения из bracesExpressionExamples.

    USB, 05 Марта 2014

    Комментарии (5)
  3. PHP / Говнокод #15359

    +143

    1. 1
    Хуь.

    Кто хочет глотнуть спермы?

    xyja4it, 05 Марта 2014

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

    +139

    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
    foreach (sp_GetPropertiesAffiliateResult paf in PropertiesAffiliate)
                {
    ...
     phConfigAffiliate.Controls.Add(new LiteralControl("<tr>"));
                    phConfigAffiliate.Controls.Add(new LiteralControl("<td><strong>"));
                    phConfigAffiliate.Controls.Add(litPropertyId);
                    phConfigAffiliate.Controls.Add(new LiteralControl("</strong></td>"));
                    phConfigAffiliate.Controls.Add(new LiteralControl("<td><strong>"));
                    phConfigAffiliate.Controls.Add(litPropertyName);
                    phConfigAffiliate.Controls.Add(new LiteralControl("</strong></td>"));
                    phConfigAffiliate.Controls.Add(new LiteralControl("<td>"));
                    phConfigAffiliate.Controls.Add(txtPropertyCode);
                    phConfigAffiliate.Controls.Add(rfvTxtPropertyCode);
                    phConfigAffiliate.Controls.Add(new LiteralControl("</td>"));
                    phConfigAffiliate.Controls.Add(new LiteralControl("<td>"));
                    phConfigAffiliate.Controls.Add(new LiteralControl(@"<table cellpadding=""2"" cellspacing=""2"" border=""0"">"));
                    phConfigAffiliate.Controls.Add(new LiteralControl("<tr>"));
                    phConfigAffiliate.Controls.Add(new LiteralControl(@"<td style=""border: 0px;"">"));
    
    ....
    }

    brusini, 05 Марта 2014

    Комментарии (5)
  5. PHP / Говнокод #15353

    +164

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    function boolConvert($value){
            if(strtolower($value)=='true')
                return 1;
            if(strtolower($value)=='false')
                return 0;
            return $value;
        }

    GoodTalkBot, 05 Марта 2014

    Комментарии (27)
  6. PHP / Говнокод #15352

    +130

    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
    public static function checkUserRights($project, $user, $action, $allowView = false)
        {
    
            $action_id = Actions::getActionIdByName($action);
            $user_role = ProjectsRoles::getUserRoleInProject($project, $user);
    
            if(is_null($user_role))
                HUtils::Exception(403);
    
            $roles = Roles::getRolesOrderedByWeight();
    
            $user_role = $user_role->role;
    
            foreach($roles as $role)
            {
    
                if($role->weight <= $user_role)
                {
                    $user_role -= $role->weight;
                    if(in_array($action_id,HUtils::Parse($role->actions)))
                        return 1;
                }
    
            }
    
            if(!$allowView)
                HUtils::Exception(403);
        }

    Функция проверки прав.

    $allowView в конце функции намекает, что доступ получен не будет. Никогда. Вроде бы.

    nulreferense, 04 Марта 2014

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

    +75

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    private boolean isShowPosition(List<Integer> lists, int p) {
            for (int l : lists) {
                if (p == l)
                    return true;
            }
            return false;
        }

    Вьетнамское творчество

    AAverin, 04 Марта 2014

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

    +163

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    require_once('bbcode.php');
    
    $bbcode_ = $bbcode;
    global $bbcode;
    $bbcode = $bbcode_;
    
    bbcode_format($text);

    При этом:
    function bbcode_format($str, $bbcode = false)

    arkham_vm, 04 Марта 2014

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

    −95

    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
    # ~*~ coding: utf8 ~*~
    
    def clear_string(str, to_int = None):
        '''
        Чистим строку от "мусора" - нечисловых символов.
        '''
        new_str = ''
        for s in str:
            # сначала ищем точку (вдруг число с плавающей точкой)
            # при этом в новой строке не должно быть больше одной точки
            # и в условии to_int не определен
            if s == '.' and '.' not in new_str and not to_int:
                new_str += s
            else:
                try:
                    i = int(s)
                    new_str += s
                except:
                    pass
        return new_str
    
    def str_to_int(str):
        '''
        Преобразование стоки в целое число
        '''
        # попробуем воспользоваться самым простым методом
        try:
            return int(str)
        except:
            # если не получилось, то проверяем почему? допускаем, что было передано не целое число в строке
            if '.' in str:
                str = str[0:str.find('.')]
                return str_to_int(str)
            else:
                # если уж совсем дела плохи, то возвращаем 0
                return 0
    
    def check_int(str):
        try:
            int(str)
            return True
        except:
            return False
    
    def str_to_float(str):
        '''
        Преобразование стоки в число с плавающей точкой
        '''
        # попробуем воспользоваться самым простым методом
        try:
            return float(str)
        except:
            # других вариантов не осталось. скорее всего функция приняла на входе мусор
            return 0
    
    def check_float(str):
        try:
            float(str)
            return True
        except:
            return False
    
    # есть у нас незатейливая строка
    str = 'a23d.d.5ff6'
    # проверяем функцию чистки строки
    print('Чищеная строка: %s' % clear_string(str))
    print('Чищеная строка с to_int: %s' % clear_string(str, to_int=True))
    # до преобразования строки в число следовало бы почистить ее
    print('Преобразуем мусор в целое число: %s' % str_to_int(str))
    print('Преобразуем чищеную строку в целое число: %s' % str_to_int(clear_string(str)))
    # преобразуем строку в число с плавающей точкой
    print('Преобразуем мусор в число с плавающей точкой: %s' % str_to_float(str))
    print('Преобразуем чищеную строку в число с плавающей точкой: %s' % str_to_float(clear_string(str)))
    
    print('Проверяем, является ли содержимое строки целочисленным: %s' % check_int(str))
    print('Проверяем, является ли содержимое чищеной строки целочисленным: %s' % check_int(clear_string(str, to_int=True)))
    print('Проверяем, является ли содержимое строки числом с плавающей точкой: %s' % check_float(str))
    print('Проверяем, является ли содержимое чищеной строки числом с плавающей точкой: %s' % check_float(clear_string(str)))

    http://www.haikson.com/blogs/hektor/programming/python/python-preobrazovanie-stroki-v-chislo/

    v0ffka, 03 Марта 2014

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

    +161

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    $g_ids = '';
    foreach($gender_ids as $gids) {
    	if($g_ids == '')
    		$g_ids = $gids;
    	else
    		$g_ids = $g_ids.",".$gids;
    }
    return $g_ids;

    угадайте за 5 секунд, что оно делает

    alterionisto, 03 Марта 2014

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