- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
private static void GetUserData(User user)
{
if (user == null)
return;
var firm = user.Firm;
if (firm == null)
return;
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+134
private static void GetUserData(User user)
{
if (user == null)
return;
var firm = user.Firm;
if (firm == null)
return;
}
Бессмысленно и беспощадно.
−137
<?php
if($argc<2) exit(0);
print_r($tmp);
for($i=1;$i<=$argc;$i++)readdir_rec($argv[$i]);
function readdir_rec($path){
$dir = opendir($path);
global $size;
while($d = readdir($dir)){
if ($d == '.' || $d == '..') continue;
if (is_file($path.'/'.$d)){
echo $path."/".$d."\n";
}
else if (is_dir($path.'/'.$d)) readdir_rec($path.'/'.$d);
}
}
?>
#!/bin/bash
c=0;
declare -a fls;
for fl in `php /home/markus/bin/ps2.php $*`
do
let c++;
fls[$c]=$fl;
done
for((i=0;i<=${#fls[@]}-1;i++))
{
for((i2=$i+1;i2<=${#fls[@]};i2++))
{
echo "${fls[$i]} ${fls[$i2]}";
diff -acBi --brief ${fls[$i]} ${fls[$i2]}
}
}
Находит одинаковые файлы по содержанию
−126
#!/bin/bash
c=0;
declare -a fls;
cat $*| while read line
do
# echo "line $line №$c"
fls[$c]=$line;
let c++;
for((i=0;i<=${#fls[@]}-1;i++))
{
for((i2=$i+1;i2<=${#fls[@]};i2++))
{
# echo "${fls[$i]} ${fls[$i2]}";
if [ ${fls[$i]} = "${fls[$i2]}" ];then
echo "Zeile $i ist gleich Zeile $i2";
#else
# echo "Строка $i не равна строке $i2";
fi
}
}
done
Находит одинаковые строки в файле
+195
for($j=0;$j<23000000;$j++); //пауза ~3 сек
Ну как вам? :)
+154
<?php
require_once('MultiAutoload.php');
class Dispatcher {
private $handle;
function __construct($event_handle) {
$this->handle = $event_handle;
}
function handleEvent() {
$name = 'Handler_'.$this->handle;
if (class_exists($name)) {
$handler_obj = new $name($this->handle);
$response = $handler_obj->secureHandler();
return $response;
}
else {
throw new Exception('Event handling is impossible!');
}
}
}
?>
Немного экзотики: PHP в стиле Win32! Говно за собой не сразу увидел,
но когда "пришло озарение" было смешно.
+127
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-запроса
+176
_ajax("/ajax.js", "script");
Тянем ajax-функцией файл с ajax-функциями
+114
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
+97
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.
Наступил сам на эти грабли и потратил драгоценный, час пока понял в чем дело.
+43
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х гиг. хнык хнык
(пока правдо не надо но я попутно свою файлопомойку хочу личную)