1. C# / Говнокод #5263

    +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
    public IQueryable<AuditEntry> ViewAudit()
    {
    	var items = _operationEntities.AuditItems.AsQueryable();
    
    	return items.Select((item) => new AuditEntry()
    	{
    		OperationID = item.Id,
    		CreationTime = item.CreationTime,
             
    		Description = item.AuditItemType.StringFormat.Replace(
    			"{0}", item.InsertionStrings.Where((x) => x.StringId == 0).Select((x) => x.String).FirstOrDefault() ?? String.Empty).Replace(
    			"{1}", item.InsertionStrings.Where((x) => x.StringId == 1).Select((x) => x.String).FirstOrDefault() ?? String.Empty).Replace(
    			"{2}", item.InsertionStrings.Where((x) => x.StringId == 2).Select((x) => x.String).FirstOrDefault() ?? String.Empty).Replace(
    			"{3}", item.InsertionStrings.Where((x) => x.StringId == 3).Select((x) => x.String).FirstOrDefault() ?? String.Empty).Replace(
    			"{4}", item.InsertionStrings.Where((x) => x.StringId == 4).Select((x) => x.String).FirstOrDefault() ?? String.Empty).Replace(
    			"{5}", item.InsertionStrings.Where((x) => x.StringId == 5).Select((x) => x.String).FirstOrDefault() ?? String.Empty).Replace(
    			"{6}", item.InsertionStrings.Where((x) => x.StringId == 6).Select((x) => x.String).FirstOrDefault() ?? String.Empty).Replace(
    			"{7}", item.InsertionStrings.Where((x) => x.StringId == 7).Select((x) => x.String).FirstOrDefault() ?? String.Empty),
                    
    		CreatedBy = item.CreatedBy,
    		OperationType = item.AuditItemType.MessageType.Name,
    		OperationCategory = item.AuditItemType.AuditCategory.Name,
    	});
    }

    Паровозик. Реализация string.Format() в виде linq-запроса

    _volt, 13 Января 2011

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

    +176

    1. 1
    _ajax("/ajax.js", "script");

    Тянем ajax-функцией файл с ajax-функциями

    fuckyounoob, 13 Января 2011

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

    +114

    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
    TMapObj = record
        Size: integer;
        Selected, Valid: boolean;
        case Kind: TKind of
    // дохрена пропущено
       koTxr: (
            TxrFileName: string [31];
            tLast: integer;
            TxrCorrect: boolean;
            LODS: array [0 .. 3] of TBitmap;
            Pixel: TBitmap;
          );
          koItem: (
            Location: TLocation;
            ItemEndSel: boolean;        // выделена ли для перетаскивания
            TimeBeforeReborn: integer;  // времени до восстановления
            DescrIndex: integer;        // индекс описателя
            Rotation: integer;
    
            TeamColor, EnemyColor: integer;
    
            iLast: integer;
    
            CannotGet: boolean;
    
            case TKindItem of
              kiWeapon: (
                iwpFallen: boolean;
                iwpBulletsLeft: integer;
                iwpState: TWeaponState;
              );
              kiHuman: (
                ihState: integer;
              );
              kiFlag: (
                ifState: TFlagState;
                ifHome: integer;
              );
              kiScepter: (
                isState: TScepterState;
              );
          );
          koItemDescr: (
            ItemFileName: string [31];  // файл с описанием предмета
            idLast: integer;
            ItemCorrect: boolean;
            ItemName: string [31];      // название предмета
            SpriteIndName: string [31];
            SpriteInd: integer;         // картинка
            RebornTime: integer;        // время перерождения
            case KindItem: TKindItem of
              kiHealth: (
                hlCount: integer;
              );                          
              kiShield: (
                shCount: integer;
              );
              kiFlag: (
                flTeam: integer;
              );        
              kiSL: (
                slTeam: integer;
              );
              kiAmmo: (
                amCount: integer;
                amIndex: integer;       // тип патрона
              );
              kiWeapon: (                          // всё про пушку
                wpAmmoIndex: integer;              // тип патронов
                wpKeyNumber: integer;              // кнопка на клавиатуре
                wpBulletsInCharge: integer;        // патронов в обойме
                wpInitBullets: integer;            // изначальное число патронов
                wpMaxBullets: integer;             // максимальное число патронов
                wpShotBullets: integer;            // патронов за раз
                wpReloadTime, wpShotTime: integer; // время перезарядки, скорострельность (скорострельность в миллисекундах)
                wpDispersion, wpKickBack: integer; // разброс самого оружия и отдача
                wpBasic: integer;       // базовое ли
                wpDamage: integer;      // урон
                wpDistance, wpBulletSpeed: integer;    // предельная дальность выстрела, скорость пуль
                wpSound: integer;       // номер ноты
                wpColor: TColor;        // цвет
              );
          );   
          koBullet: (
            bLast: integer;
    
            BLocP: array [0 .. 1] of TPoint;
            BLocRoom: integer;
    
            BVector: TPoint;           // нормализованный вектор направления
    
            BDamage: integer;          // параметры, которые надо передавать в процедуру создания пули
            BSpeed: integer;
            BLengthLeft: integer;
            BOwner: integer;
            Bn, Bm: TDistFunc;
            BColor: TColor;
        );
    end;

    Меня попросили показать, до чего может довести структурное программирование при отрицании ООП. Разветвлённая структура с кучей ветвей.
    Для лучшего эффекта обмазываться вместе с http://govnokod.ru/4249

    TarasB, 13 Января 2011

    Комментарии (4)
  4. Pascal / Говнокод #5260

    +97

    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
    TPicture = class(TInterfacedPersistent, IStreamPersist)
    ....
        property Bitmap: TBitmap read GetBitmap write SetBitmap;
        property Icon: TIcon read GetIcon write SetIcon;
        property Metafile: TMetafile read GetMetafile write SetMetafile;
    ....
    
    procedure TPicture.ForceType(GraphicType: TGraphicClass);
    begin
      if not (Graphic is GraphicType) then
      begin
        FGraphic.Free; // 0_0 йобаный стыд!!
        FGraphic := nil;
        FGraphic := GraphicType.Create;
        FGraphic.OnChange := Changed;
        FGraphic.OnProgress := Progress;
        Changed(Self);
      end;
    end;
    
    function TPicture.GetBitmap: TBitmap;
    begin
      ForceType(TBitmap);
      Result := TBitmap(Graphic);
    end;
    
    function TPicture.GetIcon: TIcon;
    begin
      ForceType(TIcon);
      Result := TIcon(Graphic);
    end;
    
    function TPicture.GetMetafile: TMetafile;
    begin
      ForceType(TMetafile);
      Result := TMetafile(Graphic);
    end;

    Взято из "ДНК", т.е. VCL от Delphi7. unit graphics.pas

    Методы get-аксессоры свойств Bitmap, Icon и Metafile вызывают ForceType(). Шутка в том, что если картинка у вас другого типа - то она будет ВНЕЗАПНО выпилена насовсем, стоит только прочитать(sic!) не то свойство объекта класса TPicture.

    Наступил сам на эти грабли и потратил драгоценный, час пока понял в чем дело.

    StriderMan, 13 Января 2011

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

    +43

    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
    function ntfs_filesize($filename) 
    {
        return exec("
                for %v in (\"".$filename."\") do @echo %~zv
        ");
    }
    // LINUX SERVERS:
    // str perl_filesize( str $filename );
    /*
    DESCRIPTION: returns the filesize of a large file in string format to... 
    ... prevent 32-bit integer walls  using perl through linux command line.
    */
    function perl_filesize($filename) 
    {
        return exec("
                perl -e 'printf \"%d\n\",(stat(shift))[7];' ".$filename."
        ");
    }

    вот вам!
    http://ru.php.net/filesize отсюда.

    вообще ебанутость filesize в пхп теперь не позволит мне без костылей хранить на сайте файлы больше 2х гиг. хнык хнык
    (пока правдо не надо но я попутно свою файлопомойку хочу личную)

    brainstorm, 13 Января 2011

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

    +165

    1. 1
    2. 2
    3. 3
    if(strpos($email,'@')===FALSE)die('error');
    if(strpos($email,'.')===FALSE)die('error');
    if(strlen($email)<7)die('error');

    Четкая проверка почты. Регулярки зря придумывали :)

    assous, 13 Января 2011

    Комментарии (11)
  7. 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)
  8. 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)
  9. 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)
  10. 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)