text:
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace LuaScriptingUnitTest
{
   /// tests Lua::State class
   TEST_CLASS(TestLuaState)
   {
   public:
      /// tests LoadSourceString()
      TEST_METHOD(TestLoadSourceString)
      {
         Lua::State state;

         state.LoadSourceString(_T("-- comment test"));
         state.LoadSourceString(_T("function run() return 42; end"));

         Assert::IsTrue(state.GetValue(_T("run")).GetType() == Lua::Value::typeFunction,
            _T("run must be of type function"));

         state.CallFunction(_T("run"));
      }

      /// tests error handling
      TEST_METHOD(TestStateErrorHandling)
      {
         Lua::State state;
         state.LoadSourceString(_T("function run() error(); end"));

         try
         {
            state.CallFunction(_T("run"));
         }
         catch (const Lua::Exception&)
         {
            // ok
            return;
         }
         catch (...)
         {
            Assert::Fail(_T("must throw Lua::Exception and nothing else"));
         }

         Assert::Fail(_T("must throw exception"));
      }

      /// tests RequireLib() method to load built-in libraries
      TEST_METHOD(TestStateRequireLib)
      {
         // setup
         Lua::State state;

         // run
         state.RequireLib("coroutine");

         // check
         Lua::Value value = state.GetValue(_T("coroutine"));
         Assert::IsTrue(value.GetType() == Lua::Value::typeTable, _T("type must be table"));

         Lua::Table table = state.GetTable(_T("coroutine"));
         Lua::Value funcYield = table.GetValue(_T("yield"));

         Assert::IsTrue(funcYield.GetType() == Lua::Value::typeFunction, _T("type must be function"));
      }

      /// tests temporary nil value handling
      TEST_METHOD(TestValueNilTemporary)
      {
         // set up
         Lua::State state;

         // run
         for (int i = 0; i < 100; i++)
         {
            Lua::Value value = state.GetValue("not_init");
            Assert::IsTrue(Lua::Value::typeNil == value.GetType(), _T("type must be nil"));
         }

         // check
         // must not overflow stack
      }

      /// tests CallFunction(), without return parameters
      TEST_METHOD(TestCallFunctionNoRet)
      {
         Lua::State state;

         state.LoadSourceString(_T("function run() return; end"));

         std::vector<Lua::Value> vecRetvals = state.CallFunction(_T("run"));
         Assert::AreEqual<size_t>(0, vecRetvals.size(), _T("must have returned zero return values"));
      }

      /// tests CallFunction(), with single return parameter
      TEST_METHOD(TestCallFunctionRetval)
      {
         Lua::State state;

         state.LoadSourceString(_T("function run() return 42; end"));

         std::vector<Lua::Value> vecRetvals = state.CallFunction(_T("run"), 1);
         Assert::AreEqual<size_t>(1, vecRetvals.size(), _T("must have returned one return value"));

         const Lua::Value& value = vecRetvals[0];
         Assert::IsTrue(Lua::Value::typeNumber == value.GetType(), _T("type must be number"));
         Assert::AreEqual(value.Get<double>(), 42.0, 1e-6, _T("value must be 42"));
      }

      /// tests CallFunction(), with multiple return parameters
      TEST_METHOD(TestCallFunctionMultipleRetvals)
      {
         Lua::State state;

         state.LoadSourceString(_T("function test() return 42, 42==6*7, \"123abc\", nil; end"));

         std::vector<Lua::Value> vecRetvals = state.CallFunction(_T("test"), 4);
         Assert::AreEqual<size_t>(4, vecRetvals.size(), _T("must have returned 4 return values"));

         Assert::IsTrue(Lua::Value::typeNumber == vecRetvals[0].GetType(), _T("type must be number"));
         Assert::IsTrue(Lua::Value::typeBoolean == vecRetvals[1].GetType(), _T("type must be boolean"));
         Assert::IsTrue(Lua::Value::typeString == vecRetvals[2].GetType(), _T("type must be string"));
         Assert::IsTrue(Lua::Value::typeNil == vecRetvals[3].GetType(), _T("type must be nil"));
      }

      TEST_METHOD(TestAddTable)
      {
         Lua::State state;

         {
            Lua::Table table = state.AddTable(_T("abc"));
         }

         state.LoadSourceString(_T("function test() return abc; end"));

         std::vector<Lua::Value> vecRetval = state.CallFunction(_T("test"), 1);
         Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

         Assert::IsTrue(Lua::Value::typeTable == vecRetval[0].GetType(), _T("type must be table"));
      }

      TEST_METHOD(TestGetTable)
      {
         Lua::State state;

         {
            Lua::Table table1 = state.AddTable(_T("abc"));
         }

         Lua::Table table2 = state.GetTable(_T("abc"));
      }

      TEST_METHOD(TestTableAddValue)
      {
         Lua::State state;

         {
            Lua::Table table1 = state.AddTable(_T("abc"));
            table1.AddValue(_T("def"), Lua::Value(42.0));
         }

         {
            state.LoadSourceString(_T("function test() return abc.def; end"));

            std::vector<Lua::Value> vecRetval = state.CallFunction(_T("test"), 1);
            Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

            const Lua::Value& val = vecRetval[0];
            Assert::IsTrue(Lua::Value::typeNumber == vecRetval[0].GetType(), _T("type must be number"));
            Assert::AreEqual(val.Get<double>(), 42.0, 1e-6, _T("value must be 42"));
         }
      }

      TEST_METHOD(TestTableAddFunction)
      {
         Lua::State state;

         // define a function to call back
         Lua::T_fnCFunction fn = [&] (Lua::State&, const std::vector<Lua::Value>& vecParams) -> std::vector<Lua::Value>
         {
            if (vecParams.size() != 1)
               throw std::runtime_error("must pass exactly 1 value");

            if (Lua::Value::typeNumber != vecParams[0].GetType())
               throw std::runtime_error("must pass a number value");

            double d = vecParams[0].Get<double>();

            std::vector<Lua::Value> vecRetValues;

            vecRetValues.push_back(Lua::Value(d));
            vecRetValues.push_back(Lua::Value(d+d));
            vecRetValues.push_back(Lua::Value(d*d));

            return vecRetValues;
         };

         {
            Lua::Table table1 = state.AddTable(_T("abc"));
            table1.AddFunction("run", fn);
         }

         {
            state.LoadSourceString(_T("function test() return abc.run(42.0); end"));

            std::vector<Lua::Value> vecRetval = state.CallFunction(_T("test"), 3);

            Assert::AreEqual<size_t>(3, vecRetval.size(), _T("must have returned 3 return value"));

            const Lua::Value& val0 = vecRetval[0];
            Assert::IsTrue(Lua::Value::typeNumber == val0.GetType(), _T("type must be number"));
            Assert::AreEqual(val0.Get<double>(), 42.0, 1e-6, _T("value must be 42"));

            Assert::AreEqual(vecRetval[1].Get<double>(), 42.0+42.0, 1e-6, _T("value must be 42+42"));

            Assert::AreEqual(vecRetval[2].Get<double>(), 42.0*42.0, 1e-6, _T("value must be 42*42"));
         }
      }

      TEST_METHOD(TestTableCallFunction)
      {
         Lua::State state;

         // setup
         state.LoadSourceString(_T("abc = { def = function(self, val) return val, val+val, val*val end }"));

         // run
         Lua::Table table = state.GetTable(_T("abc"));

         std::vector<Lua::Value> vecParam;
         vecParam.push_back(Lua::Value(42.0));

         std::vector<Lua::Value> vecRetval = table.CallFunction(_T("def"), 3, vecParam);

         // check
         Assert::AreEqual<size_t>(3, vecRetval.size(), _T("must have returned 3 return value"));

         Assert::AreEqual(vecRetval[0].Get<double>(), 42.0, 1e-6, _T("value must be 42"));
         Assert::AreEqual(vecRetval[1].Get<double>(), 42.0+42.0, 1e-6, _T("value must be 42+42"));
         Assert::AreEqual(vecRetval[2].Get<double>(), 42.0*42.0, 1e-6, _T("value must be 42*42"));
      }

      /// tests method State::AddUserdata(), and value isn't stored anywhere
      TEST_METHOD(TestStateAddUserdataTemporary)
      {
         // setup
         Lua::State state;

         // run
         {
            Lua::Userdata userdata = state.AddUserdata(4);
         }

         // check
         // must not crash
      }

      /// tests method State::AddUserdata() and copy ctor of Userdata
      TEST_METHOD(TestStateUserdataCopyCtor)
      {
         // setup
         Lua::State state;

         // run
         {
            Lua::Userdata userdata = state.AddUserdata(4);
            Lua::Userdata userdata2 = userdata; // copy ctor

            Lua::Userdata userdata3 = userdata;
            userdata3 = userdata; // assign operator
         }

         // check
         // must not crash
      }

      /// tests method State::AddUserdata() and stores it as global value
      TEST_METHOD(TestStateAddUserdataStoreGlobal)
      {
         // setup
         Lua::State state;

         const unsigned char ucValue = 42;

         // run
         {
            Lua::Userdata userdata = state.AddUserdata(4);

            userdata.Data<unsigned char>()[0] = ucValue;

            state.AddValue(_T("user"), Lua::Value(userdata));
         }

         state.LoadSourceString(_T("function test() return user; end"));

         std::vector<Lua::Value> vecRetval = state.CallFunction(_T("test"), 1);

         // check
         Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

         Assert::IsTrue(Lua::Value::typeUserdata == vecRetval[0].GetType(), _T("type must be userdata"));

         Lua::Userdata userdata = vecRetval[0].Get<Lua::Userdata>();

         Assert::IsTrue(userdata.Data<unsigned char>()[0] == ucValue, _T("stored value must match"));
      }

      /// tests method State::AddUserdata() and stores it as value in a table
      TEST_METHOD(TestStateAddUserdataStoreInTable)
      {
         // setup
         Lua::State state;

         const unsigned char ucValue = 42;

         // run
         {
            Lua::Userdata userdata = state.AddUserdata(4);

            userdata.Data<unsigned char>()[0] = ucValue;

            state.AddValue(_T("user"), Lua::Value(userdata));
         }

         {
            Lua::Value value = state.GetValue(_T("user"));
            Lua::Userdata userdata = value.Get<Lua::Userdata>();

            state.AddValue(_T("user2"), Lua::Value(userdata));
         }

         state.LoadSourceString(_T("function test() return user,user2; end"));

         std::vector<Lua::Value> vecRetval = state.CallFunction(_T("test"), 2);

         // check
         Assert::AreEqual<size_t>(2, vecRetval.size(), _T("must have returned 2 return values"));

         Assert::IsTrue(Lua::Value::typeUserdata == vecRetval[0].GetType(), _T("type must be userdata"));
         Assert::IsTrue(Lua::Value::typeUserdata == vecRetval[1].GetType(), _T("type must be userdata"));

         Lua::Userdata userdata1 = vecRetval[0].Get<Lua::Userdata>();
         Lua::Userdata userdata2 = vecRetval[1].Get<Lua::Userdata>();

         Assert::IsTrue(userdata1.Data() == userdata2.Data(), _T("pointer of two userdatas must be equal"));
      }

      /// tests method State::AddUserdata() and stores it as value in a table
      TEST_METHOD(TestStateUserdataCopy)
      {
         // setup
         Lua::State state;

         const unsigned char ucValue = 42;

         // run
         {
            Lua::Table table = state.AddTable(_T("abc"));

            Lua::Userdata userdata = state.AddUserdata(4);

            userdata.Data<unsigned char>()[0] = ucValue;

            table.AddValue(_T("user"), Lua::Value(userdata));
         }

         // check
         // must not crash
      }

      TEST_METHOD(TestStateAddFunction)
      {
         Lua::State state;

         // setup

         // define a function to call back
         Lua::T_fnCFunction fn = [&] (Lua::State&, const std::vector<Lua::Value>&) -> std::vector<Lua::Value>
         {
            std::vector<Lua::Value> vecRetValues;
            vecRetValues.push_back(Lua::Value(42.0));

            return vecRetValues;
         };

         state.AddFunction(_T("run"), fn);

         // run
         state.LoadSourceString(_T("function test() return run(); end"));

         // check
         std::vector<Lua::Value> vecRetval = state.CallFunction(_T("test"), 1);

         Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

         Assert::AreEqual(vecRetval[0].Get<double>(), 42.0, 1e-6, _T("value must be 42"));
      }

      TEST_METHOD(TestStateAddFunctionWithParam)
      {
         Lua::State state;

         // setup

         // define a function to call back
         Lua::T_fnCFunction fn = [&] (Lua::State&, const std::vector<Lua::Value>& vecParams) -> std::vector<Lua::Value>
         {
            if (vecParams.size() != 1)
               throw std::runtime_error("must pass exactly 1 value");

            if (Lua::Value::typeNumber != vecParams[0].GetType())
               throw std::runtime_error("must pass a number value");

            std::vector<Lua::Value> vecRetValues;
            vecRetValues.push_back(vecParams[0]);

            return vecRetValues;
         };

         state.AddFunction(_T("run"), fn);

         // run
         state.LoadSourceString(_T("function test(val) return run(val); end"));

         std::vector<Lua::Value> vecParam;
         vecParam.push_back(Lua::Value(42.0));

         std::vector<Lua::Value> vecRetval = state.CallFunction(_T("test"), 1, vecParam);

         // check
         Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

         Assert::AreEqual(vecRetval[0].Get<double>(), 42.0, 1e-6, _T("value must be 42"));
      }

      TEST_METHOD(TestStateAddValue)
      {
         Lua::State state;

         // setup
         state.AddValue(_T("the_value"), Lua::Value(42.0));

         // run
         state.LoadSourceString(_T("function test() return the_value; end"));

         // check
         std::vector<Lua::Value> vecRetval = state.CallFunction(_T("test"), 1);

         Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

         Assert::AreEqual(vecRetval[0].Get<double>(), 42.0, 1e-6, _T("value must be 42"));
      }

      /// Tests function call, calling a global Lua function, with a table as parameter
      TEST_METHOD(TestFunctionCall_LuaFunction_ParamTable)
      {
         Lua::State state;

         // setup
         state.LoadSourceString(_T("function test(val) return val * 42.0; end"));

         // run
         for (int i = 0; i < 1000; i++)
         {
            Lua::StackChecker checker(state.GetState());

            Lua::Value valFunc = state.GetValue(_T("test"));
            Lua::Function func = valFunc.Get<Lua::Function>();

            std::vector<Lua::Value> vecParam;
            vecParam.push_back(Lua::Value(42.0));

            std::vector<Lua::Value> vecRetval = func.Call(1, vecParam);

            // check
            Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

            Assert::AreEqual(vecRetval[0].Get<double>(), 42.0 * 42.0, 1e-6, _T("value must be 42 * 42"));
         }
      }

      /// Tests function call, calling a Lua function stored in a table, with a table as parameter
      TEST_METHOD(TestFunctionCall_TableFunction_ParamTable)
      {
         Lua::State state;

         // setup
         state.LoadSourceString(_T("abc = { test = function(self, val) return val * 42.0; end; }"));

         // run
         for (int i = 0; i < 1000; i++)
         {
            Lua::StackChecker checker(state.GetState());

            Lua::Table table = state.GetTable(_T("abc"));

            Lua::Value valFunc = table.GetValue(_T("test"));
            Lua::Function func = valFunc.Get<Lua::Function>();

            std::vector<Lua::Value> vecParam;
            vecParam.push_back(Lua::Value(table));
            vecParam.push_back(Lua::Value(42.0));

            std::vector<Lua::Value> vecRetval = func.Call(1, vecParam);

            // check
            Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

            Assert::AreEqual(vecRetval[0].Get<double>(), 42.0 * 42.0, 1e-6, _T("value must be 42 * 42"));
         }
      }

      /// Tests function call, calling a C++ bound function stored in a table, with a table as parameter
      TEST_METHOD(TestFunctionCall_CppBinding_ParamTable)
      {
         Lua::State state;

         // setup

         // define a function to call back
         Lua::T_fnCFunction fn = [](Lua::State&, const std::vector<Lua::Value>& vecParams) -> std::vector<Lua::Value>
         {
            if (vecParams.size() != 1)
               throw std::runtime_error("must pass exactly 1 value");

            std::vector<Lua::Value> vecRetValues;
            vecRetValues.push_back(Lua::Value(vecParams[0].Get<double>() * 42.0));

            return vecRetValues;
         };

         // run
         for (int i = 0; i < 1000; i++)
         {
            Lua::StackChecker checker(state.GetState());

            Lua::Table table = state.AddTable(_T("abc"));
            table.AddFunction("run", fn);

            Lua::Value valFunc = table.GetValue(_T("run"));
            Lua::Function func = valFunc.Get<Lua::Function>();

            std::vector<Lua::Value> vecParam;
            vecParam.push_back(Lua::Value(42.0));

            std::vector<Lua::Value> vecRetval = func.Call(1, vecParam);

            // check
            Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

            Assert::AreEqual(vecRetval[0].Get<double>(), 42.0 * 42.0, 1e-6, _T("value must be 42 * 42"));
         }
      }

      /// Tests function call, calling a global Lua function, with a userdata object as parameter
      TEST_METHOD(TestFunctionCall_ParamUserdata)
      {
         Lua::State state;

         // setup
         state.LoadSourceString(_T("function test(val) return val; end"));

         // run
         for (int i = 0; i < 1000; i++)
         {
            Lua::StackChecker checker(state.GetState());

            Lua::Value valFunc = state.GetValue(_T("test"));
            Lua::Function func = valFunc.Get<Lua::Function>();

            Lua::Userdata userdata = state.AddUserdata(sizeof(int));
            *userdata.Data<int>() = 42;

            std::vector<Lua::Value> vecParam;
            vecParam.push_back(Lua::Value(userdata));

            std::vector<Lua::Value> vecRetval = func.Call(1, vecParam);

            // check
            Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

            Assert::IsTrue(vecRetval[0].GetType() == Lua::Value::typeUserdata, _T("value must be of userdata type"));
         }
      }

      /// Tests function call, calling a global Lua function, with a function object as parameter
      TEST_METHOD(TestFunctionCall_ParamFunction)
      {
         Lua::State state;

         // setup
         state.LoadSourceString(_T("function test(func, val) return func(val) + 2 * func(val/2); end"));
         state.LoadSourceString(_T("function calc(val) return val * val; end"));

         // run
         for (int i = 0; i < 1000; i++)
         {
            Lua::StackChecker checker(state.GetState());

            Lua::Value valFuncTest = state.GetValue(_T("test"));
            Lua::Function funcTest = valFuncTest.Get<Lua::Function>();

            Lua::Value valFuncCalc = state.GetValue(_T("calc"));
            Lua::Function funcCalc = valFuncCalc.Get<Lua::Function>();

            std::vector<Lua::Value> vecParam;
            vecParam.push_back(Lua::Value(funcCalc));
            vecParam.push_back(Lua::Value(42.0));

            std::vector<Lua::Value> vecRetval = funcTest.Call(1, vecParam);

            // check
            Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

            Assert::IsTrue(vecRetval[0].GetType() == Lua::Value::typeNumber, _T("value must be a number"));
            Assert::AreEqual(vecRetval[0].Get<double>(),
               (42.0 * 42.0) + 2.0 * ((42.0/2.0) * (42.0 / 2.0)),
               1e-6, _T("value must be equal to calculated value"));
         }
      }

      TEST_METHOD(TestFunctionPushTable)
      {
         Lua::State state;

         // setup

         // define a function to call back
         Lua::T_fnCFunction fn = [] (Lua::State& paramState, const std::vector<Lua::Value>& vecParams) -> std::vector<Lua::Value>
         {
            if (vecParams.size() != 1)
               throw std::runtime_error("must pass exactly 1 value");

            if (Lua::Value::typeNumber != vecParams[0].GetType())
               throw std::runtime_error("must pass a number value");

            Lua::Table table = paramState.AddTable(_T(""));
            table.AddValue(_T("def"), vecParams[0]);

            std::vector<Lua::Value> vecRetValues;
            vecRetValues.push_back(Lua::Value(table));

            return vecRetValues;
         };

         state.AddFunction(_T("run"), fn);

         // run
         state.LoadSourceString(_T("function test(val) local abc = run(val); return abc.def; end"));

         std::vector<Lua::Value> vecParam;
         vecParam.push_back(Lua::Value(42.0));

         std::vector<Lua::Value> vecRetval = state.CallFunction(_T("test"), 1, vecParam);

         // check
         Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

         Assert::AreEqual(vecRetval[0].Get<double>(), 42.0, 1e-6, _T("value must be 42"));
      }

      TEST_METHOD(TestFunctionParamInClosure)
      {
         Lua::State state;

         // setup

         // define a function to call back
         Lua::T_fnCFunction fn = [&] (Lua::State&, const std::vector<Lua::Value>& vecParams) -> std::vector<Lua::Value>
         {
            if (vecParams.size() != 1)
               throw std::runtime_error("must pass exactly 1 value");

            if (Lua::Value::typeFunction != vecParams[0].GetType())
               throw std::runtime_error("must pass a function value");

            // call function
            Lua::Function func = vecParams[0].Get<Lua::Function>();

            std::vector<Lua::Value> vecCallParams;
            vecCallParams.push_back(Lua::Value(42.0));
            vecCallParams.push_back(Lua::Value(64.0));

            return func.Call(1, vecCallParams); // tail call
         };

         state.AddFunction(_T("run"), fn);

         // run
         state.LoadSourceString(_T("function calc(a, b) return a+b; end"));
         state.LoadSourceString(_T("function test() return run(calc); end"));

         std::vector<Lua::Value> vecRetval = state.CallFunction(_T("test"), 1);

         // check
         Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

         Assert::AreEqual(vecRetval[0].Get<double>(), 42.0+64.0, 1e-6, _T("value must be 42+64"));
      }

      TEST_METHOD(TestFunctionPushOnStack)
      {
         Lua::State state;

         // setup

         // define a function to call back
         Lua::T_fnCFunction fnAsyncWait = [](Lua::State& paramState, const std::vector<Lua::Value>& vecParams) -> std::vector<Lua::Value>
         {
            if (vecParams.size() != 1)
               throw std::runtime_error("must pass exactly 1 value");

            if (Lua::Value::typeFunction != vecParams[0].GetType())
               throw std::runtime_error("must pass a function value in param 0");

            Lua::Function func = vecParams[0].Get<Lua::Function>();

            // add function as value
            paramState.AddValue(_T("_the_handler"), vecParams[0]);

            return std::vector<Lua::Value>();
         };

         Lua::T_fnCFunction fnHandler = [](Lua::State&, const std::vector<Lua::Value>& vecParams)-> std::vector<Lua::Value>
         {
            if (vecParams.size() != 1)
               throw std::runtime_error("must pass exactly 1 value");

            if (Lua::Value::typeNumber != vecParams[0].GetType())
               throw std::runtime_error("must pass a number value in param 0");

            std::vector<Lua::Value> vecRetValues;
            vecRetValues.push_back(Lua::Value(42.0));

            return vecRetValues;
         };

         state.AddFunction(_T("async_wait"), fnAsyncWait);
         state.AddFunction(_T("handler"), fnHandler);

         state.LoadSourceString(_T("function wait_completed() return _the_handler(64.0); end"));
         state.LoadSourceString(_T("function test() async_wait(handler); end"));

         // run
         state.CallFunction(_T("test"));
         std::vector<Lua::Value> vecRetval = state.CallFunction(_T("wait_completed"), 1);

         // check
         Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

         Assert::AreEqual(vecRetval[0].Get<double>(), 42.0, 1e-6, _T("value must be 42.0"));
      }

      TEST_METHOD(TestFunctionPushOnTable)
      {
         Lua::State state;

         // setup

         // define a function to call back
         Lua::T_fnCFunction fnAsyncWait = [](Lua::State&, const std::vector<Lua::Value>& vecParams) -> std::vector<Lua::Value>
         {
            if (vecParams.size() != 2)
               throw std::runtime_error("must pass exactly 2 values");

            if (Lua::Value::typeTable != vecParams[0].GetType())
               throw std::runtime_error("must pass a table value in param 0");

            if (Lua::Value::typeFunction != vecParams[1].GetType())
               throw std::runtime_error("must pass a function value in param 1");

            Lua::Table self = vecParams[0].Get<Lua::Table>();
            Lua::Function func = vecParams[1].Get<Lua::Function>();

            // add function as value
            self.AddValue(_T("_the_handler"), vecParams[1]);

            return std::vector<Lua::Value>();
         };

         Lua::T_fnCFunction fnHandler = [](Lua::State&, const std::vector<Lua::Value>& vecParams)-> std::vector<Lua::Value>
         {
            if (vecParams.size() != 2)
               throw std::runtime_error("must pass exactly 2 values");

            if (Lua::Value::typeTable != vecParams[0].GetType())
               throw std::runtime_error("must pass a table value in param 0");

            if (Lua::Value::typeNumber != vecParams[1].GetType())
               throw std::runtime_error("must pass a number value in param 1");

            std::vector<Lua::Value> vecRetValues;
            vecRetValues.push_back(Lua::Value(42.0));

            return vecRetValues;
         };

         state.LoadSourceString(_T("App = { ")
            _T("wait_completed = function() return App:_the_handler(64.0); end, ")
            _T("test = function() App:async_wait(App.handler); end ")
            _T("}"));

         Lua::Table table = state.GetTable(_T("App"));
         table.AddFunction("async_wait", fnAsyncWait);
         table.AddFunction("handler", fnHandler);

         // run
         table.CallFunction(_T("test"));
         std::vector<Lua::Value> vecRetval = table.CallFunction(_T("wait_completed"), 1);

         // check
         Assert::AreEqual<size_t>(1, vecRetval.size(), _T("must have returned 1 return value"));

         Assert::AreEqual(vecRetval[0].Get<double>(), 42.0, 1e-6, _T("value must be 42.0"));
      }

      TEST_METHOD(TestThreadEmptyCtor)
      {
         // setup
         Lua::State state;
         Lua::Thread thread(state);

         // run

         // check
         Assert::IsTrue(thread.Status() == Lua::Thread::statusOK, _T("non-started thread must have status statusOK"));
      }

      TEST_METHOD(TestThreadCallFunc)
      {
         // setup
         Lua::State state;
         Lua::Thread thread(state);

         state.LoadSourceString(_T("function run() return; end"));

         // run
         Lua::Function func = thread.GetValue(_T("run")).Get<Lua::Function>();

         std::vector<Lua::Value> vecParam;
         std::pair<Lua::Thread::T_enThreadStatus, std::vector<Lua::Value>> retVal = thread.Start(func, vecParam);

         // check
         Assert::IsTrue(retVal.first == Lua::Thread::statusOK, _T("status of finished thread must be statusOK"));
         Assert::IsTrue(retVal.second.empty(), _T("must have returned no return values"));
      }

      TEST_METHOD(TestThreadCallFuncReturnValue)
      {
         // setup
         Lua::State state;
         Lua::Thread thread(state);

         state.LoadSourceString(_T("function run() return 42, 42==6*7, \"123abc\", nil; end"));

         // run
         Lua::Function func = thread.GetValue(_T("run")).Get<Lua::Function>();

         std::vector<Lua::Value> vecParam;
         std::pair<Lua::Thread::T_enThreadStatus, std::vector<Lua::Value>> retVal = thread.Start(func, vecParam);

         // check
         Assert::IsTrue(retVal.first == Lua::Thread::statusOK, _T("status of finished thread must be statusOK"));

         std::vector<Lua::Value>& vecRetvals = retVal.second;

         Assert::AreEqual<size_t>(4, vecRetvals.size(), _T("must have returned 4 return values"));

         Assert::IsTrue(Lua::Value::typeNumber == vecRetvals[0].GetType(), _T("type must be number"));
         Assert::AreEqual(vecRetvals[0].Get<double>(), 42.0, 1e-6, _T("value must be 42"));

         Assert::IsTrue(Lua::Value::typeBoolean == vecRetvals[1].GetType(), _T("type must be boolean"));
         Assert::IsTrue(Lua::Value::typeString == vecRetvals[2].GetType(), _T("type must be string"));
         Assert::IsTrue(Lua::Value::typeNil == vecRetvals[3].GetType(), _T("type must be nil"));
      }

      TEST_METHOD(TestThreadCallFunctionInTable)
      {
         // setup
         Lua::State state;
         Lua::Thread thread(state);

         state.LoadSourceString(_T("abc = { def = function(self, val) return val, val+val, val*val end }"));

         // run
         Lua::Table table = thread.GetTable(_T("abc"));

         Lua::Function func = table.GetValue(_T("def")).Get<Lua::Function>();

         std::vector<Lua::Value> vecParam;
         vecParam.push_back(Lua::Value(table));
         vecParam.push_back(Lua::Value(42.0));

         std::pair<Lua::Thread::T_enThreadStatus, std::vector<Lua::Value>> retVal = thread.Start(func, vecParam);

         // check
         Assert::IsTrue(retVal.first == Lua::Thread::statusOK, _T("status of finished thread must be statusOK"));

         std::vector<Lua::Value>& vecRetvals = retVal.second;

         Assert::AreEqual<size_t>(3, vecRetvals.size(), _T("must have returned 3 return values"));

         Assert::AreEqual(vecRetvals[0].Get<double>(), 42.0, 1e-6, _T("value must be 42"));
         Assert::AreEqual(vecRetvals[1].Get<double>(), 42.0 + 42.0, 1e-6, _T("value must be 42+42"));
         Assert::AreEqual(vecRetvals[2].Get<double>(), 42.0*42.0, 1e-6, _T("value must be 42*42"));
      }

      TEST_METHOD(TestThreadCallFunctionClosure)
      {
         // setup
         Lua::State state;
         Lua::Thread thread(state);

         // define a function to call back
         Lua::T_fnCFunction fn = [](Lua::State&, const std::vector<Lua::Value>& vecParams) -> std::vector<Lua::Value>
         {
            if (vecParams.size() != 1)
               throw std::runtime_error("must pass exactly 1 value");

            if (Lua::Value::typeNumber != vecParams[0].GetType())
               throw std::runtime_error("must pass a number value");

            std::vector<Lua::Value> vecRetValues;
            vecRetValues.push_back(Lua::Value(vecParams[0].Get<double>() * 42.0));

            return vecRetValues;
         };

         state.AddFunction(_T("run"), fn);

         // run
         Lua::Function func = thread.GetValue(_T("run")).Get<Lua::Function>();

         std::vector<Lua::Value> vecParam1;
         vecParam1.push_back(Lua::Value(3.0));
         std::pair<Lua::Thread::T_enThreadStatus, std::vector<Lua::Value>> retVal = thread.Start(func, vecParam1);

         // check
         Assert::IsTrue(retVal.first == Lua::Thread::statusOK, _T("status of finished thread must be statusOK"));

         std::vector<Lua::Value>& vecRetvals = retVal.second;

         Assert::AreEqual<size_t>(1, vecRetvals.size(), _T("must have returned 1 return values"));

         Assert::IsTrue(Lua::Value::typeNumber == vecRetvals[0].GetType(), _T("type must be number"));
         Assert::AreEqual(3.0 * 42.0, vecRetvals[0].Get<double>(), 1e-6, _T("value must match calculated value"));
      }

      TEST_METHOD(TestThreadStartYieldResume)
      {
         // setup
         Lua::State state;
         Lua::Thread thread(state);

         state.RequireLib("coroutine");
         state.LoadSourceString(_T("function run(value) return coroutine.yield(value * 42, 64); end"));

         // run 1
         Lua::Function func = thread.GetValue(_T("run")).Get<Lua::Function>();

         std::vector<Lua::Value> vecParam1;
         vecParam1.push_back(Lua::Value(3.0));
         std::pair<Lua::Thread::T_enThreadStatus, std::vector<Lua::Value>> retVal1 = thread.Start(func, vecParam1);

         // check 1
         Assert::IsTrue(retVal1.first == Lua::Thread::statusYield, _T("status of finished thread must be statusYield"));

         std::vector<Lua::Value>& vecRetvals1 = retVal1.second;
         Assert::AreEqual<size_t>(2, vecRetvals1.size(), _T("must have returned 2 return values"));

         double dValue2 = vecRetvals1[0].Get<double>() - vecRetvals1[1].Get<double>();

         // run 2
         std::vector<Lua::Value> vecParam2;
         vecParam2.push_back(Lua::Value(dValue2));

         std::pair<Lua::Thread::T_enThreadStatus, std::vector<Lua::Value>> retVal2 = thread.Resume(vecParam2);

         // check 2
         Assert::IsTrue(retVal2.first == Lua::Thread::statusOK, _T("status of finished thread must be statusOK"));

         std::vector<Lua::Value>& vecRetvals2 = retVal2.second;

         Assert::AreEqual<size_t>(1, vecRetvals2.size(), _T("must have returned 1 return values"));

         Assert::IsTrue(Lua::Value::typeNumber == vecRetvals2[0].GetType(), _T("type must be number"));
         Assert::AreEqual(3.0 * 42.0 - 64.0, 1e-6, vecRetvals2[0].Get<double>(), _T("value must match calculated value"));
      }

      TEST_METHOD(TestThreadYieldInClosure)
      {
         // setup
         Lua::State state;
         Lua::Thread thread(state);

         // define a function to call back
         Lua::T_fnCFunction fn = [&thread](Lua::State& paramState, const std::vector<Lua::Value>& vecParams) -> std::vector<Lua::Value>
         {
            if (vecParams.size() != 1)
               throw std::runtime_error("must have passed exactly 1 value");

            if (Lua::Value::typeNumber != vecParams[0].GetType())
               throw std::runtime_error("must pass a number value");

            // yield to caller
            std::vector<Lua::Value> vecYieldParams;
            vecYieldParams.push_back(Lua::Value(vecParams[0].Get<double>() * 42.0));
            vecYieldParams.push_back(Lua::Value(64.0));

            auto continuation = [&thread](Lua::State&, const std::vector<Lua::Value>& vecParams2) -> std::vector<Lua::Value>
            {
               if (vecParams2.size() != 1)
                  throw std::runtime_error("must have passed exactly 1 value");

               std::vector<Lua::Value> vecRetValues;
               vecRetValues.push_back(Lua::Value(vecParams2[0].Get<double>() - 5.0));

               return vecRetValues;
            };

            thread.Yield(paramState, vecYieldParams, continuation);
         };

         state.AddFunction(_T("run"), fn);

         // run 1
         std::pair<Lua::Thread::T_enThreadStatus, std::vector<Lua::Value>> retVal1;
         {
            Lua::Function func = thread.GetValue(_T("run")).Get<Lua::Function>();

            std::vector<Lua::Value> vecParam1;
            vecParam1.push_back(Lua::Value(3.0));
            retVal1 = thread.Start(func, vecParam1);
         }

         // check 1
         Assert::IsTrue(retVal1.first == Lua::Thread::statusYield, _T("status of finished thread must be statusYield"));

         std::vector<Lua::Value>& vecRetvals1 = retVal1.second;
         Assert::AreEqual<size_t>(2, vecRetvals1.size(), _T("must have returned 2 return values"));

         double dValue2 = vecRetvals1[0].Get<double>() - vecRetvals1[1].Get<double>();

         // run 2
         std::vector<Lua::Value> vecParam2;
         vecParam2.push_back(Lua::Value(dValue2));

         std::pair<Lua::Thread::T_enThreadStatus, std::vector<Lua::Value>> retVal2 = thread.Resume(vecParam2);

         // check 2
         Assert::IsTrue(retVal2.first == Lua::Thread::statusOK, _T("status of finished thread must be statusOK"));

         std::vector<Lua::Value>& vecRetvals2 = retVal2.second;

         Assert::AreEqual<size_t>(1, vecRetvals2.size(), _T("must have returned 1 return values"));

         Assert::IsTrue(Lua::Value::typeNumber == vecRetvals2[0].GetType(), _T("type must be number"));
         Assert::AreEqual(3.0 * 42.0 - 64.0 - 5.0, 1e-6, vecRetvals2[0].Get<double>(), _T("value must match calculated value"));
      }

      /// tests if stack is cleaned up when calling thread methods
      TEST_METHOD(TestThreadCleanupStackMultipleRuns)
      {
         // setup
         Lua::State state;
         Lua::Thread thread(state);

         state.LoadSourceString(_T("abc = { def = function(param1) return param1 + 1; end }"));

         // run
         for (int i = 0; i < 100; i++)
         {
            Lua::StackChecker checker1(state.GetState());
            Lua::StackChecker checker2(thread.GetThreadState());

            Lua::Table table = thread.GetTable(_T("abc"));

            Lua::Function func = table.GetValue(_T("def")).Get<Lua::Function>();

            std::vector<Lua::Value> vecParam;
            vecParam.push_back(Lua::Value(42.0));

            std::pair<Lua::Thread::T_enThreadStatus, std::vector<Lua::Value>> retVal = thread.Start(func, vecParam);

            // check
            Assert::IsTrue(retVal.first == Lua::Thread::statusOK, _T("status of finished thread must be statusOK"));

            std::vector<Lua::Value>& vecRetvals = retVal.second;

            Assert::AreEqual<size_t>(1, vecRetvals.size(), _T("must have returned 1 return values"));

            // stack checker must not report an error
         }
      }
   };
}


text:
//#define DEBUG
// used for database debug
#ifdef DEBUG
#define DEBUG_PRINT(fmt, args...)    fprintf(stderr, fmt, ## args)
#else
#define DEBUG_PRINT(fmt, args...)    /* Don't do anything in release builds */
#endif

//#define DRMAA2_DEBUG
// used for api debug
#ifdef DRMAA2_DEBUG
#define DRMAA2_DEBUG_PRINT(fmt, args...)    fprintf(stderr, fmt, ## args)
#else
#define DRMAA2_DEBUG_PRINT(fmt, args...)    /* Don't do anything in release builds */
#endif

redpajama_set_name: RedPajamaGithub


text:
ace.define('ace/mode/toml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/toml_highlight_rules', 'ace/mode/folding/cstyle'], function(require, exports, module) {

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var TomlHighlightRules = require("./toml_highlight_rules").TomlHighlightRules;
var FoldMode = require("./folding/cstyle").FoldMode;

var Mode = function() {
    var highlighter = new TomlHighlightRules();
    this.foldingRules = new FoldMode();
    this.$tokenizer = new Tokenizer(highlighter.getRules());
};
oop.inherits(Mode, TextMode);

(function() {
    this.lineCommentStart = "#";
}).call(Mode.prototype);

exports.Mode = Mode;
});

ace.define('ace/mode/toml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var TomlHighlightRules = function() {
    var keywordMapper = this.createKeywordMapper({
        "constant.language.boolean": "true|false"
    }, "identifier");

    var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*\\b";

    this.$rules = {
    "start": [
        {
            token: "comment.toml",
            regex: /#.*$/
        },
        {
            token : "string",
            regex : '"(?=.)',
            next  : "qqstring"
        },
        {
            token: ["variable.keygroup.toml"],
            regex: "(?:^\\s*)(\\[([^\\]]+)\\])"
        },
        {
            token : keywordMapper,
            regex : identifierRe
        },
        {
           token : "support.date.toml",
           regex: "\\d{4}-\\d{2}-\\d{2}(T)\\d{2}:\\d{2}:\\d{2}(Z)"
        },
        {
           token: "constant.numeric.toml",
           regex: "-?\\d+(\\.?\\d+)?"
        }
    ],
    "qqstring" : [
        {
            token : "string",
            regex : "\\\\$",
            next  : "qqstring"
        },
        {
            token : "constant.language.escape",
            regex : '\\\\[0tnr"\\\\]'
        },
        {
            token : "string",
            regex : '"|$',
            next  : "start"
        },
        {
            defaultToken: "string"
        }
    ]
    }

};

oop.inherits(TomlHighlightRules, TextHighlightRules);

exports.TomlHighlightRules = TomlHighlightRules;
});

ace.define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {

var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;

var FoldMode = exports.FoldMode = function(commentRegex) {
    if (commentRegex) {
        this.foldingStartMarker = new RegExp(
            this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
        );
        this.foldingStopMarker = new RegExp(
            this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
        );
    }
};
oop.inherits(FoldMode, BaseFoldMode);

(function() {

    this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
    this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;

    this.getFoldWidgetRange = function(session, foldStyle, row) {
        var line = session.getLine(row);
        var match = line.match(this.foldingStartMarker);
        if (match) {
            var i = match.index;

            if (match[1])
                return this.openingBracketBlock(session, match[1], row, i);

            return session.getCommentFoldRange(row, i + match[0].length, 1);
        }

        if (foldStyle !== "markbeginend")
            return;

        var match = line.match(this.foldingStopMarker);
        if (match) {
            var i = match.index + match[0].length;

            if (match[1])
                return this.closingBracketBlock(session, match[1], row, i);

            return session.getCommentFoldRange(row, i, -1);
        }
    };

}).call(FoldMode.prototype);

});


text:
namespace demo.toast {
	'use strict';

	angular.module('demo.toast', ['ngCordova']);
}


text:
from baroque import Baroque, Event, Reactor, GenericEventType, ReactorFactory

# instantiate the library
brq = Baroque()

# EventTypes mark categories of events
eventtype = GenericEventType()

# Events are simple objects with properties
event = Event(eventtype)

# Reactors are stateless functions
# instantiate a predefined reactor that mirrors the triggering event on stdout
reactor = ReactorFactory.stdout()

# attach the reactor to any incoming event of type "eventtype"
brq.on(eventtype).run(reactor)    # same as: brq.on("foobar").trigger(reactor)

# now fire the event
brq.publish(event)    # same as: brq.fire(event)

# view all tracked event types
print(brq.eventtypes)
print(brq.eventtypes.count())

# remove a reactor for a given event type
brq.reactors.to(eventtype).remove(reactor)

# ... or all reactors for it
brq.reactors.to(eventtype).remove_all()

# ... or remove reactors for any kind of event type
brq.reactors.remove_all()

# try again but with your custom reactors
def randomize(event):
  from random import randint
  print(randint(1, 10))

my_reactor = Reactor(randomize)

# run a reactor upon any incoming event
brq.on_any_event_run(my_reactor)
event = Event(eventtype)
brq.publish(event)

# view all attached reactors, or all reactors for a specific event type
print(brq.reactors)
print(brq.reactors.to(eventtype))
print(brq.reactors.to(eventtype).count())
print(brq.reactors.to_any_event())
print(brq.reactors.to_any_event().count())

brq.reactors.to_any_event().remove_all()
brq.reactors.remove_all()

# reactors can run only if specific conditions are met
def condition(event):
  return 'test' in event.payload
r = Reactor(randomize)
brq.on_any_event_trigger(r).only_if(condition)  # same as: brq.on_any_event_trigger(Reactor(randomize, condition))
event_with = Event(eventtype, payload=dict(test=1))
event_without = Event(eventtype, payload=dict(label='text'))
brq.publish(event_without)
brq.publish(event_with)
print('reactor reated {} times'.format(r.count_reactions()))
print(r.last_reacted_on())
print(r.last_event_reacted())


text:
"""Module that defines a Marshmallow field that deserializes a date string into
an Pendulum object.
"""

from __future__ import absolute_import

import pendulum

from marshmallow import ValidationError, fields

from fleaker._compat import text_type

from .mixin import FleakerFieldMixin

class PendulumField(fields.DateTime, FleakerFieldMixin):
    """Marshmallow field that deserialzes datetimes into Pendulum objects.

    Has the same output on dump as the standard DateTime field. Accepts the
    same kwargs on init.

    This field is effected by the following schema context variables:

    - ``'convert_dates'``: This will prevent the date string from being
        converted into a Pendulum object. This can be useful if you're going to
        be double deserialzing the value in the course of the request. This is
        needed for Webargs. By default, dates will be converted.

    Keyword Args:
        timezone (str): The timezone that the datetime must be in. If it
            doesn't match, a ``marshmallow.ValidationError`` is raised.
    """

    def _jsonschema_type_mapping(self):
        """Define the JSON Schema type for this field."""
        return {
            'type': 'string',
            'format': 'date-time',
        }

    def _deserialize(self, value, attr, obj):
        """Deserializes a string into a Pendulum object."""
        if not self.context.get('convert_dates', True) or not value:
            return value

        value = super(PendulumField, self)._deserialize(value, attr, value)
        timezone = self.get_field_value('timezone')
        target = pendulum.instance(value)

        if (timezone and (text_type(target) !=
                          text_type(target.in_timezone(timezone)))):
            raise ValidationError(
                "The provided datetime is not in the "
                "{} timezone.".format(timezone)
            )

        return target


text:
package com.cloud.api.command.admin.storage;

import com.cloud.api.ApiCmdTestUtil;

import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;

public class CreateSecondaryStagingStoreCmdTest {

    @Test
    public void getDetails() throws IllegalArgumentException,
            IllegalAccessException {
        final CreateSecondaryStagingStoreCmd cmd = new CreateSecondaryStagingStoreCmd();
        final HashMap<String, Map<String, String>> details = new HashMap<>();
        final HashMap<String, String> kv = new HashMap<>();
        kv.put("key", "TEST-KEY");
        kv.put("value", "TEST-VALUE");
        details.put("does not matter", kv);
        ApiCmdTestUtil.set(cmd, "details", details);
        final Map<String, String> detailsMap = cmd.getDetails();
        Assert.assertNotNull(detailsMap);
        Assert.assertEquals(1, detailsMap.size());
        Assert.assertTrue(detailsMap.containsKey("TEST-KEY"));
        Assert.assertEquals("TEST-VALUE", detailsMap.get("TEST-KEY"));
    }

    @Test
    public void getDetailsEmpty() throws IllegalArgumentException,
            IllegalAccessException {
        final CreateSecondaryStagingStoreCmd cmd = new CreateSecondaryStagingStoreCmd();
        ApiCmdTestUtil.set(cmd, "details", new HashMap<String, Map<String, String>>());
        Assert.assertNull(cmd.getDetails());
    }

    @Test
    public void getDetailsNull() throws IllegalArgumentException,
            IllegalAccessException {
        final CreateSecondaryStagingStoreCmd cmd = new CreateSecondaryStagingStoreCmd();
        ApiCmdTestUtil.set(cmd, "details", null);
        Assert.assertNull(cmd.getDetails());
    }
}


text:
module Quizzlr
  class QuizzesController < ApplicationController

    def index
      @quizzes = Quizzlr::Quiz.all
    end

    def new
      @quiz = Quizzlr::Quiz.new
    end

    def create
      @quiz = Quizzlr::Quiz.new params[:quiz]
      if @quiz.save
        redirect_to quizzes_path
      else
        render :new
      end
    end

    def show
      @quiz = Quizzlr::Quiz.find params[:id]
    end

    def edit
      @quiz = Quizzlr::Quiz.find params[:id]
    end

    def update
      @quiz = Quizzlr::Quiz.find params[:id]
      if @quiz.update_attributes(params[:quiz])
        redirect_to quizzes_path
      else
        render :edit
      end
    end

    def destroy
      @quiz = Quizzlr::Quiz.find params[:id]
      @quiz.destroy
      redirect_to quizzes_path
    end

    def results
      @quiz = Quizzlr::Quiz.find params[:id]
      respond_to do |format|
        format.json { render json: @quiz.results(params) }
      end
    end
  end
end


text:
import { TWITTER_SIGN_IN_CALLBACK_PATH, AUTH0_SIGN_IN_CALLBACK_PATH } from './config'

export const TWITTER_SIGN_IN_CALLBACK_URL =
  new URL(TWITTER_SIGN_IN_CALLBACK_PATH, window.location.origin).href

export const AUTH0_SIGN_IN_CALLBACK_URL =
  new URL(AUTH0_SIGN_IN_CALLBACK_PATH, window.location.origin).href

export const JUST_SIGNED_IN_PATH = 'just-signed-in'
export const JUST_SIGNED_IN_URL =
  new URL(JUST_SIGNED_IN_PATH, window.location.origin).href

export const TWITTER_SIGN_IN_PATH = 'twitter-sign-in'
export const TWITTER_URL_SIGN_IN_REDIRECT =
  TWITTER_SIGN_IN_PATH +
  '?callbackUri=' + TWITTER_SIGN_IN_CALLBACK_URL +
  '&redirectUri=' + JUST_SIGNED_IN_URL

// Path segments
export const URL_NEW_STREET = 'new'
export const URL_NEW_STREET_COPY_LAST = 'copy-last'
export const URL_GLOBAL_GALLERY = 'gallery'
export const URL_ERROR = 'error'
export const URL_NO_USER = '-'
export const URL_HELP = 'help'

export const URL_ERROR_ACCESS_DENIED = 'access-denied'
export const URL_ERROR_NO_ACCESS_TOKEN = 'no-access-token'

export const URL_ERROR_NO_TWITTER_REQUEST_TOKEN = 'no-twitter-request-token'
export const URL_ERROR_NO_TWITTER_ACCESS_TOKEN = 'no-twitter-access-token'
export const URL_ERROR_AUTHENTICATION_API_PROBLEM = 'authentication-api-problem'

export const URL_EXAMPLE_STREET = 'streetmix/7'

// Since URLs like "streetmix.net/new" are reserved, but we still want
// @new to be able to use Streetmix, we prefix any reserved URLs with ~
export const RESERVED_URLS = [
  TWITTER_SIGN_IN_PATH,
  TWITTER_SIGN_IN_CALLBACK_PATH,
  AUTH0_SIGN_IN_CALLBACK_PATH,
  JUST_SIGNED_IN_PATH,
  URL_NEW_STREET,
  URL_NEW_STREET_COPY_LAST,
  URL_HELP,
  URL_GLOBAL_GALLERY,
  URL_ERROR,
  'streets',
  'terms-of-service',
  'privacy-policy',
  'map'
]

export const URL_RESERVED_PREFIX = '~'


text:
using System;
using System.Collections;
using System.Collections.Generic;

using Kirkin.ChangeTracking;

using NUnit.Framework;

namespace Kirkin.Tests.ChangeTracking
{
    internal static class PropertyValueComparerExtensions
    {
        public static PropertyValueEqualityComparer<T> WithStringComparer<T>(
            this PropertyValueEqualityComparer<T> propertyValueComparer,
            StringComparer stringComparer)
        {
            return new PropertyValueEqualityComparer<T>(propertyValueComparer.PropertyList, new Dictionary<Type, IEqualityComparer> {
                { typeof(string), stringComparer }
            });
        }
    }

    public class PropertyValueEqualityComparerTests
    {
        [Test]
        public void EqualityComparerBenchmark()
        {
            IEqualityComparer<Dummy> comparer = PropertyValueEqualityComparer<Dummy>.Default;

            for (var i = 0; i < 1000000; i++)
            {
                var dummy1 = new Dummy {
                    ID = 1,
                    Value = "Text"
                };

                var dummy2 = new Dummy {
                    ID = 1,
                    Value = "Text"
                };

                Assert.True(comparer.Equals(dummy1, dummy2));
                Assert.False(!comparer.Equals(dummy1, dummy2));

                dummy2.Value = "zzz";

                Assert.False(comparer.Equals(dummy1, dummy2));
            }
        }

        [Test]
        public void EqualsBenchmark()
        {
            var comparer = PropertyValueEqualityComparer<Dummy>.Default;

            for (var i = 0; i < 1000000; i++)
            {
                var dummy1 = new Dummy {
                    ID = 1,
                    Value = "Text"
                };

                var dummy2 = new Dummy {
                    ID = 1,
                    Value = "Text"
                };

                Assert.True(comparer.Equals(dummy1, dummy2));
                Assert.False(!comparer.Equals(dummy1, dummy2));

                dummy2.Value = "zzz";

                Assert.False(comparer.Equals(dummy1, dummy2));
            }
        }

        [Test]
        public void EqualsNullity()
        {
            var comparer = PropertyValueEqualityComparer<Dummy>.Default;
            var dummy1 = new Dummy();
            var dummy2 = new Dummy();

            Assert.True(comparer.Equals(dummy1, dummy2));
            Assert.True(comparer.Equals(null, null));
            Assert.False(comparer.Equals(dummy1, null));
            Assert.False(comparer.Equals(null, dummy2));
        }

        [Test]
        public void EqualsStringComparer()
        {
            var comparer = PropertyValueEqualityComparer<Dummy>.Default;
            var dummy1 = new Dummy { ID = 1, Value = "zzz" };
            var dummy2 = new Dummy { ID = 1, Value = "ZZZ" };

            Assert.False(comparer.Equals(dummy1, dummy2));
            Assert.False(comparer.WithStringComparer(StringComparer.InvariantCulture).Equals(dummy1, dummy2));
            Assert.True(comparer.WithStringComparer(StringComparer.InvariantCultureIgnoreCase).Equals(dummy1, dummy2));
        }

        [Test]
        [Obsolete("Suppressing GetHashCode warnings.")]
        public new void GetHashCode()
        {
            var comparer = PropertyValueEqualityComparer<Dummy>.Default;
            var dummy = new Dummy();

            dummy.ID = 1;

            Assert.AreEqual((17 * 23 + dummy.ID.GetHashCode()) * 23, comparer.GetHashCode(dummy));

            dummy.Value = "Zzz";

            Assert.AreEqual((17 * 23 + dummy.ID.GetHashCode()) * 23 + dummy.Value.GetHashCode(), comparer.GetHashCode(dummy));

            comparer = new PropertyValueEqualityComparer<Dummy>(comparer.PropertyList.Without(d => d.Value));

            Assert.AreEqual(17 * 23 + dummy.ID.GetHashCode(), comparer.GetHashCode(dummy));
        }

        [Test]
        public void GetHashCodeStringComparer()
        {
            var comparer = PropertyValueEqualityComparer<Dummy>.Default;
            var dummy1 = new Dummy { ID = 1, Value = "zzz" };
            var dummy2 = new Dummy { ID = 1, Value = "ZZZ" };

            Assert.AreNotEqual(comparer.GetHashCode(dummy1), comparer.GetHashCode(dummy2));
            Assert.AreNotEqual(comparer.WithStringComparer(StringComparer.InvariantCulture).GetHashCode(dummy1), comparer.WithStringComparer(StringComparer.InvariantCulture).GetHashCode(dummy2));
            Assert.AreEqual(comparer.WithStringComparer(StringComparer.InvariantCultureIgnoreCase).GetHashCode(dummy1), comparer.WithStringComparer(StringComparer.InvariantCultureIgnoreCase).GetHashCode(dummy2));
        }

        [Test]
        public void SameGetHashCodeWhenEquals()
        {
            var comparer = PropertyValueEqualityComparer<Dummy>.Default;
            var dummy1 = new Dummy();
            var dummy2 = new Dummy();

            Assert.True(comparer.Equals(dummy1, dummy2));
            Assert.True(comparer.GetHashCode(dummy1) == comparer.GetHashCode(dummy2));

            dummy1.ID = 1;

            Assert.False(comparer.Equals(dummy1, dummy2));
            Assert.False(comparer.GetHashCode(dummy1) == comparer.GetHashCode(dummy2));

            dummy2.ID = 1;

            Assert.True(comparer.Equals(dummy1, dummy2));
            Assert.True(comparer.GetHashCode(dummy1) == comparer.GetHashCode(dummy2));
        }

        private class Dummy
        {
            public int ID { get; set; }
            public string Value { get; set; }
        }
    }
}


text:
/**************************************************************************//**
 * @file     FlashDev.c
 * @brief    Flash Device Description for New Device Flash
 * @version  V1.0.0
 * @date     10. January 2018
 ******************************************************************************/
/*
 * Copyright (c) 2010-2018 Arm Limited. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the License); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "FlashOS.h"        // FlashOS Structures

struct FlashDevice const FlashDevice  =  {
   FLASH_DRV_VERS,             // Driver Version, do not modify!
   "New Device 256kB Flash",   // Device Name
   ONCHIP,                     // Device Type
   0x00000000,                 // Device Start Address
   0x00040000,                 // Device Size in Bytes (256kB)
   1024,                       // Programming Page Size
   0,                          // Reserved, must be 0
   0xFF,                       // Initial Content of Erased Memory
   100,                        // Program Page Timeout 100 mSec
   3000,                       // Erase Sector Timeout 3000 mSec

// Specify Size and Address of Sectors
   0x002000, 0x000000,         // Sector Size  8kB (8 Sectors)
   0x010000, 0x010000,         // Sector Size 64kB (2 Sectors)
   0x002000, 0x030000,         // Sector Size  8kB (8 Sectors)
   SECTOR_END
};


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Oops Formulaire</title>
    <link href="../css/bootstrap.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/style.css">
    <link href='https://fonts.googleapis.com/css?family=Roboto+Condensed' rel='stylesheet' type='text/css'>

    <header class="col-sm-12 col-md-12 <col>-lg-12">

COMMANDER

CONNEXION

SUIVEZ-NOUS

    <form action="index2.html" method="post">
      <fieldset>
        <legend>Laissez-nous votre message</legend>

            <input type="text" name="société" placeholder="Société" class="champs" required/>

            <input type="email" placeholder="Mail" class="champs" required>

        <input type="text" name="objet" placeholder="Objet" class="champs" required/>

        <textarea name="message" id="message" rows="10" cols="50" required>Votre message ...</textarea>

      <input type="submit" value="Envoyer" id="bouton" />
      </fieldset>

  </form>

Contact

CGV

Mentions

F.A.Q

Oops Remercie

©2016 MyOopsPro - Tous droits réservés


text:
(function() {
	'use strict';
	var
		TEMPLATE_PATH = 'app/features/questions/',
		ROUTES = [{
			name: 'knowledgeTags',
			state: {
				url: '/knowledge',
				templateUrl: TEMPLATE_PATH + 'knowledgeareas.html',
				controller: 'wtKnowledgeAreas',
				controllerAs: "vm",
				resolve: {
					areas: 'wtQuestionTagsResolver'
				},
				data: {
					menu: {
						name: 'Study Questions'
					}
				}
			}
		}];

	angular.module('wt.knowledgeAreas', ['ngMaterial', 'wt.routes', 'wt.config'])
		.constant('wtKnowledgeAreasConfig', {
			routes: ROUTES
		})
		.config(moduleConfig)
		.controller('wtKnowledgeAreas', wtKnowledgeAreas);

	/**
	 * Module configuration
	 */
	moduleConfig.$inject = ['wtRouteProvider', 'wtKnowledgeAreasConfig'];

	function moduleConfig(wtRoutes, wtKnowledgeAreasConfig) {
		wtRoutes.$get().setRoutes(wtKnowledgeAreasConfig.routes);
	}

	/**
	 * Knowledge Area controller
	 */
	wtKnowledgeAreas.$inject = ['areas'];

	function wtKnowledgeAreas(areas) {
		var vm = this;

		// controller activation
		(function() {
			vm.areas = areas;
		})();
	}
})();


text:
using RazorLight.Tests.Models;
using System.Collections.Generic;
using System.Dynamic;
using Xunit;

namespace RazorLight.Tests
{
	public class ModelTypeInfoTest
	{
		[Fact]
		public void Real_Object_Is_StrongType_True()
		{
			var info = new ModelTypeInfo(typeof(TestViewModel));

			Assert.True(info.IsStrongType);
		}

		[Fact]
		public void Anonymous_Objects_Has_StrongType_False()
		{
			var model = new
			{
				Title = "Johny"
			};

			var info = new ModelTypeInfo(model.GetType());

			Assert.False(info.IsStrongType);
		}

		[Fact]
		public void Return_Dynamic_TemplateTypeName_On_AnonymousObjects()
		{
			var model = new { Title = "Jogny" };
			var info = new ModelTypeInfo(model.GetType());

			string expectedTemplateType = "dynamic";

			Assert.Equal(info.TemplateTypeName, expectedTemplateType);
		}

		[Fact]
		public void Return_Expando_TemplateType_On_AnonymousObjects()
		{
			var model = new { Title = "Johny" };
			var info = new ModelTypeInfo(model.GetType());

			Assert.Equal(typeof(ExpandoObject), info.TemplateType);
		}

		[Fact]
		public void Return_Same_Type_On_StrongType()
		{
			var info = new ModelTypeInfo(typeof(TestViewModel));

			Assert.Equal(typeof(TestViewModel), info.TemplateType);
		}

		[Fact]
		public void Return_Current_FriendlyName()
		{
			var info = new ModelTypeInfo(typeof(TestViewModel));

			string expectedTypeName = "RazorLight.Tests.Models.TestViewModel";

			Assert.Equal(info.TemplateTypeName, expectedTypeName);
		}

		[Fact]
		public void Return_Correct_FriendlyName_On_Generic()
		{
			var model = new List<List<TestViewModel>>();
			var info = new ModelTypeInfo(model.GetType());

			string expectedTypeName = "System.Collections.Generic.List<System.Collections.Generic.List<RazorLight.Tests.Models.TestViewModel>>";

			Assert.Equal(info.TemplateTypeName, expectedTypeName);
		}
	}
}


text:
package com.gmail.trentech.wirelessred.commands;

import java.math.BigDecimal;
import java.util.Optional;

import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.EventContext;
import org.spongepowered.api.event.cause.EventContextKeys;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.service.economy.EconomyService;
import org.spongepowered.api.service.economy.transaction.ResultType;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;

import com.gmail.trentech.pjc.core.ConfigManager;
import com.gmail.trentech.wirelessred.Main;
import com.gmail.trentech.wirelessred.init.Items;

import ninja.leaping.configurate.ConfigurationNode;

public class CMDUpgrade implements CommandExecutor {

	@Override
	public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
		if (!(src instanceof Player)) {
			throw new CommandException(Text.of(TextColors.RED, "Must be a player"));
		}
		Player player = (Player) src;

		String level = args.<String> getOne("level").get();

		int quantity = 1;

		if (args.hasAny("quantity")) {
			quantity = args.<Integer> getOne("quantity").get();
		}

		if(level.equalsIgnoreCase("64")) {
			if(charge(player, "64", quantity)) {
				ItemStack itemStack = Items.getUpgrade("64");
				itemStack.setQuantity(quantity);

				player.getInventory().offer(itemStack);
			}
		} else if (level.equalsIgnoreCase("128")) {
			if(charge(player, "128", quantity)) {
				ItemStack itemStack = Items.getUpgrade("128");
				itemStack.setQuantity(quantity);

				player.getInventory().offer(itemStack);
			}
		} else if (level.equalsIgnoreCase("256")) {
			if(charge(player, "256", quantity)) {
				ItemStack itemStack = Items.getUpgrade("256");
				itemStack.setQuantity(quantity);

				player.getInventory().offer(itemStack);
			}
		} else if (level.equalsIgnoreCase("512")) {
			if(charge(player, "512", quantity)) {
				ItemStack itemStack = Items.getUpgrade("512");
				itemStack.setQuantity(quantity);

				player.getInventory().offer(itemStack);
			}
		} else if (level.equalsIgnoreCase("Unlimited")) {
			if(charge(player, "Unlimited", quantity)) {
				ItemStack itemStack = Items.getUpgrade("Unlimited");
				itemStack.setQuantity(quantity);

				player.getInventory().offer(itemStack);
			}
		} else {
			throw new CommandException(Text.of(TextColors.RED, "Not a valid upgrade"));
		}

		return CommandResult.success();
	}

	private boolean charge(Player player, String arg, int quantity) {
		ConfigurationNode config = ConfigManager.get(Main.getPlugin()).getConfig();

		if(config.getNode("settings", "economy", "enable").getBoolean() && !player.hasPermission("wirelessred.admin")) {
			double cost = config.getNode("settings", "economy", "items", "upgrade_" + arg).getDouble() * quantity;

			Optional<EconomyService> optionalEconomy = Sponge.getServiceManager().provide(EconomyService.class);

			if (!optionalEconomy.isPresent()) {
				player.sendMessage(Text.of(TextColors.RED, "Economy plugin not found!"));
				Main.instance().getLog().error("Economy plugin not found!");
				return false;
			}

			EconomyService economy = optionalEconomy.get();

			if(economy.getOrCreateAccount(player.getUniqueId()).get().withdraw(economy.getDefaultCurrency(), new BigDecimal(cost), Cause.of(EventContext.builder().add(EventContextKeys.PLUGIN, Main.getPlugin()).build(), Main.getPlugin())).getResult() == ResultType.FAILED) {
				player.sendMessage(Text.of(TextColors.RED, "Not enough money. Need ", TextColors.YELLOW, "$", cost));
				return false;
			}

			player.sendMessage(Text.of(TextColors.GREEN, "You were charged ", TextColors.YELLOW, "$", cost));
		}

		return true;
	}

}


text:
package org.apache.stratos.common.beans;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "error")
public class ErrorResponseBean {

    private int errorCode;
    private String errorMessage;

    public ErrorResponseBean() {

    }

    public ErrorResponseBean(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public ErrorResponseBean(int errorCode, String errorMessage) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

}


text:
require "spec_helper"

describe SeasonGenerator do

	before :each do
		@generator = SeasonGenerator.new(4)
	end

	describe "#new" do
		it "throws an ArgumentError if given less than one parameter" do
			lambda { SeasonGenerator.new }.should raise_exception ArgumentError
		end

	end

	describe "#teams" do

		it "returns a list of teams" do
			SeasonGenerator.new(2).teams.should be_instance_of Array
		end

		it "generates as many teams as specified with number of teams" do
			SeasonGenerator.new(16).teams.count.should eql 16
		end

	end

	describe "#generate_pairings" do

		it "returns a list of pairings" do
			SeasonGenerator.new(2).generate_pairings.should be_instance_of Array
		end

		it "generates all pairings as specified with number of teams" do
			SeasonGenerator.new(4).generate_pairings.count.should eql 6
		end

		it "avoids duplicate pairings" do
			pairings = SeasonGenerator.new(4).generate_pairings
			pairings.count.should eql pairings.uniq.count
		end

	end

	describe "#matches" do

		it "returns a list of matches" do
			SeasonGenerator.new(2).matches.should be_instance_of Array
		end

		it "generates all matches as specified with number of teams" do
			SeasonGenerator.new(4).matches.count.should eql 12
		end

		it "generates matches with a matchday number" do
			matches = SeasonGenerator.new(4).matches
			matches.each do |match|
				match.matchday.should > 0
			end
		end

	end

	describe "#create_match" do
		it "creates a match" do
			home_team = double(:team)
			away_team = double(:team)
			date = Time.now
			matchday = 1
			@generator.create_match home_team, away_team, date, matchday
		end
	end

end


text:
using System;

namespace Itinero.Optimization.Strategies
{
    /// <summary>
    /// An operator defined by a function.
    /// </summary>
    /// <typeparam name="TCandidate">The candidate type.</typeparam>
    public sealed class FuncOperator<TCandidate> : Operator<TCandidate>
        where TCandidate : class
    {
        private readonly Func<TCandidate, bool> _func;

        /// <summary>
        /// Creates a new operator.
        /// </summary>
        /// <param name="func">The function to use.</param>
        public FuncOperator(Func<TCandidate, bool> func)
        {
            _func = func;
            Name = Constants.ANONYMOUS;
        }

        /// <summary>
        /// Creates a new operator.
        /// </summary>
        /// <param name="func">The function to use.</param>
        /// <param name="name">The name of this strategy.</param>
        public FuncOperator(Func<TCandidate, bool> func, string name)
        {
            _func = func;
            Name = name;
        }

        /// <summary>
        /// Gets the name.
        /// </summary>
        /// <returns></returns>
        public override string Name { get; }

        /// <summary>
        /// Applies this operator to the given candidate.
        /// </summary>
        /// <param name="candidate">The candidate.</param>
        /// <returns>True if an improvement was found.</returns>
        public override bool Apply(TCandidate candidate)
        {
            return _func(candidate);
        }
    }

    /// <summary>
    /// Extension methods related to the function operator.
    /// </summary>
    public static class FuncOperatorExtensions
    {
        /// <summary>
        /// Converts the function into an operator instance.
        /// </summary>
        /// <param name="func">The function to use as an operator.</param>
        /// <returns>An operator based on the given function.</returns>
        public static FuncOperator<TCandidate> ToOperator<TCandidate>(this Func<TCandidate, bool> func)
            where TCandidate : class
        {
            return new FuncOperator<TCandidate>(func);
        }

        /// <summary>
        /// Converts the function into an operator instance.
        /// </summary>
        /// <param name="func">The function to use as an operator.</param>
        /// <param name="name">The name of the operator.</param>
        /// <returns>An operator based on the given function.</returns>
        public static FuncOperator<TCandidate> ToOperator<TCandidate>(this Func<TCandidate, bool> func, string name)
            where TCandidate : class
        {
            return new FuncOperator<TCandidate>(func, name);
        }
    }
}


text:
<?php
  $this -> load -> view('admin/head');
  $this -> load -> view('admin/layout_start');
?>

Potwierdź usunięcie składnika

  <?php if(isset($errors)): ?>

Nie udało się usunąć składnika. Spróbuj ponownie

  <?php endif; ?>
  <?php if(isset($success)): ?>

Pomyślnie usunięto składnik

  <?php else: ?>

Czy na pewno chcesz usunąć składnik <?=$component -> name?>?

      <a href="<?=base_url('admin/components/')?>" class="btn btn-default btn-block">Anuluj

      <form method="post" action="<?=base_url('admin/components/delete/' . $component -> id)?>">
        <input type="hidden" name="id" value="<?=$component -> id?>" />
        <button type="submit" class="btn btn-danger btn-block">Usuń</button>
      </form>

  <?php endif; ?>

<?php
  $this -> load -> view('admin/layout_end');
  $this -> load -> view('admin/footer');
?>


text:
module Api::V1
  class UserSerializer < ActiveModel::Serializer
    attributes :id, :name, :email, :admin, :color, :round, :settings, :tiles

    belongs_to :game
  end
end


text:
describe AllegroApi::JournalEvent do
  describe 'from_api' do
    let(:api_data) do
      {
        row_id: 2869399784,
        item_id: 975967833,
        change_type: 'start',
        change_date: 1269603383,
        current_price: 0,
        item_seller_id: 4109848
      }
    end

    subject { AllegroApi::JournalEvent.from_api(api_data) }

    it 'sets event id' do
      expect(subject.id).to eq 2869399784
    end

    it 'sets item id' do
      expect(subject.item_id).to eq 975967833
    end

    it 'sets change type for event' do
      expect(subject.change_type).to eq 'start'
    end

    it 'sets changed at for event' do
      expect(subject.changed_at).to eq Time.at(1269603383)
    end

    it 'sets current price' do
      expect(subject.current_price).to eq 0
    end

    it 'sets seller id' do
      expect(subject.seller_id).to eq 4109848
    end
  end

  describe '#buy_now?' do
    let(:event) { AllegroApi::JournalEvent.new }

    it 'is true for "now" type events' do
      event.change_type = 'now'
      expect(event.buy_now?).to eq true
    end

    it 'is false for not "now" type events' do
      event.change_type = 'end'
      expect(event.buy_now?).to eq false
    end
  end

  describe '#auction_ended?' do
    let(:event) { AllegroApi::JournalEvent.new }

    it 'is true for "end" type events' do
      event.change_type = 'end'
      expect(event.auction_ended?).to eq true
    end

    it 'is false for not "end" type events' do
      event.change_type = 'now'
      expect(event.auction_ended?).to eq false
    end
  end
end


text:
module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config
};


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	function greeting_msg (){
		date_default_timezone_set("Asia/Jakarta");

		$hour = date("G",time());

		if ($hour>=0 && $hour<=11)
		{
			return "Selamat Pagi";
		}
		elseif ($hour >=12 && $hour<=14)
		{
			return "Selamat Siang";
		}
		elseif ($hour >=15 && $hour<=17)
		{
			return "Selamat Sore";
		}
		elseif ($hour >=17 && $hour<=18)
		{
			return "Selamat Petang";
		}
		elseif ($hour >=19 && $hour<=23)
		{
			return "Selamat Malam";
		}
	}

	public function __construct()
    {
        parent::__construct();
        $this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
		$this->output->set_header("Pragma: no-cache");

        $this->load->model('Auth');

        if ( ($this->session->userdata('nim') || $this->session->userdata('token')) == NULL) {
        	$array = array(
	        	'nim' 	=> $this->input->post('nim'),
	        	'token' => $this->input->post('token')
	        );

	        $this->session->set_userdata( $array );
        }

        $nim 	= $this->session->userdata('nim');
	    $token	= $this->session->userdata('token');

	    // die($nim);
        $this->Auth->voterAuth($nim, $token);

        if($this->Auth->isVoter() == FALSE){
        	redirect('login');
        }
    }

	public function index()
	{
		$this->load->view('user/layout');
	}

	public function bem()
	{
        if (($this->session->userdata('bem') || $this->session->userdata('senat')) !== NULL) {
			$voted = array(
				'bem' 	=> $this->session->userdata('bem'),
				'senat' => $this->session->userdata('senat')
			);
			$this->session->unset_userdata($voted);
		}

		$data['waktu'] 	= $this->greeting_msg();
		$data['view']	= 'vote-bem';
		$data['title']	= 'Vote BEM';
		$this->load->view('user/layout', $data);
	}

	public function senat()
	{
		$array = array(
			'bem' 	=> $this->input->post('paslonbem')
		);

		$this->session->set_userdata( $array );
		$data['waktu'] = $this->greeting_msg();
		$data['view']	= 'vote-senat';
		$data['title']	= 'Vote Senator';
		$this->load->view('user/layout', $data);
	}

	public function review() {
		$array = array(
			'bem' 	=> $this->input->post('paslonbem'),
			'senat' => $this->input->post('senator')
		);

		$this->session->set_userdata( $array );

		$data['waktu'] = $this->greeting_msg();
		$data['view']	= 'vote-review';
		$data['title']	= 'Vote Review';
		$this->load->view('user/layout',$data);
	}

	public function thanks() {

		$nim		= $this->session->userdata('nim');
		$bem 		= $this->session->userdata('bem');
		$senat 		= $this->session->userdata('senat');
		$angkatan 	= $this->session->userdata('angkatan');

		$this->load->model('User_model');
		$this->User_model->voting($nim, $bem, $senat, $angkatan);

		$data['waktu'] = $this->greeting_msg();
		$data['view']	= 'thanks-msg';
		$data['title']	= 'Thank You';
		$this->load->view('user/layout', $data);
	}

}


text:
@interface TDCharTest : XCTestCase {
    NSString *s;
    PKCharacterAssembly *a;
    PKChar *p;
    PKAssembly *result;
}

@end