1. Python / Говнокод #5257

    −81

    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
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    import psycopg2
    from loki.libs.net.ipaddr import IPAddress
    import sys
    sys.path.append('../libs/')
    
    try:
        loki_db = psycopg2.connect (port="15432", host="noc2.t72.ru", database="loki_db", user="utkin", password="2UtaWEvaspuv")
        loki_cur = loki_db.cursor()
    except:
        print "Нет коннекта к локи_дб"
    
    try:
        cherry_db = psycopg2.connect (port="5432", host="noc2.72.ru", database="cherry", user="utkin", password="2UtaWEvaspuv")
        cherry_cur = cherry_db.cursor()
    except:
        print "Нет коннекта к черри_дб"
    
    loki_cur.execute("""
    select id, nas_id, service, ip_addr_id from inet_inetsessionactive;
    """);
    
    rows = loki_cur.fetchall()
    
    for (id, nas_id, service, ip_addr_id) in rows:
        loki_cur.execute("""select ip from inet_nasserver where id = %s;""",(nas_id,))
        try:
            nas_ip = loki_cur.fetchone()[0]
        except:
            print "Нет записи о NAS-сервере"
        loki_cur.execute("""select addr from inet_ouripall where id = %s;""",(ip_addr_id,))
    
        ip = str(IPAddress(int(loki_cur.fetchone()[0]))._ip)
    
        cherry_cur.execute("""select client_id, water_mark from inet_dynamic_ip_services where id = %s;""", (service,))
        try:
            (client_id, water_mark) = cherry_cur.fetchone()
        except:
            print "Нет записи в таблице inet_dynamic_ip_services: id, nas_id, service = (%s, %s, %s)"%(id, nas_id, service)
            
        cherry_cur.execute("""select balance from base_clients where client_id = %s;""",(client_id,));
        try:
            balance = cherry_cur.fetchone()[0]
            if balance <= water_mark:
                kill(ip, nas_ip)
        except:
            print "Нет записи в base_clients: client_id = %s"%client_id

    tanenn, 13 Января 2011

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

    +162

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    function check_all(){
    	<?
    		if(!empty($this->params["show"]))  foreach($this->params["show"] as $key_ar => $ar){			
    			echo "document.getElementById('id[".$ar["id"]."]').checked=true; \n";
    		}
    	?>
    }

    Вот так в проектах одной из ведущих компаний по разработке сайтов в моем городе пишут функции для выбора всех checkbox.
    p.s. сам код в HTML файле. $this->params["show"] это массив данных полученный после запроса к mysql (фактически выборка данных из справочника)
    p.p.s на сайте даже jquery подключен.

    supercoder, 13 Января 2011

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

    +119

    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
    public enum PageType
    {
        Default,
        Billing,
        UserCabinet
    }
    
    public PageType GetPageType(int code)
    {
         if(code == 1){return PageType.Default;}
         if(code == 2){return PageType.Billing;}
         if(code == 3){return PageType.UserCabinet;}
         return PageType.Default;
    }
    
    private int PageType
    {
        get
        {
                int page;
                Int32.TryParse(Request["page"], out page);
                return page;
        }
    }

    Думаю что объяснять тут ничего не нужно...

    Arnezami, 13 Января 2011

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

    +112

    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
    static Concept()
            {
                s_deserialize = new Dictionary<string, deserializationHandler>
                                    {{"1.0", (deserialize_1_0)}};
            }
    
            private static void serialize(Concept concept, BinaryWriter writer)
      {
                writer.Write ( concept.Name );
                writer.Write ( concept.Score );
    
                writer.Write ( concept.Documents.Count );
                foreach (var doc in concept.Documents)
                    writer.Write(doc.ToString());
    
                writer.Write ( concept.Nested.Count );
                foreach (var nested in concept.Nested)
                    serialize ( nested, writer );
    }
    
           public static List<Concept> Deserialize(Stream stream)
            {
                using (var reader = new BinaryReader(stream, Encoding.UTF8))
                {
                    var version = reader.ReadString();
                    if (!s_deserialize.ContainsKey(version))
                        throw new NotSupportedException(String.Format("Unsupported version of format. Version: {0}", version));
    
                    var concepts = new List<Concept>(50);
                    s_deserialize[version](null, concepts, reader);
                    return concepts;
                }
            }
    
    private delegate void deserializationHandler(Concept parent, IList<Concept> concepts, BinaryReader reader);
    
    private static readonly Dictionary<string, deserializationHandler> s_deserialize;
    
      private static int s_lastId = 0;
           private static int getNextConceptId()
            {
                if (s_lastId == Int32.MaxValue)
                    s_lastId = 0;
                return System.Threading.Interlocked.Increment(ref s_lastId);
            }
    
    private static void deserialize_1_0(Concept parent, IList<Concept> concepts, BinaryReader reader)
    		{
                for (var i = reader.ReadInt32(); i > 0; i--)
    			{
                    var c = new Concept(reader.ReadString(), reader.ReadDouble(), parent);
    				concepts.Add(c);
    
                    for (var d = reader.ReadInt32(); d > 0; d--)
                        c.Documents.Add(Convert.ToInt32(reader.ReadString()));
    
    				deserialize_1_0(c, c.Nested, reader);
    			}
            }
    }

    Человек в очередной раз изобрел свой велосипед, на этот раз как сериализовать _свои_ классы - с поддержкой версий! По тому что некоторые переменные в классе были помечены [NonSerialized] было похоже что он что то слышал про уже имеющиеся но решил как обычно что самописный - всегда лучше. Но аттрибуты оставил - на всякий пожарный :)

    eval_2009, 13 Января 2011

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

    −97

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    import string
    k=input()
    a=range(1000)
    if k==1:
            a[0]=input()
    else:
            t = string.replace(str(raw_input()), ' ', ', ')
            a=eval('('+t+')')

    4
    2 3 4 5
    ----
    Не знаю я питон :(
    По другому не смог быстро написать..

    Tanger, 13 Января 2011

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

    +161

    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
    function toTrash($id)
        {
            $data = array(
                'order_id'          => $id,
                'order_archived'    => 0,
                'order_trashed'     => 1,
    			'order_candelled' 	=> 0
            );
    
            return $this->update_order($data);
        }
    
        function toArchive($id)
        {
            $data = array(
                'order_id'          => $id,
                'order_archived'    => 1,
                'order_trashed'     => 0,
    			'order_candelled' 	=> 0
            );
    
            return $this->update_order($data);
        }
    
        function restore($id)
        {
            $data = array(
                'order_id'          => $id,
                'order_archived'    => 0,
                'order_trashed'     => 0
    			'order_candelled' 	=> 0
            );
    
            return $this->update_order($data);
        }
    	    
    	function cancelled($id)
    	    {
    	        $data = array(
    	            'order_id'          => $id,
    	            'order_archived'    => 0,
    	            'order_trashed'     => 0,
    				'order_candelled' 	=> 1
    	        );
    
    	        return $this->update_order($data);
    	    }

    DyX_LesA, 12 Января 2011

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

    +170

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    function loger2($comment)
    {
    	$f = fopen(dirname(__FILE__).'/log2.html', 'a+');
    	fwrite($f, $comment);
    	fclose($f);
    }
    function loger($comment)
    {
    	$f = fopen(dirname(__FILE__).'/log.html', 'a+');
    	fwrite($f, $comment);
    	fclose($f);
    }

    loger100500?

    govnozmey, 12 Января 2011

    Комментарии (11)
  8. Ruby / Говнокод #5250

    −104

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    def query(sql)
    		begin
    			@mysql.query(sql)
    		rescue StandardError => err
    			@log.error("Mysql query: '#{sql}\n#{err}'") if @log.class == LoggerHandler
    		end
    	end

    Говнообертка. LoggerHandler - класс, наследующийся от Logger.
    Говнонюанс в том, что Logger.error возвращает true/false в зависимости от того была ли запись в лог успешной, что приводит потом к ошибкам вида NoMethodError: undefined method `each' for true:TrueClass

    govnozmey, 12 Января 2011

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

    +163

    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
    function db_query($sql)
    {
    	global $dbcnx;
    	$k=0;
    	while(!@$res=mysql_query($sql))
    	{
    		if($k>5)
    		{
    			$f=fopen(dirname(__FILE__).'/tmp/error.log','a');
    			fwrite($f,"\n".mysql_error().' in '.$sql."\n");
    			fclose($f);
    			die();
    		}
    		//@mysql_close($dbcnx);
    		//MysqlConnect();
    		$k++;
    	}
    	return $res;
    }

    govnozmey, 12 Января 2011

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

    +160

    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
    function sinonimizer($my_text)
    {
    $arr_ = file(dirname(__FILE__).'/new_words.txt');
    $arr = array();
    foreach ($arr_ as $str)
    {
        $str = trim($str);
    	$t1 = explode('|', $str);
    	$master = trim($t1[0]); //пихаем слово которое заменять
    	if (!isset($t1[1]))
    		continue;
    	$t2 = explode('|', $t1[1]); //Тут слово которым заменять
    	if (sizeof($t2) == 0)
    		continue;
    	//Дальше волшебные мунипуляции
    
    	foreach ($t2 as $t)
    		$arr[crc32(strtolower($master))][crc32(strtolower(trim($t)))] = array('word' =>
    		trim($t), 'rep' => 0);
    }
    $my_text=str_replace(array("\n","\t","\r")," ",$my_text);
    $text_arr = explode(' ', $my_text);
    $str_ = '';
    
    foreach ($text_arr as $item)
    {
    	$fl = false;
    	$t = str_replace('.', '', str_replace(',', '', str_replace('!', '',
    	str_replace('?', '', str_replace('"', '', str_replace('\'', '',
    	str_replace('<', '', str_replace('>', '', str_replace(':', '',
    	str_replace(';', '', $item))))))))));
    	if (isset($arr[crc32(strtolower($t))]))
    	{
    		foreach ($arr[crc32(strtolower($t))] as $k => $v)
        		if ($v['rep'] == 0)
    			{
    				$str_ .= str_ireplace($t, "$v[word]", $item) . ' ';
    				$$v['rep'] = 1;
    				$fl = true;
    				break;
    			}
    	}
    	if (!$fl) $str_ .= $item . ' ';
    }
    
    return $str_;
    }
    
    function sinonimizer_new($my_text)
    {
    $arr_ = file(dirname(__FILE__).'/new_words.txt');
    $arr = array();
    foreach ($arr_ as $str)
    {
        $str = trim($str);
    	$t1 = explode('|', $str);
    	$master = trim($t1[0]); //пихаем слово которое заменять
    	if (!isset($t1[1]))
    		continue;
    	$t2 = explode('|', $t1[1]); //Тут слово которым заменять
    	if (sizeof($t2) == 0)
    		continue;
    	//Дальше волшебные мунипуляции
    
    	foreach ($t2 as $t)
    		$arr[(strtolower($master))][(strtolower(trim($t)))] = array('word' =>
    		trim($t), 'rep' => 0);
    }
    $my_text=str_replace(array("\n","\t","\r")," ",$my_text);
    $text_arr = explode(' ', $my_text);
    
    $str_ = '';
    
    foreach ($text_arr as $item)
    {
    	$fl = false;
    	$t = str_replace('.', '', str_replace(',', '', str_replace('!', '',
    	str_replace('?', '', str_replace('"', '', str_replace('\'', '',
    	str_replace('<', '', str_replace('>', '', str_replace(':', '',
    	str_replace(';', '', $item))))))))));
    
    	if (isset($arr[(strtolower($t))]))
    	{
           
    		foreach ($arr[(strtolower($t))] as $k => $v)
        		if ($v['rep'] == 0)
    			{
    				$str_ .= str_ireplace($t, "$v[word]", $item) . ' ';
    				$$v['rep'] = 1;
    				$fl = true;
    				break;
    			}
    	}
    	if (!$fl) $str_ .= $item . ' ';
    
    
    }
    
    return $str_;

    волшебные мунипуляции

    govnozmey, 12 Января 2011

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