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

    −3

    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
    template<unsigned int I, unsigned int F>
    struct Lua_dispatch_ {
        template<typename R, typename... Args>
        inline static R Lua_dispatch(lua_State*&& lua, Args&&... args) noexcept {
            constexpr ScriptFunctionData const& F_ = ScriptFunctions::functions[F];
            auto arg = luabridge::Stack<typename CharType<F_.func.types[I - 1]>::type>::get(lua, -1);
            return Lua_dispatch_<I - 1, F>::template Lua_dispatch<R>(
                    forward<lua_State*>(lua),
                    arg,
                    forward<Args>(args)...);
        }
    };
    
    template<unsigned int F>
    struct Lua_dispatch_<0, F> {
        template<typename R, typename... Args>
        inline static R Lua_dispatch(lua_State*&&, Args&&... args) noexcept {
            constexpr ScriptFunctionData const& F_ = ScriptFunctions::functions[F];
            return reinterpret_cast<FunctionEllipsis<R>>(F_.func.addr)(forward<Args>(args)...);
        }
    };
    
    template<unsigned int I>
    static typename enable_if<ScriptFunctions::functions[I].func.ret == 'v', int>::type wrapper(lua_State* lua) noexcept {
        Lua_dispatch_<ScriptFunctions::functions[I].func.numargs, I>::template Lua_dispatch<void>(forward<lua_State*>(lua));
        return 0;
    }
    
    template<unsigned int I>
    static typename enable_if<ScriptFunctions::functions[I].func.ret != 'v', int>::type wrapper(lua_State* lua) noexcept {
        auto ret = Lua_dispatch_<ScriptFunctions::functions[I].func.numargs, I>::template Lua_dispatch<typename CharType<ScriptFunctions::functions[I].func.ret>::type>(forward<lua_State*>(lua));
        luabridge::Stack <typename CharType<ScriptFunctions::functions[I].func.ret>::type>::push (lua, ret);
        return 1;
    }
    
    template<unsigned int I>
    struct F_
    {
        static constexpr LuaFuctionData F{ScriptFunctions::functions[I].name, wrapper<I>};
    };
    
    template<> struct F_<0> { static constexpr LuaFuctionData F{"CreateTimer", LangLua::CreateTimer}; };
    template<> struct F_<1> { static constexpr LuaFuctionData F{"CreateTimerEx", LangLua::CreateTimerEx}; };
    
    template<size_t... Indices>
    inline LuaFuctionData *LangLua::functions(indices<Indices...>)
    {
    
        static LuaFuctionData functions_[sizeof...(Indices)]{
                F_<Indices>::F...
        };
    
        static_assert(
                sizeof(functions_) / sizeof(functions_[0]) ==
                sizeof(ScriptFunctions::functions) / sizeof(ScriptFunctions::functions[0]),
                "Not all functions have been mapped to Lua");
    
        return functions_;
    }
    
    void LangLua::LoadProgram(const char *filename)
    {
        int err = 0;
    
        if ((err = terra_loadfile(lua, filename)) != 0)
            throw runtime_error("Lua script " + string(filename) + " error (" + to_string(err) + "): \"" +
                                string(lua_tostring(lua, -1)) + "\"");
    
        constexpr auto functions_n = sizeof(ScriptFunctions::functions) / sizeof(ScriptFunctions::functions[0]);
    
        LuaFuctionData *functions_ = functions(IndicesFor<functions_n>{});
    
        luabridge::Namespace tes3mp = luabridge::getGlobalNamespace(lua).beginNamespace("tes3mp");
    
        for(int i = 0; i < functions_n; i++)
            tes3mp.addCFunction(functions_[i].name, functions_[i].func);
    
        tes3mp.endNamespace();
    
        if ((err = lua_pcall(lua, 0, 0, 0)) != 0) // Run once script for load in memory.
            throw runtime_error("Lua script " + string(filename) + " error (" + to_string(err) + "): \"" +
                                string(lua_tostring(lua, -1)) + "\"");
    }

    Это часть модуля скриптинга на Lua для моего проекта. Так же поддерживаются нативные языки и Pawn.

    Koncord, 13 Мая 2016

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

    +5

    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
    #include <iostream>
    
    namespace __hidden__ {
      struct print {
        bool space;
        print() : space(false) {}
        ~print() { std::cout << std::endl; }
    
        template <typename T>
        print &operator , (const T &t) {
          if (space) std::cout << ' ';
          else space = true;
          std::cout << t;
          return *this;
        }
      };
    }
    
    #define print __hidden__::print(),
    
    int main() {
      int a = 1, b = 2;
      print "this is a test";
      print "the sum of", a, "and", b, "is", a + b;
      return 0;
    }

    Отсюда: [color=violet]http://madebyevan.com/obscure-cpp-features/[/color]

    myaut, 13 Мая 2016

    Комментарии (12)
  3. JavaScript / Говнокод #19991

    0

    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
    /**
     * Static Content Helpers
     */
    (function (window, ng, app) {
    
        app.service('$StaticContentHelpers', function () {
    
            var instance = null;
    
            /**
             * Конструктор хелперов
             *
             * @returns {Object} Функции-хелперы
             * @constructor
             */
            function Init () {
    
                /**
                 * Обертка для статического контента,
                 * добавляет static домен, который пришел с бэкенда
                 *
                 * @param {String} url Урл, к которому необходимо добавить домен для статики
                 *
                 * @return {String} Готовый абсолютный url для статического контента
                 */
                function wrapStaticContent (url) {
                    // Проверим, от корня ли путь
                    return window.currentStaticDomain + ((/(^\/)/.test(url)) ? '' : '/') + url;
                }
    
                return {
                    wrapStaticContent: wrapStaticContent
                }
    
            }
    
            function getInstance () {
                if (!instance) {
                    instance = new Init();
                }
                return instance;
            }
    
            return {
                getInstance: getInstance
            };
    
        });
    
    }(window, angular, mainModule));

    гуру паттернов..

    _finico, 13 Мая 2016

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

    −1

    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
    _colorFlashlightAnimation = compositor.CreateExpressionAnimation(
                      "1.0 - min("
                    + "    1.0,"
                    + "    ("
                    + "        ("
                    + "            ( frame.Offset.x + (frame.Size.x * 0.5) + grid.Offset.x - (windowWidth * 0.5) )"
                    + "          * ( frame.Offset.x + (frame.Size.x * 0.5) + grid.Offset.x - (windowWidth * 0.5) )"
                    + "        ) + ("
                    + "            ( frame.Offset.y + (frame.Size.y * 0.5) + grid.Offset.y - (windowHeight * 0.5) )"
                    + "          * ( frame.Offset.y + (frame.Size.y * 0.5) + grid.Offset.y - (windowHeight * 0.5) )"
                    + "        )"
                    + "    ) / ( radius * radius )"
    + ")");

    Удивитесь, но это Microsoft
    https://github.com/Microsoft/WindowsUIDevLabs/blob/master/Demos/SlideShow/SlideShow/TransitionLibrary.cs

    cherepets, 12 Мая 2016

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

    −1

    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
    typedef std::vector<LogicalTypeNamedItem_t> LogicalTypeNamedItems_t;
    
    class LogicalTypesContainer
    {
    ...
    ...
    ...
    public:
        bool Find(QString Name, QString Type);
        LogicalTypeItems_t m_Result;
    };
    
    
    bool LogicalTypesContainer::Find(QString Name, QString Type)
    {
        for(LogicalTypeNamedItems_t::iterator it = m_LogicalTypeNamedItems.begin();
            it < m_LogicalTypeNamedItems.end(); ++it)
        {
            LogicalTypeNamedItem_t LogicalTypeNamedItem = *it;
            if(QString::compare(LogicalTypeNamedItem.GetName(), Name, Qt::CaseInsensitive) == 0)
            {
                LogicalTypeTypedItems_t LogicalTypeTypedItems = LogicalTypeNamedItem.GetLogicalTypeTypedItems();
                for(LogicalTypeTypedItems_t::iterator devIt = LogicalTypeTypedItems.begin();
                    devIt < LogicalTypeTypedItems.end(); ++devIt)
                {
                    LogicalTypeTypedItem_t LogicalTypeTypedItem = *devIt;
                    if(QString::compare(LogicalTypeTypedItem.GetType(), Type, Qt::CaseInsensitive) == 0)
                    {
                        m_Result = LogicalTypeTypedItem.GetLogicalTypes();
                        return true;
                    }
                }
            }
        }
        return false;
    }

    Есть некий контейнер LogicalTypesContainer, хранящий данные, необходимые во множестве мест. В главном окне приложения создается экземпляр LogicalTypesContainer. У главного окна реализуется интерфейс, возвращающий указатель на данный объект. Далее во все мыслимые и немыслимые места передается указатель на форму главного окна. Суть приведенного фрагмента кода в том, что требуется по некоторому ключу найти в map'е вектор и далее в этом векторе найти некий объект. Делается это во множестве мест. Идиотизм в том, что метод find не просто ищет по ключу, а создает копию вектора, в котором потом самостоятельно надо искать требуемый элемент.

    AlexRider, 12 Мая 2016

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

    +3

    1. 1
    https://github.com/3dfxdev/hyper3DGE/commit/bdc2d2309a24f5f729c07cdf386ecaa75403c980

    Куча километров кода сокращена в пару строчек. Нафиг тогда было писать ту кучу километров?

    UsernameAK, 12 Мая 2016

    Комментарии (45)
  7. C++ / Говнокод #19987

    +2

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    template <typename T, typename ...Args>
    std::future<T> looped_thread::add_task(std::function<T(Args...)> func, Args ...args) {
        std::packaged_task<T()> task(std::bind(func,args...));
        std::future<T> fut = task.get_future();
        std::lock_guard<std::mutex> lock(_mutex);
        /*std::queue<std::function<void()>>*/ _tasks.push(/*std::packaged_task<T()> -> std::function<void()> ??*/);
        /*std::condition_variable*/ _cv.notify_one(); 
        return std::move(fut);
    }

    Задача: написать собственный пул потоков с блекджеком и шлюхами
    Подзадача: реализовать метод, добавляющий функтор в очередь команд и возвращающий std::future
    Что не так: std::packaged_task не конвертируется в std::future. Он не копируется, а поэтому:
    а. его нельзя передать через std::bind;
    б. при захвате через с++14 lambda capture expressions (аля

    auto f = [t = std::move(task)](){/**/};
    ) мы получаем t типа const std::packaged_task (мб это особенность mingw, конечно, но один фиг работать должно везде). Ни выполнить, ни мувнуть, ни скопировать. mutable в спецификации лямбды не помогает
    в. Примерно все те же самые проблемы возникают при попытке обернуть packaged_task в unique_ptr
    г. если чуть-чуть погуглить, можно найти кучу страшных решений через виртуальные методы, наследование, оборачивание packaged_task в shared_ptr и пр. Например: https://rsdn.ru/forum/cpp/5824551.all

    Но есть куда более простое и изящное решение. Угадаете?

    Antervis, 12 Мая 2016

    Комментарии (67)
  8. C++ / Говнокод #19986

    0

    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
    #include <fstream>
    #include <iostream>
    #include <string>
    #include <list>
    #include <vector>
    #include <set>
    #include <algorithm>
    
    std::vector<std::string> split(const std::string &text, char sep) {
    	std::vector<std::string> tokens;
    
    	std::size_t start = 0, end = 0;
    	while ((end = text.find(sep, start)) != std::string::npos) {
    		std::string temp = text.substr(start, end - start);
    		if (temp != "") tokens.push_back(temp);
    		start = end + 1;
    	}
    	std::string temp = text.substr(start);
    	if (temp != "") tokens.push_back(temp);
    	return tokens;
    
    }
    
    void ReplaceStringInPlace(std::string& subject, const std::string& search,
    	const std::string& replace) {
    	size_t pos = 0;
    	while ((pos = subject.find(search, pos)) != std::string::npos) {
    		subject.replace(pos, search.length(), replace);
    		pos += replace.length();
    	}
    }
    
    
    using namespace std;
    using std::vector;
    using std::list;
    using std::set;
    
    int main()
    {
    	setlocale(LC_ALL, "rus");
    
    	// задание 1
    	string buff;
    	list<string> allText;
    
    	//задание 2
    	list<string> chap1;
    	list<string> chap2;
    	list<string> chap3;
    	list<string> chap4;
    	list<string> chap5;
    	string::size_type n;
    	int chapter = 0;
    
    	//задание 5
    
    	vector<string> textWord;
    	vector<string> rezult;
    	vector <string>::size_type kolvotext=0;
    	set<string>Unique_word;
    	vector<string>::iterator j;
    
    	ifstream fin("D:\\lab_c__5_text.txt");
    	if (!fin.is_open())
    		cout << "Файл не может быть открыт!\n";
    	else {
    
    		while (getline(fin, buff)) {
    			allText.push_back(buff);
    			//разбиение по главам
    			n = buff.find("CHAPTER");
    			if (n == 0) {
    				chapter++;
    			}
    			if (chapter == 1) {
    				chap1.push_back(buff);
    			}
    			else if (chapter == 2) {
    				chap2.push_back(buff);
    			}
    			else if (chapter == 3) {
    				chap3.push_back(buff);
    			}
    			else if (chapter == 4) {
    				chap4.push_back(buff);
    			}
    			else if (chapter == 5) {
    				chap5.push_back(buff);
    			}
    			//разбиение по словам
    			
    			ReplaceStringInPlace(buff, ".", "");
    			ReplaceStringInPlace(buff, "!", "");
    			ReplaceStringInPlace(buff, "?", "");
    			ReplaceStringInPlace(buff, ",", "");
    			ReplaceStringInPlace(buff, ";", "");
    			ReplaceStringInPlace(buff, ":", "");

    http://cpp.sh/3nlm6
    Хз что там за задание, какая-то долгая и муторная работа с текстом.

    Fluttie, 12 Мая 2016

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

    +5

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    $(document).on('click', 'a.switcher_link', function(e) {
        e.preventDefault();
        var btn = $(this);
        $.getJSON(btn.attr('href'), {type: 'json'}, function(data) {
          btn.parent().parent().parent().parent().parent().parent().parent().parent().replaceWith(data.data);
        });
      });

    Нашел и ахуел....

    gerasim13, 11 Мая 2016

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

    +4

    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
    $ nodejs
    > var buffer = new ArrayBuffer(2);
    undefined
    > var uint16View = new Uint16Array(buffer);
    undefined
    > var uint8View = new Uint8Array(buffer);
    undefined
    > uint16View[0]=0xff00
    65280
    > uint8View[1]
    255
    > uint8View[0]
    0

    https://developer.mozilla.org/en/docs/Web/JavaScript/Typed_arrays
    endianness - теперь и в жабаскрипте. Почти как union

    j123123, 11 Мая 2016

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