- 1
echo `getent passwd | awk -F: '{ if($1 == "myaut") print $3; }'`Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−119
echo `getent passwd | awk -F: '{ if($1 == "myaut") print $3; }'`Определяет id пользователя myaut. Откопано в старой (моей) переписке. Эх...
+23
//VS 2010 C++
#include <Windows.h>
#include <time.h>
#include <queue>
#pragma comment(lib, "winmm.lib")
char shapeForms[7][4][5][6] = {{{{0,0,0,0,0},{0,0,1,0,0},{0,0,1,0,0},{0,0,1,0,0},{0,0,1,0,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,1,1,1,1},{0,0,0,0,0}},{{0,0,0,0,0},{0,0,1,0,0},{0,0,1,0,0},{0,0,1,0,0},{0,0,1,0,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,1,1,1,1},{0,0,0,0,0}}},{{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,0},{0,0,1,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,0},{0,0,1,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,0},{0,0,1,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,0},{0,0,1,1,0}}},{{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,1},{0,0,0,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,1,0},{0,0,0,1,1},{0,0,0,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,1,0},{0,0,1,1,1},{0,0,0,0,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,1,0},{0,0,1,1,0},{0,0,0,1,0}}},{{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,0},{0,0,0,1,1}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,1,0},{0,0,1,1,0},{0,0,1,0,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,0},{0,0,0,1,1}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,1,0},{0,0,1,1,0},{0,0,1,0,0}}},{{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,1},{0,0,1,0,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,0},{0,0,0,1,0},{0,0,0,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,1,0},{0,1,1,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,1,0,0},{0,0,1,0,0},{0,0,1,1,0}}},{{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,1,1},{0,0,1,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,1,0,0},{0,0,1,1,0},{0,0,0,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,0,1,1},{0,0,1,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,1,0,0},{0,0,1,1,0},{0,0,0,1,0}}},{{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,1},{0,0,0,0,1}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,1,1,0},{0,0,1,0,0},{0,0,1,0,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{0,1,0,0,0},{0,1,1,1,0}},{{0,0,0,0,0},{0,0,0,0,0},{0,0,0,1,0},{0,0,0,1,0},{0,0,1,1,0}}}}, field[32][28] = {0}, shape[5], shape_r[5], modifiers[4][3] = {{0,-1,0},{0,1,0},{1,0,0},{0,0,64}}, keys[4] = {'A', 'D', 'W', 'S'}, keyPressed = -1, lk = 0; //shape - 1: shape state; 2: shape type; 3: y; 4: x;
std::queue<std::pair<COORD, std::pair<char, char>>> paste;
COORD t;
unsigned int Score(0);
void draw(COORD cd, char c) {if((cd.Y = cd.Y - 4)||true) if(cd.Y >= 0) {SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cd);
printf("%c", c);}}
bool next_frame(bool mode, bool isShapeFell) {for(char y(0); y != 5; ++y) {for(char x(0); x != 6; ++x) {t.X = shape[4]+x; t.Y = shape[3]+y; 
			if(shapeForms[shape[2]][shape[1]][y][x] == 1) {if(field[t.Y][t.X] == 0) paste.push(std::make_pair(t, std::make_pair(-37, 1)));
				if(field[t.Y][t.X] == 2 || field[t.Y][t.X] == 3) isShapeFell = true;}else if(field[t.Y][t.X] == 1) paste.push(std::make_pair(t, std::make_pair(32, 0)));}}
	if(isShapeFell) {while(paste.size()) paste.pop();
		if(mode) for(char i(0); i != 31; ++i) for(char j(0); j != 25; ++j) if(field[i][j] == 1) field[i][j] = 3;
		return false;}else {for(paste; paste.size() != 0; paste.pop()) {draw(paste.front().first, paste.front().second.first);
			field[paste.front().first.Y][paste.front().first.X] = paste.front().second.second;}}
	return true;}
bool clearFullLines() {for(char isLineExist(1); isLineExist == 1;) {isLineExist = 0;
		for(char j(0), up(0), down(0), cnt(0); j != 31; (++j) && (cnt = 0)) {for(char i(3); i != 25; ++i) if(field[j][i] == 3) if(j < 5) return false; else cnt++;
			if(cnt == 22) {if(isLineExist == 0 && (isLineExist = 1) && (down = j)) up = j;
			else down = j;}else if(isLineExist == 1 && (Score = Score + down-up+1)) {for(char q = down, tmp(0); q >= char(4); (--q)) for(char p(3); p != 25; (++p) && (tmp = 0)) {for(t.X = p, t.Y = q; tmp == 0; tmp = 1);
					field[q][p] = 0; draw(t, 32);
					if(field[up+q-down-1][p] == 3) draw(t, -37);
					t.Y = up+q-down-1;
					field[q][p] = field[up+q-down-1][p];
					field[up+q-down-1][p] = 0;}
				goto next_search;}}
	next_search:;}
	return true;}
int main() {timeBeginPeriod(2);
	system("mode con cols=42 lines=28");
	srand(clock()+time(NULL));
	memset(field, 2, sizeof(field));
	for(char i(0); i != 28; ++i) for(char j(0), q(0); j != 32; ++j && (q = 0)) for(t.X = i, t.Y = j; q == 0; q = 1) draw(t, -80);
	for(char i(3); i != 25; ++i) for(char j(0), q(0); j != 30; ++j && (q = 0)) for(t.X = i, t.Y = j; q == 0; (q = 1) && (field[j][i] = 0)) draw(t, 32);
	for(int tm = 100;true;) {next_turn: if(!clearFullLines() && printf("You fail!")) {system("pause");
			return 0;}
		for(t.X = 30, t.Y = 5; false;);  
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), t);
		printf("Score: %i ", Score);
		shape[1] = rand()*4/(RAND_MAX+1); shape[2] = rand()*7/(RAND_MAX+1); shape[4] = rand()*20/(RAND_MAX+1)+3;
		for(shape[3] = 0; true; shape[3]++) {for(char h(0); h != 5; ++h) {Sleep(tm); tm = 70;
				for(char i(0); i != 4 && keyPressed == -1; ++i) if(GetKeyState(keys[i]) < 0) keyPressed = i;
				if(keyPressed != -1 && !(lk == keyPressed && lk == 2)) {for(char j(0); j != 5; ++j) shape_r[j] = shape[j];
					shape[4] += modifiers[keyPressed][1]; shape[1] = (shape[1] + modifiers[keyPressed][0])%4;
					tm -= modifiers[keyPressed][2];
					lk = keyPressed;
					keyPressed = -1; 
					if(!next_frame(false, false)) {for(char j(0); j != 5; ++j) shape[j] = shape_r[j];
						if(!next_frame(true, false)) goto next_turn;}}else {if(!next_frame(true, false)) goto next_turn;
					if(keyPressed == -1) lk = -1;
					if(lk != 2) lk = 0;else keyPressed = -1;}}}}}
            Была задача за минимальное кол-во строк реализовать простой тетрис. Особого внимания заслуживает 6 строчка кода. Всё очень плохо?
Управление WSAD.
        
+153
<?php
namespace Custom\Entity;
class slideshow{
    const IBLOCK_ID = SLIDER_ON_INDEX_IBLOCK_ID;
    static function getLabel($type){
        $label = "";
        switch($type){
            case NEW_OF_DAY_ENUM_ID_PROPERTY_MAIN_ARTICLES_IBLOCK_ID:
                $label = '<img class="sticker news_of_day" src="/static/img/labels/news_of_day_l.png"><img class="sticker news_of_day_r" src="/static/img/labels/news_of_day_r.png">';
                break;
            case HOT_ENUM_ID_PROPERTY_MAIN_ARTICLES_IBLOCK_ID:
                $label = '<img class="sticker hot infoBlock rsABlock rsNoDrag" src="/static/img/labels/hot.png">';
                break;
            case SLUH_ENUM_ID_PROPERTY_MAIN_ARTICLES_IBLOCK_ID:
                $label = '<img class="sticker infoBlock infoBlockLeftBlack rsABlock rsNoDrag" src="/static/img/labels/gossip.png">';
                break;
            case ITEM_ENUM_ID_PROPERTY_MAIN_ARTICLES_IBLOCK_ID:
                $label = '<img class="sticker thing_of_week infoBlock rsABlock rsNoDrag" src="/static/img/labels/thing_of_week.png">';
                break;
            case POPULAR_ENUM_ID_PROPERTY_MAIN_ARTICLES_IBLOCK_ID:
                $label = '<img class="sticker most_popular infoBlock rsABlock rsNoDrag" src="/static/img/labels/most_popular.png">';
                break;
            case CHOOSE_ENUM_ID_PROPERTY_MAIN_ARTICLES_IBLOCK_ID:
                $label = '<img class="sticker editors_choice infoBlock" src="/static/img/labels/editors_choice.png">';
                break;
            case BEST_ENUM_ID_PROPERTY_MAIN_ARTICLES_IBLOCK_ID:
                $label = '<img class="sticker the_best infoBlock rsABlock rsNoDrag" src="/static/img/labels/the_best.png">';
                break;
            case NEW_ENUM_ID_PROPERTY_MAIN_ARTICLES_IBLOCK_ID:
                $label = '<img class="sticker new infoBlock rsABlock rsNoDrag" src="/static/img/labels/new.png">';
                break;
        }
        return $label;
    }
}
?>И еще один замечательный пример ChinaCode от "грамотных разработчиков на битриксе, которые знают неймспейсы". Особенно порадовал css-класс rsNoDrag, хотя по большому счету надо было бы данный класс назвать "NoDrugs" и взять на вооружение данным "пейсателям".
+138
/// generic Singleton<T> (потокобезопасный с использованием generic-класса и с отложенной инициализацией)
 
/// <typeparam name="T">Singleton class</typeparam>
public class Singleton<T> where T : class
{
  /// Защищённый конструктор необходим для того, чтобы предотвратить создание экземпляра класса Singleton. 
  /// Он будет вызван из закрытого конструктора наследственного класса.
  protected Singleton() { }
 
  /// Фабрика используется для отложенной инициализации экземпляра класса
  private sealed class SingletonCreator<S> where S : class
  {
    //Используется Reflection для создания экземпляра класса без публичного конструктора
    private static readonly S instance = (S) typeof(S).GetConstructor(
                BindingFlags.Instance | BindingFlags.NonPublic,
                null,
                new Type[0],
                new ParameterModifier[0]).Invoke(null);
 
    public static S CreatorInstance
    {
      get { return instance; }
    }
  }
 
  public static T Instance
  {
    get { return SingletonCreator<T>.CreatorInstance; }
  }
 
}
 
/// Использование Singleton
public class TestClass : Singleton<TestClass>
{
    /// Вызовет защищенный конструктор класса Singleton
    private TestClass() { }
 
    public string TestProc()
    {
        return "Hello World";
    }
}
            Код из Википедии. Создание синглтона на шарпике с излишествами и извращениями
В самом деле, кому нужна инкапсуляция, нам же нужен синглтон
P.S  может я чего не понимаю.
        
+158
public static function getAssoc($constBlock,$const){
        if (defined($constBlock)){
            $arLabels = unserialize($const);
            $assoc = array(
                $arLabels['news_day'] => array(
                    'img' => array(
                        0 => array(
                            'class' => 'sticker infoBlock news_of_day',
                            'big' => '/static/img/labels/news_of_day.png',
                            'small' => '/static/img/labels/news_of_day_s.png'
                        ),
                        /*1 => array(
                            'class' => 'sticker news_of_day_r',
                            'big' => '/static/img/labels/news_of_day_r.png',
                            'small' => '/static/img/labels/news_of_day_s_r.png'
                        ),*/
                    )
                ),
                $arLabels['hot'] => array(
                    'img' => array(
                        0 => array(
                            'class' => 'sticker hot infoBlock',
                            'big' => '/static/img/labels/hot.png',
                            'small' => '/static/img/labels/hot_s.png'
                        )
                    )
                ),
                $arLabels['gossip'] => array(
                    'img' => array(
                        0 => array(
                            'class' => 'sticker infoBlock gossip',
                            'big' => '/static/img/labels/gossip.png',
                            'small' => '/static/img/labels/gossip_s.png'
                        )
                    )
                ),
                $arLabels['thing_of_week'] => array(
                    'img' => array(
                        0 => array(
                            'class' => 'sticker thing_of_week infoBlock',
                            'big' => '/static/img/labels/thing_of_week.png',
                            'small' => '/static/img/labels/thing_of_week_s.png'
                        )
                    )
                ),
                ...
                ...
                ...
                ...
                ...
                $arLabels['new_role'] => array(
                    'img' => array(
                        0 => array(
                            'class' => 'sticker new_role infoBlock',
                            'big' => '/static/img/labels/new_role.png',
                            'small' => '/static/img/labels/new_role_s.png'
                        )
                    )
                )
            );
        }
        return $assoc;
    }Так пишут "грамотные разработчики на битриксе" (они знают неймспейсы). Естественно, что все методы в классах должны быть статическими. Это по-битриксовому, значит правильно. Заполнение массива ChinaStyle, т.е. вручную - это тоже правильно, ибо тоже по-битриксовому. И конечно же, вся эта НЁХ должна храниться в текущем методе. "Циклы? Нет, не слышали... Запросы к базе данных? Битрикс говорит, что это плохо, поэтому мы с уверенностью эти лекции проебали. Зато мы знаем неймспейсы!"
+155
$actions = new BlogsActions;
return $actions::model();платили бы им за строчки кода...
+153
public static function translite($string) {
        $rus=array(
            "A","B","C","D","e","F","G","H","I",
            "J","K","L","M","N","O","P","Q","R",
            "S","T","U","V","W","X","Y","Z",
            "ё","й","ю","ь","ч","щ","ц","у","к",
            "е","н","г","ш","з","х","ъ","ф","ы","в",
            "а","п","р","о","л","д","ж","э","я","с",
            "м","и","т","б","Ё","Й","Ю","Ч","Ь",
            "Щ","Ц","У","К","Е","Н","Г","Ш","З",
            "Х","Ъ","Ф","Ы","В","А","П","Р","О",
            "Л","Д","Ж","Э","Я","С","М","И","Т","Б",
            "-"," ","–","?",'"',",",".","«","»","'","!",
            "/","\\",":",";","<",">","(",")","[","]",
            "{","}","@","#","№","$","%","^","&","*",
            "~");
        $eng = array(
            "a","b","c","d","e","f","g","h","i",
            "j","k","l","m","n","o","p","q","r",
            "s","t","u","v","w","x","y","z",
            "yo","iy","yu","","ch","sh","c","u","k",
            "e","n","g","sh","z","h","","f","y","v",
            "a","p","r","o","l","d","j","е","ya","s",
            "m","i","t","b","yo","iy","yu","ch","",
            "sh","c","u","k","e","n","g","sh","z",
            "h","","f","y","v","a","p","r","o",
            "l","d","j","e","ya","s","m","i","t","b",
            "_","_","_","","","","","","","","",
            "","","","","","","","","","",
            "","","","","","","","","","",
            "");
        $string = str_replace($rus, $eng,  $string);
        if(!empty($string)) {
            return $string;
        }
        else return("");
    }
            Как соответсвует название функции той неведомой херне, которую она делает я так и не понял.
Столько травы у меня нет.
        
+160
{if $smarty.foreach.categories.iteration == 2 || $smarty.foreach.categories.iteration == 4 || $smarty.foreach.categories.iteration == 6 || $smarty.foreach.categories.iteration == 8 || $smarty.foreach.categories.iteration == 10 || $smarty.foreach.categories.iteration == 12  || $smarty.foreach.categories.iteration == 14  || $smarty.foreach.categories.iteration == 16}
      <div class="clear"></div>
{/if}Smarty
+154
if((int)$this->tmpl['detailwindow'] == 4 || (int)$this->tmpl['detailwindow'] == 5 || (int)$this->tmpl['detailwindow'] == 7) {
  } else { 
   echo '<td align="center">' . str_replace("%onclickclose%", $this->tmpl['detailwindowclose'], $this->item->closebutton). '</td>';
  }
            Какая глубина мысли!
Интересно, а чтобы ОНО написало в С++?
        
+138
const bool ShowOkIfAllIsCool = true;
book OK()
{
    return ShowOkIfAllIsCool;
}
bool GetFileExists(string filePath)
{
     return File.Exists(filePath);
}
int GetLengthFileName(string filePath)
{
    return filePath.Lenght;
}
int SetMaxValue(int maxValue)
{
    _OPENWINDOWSAFTERINITIALIZATION = maxValue;
}Программированием занимаюсь много лет, а так и не могу понять, для чего создавать подобные методы в 1 строку и константы заглавными буквами огромной длины? Их люди пишут или это автоматически созданный код какой-то прогой? В чужих программах такое часто можно встретить.