text
stringlengths
8
6.88M
#pragma once #include "ExampleBase.h" class CreateGLContext : public ExampleBase { public: void initGLData() { // 面剔除需要手动开启 glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); glFrontFace(GL_CCW); glViewport(0, 0, WINDOW_WIDTH - 100, WINDOW_HEIGHT - 100); } void renderLoop() { glClearColor(0.3f, 0.3f, 0.7f, 1.f); glClear(GL_COLOR_BUFFER_BIT); } };
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef MOUSE_BAJKA_EVENT_H_ #define MOUSE_BAJKA_EVENT_H_ #include "IEvent.h" #include "geometry/Point.h" #include "KeyCode.h" #include <stdint.h> namespace Event { #define MAX_POINTERS 10 /** * Wartości przedstawiające guziki myszy. Można z nich robić maskę bitową. */ enum MotionButton { BUTTON0 = 1 << 0, //!< Lewy guzik myszy lub pierwszy pointer ekranu dotykowego BUTTON1 = 1 << 1, //!< Środkowy guzik myszy lub drugi pointer ekranu dotykowego BUTTON2 = 1 << 2, //!< Prawy guzik myszy lub trzeci pointer ekranu dotykowego BUTTON3 = 1 << 3, BUTTON4 = 1 << 4, BUTTON5 = 1 << 5, BUTTON6 = 1 << 6, BUTTON7 = 1 << 7, BUTTON8 = 1 << 8, BUTTON9 = 1 << 0 }; /** * Pojedynczy pointer. */ struct MotionPointer { MotionPointer (); /// Współrzędne ekranowe kursora. Geometry::Point position; /// Przesunięcie kursora w stosunku do poprzendiego punktu. Geometry::Point movement; /// Siła nacisku. float pressure; /// Rozmiar punktu. float size; /// Słuzy do rozróżniania pointerów. Dla myszki nie ma znaczenia, bo 1 pointer. int32_t id; }; /** * Źródło eventu. */ enum MotionSource { MOUSE, //!< Mysz - jeden pointer, ale wile guzików. TOUCH, //!< Ekran dotykowy - wiele pointerów, kazdy po jednmym "guziku", nie można odrywać palca od ekranu poczas ruchu (w szczególnosci nie działa onMotionOver i Out). OTHER //!< Inne. }; /** * Event związany myszą lub z ekranem dotykowym. Dane pogrupowane są na kursory. Kiedy * podłączona jest mysz, to kursor jest tylko jeden. Kiedy używamy ekranu dotykowego, * kursorów jest tyle ile palców dotykających ekranu. * \ingroup Events */ class MotionEvent : public IEvent { public: MotionEvent (); virtual ~MotionEvent () {} /* * Dodatkowe klawisze na klawiaturze naciśnięte podczas tego eventu (takie jak ALT, CTRL etc). * Działa tylko na Androidzie. */ KeyMod getMetaState () const { return metaState; } void setMetaState (KeyMod metaState) { this->metaState = metaState; } /** * Liczba naciśniętych przycisków myszy lub, liczba pointerów na ekranie dotykowym (liczba * palców dotykających ekranu). */ int getPointerCount () const { return pointerCount; } void setPointerCount (int pointerCount) { this->pointerCount = pointerCount; } /** * Maska bitowa zawierająca informację o naciśniętych przyciskach myszy, albo o * aktywnych pointerach na ekranie dotykowym. Można testowac z wartościami z enumu * MotionPointer. */ uint32_t getButtons () const { return buttons; } void setButtons (uint32_t buttons) { this->buttons = buttons; } /** * Zwraca pointer o danym indeksie. Nie dokonuje */ MotionPointer const &getPointer (unsigned int i) const; MotionPointer &getPointer (unsigned int i); MotionSource getSource () const { return source; } void setSource (MotionSource s) { source = s; } virtual std::string toString () const; private: KeyMod metaState; int pointerCount; uint32_t buttons; MotionSource source; MotionPointer pointers[MAX_POINTERS]; }; } // namespace Event # endif /* MOUSE_BAJKA_EVENT_H_ */
/* * validatorTests.cpp * * Created on: 19. 12. 2016 * Author: ondra */ #include <iostream> #include <fstream> #include "testClass.h" #include "../imtjson/validator.h" #include "../imtjson/object.h" #include "../imtjson/string.h" using namespace json; void ok(std::ostream &out, bool res) { if (res) out <<"ok"; else out << "fail"; } void vtest(std::ostream &out, Value def, Value test) { Validator vd(def); if (vd.validate(test,"_root")) { out << "ok"; } else { out << vd.getRejections().toString(); } } void runValidatorTests(TestSimple &tst) { tst.test("Validator.string","ok") >> [](std::ostream &out) { vtest(out,Object("_root","string"),"aaa"); }; tst.test("Validator.not_string","[[[],\"string\"]]") >> [](std::ostream &out) { vtest(out,Object("_root","string"),12.5); }; tst.test("Validator.charset","ok") >> [](std::ostream &out) { vtest(out,Object("_root","[a-z-0-9XY]"),"ahoj-123"); }; tst.test("Validator.charset.neg","ok") >> [](std::ostream &out) { vtest(out,Object("_root","[^a-z-0-9XY]"),"AHOJ!"); }; tst.test("Validator.charset.not_ok",R"([[[],"[a-z-123]"]])") >> [](std::ostream &out) { vtest(out,Object("_root","[a-z-123]"),"ahoj_123"); }; tst.test("Validator.charset.neg.not_ok",R"([[[],"[^a-z-]"]])") >> [](std::ostream &out) { vtest(out,Object("_root","[^a-z-]"),"AHOJ-AHOJ"); }; tst.test("Validator.not_string","[[[],\"string\"]]") >> [](std::ostream &out) { vtest(out,Object("_root","string"),12.5); }; tst.test("Validator.number","ok") >> [](std::ostream &out) { vtest(out,Object("_root","number"),12.5); }; tst.test("Validator.not_number","[[[],\"number\"]]") >> [](std::ostream &out) { vtest(out,Object("_root","number"),"12.5"); }; tst.test("Validator.boolean","ok") >> [](std::ostream &out) { vtest(out,Object("_root","boolean"),true); }; tst.test("Validator.not_boolean","[[[],\"boolean\"]]") >> [](std::ostream &out) { vtest(out,Object("_root","boolean"),"w2133"); }; tst.test("Validator.array","ok") >> [](std::ostream &out) { vtest(out,Object("_root",{array,"number"}),{12,32,87,21}); }; tst.test("Validator.arrayMixed","ok") >> [](std::ostream &out) { vtest(out,Object("_root",{array,"number","boolean"}),{12,32,87,true,12}); }; tst.test("Validator.array.fail","[[[1],\"number\"]]") >> [](std::ostream &out) { vtest(out,Object("_root",{array,"number"}),{12,"pp",32,87,21}); }; tst.test("Validator.arrayMixed-fail","[[[2],\"number\"],[[2],\"boolean\"]]") >> [](std::ostream &out) { vtest(out,Object("_root",{array,"number","boolean"}),{12,32,"aa",87,true,12}); }; tst.test("Validator.array.limit","ok") >> [](std::ostream &out) { vtest(out,Object("_root",{{array,"number"},{"maxsize",3}}),{10,20,30}); }; tst.test("Validator.array.limit-fail","[[[],[\"maxsize\",3]]]") >> [](std::ostream &out) { vtest(out,Object("_root",{"^",{array,"number"},{"maxsize",3}}),{10,20,30,40}); }; tst.test("Validator.tuple","ok") >> [](std::ostream &out) { vtest(out, Object("_root", { {3},"number","string","string" }), { 12,"abc","cdf" }); }; tst.test("Validator.tuple-fail1","[[[3],[[3],\"number\",\"string\",\"string\"]]]") >> [](std::ostream &out) { vtest(out, Object("_root", { {3},"number","string","string" }), { 12,"abc","cdf",232 }); }; tst.test("Validator.tuple-fail2","[[[2],\"string\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", { {3},"number","string","string" }), { 12,"abc" }); }; tst.test("Validator.tuple-optional","ok") >> [](std::ostream &out) { vtest(out, Object("_root", { {3},"number","string",{"string","optional"} }), { 12,"abc" }); }; tst.test("Validator.tuple-fail3","[[[1],\"string\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", { {3},"number","string","string" }), { 12,21,"abc" }); }; tst.test("Validator.tuple+","ok") >> [](std::ostream &out) { vtest(out, Object("_root", { {2},"number","string","number" }), { 12,"abc",11,12,13,14 }); }; tst.test("Validator.object", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", Object("aaa","number")("bbb","string")("ccc","boolean")), Object("aaa",12)("bbb","xyz")("ccc",true)); }; tst.test("Validator.object.failExtra", "[[[\"ddd\"],\"undefined\"],[[],{\"aaa\":\"number\",\"bbb\":\"string\",\"ccc\":\"boolean\"}]]") >> [](std::ostream &out) { vtest(out, Object("_root", Object("aaa", "number")("bbb", "string")("ccc", "boolean")), Object("aaa", 12)("bbb", "xyz")("ccc", true)("ddd",12)); }; tst.test("Validator.object.failMissing", "[[[\"bbb\"],\"string\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", Object("aaa", "number")("bbb", "string")("ccc", "boolean")), Object("aaa", 12)("ccc", true)); }; tst.test("Validator.object.okExtra", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", Object("aaa", "number")("bbb", "string")("ccc", "boolean")("%","number")), Object("aaa", 12)("bbb", "xyz")("ccc", true)("ddd", 12)); }; tst.test("Validator.object.extraFailType", "[[[\"ddd\"],\"number\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", Object("aaa", "number")("bbb", "string")("ccc", "boolean")("%", "number")), Object("aaa", 12)("bbb", "xyz")("ccc", true)("ddd", "3232")); }; tst.test("Validator.object.okMissing", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", Object("aaa", "number")("bbb", {"string","optional"})("ccc", "boolean")("%","number")), Object("aaa", 12)("ccc", true)); }; tst.test("Validator.object.array", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", Object("_xxx", {array,"any"})), Object("_xxx", {10,20,30})); }; tst.test("Validator.userClass", "ok") >> [](std::ostream &out) { vtest(out, Object("test", { "string","number" })("_root", Object("aaa", "test")("bbb","test")), Object("aaa", 12)("bbb","ahoj")); }; tst.test("Validator.recursive", "ok") >> [](std::ostream &out) { vtest(out, Object("test", { "string",{array,"test"} })("_root", { array, "number","test" }), { 10,{{"aaa"}} }); }; tst.test("Validator.recursive.fail", "[[[],\"number\"],[[],\"string\"],[[0,1,0],[[],\"test\"]],[[0,1,0],\"test\"],[[0,1],\"test\"],[[0],\"test\"],[[],\"test\"]]") >> [](std::ostream &out) { vtest(out, Object("test", { "string",{ array,"test" } })("_root", { "number","test" }), { { "ahoj",{ 12 } } }); }; tst.test("Validator.range", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { array, {">",0,"<",10} ,"string" } ), { "ahoj",4 }); }; tst.test("Validator.range.fail", "[[[1],\"string\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", { array, {">",0,"<",10},"string" }), { "ahoj",15 }); }; tst.test("Validator.range.multiple", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { array, {">",0,"<",10},{">=","A","<=","Z" } }), { "A",5 }); }; tst.test("Validator.range.multiple.fail", "[[[0],[\">\",0,\"<\",10]],[[0],[\">=\",\"A\",\"<=\",\"Z\"]]]") >> [](std::ostream &out) { vtest(out, Object("_root", { array, {">",0,"<",10},{">=","A","<=","Z" } }), { "a",5 }); }; tst.test("Validator.fnAll", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { "^","hex",">=","0","<=","9", "#comment" } ), "01255"); }; tst.test("Validator.fnAll.fail", "[[[],[\"^\",\"hex\",\">=\",\"0\",\"<=\",\"9\",\"#comment\"]]]") >> [](std::ostream &out) { vtest(out, Object("_root", { "^","hex", ">=","0","<=","9", "#comment" }), "A589"); }; tst.test("Validator.fnAll.fail2", "[[[],\"hex\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", { "^","hex",{ ">=","0","<=","9" } }), "lkoo"); }; tst.test("Validator.prefix.ok", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { "prefix","abc." }), "abc.123"); }; tst.test("Validator.prefix.fail", "[[[],[\"prefix\",\"abc.\"]]]") >> [](std::ostream &out) { vtest(out, Object("_root", { "prefix","abc." }), "abd.123"); }; tst.test("Validator.suffix.ok", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { "suffix",".abc" }), "123.abc"); }; tst.test("Validator.suffix.fail", "[[[],[\"suffix\",\".abc\"]]]") >> [](std::ostream &out) { vtest(out, Object("_root", { "suffix",".abc" }), "123.abd"); }; tst.test("Validator.prefix.tonumber.ok", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { "prefix","abc.", {"tonumber",{">",100}} }), "abc.123"); }; tst.test("Validator.suffix.tonumber.ok", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { "suffix",".abc",{ "tonumber",{ ">",100 } } }), "123.abc"); }; tst.test("Validator.comment.any", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { "#comment","any" }), 123); }; tst.test("Validator.comment.any2", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { "#comment","any" }), "3232"); }; tst.test("Validator.comment.any.fail", "[[[],\"#comment\"],[[],\"any\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", { "#comment","any" }), undefined); }; tst.test("Validator.enum1", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", {"'aaa","'bbb","'ccc" }), "aaa"); }; tst.test("Validator.enum2", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { "'aaa","'bbb","'ccc" }), "bbb"); }; tst.test("Validator.enum3", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { "'aaa","'bbb","'ccc" }), "ccc"); }; tst.test("Validator.enum4", "[[[],\"'aaa\"],[[],\"'bbb\"],[[],\"'ccc\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", { "'aaa","'bbb","'ccc" }), "ddd"); }; tst.test("Validator.enum5", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { 111,222,333 }), 111); }; tst.test("Validator.enum6", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { 111,222,333 }),222); }; tst.test("Validator.enum7", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { 111,222,333 }), 333); }; tst.test("Validator.enum8", "[[[],[111,222,333]]]") >> [](std::ostream &out) { vtest(out, Object("_root", { 111,222,333 }), "111"); }; tst.test("Validator.set1", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { array, 1,2,3 }), { 1,2 }); }; tst.test("Validator.set2", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { array, 1,2,3 }), { 1,3 }); }; tst.test("Validator.set3", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { array, 1,2,3 }), array); }; tst.test("Validator.set4", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { array, 1,2,3 }), { 2,3 }); }; tst.test("Validator.set5", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { array, 1,2,3 }), { 2, 3,3 }); }; tst.test("Validator.set6", "[[[1],[[],1,2,3]]]") >> [](std::ostream &out) { vtest(out, Object("_root", { array, 1,2,3 }), { 2,4}); }; tst.test("Validator.prefix-array.ok", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { "prefix",{"a","b"} }), { "a","b","c","d" }); }; tst.test("Validator.prefix-array.fail", "[[[],[\"prefix\",[\"a\",\"b\"]]]]") >> [](std::ostream &out) { vtest(out, Object("_root", { "prefix",{ "a","b" } }), { "a","c","b","d" }); }; tst.test("Validator.suffix-arrau.ok", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { "suffix",{ "c","d" } }), { "a","b","c","d" }); }; tst.test("Validator.suffix-array.fail", "[[[],[\"suffix\",[\"c\",\"d\"]]]]") >> [](std::ostream &out) { vtest(out, Object("_root", { "suffix",{ "c","d" } }), { "a","c","b","d" }); }; tst.test("Validator.key.ok", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", Object("%", { "^",{ "key",{"^","lowercase",{"maxsize",2} } },"number" })), Object("ab", 123)("cx", 456)); }; tst.test("Validator.key.fail", "[[[\"abc\"],[\"maxsize\",2]]]") >> [](std::ostream &out) { vtest(out, Object("_root", Object("%", { "^",{ "key",{ "^","lowercase",{ "maxsize",2 } } },"number" })), Object("abc", 123)("cx", 456)); }; tst.test("Validator.base64.ok", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", "base64"), "flZhTGlEYVRvUn5+flRlc1R+fg=="); }; tst.test("Validator.base64.fail1", "[[[],\"base64\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "base64"), "flZhTGl@YVRvUn5+flRlc1R+fg=="); }; tst.test("Validator.base64.fail2", "[[[],\"base64\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "base64"), "flZhTGlEYVRvUn5+flRlc1R+f==="); }; tst.test("Validator.base64.fail3", "[[[],\"base64\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "base64"), "flZhTGlEYVRvUn5+flRlc1R+f=="); }; tst.test("Validator.base64url.ok", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", "base64url"), "flZhTGlEYVRvUn5_flRlc1R_fg"); }; tst.test("Validator.base64url.fail1", "[[[],\"base64url\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "base64url"), "flZhTGlEYVRvUn5+flRlc1R+fg"); }; tst.test("Validator.not1", "ok") >> [](std::ostream &out) { vtest(out, Object("_root", { array, {"!",1,2,3} }), { 10,20 }); }; tst.test("Validator.not2", "[[[0],[\"!\",1,2,3]]]") >> [](std::ostream &out) { vtest(out, Object("_root", { array,{ "!",1,2,3 } }), { 1,3 }); }; tst.test("Validator.datetime","ok") >> [](std::ostream &out) { vtest(out, Object("_root", "datetime"), "2016-12-20T12:38:00Z"); }; tst.test("Validator.datetime.fail1","[[[],\"datetime\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "datetime"), "2016-13-20T12:38:00Z"); }; tst.test("Validator.datetime.fail2","[[[],\"datetime\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "datetime"), "2016-00-20T12:38:00Z"); }; tst.test("Validator.datetime.leap.fail","[[[],\"datetime\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "datetime"), "2015-02-29T12:38:00Z"); }; tst.test("Validator.datetime.leap.ok","ok") >> [](std::ostream &out) { vtest(out, Object("_root", "datetime"), "2016-02-29T12:38:00Z"); }; tst.test("Validator.datetime.fail3","[[[],\"datetime\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "datetime"), "2016-01-29T25:38:00Z"); }; tst.test("Validator.datetime.fail4","[[[],\"datetime\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "datetime"), "2016-12-20T12:70:00Z"); }; tst.test("Validator.datetime.fail5","[[[],\"datetime\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "datetime"), "2016-12-20T12:38:72Z"); }; tst.test("Validator.datetime.fail6","[[[],\"datetime\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "datetime"), "K<oe23HBY932pPLO(*JN"); }; tst.test("Validator.date.ok","ok") >> [](std::ostream &out) { vtest(out, Object("_root", "date"), "1985-10-17"); }; tst.test("Validator.date.fail","[[[],\"date\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "date"), "1985-10-17 EOX"); }; tst.test("Validator.time.ok","ok") >> [](std::ostream &out) { vtest(out, Object("_root", "timez"), "12:50:34Z"); }; tst.test("Validator.time.fail","[[[],\"timez\"]]") >> [](std::ostream &out) { vtest(out, Object("_root", "timez"), "A2xE0:34Z"); }; tst.test("Validator.explode.ok","ok") >> [](std::ostream &out) { vtest(out, Value::fromString(R"({"_root":["explode",".",[[3],"alpha","alpha","alpha"]]})"),"ahoj.nazdar.cau"); }; tst.test("Validator.explode.fail1",R"([[[2],"alpha"]])") >> [](std::ostream &out) { vtest(out, Value::fromString(R"({"_root":["explode",".",[[3],"alpha","alpha","alpha"]]})"),"ahoj.nazdar.123"); }; tst.test("Validator.explode.fail2",R"([[[2],"alpha"]])") >> [](std::ostream &out) { vtest(out, Value::fromString(R"({"_root":["explode",".",[[3],"alpha","alpha","alpha"]]})"),"ahoj.nazdar"); }; tst.test("Validator.explode.fail3",R"([[[3],[[3],"alpha","alpha","alpha"]]])") >> [](std::ostream &out) { vtest(out, Value::fromString(R"({"_root":["explode",".",[[3],"alpha","alpha","alpha"]]})"),"ahoj.nazdar.cau.tepic"); }; tst.test("Validator.explode.ok2","ok") >> [](std::ostream &out) { vtest(out, Value::fromString(R"({"_root":["explode",".",[[2],"alpha","any"],1]})"),"ahoj.nazdar.cau.tepic"); }; tst.test("Validator.explode.fail4",R"([[[1],"alpha"]])") >> [](std::ostream &out) { vtest(out, Value::fromString(R"({"_root":["explode",".",[[2],"alpha","alpha"],1]})"),"ahoj.123"); }; tst.test("Validator.explode.fail5",R"([[[1],"any"]])") >> [](std::ostream &out) { vtest(out, Value::fromString(R"({"_root":["explode",".",[[2],"alpha","any"],1]})"),"ahoj"); }; tst.test("Validator.customtime.ok","ok") >> [](std::ostream &out) { vtest(out, Object("_root", {"datetime","DD.MM.YYYY hh:mm:ss"} ), "02.04.2004 12:32:46"); }; tst.test("Validator.customtime.fail","[[[],[\"datetime\",\"DD.MM.YYYY hh:mm:ss\"]]]") >> [](std::ostream &out) { vtest(out, Object("_root", {"datetime","DD.MM.YYYY hh:mm:ss"} ), "2016-12-20T12:38:72Z"); }; tst.test("Validator.entime.ok1","ok") >> [](std::ostream &out) { vtest(out, Object("tm",{ {"datetime","M:mm"},{"datetime","MM:mm"} })("_root",{{"suffix","am","tm"},{"suffix","pm"}}), "1:23am"); }; tst.test("Validator.entime.ok2","ok") >> [](std::ostream &out) { vtest(out, Object("tm",{ {"datetime","M:mm"},{"datetime","MM:mm"} })("_root",{{"suffix","am","tm"},{"suffix","pm"}}), "11:45pm"); }; tst.test("Validator.entime.fail1","[[[],[\"datetime\",\"M:mm\"]],[[],[\"datetime\",\"MM:mm\"]],[[],\"tm\"],[[],[\"suffix\",\"pm\"]]]") >> [](std::ostream &out) { vtest(out, Object("tm",{ {"datetime","M:mm"},{"datetime","MM:mm"} })("_root",{{"suffix","am","tm"},{"suffix","pm"}}), "13:23am"); }; tst.test("Validator.entime.fail2","[[[],[\"suffix\",\"am\",\"tm\"]],[[],[\"suffix\",\"pm\"]]]") >> [](std::ostream &out) { vtest(out, Object("tm",{ {"datetime","M:mm"},{"datetime","MM:mm"} })("_root",{{"suffix","am","tm"},{"suffix","pm"}}), "2:45xa"); }; tst.test("Validator.setvar1","ok") >> [](std::ostream &out) { vtest(out, Object("_root",{"setvar","$test",Object("aaa",{"$test","bbb"})("bbb","number")}), Object("aaa",10)("bbb",10)); }; tst.test("Validator.setvar1.fail","[[[\"aaa\"],[\"$test\",\"bbb\"]]]") >> [](std::ostream &out) { vtest(out, Object("_root",{"setvar","$test",Object("aaa",{"$test","bbb"})("bbb","number")}), Object("aaa",20)("bbb",10)); }; tst.test("Validator.setvar2","ok") >> [](std::ostream &out) { vtest(out, Object("_root",{"setvar","$test",Object("aaa",{"<",{"$test","bbb"}})("bbb","number")}), Object("aaa",10)("bbb",20)); }; tst.test("Validator.setvar2.fail","[[[\"aaa\"],[\"<\",[\"$test\",\"bbb\"]]]]") >> [](std::ostream &out) { vtest(out, Object("_root",{"setvar","$test",Object("aaa",{"<",{"$test","bbb"}})("bbb","number")}), Object("aaa",10)("bbb",5)); }; tst.test("Validator.setvar3","ok") >> [](std::ostream &out) { vtest(out, Object("_root",{"setvar","$test",Object("count","digits")("data",{"maxsize",{"$test","count"}})}), Object("count",3)("data",{10,20,30})); }; tst.test("Validator.setvar3.fail","[[[\"data\"],[\"maxsize\",[\"$test\",\"count\"]]]]") >> [](std::ostream &out) { vtest(out, Object("_root",{"setvar","$test",Object("count","digits")("data",{"maxsize",{"$test","count"}})}), Object("count",3)("data",{10,20,30,40})); }; tst.test("Validator.version.fail","[[[\"_version\"],2]]") >> [](std::ostream &out) { vtest(out, Object("_root","any")("_version",2.0), 42); }; tst.test("Validator.selfValidate", "ok") >> [](std::ostream &out) { std::ifstream fstr("src/imtjson/validator.json", std::ios::binary); Value def = Value::fromStream(fstr); Validator vd(def); if (vd.validate(def)) { out << "ok"; } else { out << vd.getRejections().toString(); } }; }
#ifndef TENSOR_vec2_INCLUDED #define TENSOR_vec2_INCLUDED #include <iostream> using namespace std; struct vec2 { float x, y; vec2(); vec2(float); vec2(float, float); vec2& operator+=(const vec2&); vec2& operator-=(const vec2&); vec2& operator*=(const float); vec2& operator/=(const float); vec2 operator-(); float radians(); float degrees(); }; vec2 operator+(vec2, const vec2&); vec2 operator-(vec2, const vec2&); vec2 operator*(vec2, const float); vec2 operator*(const float, vec2); vec2 operator/(vec2, const float); ostream& operator<<(ostream&, const vec2&); //convert between angles and vectors vec2 deg2vec(float); vec2 rad2vec(float); float vec2deg(vec2); float vec2rad(vec2); float dot(const vec2&, const vec2&); float length(const vec2&); vec2 normalize(const vec2&); #endif
// // Created by 송지원 on 2019-12-06. // #include "iostream" using namespace std; int main() { int N; int D[31]; cin >> N; D[0] = 1; D[1] = 0; D[2] = 3; D[3] = 0; D[4] = 3*3 + 2*1; if (N%2 == 1) { cout<< 0 << endl; return 0; } if (N <= 4) { cout << D[N] << endl; return 0; } for (int i=6; i<=N; i=i+2) { int temp = 0; for (int j=0; j<=i-4; j+=2) { temp += D[j] * 2; } temp += D[i-2] * 3; D[i] = temp; } cout << D[N] << endl; return 0; }
#ifndef PLAYER_H_ #define PLAYER_H_ class Player { public: Player(); virtual ~Player(); }; #endif
#include<iostream> #include<vector> using namespace std; class Solution { public: bool isMatch(string s, string p) { //简化版:动态规划 vector<vector<bool>> dp(s.size()+1,vector<bool>(p.size()+1,false)); dp[0][0]=true; for(int i=1;i<=p.size();i++) { if(p[i-1]=='*') dp[0][i]=true; else break; } for(int i=1;i<=s.size();i++) { for(int j=1;j<=p.size();j++) { if(p[j-1]=='?'||s[i-1]==p[j-1]) dp[i][j]=dp[i-1][j-1]; else if(p[j-1]=='*') dp[i][j]=dp[i][j-1]||dp[i-1][j]; } } return dp[s.size()][p.size()]; } }; class Solution1 { public: bool isMatch(string s, string p) { //基本思想:递归法,尽管有优化还是超时,但这是一种思想记录一下 string p1; int i = 0; //剪枝优化,去除重复的* p1 = Remove_stars(p); //递归调用 return Recursion(s, p1, 0, 0); } //剪枝优化,去除重复的* string Remove_stars(string &p) { string p1; int i; if (p.size() == 0) return ""; while (i < p.size() - 1) { if (p[i] == '*' && p[i + 1] == '*') { i++; continue; } else p1 += p[i]; i++; } p1 += p[p.size() - 1]; return p1; } bool Recursion(string s, string p, int m, int n) { //如果s的下标m和p的下标n都已经到头,说明匹配成功 if (m == s.size() && n == p.size()) return true; //如果s的下标m到头p的下标n没有到头,且p剩余字符不是*,说明匹配不成功 if (m == s.size() && n < p.size() && p[n] != '*') return false; //如果s的下标m到头p的下标n没有到头,且p下一字符是*,继续递归调用看剩余字符是否是* if (m == s.size() && n < p.size() && p[n] == '*') { return Recursion(s, p, m, n + 1); } //如果s的下标m没有到头p的下标n到头,说明匹配不成功 if (m < s.size() && n == p.size()) return false; //如果当前s所指字符和p所指字符相同,递归调用s和p下标都+1 if (s[m] == p[n]) { if (Recursion(s, p, m + 1, n + 1)) return true; } //如果p所指字符为*,则可能有三种匹配情况,*匹配空字符串,*匹配多个字符,*匹配完当前字符不再匹配 else if (p[n] == '*') { if (Recursion(s, p, m, n + 1)) return true; if (Recursion(s, p, m + 1, n)) return true; if (Recursion(s, p, m + 1, n + 1)) return true; } //如果当前p所指字符为?,递归调用s和p下标都+1 else if (p[n] == '?') { if (Recursion(s, p, m + 1, n + 1)) return true; } //如果当前s所指字符和p所指字符不相等,说明匹配不成功 else if (s[m] != p[n]) { return false; } //最后一定要返回false,因为上面进入if后调用Recursion,但如果成功返回true但如果不成功,会退出if执行下一条语句,而这个bool函数没有语句运行了,返回的是随机数 return false; } }; class Solution2 { public: bool isMatch(string s, string p) { //基本思想:动态规划法,所有字符串匹配问题都可以用动态规划法,利用已匹配的信息计算未匹配的信息。 int m = s.size(), n = p.size(), i, j; //dp[i][j]表示s[0,i-1]前i个字符与p[0,j-1]前j个字符是否匹配 vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false)); //当s和p都为空时匹配成功 dp[0][0] = true; //当s不为空p为空时不匹配 for (i = 1; i < m; i++) dp[i][0] = false; //当s为空j开头都为*,*可以匹配空串,开头都能匹配成功 for (j = 0; j < n; j++) { if (p[j] == '*') dp[0][j + 1] = true; else break; } //两重循环给二维数组dp赋值 for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { //若当前p[j]为*,如果*算作空串则s前i个串与p前j个串是否匹配取决于s前i个串p前j-1个串是否匹配 //如果*匹配当前s[i]字符则s前i个串与p前j个串是否匹配取决于s前i-1个串p前j个串是否匹配 if (p[j] == '*') { dp[i + 1][j + 1] = dp[i + 1][j] || dp[i][j + 1]; } //若当前s[i]字符与当前p[j]字符相等,或者当前p[j]为?,s前i个串与p前j个串是否匹配取决于s前i-1个串p前j-1个串是否匹配 else if (s[i] == p[j] || p[j] == '?') { dp[i + 1][j + 1] = dp[i][j]; } //上述情况都不满足,s前i个串与p前j个串不匹配 else dp[i + 1][j + 1] = false; } } return dp[m][n]; } }; class Solution3 { public: bool isMatch(string s, string p) { //基本思想:贪心回溯法 int m = s.size(), n = p.size(), i, j, flag_i, flag_j; i = 0; j = 0; //初始化标记点为-1,如果标记点大于等于0,说明有标记才能回溯 flag_j = -1; flag_i = -1; //一重循环对s每个字符尝试匹配 while (i < m) { //当前s[i]字符与当前p[j]字符相等,s和p的下标都后移一位 if (j < n && (s[i] == p[j] || p[j] == '?')) { i++; j++; } //当前p[j]为*,标记当前s中字符的位置,标记p中*所在位置为flag_j,j后移一位到*的下一个字符,说明*匹配空串 else if (j < n && p[j] == '*') { flag_i = i; flag_j = j; j++; } //如果*匹配空串后,p中*的后一位与标记处的s字符不匹配,说明*不能匹配空串,*匹配s当前字符,i后移一位,j继续指向*的下一个字符 else if (flag_i >= 0) { flag_i++; i = flag_i; j = flag_j + 1; } //如果上述都不匹配,返回false匹配不成功,可能是p到头了而s中还有字符,可能是当前s所指字符和p所指字符不相等 else return false; } //s已经到头了,去除p后多余的*,如果最后j能到p的头说明匹配成功,否则说明不匹配成功除了*还多了其他字符 while (j < n && p[j] == '*') j++; return j==n; } }; int main() { Solution2 solute; string s = "aa"; string p = "*"; cout << solute.isMatch(s, p) << endl; return 0; }
/* * Vector.cpp * * Created on: 05-Apr-2015 * Author: kishor */ #include "Vector.h" template <class Object> Vector<Object>::Vector(int size) { m_data = new Object[size]; m_capacity = size; m_size = 0; } template <class Object> void Vector<Object>::push_back(Object val) { m_data[m_size] = val; m_size++; } template <class Object> int Vector<Object>::size() { return m_size; } template <class Object> int Vector<Object>::capacity() { return m_capacity; } template <class Object> void Vector<Object>::resize(int val) { Object new_data = new Object[val]; for(int i=0; i < m_size; i++) { new_data[i] = m_data[i]; } delete [] m_data; m_data = new_data; } template <class Object> Vector<Object>::~Vector(){ delete [] m_data; }
#ifndef E_FVEC2 #define E_FVEC2 #include "types.hpp" class fvec2{ public: sreal x, y; public: fvec2(){} fvec2(sreal x, sreal y) : x(x), y(y){} sreal length() const; }; bool operator!=(fvec2 m, fvec2 n); bool operator<(fvec2 m, fvec2 n); fvec2 operator-(fvec2 a, fvec2 b); fvec2 intersection(fvec2 a, fvec2 b, fvec2 c, fvec2 d); sreal distance(fvec2 a, fvec2 b); bool onlineside(fvec2 pointa, fvec2 pointb, fvec2 testpoint); #endif
// // Created by yus on 03.05.2020. // #ifndef LINAL_MATRIX_H #define LINAL_MATRIX_H #include <iostream> #include <vector> class Matrix { private: int n; int m; std::vector<std::vector<double>> value; public: Matrix(int n, int m); Matrix(std::vector <std::vector<double>> value); ~Matrix(); void InsertValue(); void InsertValue(int i, int j, double value); double getValue(int n1, int m1) const; int getN() const; int getM() const; Matrix operator + (const Matrix &a); Matrix operator - (const Matrix &a); Matrix operator * (const double a); Matrix operator / (const double a); Matrix operator * (const Matrix &a); Matrix operator += (const Matrix &a); Matrix operator -= (const Matrix &a); Matrix operator *= (const double a); Matrix operator /= (const double a); Matrix transpose(); }; std::ostream &operator << (std::ostream &os, const Matrix &a); std::istream &operator>>(std::istream &is, Matrix &a); #endif //LINAL_MATRIX_H
#include "../headers/BlockNode.hpp" #include <string> #include <sstream> BlockNode::BlockNode() = default; Node *BlockNode::getLastField() { if (!s.empty()) return s.at(s.size() - 1); return nullptr; } void BlockNode::addNode(Node *node) { s.push_back(node); type = node->getType(); } void BlockNode::printTree() { if (s.size() > 1) printf("["); for (int i = 0; i < s.size(); ++i) { s.at(i)->printTree(); if (i < s.size() - 1) printf(","); } if (s.size() > 1) printf("]\n"); } string BlockNode::printCheck(ClassNode *classNode) { string retString; if (s.size() > 1) retString += "["; for (int i = 0; i < s.size(); ++i) { if (s.at(i)->printCheck(classNode).find("ErrorSemanticOneTime:") != string::npos) return s.at(i)->printCheck(classNode); retString += s.at(i)->printCheck(classNode); if (i < s.size() - 1) retString += ",\n"; } if (classNode->getVariableTable()->getVariable(s.at(s.size() - 1)->getValue()) != "none") type = classNode->getVariableTable()->getVariable(s[s.size() - 1]->getValue()); else if (!s.empty()) type = s.at(s.size() - 1)->getType(); if (s.size() > 1) { retString += "]\n"; retString += " : " + type; } return retString; }
#include "Personne.hpp" namespace enseirb{ Personne::Personne():_nom(""){} Personne::Personne(const Chaine &c): _nom(c) {printf("%s (%d): %s\n", __FILE__,__LINE__,__func__);} Personne::Personne(const Personne &P): _nom(P.nom()) {printf("%s (%d): %s\n", __FILE__,__LINE__,__func__);} Chaine Personne::nom()const{ return _nom; } }
// // AbsWordStats.cpp // TopFrequent // // Created by Steven on 20/5/18. // Copyright © 2018 tengx. All rights reserved. // #include "AbsWordStats.hpp"
module Color = { let color_enabled = lazy(Unix.isatty(Unix.stdout)); let forceColor = ref(false); let get_color_enabled = () => { forceColor^ || Lazy.force(color_enabled); }; type color = | Red | Yellow | Magenta | Cyan; type style = | FG(color) | Bold | Dim; let code_of_style = fun | FG(Red) => "31" | FG(Yellow) => "33" | FG(Magenta) => "35" | FG(Cyan) => "36" | Bold => "1" | Dim => "2"; let style_of_tag = s => switch (s) { #if OCAML_MINOR >= 8 | Format.String_tag(s) => switch (s) { #else #endif | "error" => [Bold, FG(Red)] | "warning" => [Bold, FG(Magenta)] | "info" => [Bold, FG(Yellow)] | "dim" => [Dim] | "filename" => [FG(Cyan)] | _ => [] #if OCAML_MINOR >= 8 } | _ => [] }; #else }; #endif let ansi_of_tag = s => { let l = style_of_tag(s); let s = String.concat(";", List.map(code_of_style, l)); "\027[" ++ s ++ "m"; }; let reset_lit = "\027[0m"; let color_functions = { #if OCAML_MINOR >= 8 Format.mark_open_stag: s => #else Format.mark_open_tag: s => #endif if (get_color_enabled()) { ansi_of_tag(s); } else { ""; }, #if OCAML_MINOR >= 8 mark_close_stag: _ => #else mark_close_tag: _ => #endif if (get_color_enabled()) { reset_lit; } else { ""; }, #if OCAML_MINOR >= 8 print_open_stag: _ => (), print_close_stag: _ => (), #else print_open_tag: _ => (), print_close_tag: _ => (), #endif }; let setup = () => { Format.pp_set_mark_tags(Format.std_formatter, true); #if OCAML_MINOR >= 8 Format.pp_set_formatter_stag_functions #else Format.pp_set_formatter_tag_functions #endif ( Format.std_formatter, color_functions, ); }; let error = (ppf, s) => Format.fprintf(ppf, "@{<error>%s@}", s); let info = (ppf, s) => Format.fprintf(ppf, "@{<info>%s@}", s); }; module Loc = { let print_filename = (ppf, file) => switch (file) { /* modified */ | "_none_" | "" => Format.fprintf(ppf, "(No file name)") | real_file => Format.fprintf(ppf, "%s", Location.show_filename(real_file)) }; let print_loc = (~normalizedRange, ppf, loc: Location.t) => { let (file, _, _) = Location.get_pos_info(loc.loc_start); let dim_loc = ppf => fun | None => () | Some(( (start_line, start_line_start_char), (end_line, end_line_end_char), )) => if (start_line == end_line) { if (start_line_start_char == end_line_end_char) { Format.fprintf( ppf, " @{<dim>%i:%i@}", start_line, start_line_start_char, ); } else { Format.fprintf( ppf, " @{<dim>%i:%i-%i@}", start_line, start_line_start_char, end_line_end_char, ); }; } else { Format.fprintf( ppf, " @{<dim>%i:%i-%i:%i@}", start_line, start_line_start_char, end_line, end_line_end_char, ); }; Format.fprintf( ppf, "@{<filename>%a@}%a", print_filename, file, dim_loc, normalizedRange, ); }; let print = (ppf, loc: Location.t) => { let (_file, start_line, start_char) = Location.get_pos_info(loc.loc_start); let (_, end_line, end_char) = Location.get_pos_info(loc.loc_end); let normalizedRange = if (start_char === (-1) || end_char === (-1)) { None; } else if (start_line == end_line && start_char >= end_char) { let same_char = start_char + 1; Some(((start_line, same_char), (end_line, same_char))); } else { Some(((start_line, start_char + 1), (end_line, end_char))); }; Format.fprintf(ppf, "@[%a@]", print_loc(~normalizedRange), loc); }; }; let log = x => { Format.fprintf(Format.std_formatter, x); }; let item = x => { Format.fprintf(Format.std_formatter, " "); Format.fprintf(Format.std_formatter, x); }; let logKind = (body, ~color, ~loc, ~name) => { Format.fprintf( Format.std_formatter, "@[<v 2>@,%a@,%a@,%a@]@.", color, name, Loc.print, loc, body, (), ); }; let info = (body, ~loc, ~name) => logKind(body, ~color=Color.info, ~loc, ~name); let error = (body, ~loc, ~name) => logKind(body, ~color=Color.error, ~loc, ~name);
#include <cstdio> #include <iostream> using namespace std; #include <boost/bimap.hpp> #include <boost/flyweight.hpp> using namespace boost; typedef uint32_t key; struct User { User(const string& first_name, const string& last_name) : first_name{add(first_name)}, last_name{add(last_name)} {} const string& get_first_name() const { return names.left.find(first_name)->second; } const string& get_last_name() const { return names.left.find(last_name)->second; } friend ostream& operator<<(ostream& os, const User& obj) { return os << "first name: " << obj.first_name << " " << obj.get_first_name() << " last name: " << obj.last_name << " " << obj.get_last_name(); } protected: static bimap<key, string> names; static int seed; static key add(const string& s) { auto it = names.right.find(s); if (it == names.right.end()) { key id = ++seed; names.insert(bimap<key, string>::value_type(seed, s)); return id; } return it->second; } key first_name, last_name; }; int User::seed = 0; bimap<key, string> User::names{}; struct User2 { flyweight<string> first_name, last_name; User2(const string& first_name, const string& last_name) : first_name{first_name}, last_name{last_name} {} friend std::ostream& operator<<(std::ostream& os, const User2& obj) { return os << "first_name: " << obj.first_name << " last_name: " << obj.last_name; } }; int main() { User2 john_doe{"John", "Doe"}; User2 jane_doe{"Jane", "Doe"}; cout << "John " << john_doe << endl; cout << "Jane " << jane_doe << endl; // "Doe" is only saved once in the system. assert(&jane_doe.last_name.get() == &john_doe.last_name.get()); return 0; }
#pragma once #include "Image.hpp" #include <iostream> #include <unistd.h> #include <fstream> using std::ofstream; using std::ifstream; #pragma pack(push, 1) typedef int LONG; // 4 Byte typedef unsigned short WORD; // 2 Byte typedef unsigned DWORD; // 4 Byte typedef struct tagBITMAPFILEHEADER { WORD bfType; DWORD bfSize; WORD bfReserved1; WORD bfReserved2; DWORD bfOffBits; } BITMAPFILEHEADER, *PBITMAPFILEHEADER; typedef struct tagBITMAPINFOHEADER { DWORD biSize; LONG biWidth; LONG biHeight; WORD biPlanes; WORD biBitCount; DWORD biCompression; DWORD biSizeImage; LONG biXPelsPerMeter; LONG biYPelsPerMeter; DWORD biClrUsed; DWORD biClrImportant; } BITMAPINFOHEADER, *PBITMAPINFOHEADER; #pragma pack(pop) class Bitmap { public: Bitmap(const char* fileName); void save(const char* fileName); Image imageData; // This class only contains the pixel information of the image bool loaded; void setImageData(Image* image); private: bool load(const char* imageLocation); void extractPixels(); char* bitmapData; // This buffer stores the entire bitmap file (headers + pixels) as raw bytes int bufferSize; DWORD headerOffset; PBITMAPFILEHEADER file_header; PBITMAPINFOHEADER info_header; };
#include <opencv2/photo.hpp> #include "opencv2/imgcodecs.hpp" #include <opencv2/highgui.hpp> #include <vector> #include <iostream> #include <fstream> using namespace cv; using namespace std; void loadExposureSeq(String, vector<Mat>&, vector<float>&); int main(int, char**argv) { vector<Mat> images; vector<float> times; loadExposureSeq(argv[1], images, times); Mat response; Ptr<CalibrateDebevec> calibrate = createCalibrateDebevec(); calibrate->process(images, response, times); Mat hdr; Ptr<MergeDebevec> merge_debevec = createMergeDebevec(); merge_debevec->process(images, hdr, times, response); Mat ldr; Ptr<TonemapDurand> tonemap = createTonemapDurand(2.2f); tonemap->process(hdr, ldr); Mat fusion; Ptr<MergeMertens> merge_mertens = createMergeMertens(); merge_mertens->process(images, fusion); imwrite("fusion.png", fusion * 255); imwrite("ldr.png", ldr * 255); imwrite("hdr.hdr", hdr); return 0; } void loadExposureSeq(String path, vector<Mat>& images, vector<float>& times) { path = path + std::string("/"); ifstream list_file((path + "list.txt").c_str()); string name; float val; while(list_file >> name >> val) { Mat img = imread(path + name); images.push_back(img); times.push_back(1 / val); } list_file.close(); }
#include<stdio.h> int main() { float a,b; scanf_s("%f",&a); if(a>=30) { b=(a-32)*5/9; printf("%.2f f = %.2f c",a,b); } else { printf("Too cold to live"); } return 0; }
#include "gtest/gtest.h" #include <sstream> #include <boost/scoped_ptr.hpp> #include "wali/domains/matrix/Matrix.hpp" #include "fixtures-minplus-matrix.hpp" #include "matrix-equal.hpp" using namespace testing::minplus_matrix; namespace wali { namespace domains { TEST(wali$domains$matrix$MinPlusIntMatrix$$constructorAndMatrix, basicTest3x3) { RandomMatrix1_3x3 f; MinPlusIntMatrix m(f.mat); EXPECT_EQ(m.matrix(), f.mat); } #define NUM_ELEMENTS(arr) ((sizeof arr)/(sizeof arr[0])) TEST(wali$domains$matrix$MinPlusIntMatrix$$equalAndIsZeroAndIsOne, battery) { MatrixFixtures_3x3 f; MinPlusIntMatrix mats[] = { MinPlusIntMatrix(f.zero.mat), MinPlusIntMatrix(f.id.mat), MinPlusIntMatrix(f.r1.mat), MinPlusIntMatrix(f.r2.mat), MinPlusIntMatrix(f.ext_r1_r2.mat), MinPlusIntMatrix(f.ext_r2_r1.mat), }; for (size_t left=0; left<NUM_ELEMENTS(mats); ++left) { for (size_t right=0; right<NUM_ELEMENTS(mats); ++right) { EXPECT_EQ(left == right, mats[left].equal(&mats[right])); } } } TEST(wali$domains$matrix$MinPlusIntMatrix$$zero_raw, basicTest3x3) { RandomMatrix1_3x3 f; ZeroBackingMatrix_3x3 z; MinPlusIntMatrix m(f.mat); MinPlusIntMatrix mz(z.mat); boost::scoped_ptr<MinPlusIntMatrix> result(m.zero_raw()); EXPECT_EQ(z.mat, result->matrix()); EXPECT_TRUE(mz.equal(result.get())); } TEST(wali$domains$matrix$MinPlusIntMatrix$$one_raw, basicTest3x3) { RandomMatrix1_3x3 f; IdBackingMatrix_3x3 z; MinPlusIntMatrix m(f.mat); MinPlusIntMatrix mid(z.mat); boost::scoped_ptr<MinPlusIntMatrix> result(m.one_raw()); EXPECT_EQ(z.mat, result->matrix()); EXPECT_TRUE(mid.equal(result.get())); } TEST(wali$domains$matrix$MinPlusIntMatrix$$extend_raw, twoRandomMatrices) { RandomMatrix1_3x3 f1; RandomMatrix2_3x3 f2; ExtendR1R2_3x3 fr12; ExtendR2R1_3x3 fr21; MinPlusIntMatrix m1(f1.mat); MinPlusIntMatrix m2(f2.mat); boost::scoped_ptr<MinPlusIntMatrix> result12(m1.extend_raw(&m2)); boost::scoped_ptr<MinPlusIntMatrix> result21(m2.extend_raw(&m1)); EXPECT_EQ(fr12.mat, result12->matrix()); EXPECT_EQ(fr21.mat, result21->matrix()); } TEST(wali$domains$matrix$MinPlusIntMatrix$$extend_raw, extendAgainstZero) { RandomMatrix1_3x3 f; ZeroBackingMatrix_3x3 z; MinPlusIntMatrix mf(f.mat); MinPlusIntMatrix mz(z.mat); boost::scoped_ptr<MinPlusIntMatrix> result1Z(mf.extend_raw(&mz)), resultZ1(mz.extend_raw(&mf)), resultZZ(mz.extend_raw(&mz)); EXPECT_EQ(z.mat, result1Z->matrix()); EXPECT_EQ(z.mat, resultZ1->matrix()); EXPECT_EQ(z.mat, resultZZ->matrix()); EXPECT_TRUE(mz.equal(result1Z.get())); EXPECT_TRUE(mz.equal(resultZ1.get())); EXPECT_TRUE(mz.equal(resultZZ.get())); } TEST(wali$domains$matrix$MinPlusIntMatrix$$extend_raw, extendAgainstOne) { RandomMatrix1_3x3 fr1; IdBackingMatrix_3x3 id; MinPlusIntMatrix mr1(fr1.mat); MinPlusIntMatrix mid(id.mat); boost::scoped_ptr<MinPlusIntMatrix> result_R1_Id(mr1.extend_raw(&mid)), result_Id_R1(mid.extend_raw(&mr1)), result_Id_Id(mid.extend_raw(&mid)); EXPECT_EQ(fr1.mat, result_R1_Id->matrix()); EXPECT_EQ(fr1.mat, result_Id_R1->matrix()); EXPECT_EQ(id.mat, result_Id_Id->matrix()); EXPECT_TRUE(mr1.equal(result_R1_Id.get())); EXPECT_TRUE(mr1.equal(result_Id_R1.get())); EXPECT_TRUE(mid.equal(result_Id_Id.get())); } TEST(wali$domains$matrix$MinPlusIntMatrix$$print, random) { RandomMatrix1_3x3 f; MinPlusIntMatrix m(f.mat); std::stringstream ss; m.print(ss); EXPECT_EQ("Matrix: [3,3]" "(([1],[infinity],[infinity])," "([12],[0],[1])," "([infinity],[infinity],[17]))", ss.str()); } TEST(wali$domains$matrix$MinPlusIntMatrix, callWaliTestSemElemImpl) { RandomMatrix1_3x3 f; sem_elem_t m = new MinPlusIntMatrix(f.mat); test_semelem_impl(m); } } }
#include "Draw.h" void CDraw::ReloadFonts() { g_Fonts[EFonts::DEBUG] = { "Verdana", 16, FONTFLAG_OUTLINE }; for (auto &v : g_Fonts) I::Surface->SetFontGlyphSet(v.second.m_dwFont = I::Surface->CreateFont(), v.second.m_szName, v.second.m_nTall, 0, 0, 0, v.second.m_nFlags); } void CDraw::UpdateScreenSize() { m_nScreenW = I::BaseClientDLL->GetScreenWidth(); m_nScreenH = I::BaseClientDLL->GetScreenHeight(); } void CDraw::UpdateW2SMatrix() { CViewSetup ViewSetup = {}; if (I::BaseClientDLL->GetPlayerView(ViewSetup)) { static VMatrix WorldToView = {}, ViewToProjection = {}, WorldToPixels = {}; I::RenderView->GetMatricesForView(ViewSetup, &WorldToView, &ViewToProjection, &g_Draw.m_WorldToProjection, &WorldToPixels); } } void CDraw::String(const DWORD &font, int x, int y, Color_t clr, short align, const char *str, ...) { if (str == 0) return; va_list va_alist; char cbuffer[1024] = { '\0' }; wchar_t wstr[1024] = { '\0' }; va_start(va_alist, str); vsprintf_s(cbuffer, str, va_alist); va_end(va_alist); wsprintfW(wstr, L"%hs", cbuffer); if (align) { int w = 0, h = 0; I::Surface->GetTextSize(font, wstr, w, h); if (align & TXT_LEFT) x -= w; if (align & TXT_TOP) y -= h; if (align & TXT_CENTERX) x -= (w / 2); if (align & TXT_CENTERY) y -= (h / 2); } I::Surface->DrawSetTextPos(x, y); I::Surface->DrawSetTextFont(font); I::Surface->DrawSetTextColor(clr.r, clr.g, clr.b, clr.a); I::Surface->DrawPrintText(wstr, wcslen(wstr)); } void CDraw::String(const DWORD &font, int x, int y, Color_t clr, short align, const wchar_t *str, ...) { if (str == 0) return; va_list va_alist; wchar_t wstr[1024] = { '\0' }; va_start(va_alist, str); vswprintf_s(wstr, str, va_alist); va_end(va_alist); if (align) { int w = 0, h = 0; I::Surface->GetTextSize(font, wstr, w, h); if (align & TXT_LEFT) x -= w; if (align & TXT_TOP) y -= h; if (align & TXT_CENTERX) x -= (w / 2); if (align & TXT_CENTERY) y -= (h / 2); } I::Surface->DrawSetTextPos(x, y); I::Surface->DrawSetTextFont(font); I::Surface->DrawSetTextColor(clr.r, clr.g, clr.b, clr.a); I::Surface->DrawPrintText(wstr, wcslen(wstr)); } void CDraw::Line(int x, int y, int x1, int y1, Color_t clr) { I::Surface->DrawSetColor(clr.r, clr.g, clr.b, clr.a); I::Surface->DrawLine(x, y, x1, y1); } void CDraw::Rect(int x, int y, int w, int h, Color_t clr) { I::Surface->DrawSetColor(clr.r, clr.g, clr.b, clr.a); I::Surface->DrawFilledRect(x, y, x + w, y + h); } void CDraw::OutlinedRect(int x, int y, int w, int h, Color_t clr) { I::Surface->DrawSetColor(clr.r, clr.g, clr.b, clr.a); I::Surface->DrawOutlinedRect(x, y, x + w, y + h); } void CDraw::GradientRect(int x, int y, int x1, int y1, Color_t top_clr, Color_t bottom_clr, bool horizontal) { I::Surface->DrawSetColor(top_clr.r, top_clr.g, top_clr.b, top_clr.a); I::Surface->DrawFilledRectFade(x, y, x1, y1, 255, 255, horizontal); I::Surface->DrawSetColor(bottom_clr.r, bottom_clr.g, bottom_clr.b, bottom_clr.a); I::Surface->DrawFilledRectFade(x, y, x1, y1, 0, 255, horizontal); }
#include<bits/stdc++.h> using namespace std; main() { int n, m; while(cin>>n>>m) { double ans1, ans, a, b; cin>>a>>b; ans1=(a/b)*m; for(int i=1; i<n; i++) { cin>>a>>b; ans = (a/b)*m; if(ans1>ans) ans1=ans; } printf("%.8llf\n",ans1); } return 0; }
#ifdef CURSES_HAS_PRAGMA_ONCE #pragma once #endif #ifndef __CURSES_NONCOPYABLE_HPP_INCLUDED__ #define __CURSES_NONCOPYABLE_HPP_INCLUDED__ #include "config.hpp" /// Macro for hide/delete the private constructor and assign operator #ifdef CURSES_HAS_CPP11 # define CURSES_MOVABLE_BUT_NOT_COPYABLE(__CLASS) \ __CLASS(const __CLASS&) = delete;\ __CLASS& operator=(const __CLASS&) = delete; #else # define CURSES_MOVABLE_BUT_NOT_COPYABLE(__CLASS) \ private:\ __CLASS(const __CLASS&) {}\ __CLASS& operator=(const __CLASS&) {return *this;} #endif // CURSES_HAS_CPP11 namespace curses { /// ! \brief private extending of noncopyable /// allow you not to hide/delete copy constructor and /// assign operators in the target class class noncopyable { CURSES_MOVABLE_BUT_NOT_COPYABLE(noncopyable) protected: #ifdef CURSES_HAS_CPP11 noncopyable() = default; ~noncopyable() = default; #else noncopyable() {} ~noncopyable() {} #endif // CURSES_HAS_CPP11 }; } // namespace curses #endif // __CURSES_NONCOPYABLE_HPP_INCLUDED__
// Created on: 1994-12-21 // Created by: Christian CAILLET // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IFSelect_DispPerSignature_HeaderFile #define _IFSelect_DispPerSignature_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <IFSelect_Dispatch.hxx> #include <Standard_Integer.hxx> class IFSelect_SignCounter; class TCollection_AsciiString; class Interface_Graph; class IFGraph_SubPartsIterator; class IFSelect_DispPerSignature; DEFINE_STANDARD_HANDLE(IFSelect_DispPerSignature, IFSelect_Dispatch) //! A DispPerSignature sorts input Entities according to a //! Signature : it works with a SignCounter to do this. class IFSelect_DispPerSignature : public IFSelect_Dispatch { public: //! Creates a DispPerSignature with no SignCounter (by default, //! produces only one packet) Standard_EXPORT IFSelect_DispPerSignature(); //! Returns the SignCounter used for splitting Standard_EXPORT Handle(IFSelect_SignCounter) SignCounter() const; //! Sets a SignCounter for sort //! Remark : it is set to record lists of entities, not only counts Standard_EXPORT void SetSignCounter (const Handle(IFSelect_SignCounter)& sign); //! Returns the name of the SignCounter, which caracterises the //! sorting criterium for this Dispatch Standard_EXPORT Standard_CString SignName() const; //! Returns as Label, "One File per Signature <name>" Standard_EXPORT TCollection_AsciiString Label() const Standard_OVERRIDE; //! Returns True, maximum count is given as <nbent> Standard_EXPORT virtual Standard_Boolean LimitedMax (const Standard_Integer nbent, Standard_Integer& max) const Standard_OVERRIDE; //! Computes the list of produced Packets. It defines Packets from //! the SignCounter, which sirts the input Entities per Signature //! (specific of the SignCounter). Standard_EXPORT void Packets (const Interface_Graph& G, IFGraph_SubPartsIterator& packs) const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(IFSelect_DispPerSignature,IFSelect_Dispatch) protected: private: Handle(IFSelect_SignCounter) thesign; }; #endif // _IFSelect_DispPerSignature_HeaderFile
#ifndef CAPP_TEST_H #define CAPP_TEST_H #include <iostream> #include <mutex> #include <thread> using namespace std; class Data { private: int data; int datas[2];//if int datas[]; undertermined on value init public: //Data(int a); static volatile int s; void proc(recursive_mutex& mtx, int n); int getData(); }; #endif //CAPP_TEST_H
#include<cstdio> using namespace std; int main(){ //input int a,b; scanf("%d %d",&a,&b); //output int i,j; for(i=a,j=1;i<=b;++i,++j){ printf("%5d",i); if(j%5==0){ printf("\n"); } } if(j%5!=1){ printf("\n"); } int sum = 0; if(a>=0){ sum = (a+b)*(b-a+1)/2; }else{ sum += (1+b)*b/2; a = -a; sum -= (1+a)*a/2; } printf("Sum = %d",sum); return 0; } //1. 12line j rather than i //2. 16line j rather than i and 1 rather than 0
#include <stdio.h> #include <iostream> using namespace std; int fun(int now, int m) { if(now == 1) return m; else return 2 * (fun(now - 1, m) + 1); } int main() { int x, y, z; while (~scanf("%d %d %d", &x, &y, &z)) { int sum; sum = (z) * fun(x, y); printf("%d\n", sum); } return 0; }
class equip_aa_battery : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_aa_battery; descriptionShort = $STR_ITEM_DESC_equip_aa_battery; model = "\z\addons\dayz_epoch_w\magazine\dze_aa_battery.p3d"; picture = "\z\addons\dayz_communityassets\pictures\equip_aa_battery_ca.paa"; type = 256; }; class equip_aa_battery_empty : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_aa_battery_empty; descriptionShort = $STR_ITEM_DESC_equip_aa_battery_empty; model = "\z\addons\dayz_epoch_w\magazine\dze_aa_battery.p3d"; picture = "\z\addons\dayz_communityassets\pictures\equip_aa_battery_ca.paa"; type = 256; }; class equip_d_battery : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_d_battery; descriptionShort = $STR_ITEM_DESC_equip_d_battery_empty; model = "\z\addons\dayz_epoch_w\magazine\dze_d_battery.p3d"; picture = "\z\addons\dayz_communityassets\pictures\equip_d_battery_ca.paa"; type = 256; }; class equip_d_battery_empty : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_d_battery_empty; descriptionShort = $STR_ITEM_DESC_equip_d_battery; model = "\z\addons\dayz_epoch_w\magazine\dze_d_battery.p3d"; picture = "\z\addons\dayz_communityassets\pictures\equip_d_battery_ca.paa"; type = 256; }; class equip_floppywire : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_floppywire; descriptionShort = $STR_ITEM_DESC_equip_floppywire; model = "\z\addons\dayz_communityassets\models\floppywire.p3d"; picture = "\z\addons\dayz_communityassets\pictures\equip_floppywire.paa"; type = 256; }; class equip_satawire : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_satawire; descriptionShort = $STR_ITEM_DESC_equip_satawire; model = "\z\addons\dayz_communityassets\models\floppywire.p3d"; picture = "\z\addons\dayz_communityassets\pictures\equip_floppywire.paa"; type = 256; }; class equip_scrapelectronics : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_scrapelectronics; descriptionShort = $STR_ITEM_DESC_equip_scrapelectronics; model = "\z\addons\dayz_communityassets\models\scrapelectronics.p3d"; picture = "\z\addons\dayz_communityassets\pictures\scrapelectronics.paa"; type = 256; }; class equip_graphicscard : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_graphicscard; descriptionShort = $STR_ITEM_DESC_equip_graphicscard; model = "\z\addons\dayz_communityassets\models\scrapelectronics.p3d"; picture = "\z\addons\dayz_communityassets\pictures\scrapelectronics.paa"; type = 256; }; class equip_graphicscard_broken : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_graphicscard_broken; descriptionShort = $STR_ITEM_DESC_equip_graphicscard_broken; model = "\z\addons\dayz_communityassets\models\scrapelectronics.p3d"; picture = "\z\addons\dayz_communityassets\pictures\scrapelectronics.paa"; type = 256; }; class equip_soundcard : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_soundcard; descriptionShort = $STR_ITEM_DESC_equip_soundcard; model = "\z\addons\dayz_communityassets\models\scrapelectronics.p3d"; picture = "\z\addons\dayz_communityassets\pictures\scrapelectronics.paa"; type = 256; }; class equip_soundcard_broken : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_soundcard_broken; descriptionShort = $STR_ITEM_DESC_equip_soundcard_broken; model = "\z\addons\dayz_communityassets\models\scrapelectronics.p3d"; picture = "\z\addons\dayz_communityassets\pictures\scrapelectronics.paa"; type = 256; }; class equip_pcicard : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_pcicard; descriptionShort = $STR_ITEM_DESC_equip_pcicard; model = "\z\addons\dayz_communityassets\models\scrapelectronics.p3d"; picture = "\z\addons\dayz_communityassets\pictures\scrapelectronics.paa"; type = 256; }; class equip_pcicard_broken : CA_Magazine { scope = 2; count = 1; displayName = $STR_ITEM_NAME_equip_pcicard_broken; descriptionShort = $STR_ITEM_DESC_equip_pcicard_broken; model = "\z\addons\dayz_communityassets\models\scrapelectronics.p3d"; picture = "\z\addons\dayz_communityassets\pictures\scrapelectronics.paa"; type = 256; }; class ItemLightBulb: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_LIGHTBULB; model = "\z\addons\dayz_epoch\models\bulb.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_bulb_CA.paa"; descriptionShort = $STR_EPOCH_LIGHTBULB_DESC; class ItemActions { class Crafting { text = $STR_EPOCH_PLAYER_196; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {"workshop"}; requiretools[] = {"ItemEtool","ItemToolbox"}; output[] = {{"light_pole_kit",1}}; input[] = {{"ItemLightBulb",1},{"PartGeneric",1},{"PartWoodLumber",6}}; }; }; }; class ItemLightBulbBroken: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_LIGHTBULB_BROKEN; model = "\z\addons\dayz_epoch\models\bulb.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_bulb_CA.paa"; descriptionShort = $STR_EPOCH_LIGHTBULB_BROKEN_DESC; }; class ItemNotebook: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_ITEM_NOTEBOOK; descriptionShort = $STR_EPOCH_ITEM_NOTEBOOK_DESC; model = "\CA\misc2\notebook\notebook.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemNotebookBroken: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_NOTEBOOK_BROKEN; descriptionShort = $STR_EPOCH_NOTEBOOK_BROKEN_DESC; model = "\CA\misc2\notebook\notebook.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemSmallTV: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_SMALL_TV; descriptionShort = $STR_EPOCH_SMALL_TV_DESC; model = "\CA\misc2\smallTV\smallTV.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemSmallTVBroken: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_SMALL_TV_BROKEN; descriptionShort = $STR_EPOCH_SMALL_TV_BROKEN_DESC; model = "\CA\misc2\smallTV\smallTV.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemBigTV: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_BIG_TV; descriptionShort = $STR_EPOCH_BIG_TV_DESC; model = "\CA\Structures\Furniture\Eletrical_appliances\tv_a\tv_a.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemBigTVBroken: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_BIG_TV_BROKEN; descriptionShort = $STR_EPOCH_BIG_TV_BROKEN_DESC; model = "\CA\Structures\Furniture\Eletrical_appliances\tv_a\tv_a.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemSatelitePhone: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_SATELLITE_PHONE; descriptionShort = $STR_EPOCH_SATELLITE_PHONE_DESC; model = "\CA\misc3\satelitePhone\satellitePhone.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemSatelitePhoneBroken: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_SATELLITE_PHONE_BROKEN; descriptionShort = $STR_EPOCH_SATELLITE_PHONE_BROKEN_DESC; model = "\CA\misc3\satelitePhone\satellitePhone.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemPC: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_PC; descriptionShort = $STR_EPOCH_PC_DESC; model = "\CA\Structures\Furniture\Eletrical_appliances\pc\pc.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemPCBroken: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_PC_BROKEN; descriptionShort = $STR_EPOCH_PC_BROKEN_DESC; model = "\CA\Structures\Furniture\Eletrical_appliances\pc\pc.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemDesktopRadio: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_DESKTOP_RADIO; descriptionShort = $STR_EPOCH_DESKTOP_RADIO_DESC; model = "\CA\misc\mutt_vysilacka.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemDesktopRadioBroken: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_DESKTOP_RADIO_BROKEN; descriptionShort = $STR_EPOCH_DESKTOP_RADIO_BROKEN_DESC; model = "\CA\misc\mutt_vysilacka.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemMusicRadio1: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_RADIO_MUSIC1; descriptionShort = $STR_EPOCH_RADIO_MUSIC1_DESC; model = "\CA\misc\radio.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemMusicRadio1Broken: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_RADIO_MUSIC1_BROKEN; descriptionShort = $STR_EPOCH_RADIO_MUSIC1_BROKEN_DESC; model = "\CA\misc\radio.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemMusicRadio2: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_RADIO_MUSIC2; descriptionShort = $STR_EPOCH_RADIO_MUSIC2_DESC; model = "\CA\Structures\Furniture\Eletrical_appliances\radio_b\radio_b.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; }; class ItemMusicRadio2Broken: CA_Magazine { scope = 2; count = 1; type = 256; displayName = $STR_EPOCH_RADIO_MUSIC2_BROKEN; descriptionShort = $STR_EPOCH_RADIO_MUSIC2_BROKEN_DESC; model = "\CA\Structures\Furniture\Eletrical_appliances\radio_b\radio_b.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_wooden_crate_ca.paa"; };
// Copyright (c) 2013 Nick Porcino, All rights reserved. // License is MIT: http://opensource.org/licenses/MIT #pragma once #include <vector> #include "LandruVM/VarObj.h" namespace Landru { class Exemplar; class Fiber; struct MachineCacheEntry { MachineCacheEntry(std::unique_ptr<Exemplar> e); MachineCacheEntry(const MachineCacheEntry& mc); /// @TODO The program store should go here instead of /// on every fiber. In order for that to happen, there /// has to be a way to reference vars per fiber, without /// modifying the program store per fiber // Shared variables are keyed from the exemplar std::shared_ptr<Exemplar> exemplar; std::shared_ptr<VarObjArray> sharedVars; }; class MachineCache { public: MachineCache(); ~MachineCache(); std::shared_ptr<MachineCacheEntry> findExemplar(const char* name); void add(VarObjFactory* factory, std::shared_ptr<Exemplar> e); std::shared_ptr<Fiber> createFiber(VarObjFactory* factory, char const* name); private: std::vector<std::shared_ptr<MachineCacheEntry>> cache; }; } // Landru
#include "ParamConfig.h" #include <iostream> using namespace std; #include <TDirectory.h> #include <TParameter.h> ParamConfig *ParamConfig::params = NULL; ParamConfig::ParamConfig(TString conffile) : TEnv(conffile) { cout << "load parameters ... " << conffile << endl; } template <class T> void ParamConfig::Save(TString name, T value) { TParameter<T> p(name, value); p.Write(); } void ParamConfig::Write(TString dir) { TDirectory *tmp = gDirectory; if(dir.Length() > 0) gDirectory->mkdir(dir)->cd(); Save<Double_t>("bragg_Detector_Beam.L1", BeamL1()); Save<Double_t>("bragg_Detector_Beam.L2", BeamL2()); //Save<const char*>("bragg_Detector_Beam.Particle", BeamParticle()); Save<Int_t>("bragg_Detector_Pixel_Nx", NxPixels()); Save<Int_t>("bragg_Detector_Pixel_Ny", NyPixels()); Save<Int_t>("bragg_Detector_Pixel_CenterX", PixelCenterX()); Save<Int_t>("bragg_Detector_Pixel_CenterY", PixelCenterY()); Save<Double_t>("bragg_Detector_Pixel_Width", PixelWidth()); Save<Int_t>("bragg_Vana_Hist_Tof_Nbin", VanaHistTofNbin()); Save<Double_t>("bragg_Vana_Hist_Tof_Xmin", VanaHistTofMin()); Save<Double_t>("bragg_Vana_Hist_Tof_Xmax", VanaHistTofMax()); Save<Int_t>("bragg_Vana_Hist_Lambda_Nbin", VanaHistLambdaNbin()); Save<Double_t>("bragg_Vana_Hist_Lambda_Min", VanaHistLambdaMin()); Save<Double_t>("bragg_Vana_Hist_Lambda_Max", VanaHistLambdaMax()); Save<Double_t>("bragg_Vana_Lambda_Min", VanaLambdaMin()); Save<Double_t>("bragg_Vana_Lambda_Max", VanaLambdaMax()); Save<Double_t>("bragg_Vana_Conv_Lambda_Min", VanaConvLambdaMin()); Save<Double_t>("bragg_Vana_Conv_Lambda_Max", VanaConvLambdaMax()); Save<Int_t>("bragg_Bragg_Hist_Tof_Nbin", BraggTofNbin()); Save<Double_t>("bragg_Bragg_Hist_Tof_Xmin", BraggTofXmin()); Save<Double_t>("bragg_Bragg_Hist_Tof_Xmax", BraggTofXmax()); Save<Double_t>("bragg.Bragg.Fit.Sigma.Low", BraggFitSigmaLow()); Save<Double_t>("bragg.Bragg.Fit.Sigam.High", BraggFitSigmaHigh()); tmp->cd(); } Int_t ParamConfig::BraggAreaX1(Int_t run) { TString name = TString::Format("bragg.Bragg.Run.%d.Area.X1", run); return GetValue(name, (Int_t)-1); } Int_t ParamConfig::BraggAreaX2(Int_t run) { TString name = TString::Format("bragg.Bragg.Run.%d.Area.X2", run); return GetValue(name, (Int_t)-1); } Int_t ParamConfig::BraggAreaY1(Int_t run) { TString name = TString::Format("bragg.Bragg.Run.%d.Area.Y1", run); return GetValue(name, (Int_t)-1); } Int_t ParamConfig::BraggAreaY2(Int_t run) { TString name = TString::Format("bragg.Bragg.Run.%d.Area.Y2", run); return GetValue(name, (Int_t)-1); }
//====C++ #include <iostream> #include <fstream> #include <vector> //===ROOT #include "TLorentzVector.h" #include "TH1F.h" #include "TH2F.h" #include "TProfile.h" #include "TProfile2D.h" #include "TF1.h" #include "TList.h" #include "TFile.h" #include "TTree.h" #include "TString.h" #include "TMath.h" #include "TRandom3.h" //===OTHERS #include "PbScIndexer.h" #include "PbScIndexer.C" #include "PbGlIndexer.h" #include "PbGlIndexer.C" #include "EmcIndexer.h" #include "EmcIndexer.C" using namespace std; const double kSpeedOfLightinNS = 29.979245829979; //[cm/ns] const int kNTWRS = 24768; unsigned int kBBCnc = 0x00000008; unsigned int kBBCn = 0x00000010; TTree *fTree; typedef struct MyTreeRegister2 { Float_t vtxZ; Float_t cent; Float_t bbct; Float_t bbctmin; Float_t bbctmax; Float_t frac; UInt_t trig; } MyTreeRegister2_t; MyTreeRegister2_t fGLB; std::vector<Int_t> *pEMCtwrid; std::vector<Int_t> *pEMCtdc; std::vector<Int_t> *pEMCadc; std::vector<Float_t> *pEMClen; std::vector<Float_t> *pEMCene;
#include<iostream> #include<vector> #include<algorithm> #include<numeric> using namespace std; class Solution { public: bool canPartition(vector<int>& nums) { //基本思想:动态规划,01背包问题,用递归回溯必超时 int sum=accumulate(nums.begin(),nums.end(),0); if(sum&1) return false; //dp[i]表示能否填满容量为i的背包 vector<bool> dp(sum/2+1,false); dp[0]=true; for(int i=0;i<nums.size();i++) { for(int j=sum/2;j>=nums[i];j--) dp[j]=dp[j]||dp[j-nums[i]]; } return dp[sum/2]; } }; int main() { Solution solute; vector<int> nums={1,2,3,4,6,7,8,9}; cout<<solute.canPartition(nums)<<endl; return 0; }
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "11541" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif int kase; scanf("%d",&kase); string str; int Case = 1; while( kase-- ){ printf("Case %d: ",Case++); cin >> str; char tmp; int num = 0; for(int i = 0 ; i <= str.size() ; i++ ){ if( i == str.size() || str[i] >= 'A' && str[i] <= 'Z' ){ for(int j = 0 ; j < num ; j++ ) cout << tmp ; num = 0; tmp = str[i]; } else{ num *= 10; num = num + (str[i]-'0'); } } cout << endl; } return 0; }
#include <SoftwareSerial.h> // Inclui Biblioteca SoftwareSerial mySerial(10, 11); // Simula RX e TX em outras portas const int ordemServico = 2; int buttonA = 4; int buttonB = 5; int buttonC = 6; int buttonD = 7; int ledPin = 13; void setup() { Serial.begin(9600); // Taxa de transferência da Serial mySerial.begin(9600); // Taxa de transferência do HC12 pinMode(ledPin, OUTPUT); pinMode(buttonA, INPUT_PULLUP); pinMode(buttonB, INPUT_PULLUP); pinMode(buttonC, INPUT_PULLUP); pinMode(buttonD, INPUT_PULLUP); } void loop() { int actionA = digitalRead(buttonA); int actionB = digitalRead(buttonB); int actionC = digitalRead(buttonC); int actionD = digitalRead(buttonD); if (actionA == LOW) { mySerial.write(getCommand(2)); digitalWrite(ledPin, HIGH); } else if (actionB == LOW) { mySerial.write(getCommand(3)); digitalWrite(ledPin, HIGH); } else if (actionC == LOW) { mySerial.write(getCommand(4)); digitalWrite(ledPin, HIGH); } else if (actionD == LOW) { mySerial.write(getCommand(5)); digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } mySerial.flush(); delay(100); } int getCommand(int action) { return action * ordemServico; }
void printdata(void) { /* * This function: * 1. Prints data generated by IMU handling functions. It is a function for testing. */ SerialUSB.print("!"); #if PRINT_EULER == 1 SerialUSB.print("ANG:"); SerialUSB.print(ToDeg(roll)); SerialUSB.print(","); SerialUSB.print(ToDeg(pitch)); SerialUSB.print(","); SerialUSB.print(ToDeg(yaw)); #endif #if PRINT_ANALOGS==1 SerialUSB.print(",AN:"); SerialUSB.print(AN[0]); //(int)read_adc(0) SerialUSB.print(","); SerialUSB.print(AN[1]); SerialUSB.print(","); SerialUSB.print(AN[2]); SerialUSB.print(","); SerialUSB.print(AN[3]); SerialUSB.print (","); SerialUSB.print(AN[4]); SerialUSB.print (","); SerialUSB.print(AN[5]); SerialUSB.print(","); SerialUSB.print(c_magnetom_x); SerialUSB.print (","); SerialUSB.print(c_magnetom_y); SerialUSB.print (","); SerialUSB.print(c_magnetom_z); #endif #if PRINT_DCM == 1 SerialUSB.print (",DCM:"); SerialUSB.print(DCM_Matrix[0][0]); SerialUSB.print (","); SerialUSB.print(DCM_Matrix[0][1]); SerialUSB.print (","); SerialUSB.print(DCM_Matrix[0][2]); SerialUSB.print (","); SerialUSB.print(DCM_Matrix[1][0]); SerialUSB.print (","); SerialUSB.print(DCM_Matrix[1][1]); SerialUSB.print (","); SerialUSB.print(DCM_Matrix[1][2]); SerialUSB.print (","); SerialUSB.print(DCM_Matrix[2][0]); SerialUSB.print (","); SerialUSB.print(DCM_Matrix[2][1]); SerialUSB.print (","); SerialUSB.print(DCM_Matrix[2][2]); #endif SerialUSB.println(); } /*long convert_to_dec(float x) { return x*10000000; }*/
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2012 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef WINDOWSOPASYNCICONLOADER_H #define WINDOWSOPASYNCICONLOADER_H #include "adjunct/desktop_pi/loadicons_pi.h" #ifndef DESKTOP_ASYNC_ICON_LOADER class WindowsOpAsyncFileBitmapLoader : public OpAsyncFileBitmapLoader, public MessageObject { public: WindowsOpAsyncFileBitmapLoader(); virtual ~WindowsOpAsyncFileBitmapLoader(); virtual OP_STATUS Init(OpAsyncFileBitmapHandlerListener *listener); virtual void Start(OpVector<TransferItemContainer>& transferitems); void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); private: OpAsyncFileBitmapHandlerListener* m_listener; OpAutoVector<OpString> m_filenames; // the filenames of the files to get the icon for. Only accessed from the thread. HANDLE m_thread_handle; static unsigned __stdcall IconLoadThreadFunc( void* pArguments ); }; #endif /// !DESKTOP_ASYNC_ICON_LOADER #endif // WINDOWSOPASYNCICONLOADER_H
#pragma once #include "ExampleBase.h" #include <cmath> class UseTexture : public ExampleBase { private: GLuint vao; GLuint textures[2]; Shader *shader; GLfloat factor = 0.5f; public: void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { __super::key_callback(window, key, scancode, action, mods); // 有个 repeat 事件,表示按下不松,不用自己记录按下和抬起的状态 if (key == GLFW_KEY_LEFT && action == GLFW_REPEAT) { factor -= 0.01f; factor = fmax(factor, 0.f); } if (key == GLFW_KEY_RIGHT && action == GLFW_REPEAT) { factor += 0.01f; factor = fmin(factor, 1.f); } } void initGLData() { glViewport(0, 0, WINDOW_WIDTH - 100, WINDOW_HEIGHT - 100); const char *className = typeid(*this).name() + 6; shader = new Shader(className); initTextures(); GLfloat vertices[] = { // Positions // Colors // Texture Coords 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // Top Right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Bottom Right -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Left -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // Top Left }; GLuint indices[] = { 0,1,2, 0,2,3 }; GLuint ibo, vbo; { // 创建普通 buffer 并上传索引数据 glGenBuffers(1, &ibo); glBindBuffer(GL_COPY_WRITE_BUFFER, ibo); glBufferData(GL_COPY_WRITE_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); } { // 创建普通 buffer 并上传顶点数据 glGenBuffers(1, &vbo); glBindBuffer(GL_COPY_WRITE_BUFFER, vbo); glBufferData(GL_COPY_WRITE_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_COPY_WRITE_BUFFER, 0); } { // 创建 VAO glGenVertexArrays(1, &vao); glBindVertexArray(vao); // 把刚才上传了数据的 ibo 绑定到 GL_ELEMENT_ARRAY_BUFFER // 注意:即使上面已经绑定了 GL_ELEMENT_ARRAY_BUFFER,但是由于 // 创建了新的 VAO 所以还要重新绑定一遍 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); // 把刚才上传了数据的 buffer 绑定到 GL_ARRAY_BUFFER,用以指定属性对应的数据源 glBindBuffer(GL_ARRAY_BUFFER, vbo); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), (GLvoid *)(6 * sizeof(GL_FLOAT))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } shader->use(); // !!!! glUniform 必须在 shader Use 之后调用 glUniform1i(shader->getUniformId("boxTexture"), 0); glUniform1i(shader->getUniformId("wallTexture"), 1); } void renderLoop() { glClearColor(0.3f, 0.3f, 0.7f, 1.f); glClear(GL_COLOR_BUFFER_BIT); glUniform1f(shader->getUniformId("factor"), factor); glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } void initTextures() { glGenTextures(2, textures); char* pics[2] = { "images/container.jpg", "images/wall.jpg" }; int width, height, nrChannels; for (int i = 0; i < 2; i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, textures[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_uc *data = stbi_load(pics[i], &width, &height, &nrChannels, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); stbi_image_free(data); } } };
#pragma once #include <SFML\System\Vector2.hpp> #include <SFML\Graphics\Rect.hpp> #include <string> #include <cinttypes> class PhysicsEngine; using namespace sf; class Collisionable { friend class PhysicsEngine; public: Collisionable(); std::string tag; uint64_t id; bool isTrigger; virtual Vector2f GetVelocity() = 0; virtual FloatRect GetCollider() = 0; bool IsCollision(Collisionable* other, Vector2f& offset = Vector2f(0.f,0.f)); protected: Vector2f m_velocity; virtual void Update(const float* deltaTime) = 0; virtual void OnCollisionEnter(Collisionable& collider) = 0; };
ifndef MINE_H #define MINE_H /*class mine { public: mine(int nval = 9); bool getChecked(); int getVal(); void setVal(int newVal); void setChecked(); private: int val; bool checked = false; }; class cords { public: int getX(); int getY(); void setX(int X); void setY(int Y); private: int x = -1; int y = -1 ; };*/ #endif // MINE_H
/* You are given N, and for a given N x N chessboard, find a way to place N queens such that no queen can attack any other queen on the chess board. A queen can be killed when it lies in the same row, or same column, or the same diagonal of any of the other queens. You have to print all such configurations. Input Format : Line 1 : Integer N Output Format : One Line for every board configuration. Every line will have N*N board elements printed row wise and are separated by space Note : Don't print anything if there isn't any valid configuration. Constraints : 1<=N<=10 Sample Input 1: 4 Sample Output 1 : 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 */ #include <bits/stdc++.h> using namespace std; #define IOS ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define ll long long int n; bool grid[10][10]={0}; void print(){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cout<<grid[i][j]<<" "; } } cout<<'\n'; } bool good(int r,int c){ for(int i=r-1;i>=0;i--) if(grid[i][c]) return false; //check upper rows for(int i=r-1,j=c-1;i>=0 && j<n;i--,j--) if(grid[i][j]) return false; for(int i=r-1,j=c+1;i>=0 && j<n;i--,j++) if(grid[i][j]) return false; return true; } void placeQueens(int r){ if(r==n){ print(); return; } for(int i=0;i<n;i++){ if(good(r,i)){ grid[r][i]=1; placeQueens(r+1); grid[r][i]=0; } } return; } int main(){ IOS; cin>>n; placeQueens(0); return 0; }
#include "AnimSpriteComponent.h" #include "Math.h" AnimSpriteComponent::AnimSpriteComponent(Actor* owner, int drawOrder) : SpriteComponent(owner, drawOrder), mCurrFrame(0.0f), mAnimFPS(24.0f), mLoop(true) { } void AnimSpriteComponent::Update(float deltaTime) { SpriteComponent::Update(deltaTime); if (mAnimTextures[mAnimName].size() > 0) { // Update the current frame based on frame rate // and delta time mCurrFrame += mAnimFPS * deltaTime; if (mLoop) { // Wrap current frame if needed while (mCurrFrame >= mAnimTextures[mAnimName].size()) { mCurrFrame -= mAnimTextures[mAnimName].size(); } } else { if (mCurrFrame >= mAnimTextures[mAnimName].size()) { mCurrFrame = mAnimTextures[mAnimName].size() - 1; } } // Set the current texture SetTexture(mAnimTextures[mAnimName][static_cast<int>(mCurrFrame)]); } else { mCurrFrame = 0.0f; } } void AnimSpriteComponent::SetAnimTextures(const std::string name, const std::vector<SDL_Texture*>& textures) { mAnimTextures[name] = textures; mAnimName = name; if (mAnimTextures.size() > 0) { // Set the active texture to first frame mCurrFrame = 0.0f; SetTexture(mAnimTextures[name][0]); } } void AnimSpriteComponent::PlayAnim(std::string name, bool loop) { if (mAnimTextures.find(name) != mAnimTextures.end()) { mAnimName = name; } mLoop = loop; } void AnimSpriteComponent::StopAnim() { mAnimName = ""; } bool AnimSpriteComponent::IsLoop() { return mLoop; } void AnimSpriteComponent::SetLoop(bool loop) { mLoop = loop; }
#include "msg_0x6c_encnahtitem_stc.h" namespace MC { namespace Protocol { namespace Msg { EncnahtItem::EncnahtItem() { _pf_packetId = static_cast<int8_t>(0x6C); _pf_initialized = false; } EncnahtItem::EncnahtItem(int8_t _windowId, int8_t _enchantment) : _pf_windowId(_windowId) , _pf_enchantment(_enchantment) { _pf_packetId = static_cast<int8_t>(0x6C); _pf_initialized = true; } size_t EncnahtItem::serialize(Buffer& _dst, size_t _offset) { _pm_checkInit(); if(_offset == 0) _dst.clear(); _offset = WriteInt8(_dst, _offset, _pf_packetId); _offset = WriteInt8(_dst, _offset, _pf_windowId); _offset = WriteInt8(_dst, _offset, _pf_enchantment); return _offset; } size_t EncnahtItem::deserialize(const Buffer& _src, size_t _offset) { _offset = _pm_checkPacketId(_src, _offset); _offset = ReadInt8(_src, _offset, _pf_windowId); _offset = ReadInt8(_src, _offset, _pf_enchantment); _pf_initialized = true; return _offset; } int8_t EncnahtItem::getWindowId() const { return _pf_windowId; } int8_t EncnahtItem::getEnchantment() const { return _pf_enchantment; } void EncnahtItem::setWindowId(int8_t _val) { _pf_windowId = _val; } void EncnahtItem::setEnchantment(int8_t _val) { _pf_enchantment = _val; } } // namespace Msg } // namespace Protocol } // namespace MC
#include "rplidar.h"
#include "GamePch.h" #include "BossAgent.h" #include "GameMessage.h" IMPLEMENT_GAME_COMPONENT_TYPEID(BossAgent) void BossAgent::Start() { m_health = GetEntity()->GetComponent<Health>(); m_Bar = hg::Entity::FindByName(SID(Boss_Indicator_Bar)); } void BossAgent::Update() { if (hg::g_Time.GetTimeScale() != 0) { float hpRatio = m_health->GetHealthRatio(); float percent = ceilf(hpRatio * 10) * 0.1f; m_Bar->GetTransform()->SetScale(percent, 1, 1); if (hpRatio <= FLT_EPSILON) { LevelCompleteMessage win; hg::g_EntityManager.BroadcastMessage(&win); } } }
#include "stdafx.h" #include "CartoonScene.h" #include "ZeroSceneManager.h" #include "MenuScene.h" #include <conio.h> CartoonScene::CartoonScene() : index(1) { page1 = new ZeroSprite("Resource/UI/Menu/Cartoon/cartoon_1.png"); page2 = new ZeroSprite("Resource/UI/Menu/Cartoon/cartoon_2.png"); page3 = new ZeroSprite("Resource/UI/Menu/Cartoon/cartoon_3.png"); page4 = new ZeroSprite("Resource/UI/Menu/Cartoon/cartoon_4.png"); PushScene(page1); PushScene(page2); PushScene(page3); PushScene(page4); } CartoonScene::~CartoonScene() { } void CartoonScene::Update(float eTime) { ZeroIScene::Update(eTime); if (ZeroInputMgr->GetKey(VK_RIGHT) == INPUTMGR_KEYDOWN) { index += 1; if (index > 4) { PopScene(page1); PopScene(page2); PopScene(page3); PopScene(page4); ZeroSceneMgr->ChangeScene(new MenuScene()); } } } void CartoonScene::Render() { ZeroIScene::Render(); switch (index) { case 1: page1->Render(); break; case 2: page2->Render(); break; case 3: page3->Render(); break; case 4: page4->Render(); break; } }
#include "Functions.h" class Implementation : public Interface { void Method() {} }; DECL(void) GetInterfaces(int numInstances, Interface** results) { for (int i = 0; i < numInstances; ++i) { results[i] = new Implementation(); } } DECL(void) GetInterfacesOptional(int numInstances, Interface** results) { if (results != nullptr) { GetInterfaces(numInstances, results); } } DECL(void) GetIntArray(int numInts, int* results) { for (int i = 0; i < numInts; ++i) { results[i] = i; } } DECL(wchar_t) GetFirstCharacter(wchar_t* string) { return string[0]; } DECL(char) GetFirstAnsiCharacter(char* string) { return string[0]; } DECL(void) BoolToIntTest(int in, int* out) { *out = in; } DECL(void) BoolArrayTest(bool* in, bool* out, int numElements) { for (int i = 0; i < numElements; ++i) { out[i] = in[i]; } } DECL(void) StructMarshalling(StructWithMarshal in, StructWithStaticMarshal inStatic, StructWithMarshal* out, StructWithStaticMarshal* outStatic) { *out = in; *outStatic = inStatic; } DECL(void) StructArrayMarshalling(StructWithMarshal in[1], StructWithStaticMarshal inStatic[1], StructWithMarshal out[1], StructWithStaticMarshal outStatic[1]) { out[0] = in[0]; outStatic[0] = inStatic[0]; } DECL(void) SetAllElements(StructWithMarshal* ref) { ref->i[0] = 10; ref->i[1] = 10; ref->i[2] = 10; } DECL(int) FirstElementOrZero(StructWithMarshal* ref) { if (ref != nullptr) { return ref->i[0]; } return 0; } DECL(void) FastOutTest(Interface** out) { *out = new Implementation(); } DECL(MyEnum) PassThroughEnum(MyEnum testEnum) { return testEnum; } DECL(void) Increment(int* cell) { (*cell)++; } DECL(int) Add(int* lhs, int* rhs_opt) { if (rhs_opt != nullptr) { return *lhs + *rhs_opt; } return *lhs; } DECL(const char*) GetName() { return "Functions"; } DECL(int) Sum(int numElements, SimpleStruct elements[]) { int sum = 0; if (elements == nullptr) { return sum; } for (int i = 0; i < numElements; ++i) { sum += elements[i].i; } return sum; } DECL(int) Product(int numElements, SimpleStruct elements[]) { int product = 1; for (int i = 0; i < numElements; ++i) { product *= elements[i].i; } return product; } DECL(long long) SumValues(LargeStruct val) { return val.i[0] + val.i[1] + val.i[2]; } DECL(PointerSize) PassThroughPointerSize(PointerSize param) { return param; } DECL(void) StructArrayOut(StructWithMarshal in, StructWithMarshal out[]) { if (out != nullptr) { out[0] = in; } } DECL(int) SumInner(StructAsClass test[], int length) { int sum = 0; for (int i = 0; i < length; i++) { sum += test[i].i; } return sum; } DECL(void) AddOne(SimpleStruct* param) { if(param != nullptr) param->i++; } DECL(void) EnumOut(MyEnum *enumOut) { *enumOut = TestValue; } DECL(MyEnum) FirstEnumElement(MyEnum test[]) { return test[0]; } DECL(int) ArrayRelationSum(int length, SimpleStruct elements[]) { return Sum(length, elements); } DECL(void) ArrayRelationOutInitBoolArray(bool out[], int length) { for(size_t i = 0; i < length; i++) { out[i] = true; } } DECL(void) ArrayRelationOutGetInterfacesWithRelation(int length, Interface** array) { GetInterfaces(length, array); } DECL(void) ArrayRelationInInterfaceArray(int length, Interface* array[]) { for(size_t i = 0; i < length; i++) { array[i]->Method(); } } DECL(int) ArrayRelationSumStructWithMarshal(int length, StructWithMarshal array[]) { int sum = 0; for(size_t i = 0; i < length; i++) { for(size_t j = 0; j < 3; j++) { sum += array[i].i[j]; } } return sum; } DECL(bool) VerifyReservedParam(int reserved) { return reserved == 42; } DECL(bool) PreserveVoidPointer1_None(void* array) { int* v = (int*)array; return *v == 42; } DECL(bool) PreserveVoidPointer1_False(void* array) { int* v = (int*)array; return *v == 42; } DECL(bool) PreserveVoidPointer1_True(void* array) { int* v = (int*)array; return *v == 42; } DECL(bool) PreserveVoidPointer2_None(void* array) { return (size_t) array == 42u; } DECL(bool) PreserveVoidPointer2_False(void* array) { return (size_t) array == 42u; } DECL(bool) PreserveVoidPointer2_True(void* array) { return (size_t) array == 42u; } DECL(StructAsClassWrapper) GetWrapper() { return {{1}}; }
#include <iostream> #include <utility> #include <string> #include <algorithm> #include <vector> #include <dirent.h> #include <unistd.h> #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <signal.h> using namespace std; #define PROCESS_COUNT "prc_cnt" #define DIRECTORY "dir" #define ASCEND "ascend" #define DESCEND "descend" #define WORKER_EXEC "./WORKER" #define PRESENTER_EXEC "./PRESENTER" #define DELIMITER "-" #define ASSIGN "=" #define NAMED_PIPE_PATH "./named_pipe" #define QUIT "quit" void tokenizeInput(string request, vector<pair<string, string> > &data, int &processCount, string &directory); void printData(vector<pair<string, string> > &data); bool getFilesOfDir(string name, vector <string> &files); void createWorkers(int processCount, vector <pid_t> &workersPIDs, vector <vector<int> > &fds); void createPresenter(pid_t &presenterPID); void waitForChildren(vector <pid_t> workersPIDs, pid_t presenterPID); void createWorkersPipes(int processCount, vector <vector<int> > &fds); void shareDataOnWorkersPipe(vector <string> files, vector <vector<int> > fds, string workerData, int processCount, string directory); string convertFilteringInfoToString(vector<pair<string, string> > data); void createPresenterPipe(vector<pair<string, string> > data, int processCount, vector <pid_t> workersPIDs); int main() { string request, directory; vector<pair<string, string> > data; vector <pid_t> workersPIDs; pid_t presenterPID; vector <string> files; vector <vector<int> > fds; int processCount; string workerData; mkfifo(NAMED_PIPE_PATH, 0666); while(true) { getline(cin, request); if(request == QUIT) { unlink(NAMED_PIPE_PATH); break; } tokenizeInput(request, data, processCount, directory); if(!getFilesOfDir(directory, files)) {continue;} createWorkersPipes(processCount, fds); workerData = convertFilteringInfoToString(data); createPresenter(presenterPID); createWorkers(processCount, workersPIDs, fds); createPresenterPipe(data, processCount, workersPIDs); shareDataOnWorkersPipe(files, fds, workerData, processCount, directory); waitForChildren(workersPIDs, presenterPID); workersPIDs.clear(); } } void createPresenterPipe(vector<pair<string, string> > data, int processCount, vector <pid_t> workersPIDs) { int fd; //create mkfifo(NAMED_PIPE_PATH, 0666); string sortingData = ""; if(data.size() > 0) { if((data[data.size() - 1].second == ASCEND || data[data.size() - 1].second == DESCEND)) sortingData = data[data.size() - 1].first + ASSIGN + data[data.size() - 1].second; } sortingData += ("/" + to_string(processCount)); sortingData += "@" ; //cerr << "HERE : " << sortingData << endl; for(int i = 0; i < processCount; i++) sortingData += (to_string(workersPIDs[i]) + " "); fd = open(NAMED_PIPE_PATH, O_WRONLY); write(fd, sortingData.c_str(), sortingData.size()+1); close(fd); } string convertFilteringInfoToString(vector<pair<string, string> > data) { string dataToBeSent = ""; if(data.size() != 0) { int indexLimit = ((data[data.size() - 1].second == ASCEND || data[data.size() - 1].second == DESCEND) ? data.size() - 1 : data.size()); //not sending the sort part for(int i = 0; i < indexLimit; i++) { dataToBeSent = dataToBeSent + data[i].first + ASSIGN + data[i].second; if(i != indexLimit - 1) dataToBeSent += DELIMITER; } } return dataToBeSent; } void shareDataOnWorkersPipe(vector <string> files, vector <vector<int> > fds, string workerData, int processCount, string directory) { vector <string> data; for(int i = 0; i < processCount; i++) { string allData = ""; if(workerData != "") allData += workerData + DELIMITER; allData += ("dir=" + directory + "*"); data.push_back(allData); } int j = 0; for(int i = 0; i < files.size(); i++) { data[j] = data[j] + files[i] + '-'; j = (j + 1) % processCount; } for(int i = 0; i < fds.size(); i++) { close(fds[i][0]); //close reading endpoint write(fds[i][1], (data[i]+ '|' ).c_str(), data[i].size()+1); } for(int i = 0; i < fds.size(); i++) close(fds[i][1]); } void createWorkersPipes(int processCount, vector <vector<int> > &fds) { fds.clear(); for(int i = 0; i < processCount; i++) { int fd[2]; if(pipe(fd) == -1) { cerr << "Creating worker pipe failed." << endl; return; } vector <int> fdInfo; fdInfo.push_back(fd[0]); fdInfo.push_back(fd[1]); fds.push_back(fdInfo); } } void waitForChildren(vector <pid_t> workersPIDs, pid_t presenterPID) { for(int i = 0; i < workersPIDs.size(); i++) waitpid(workersPIDs[i], NULL, WNOHANG); waitpid(presenterPID, NULL, WNOHANG); } void createPresenter(pid_t &presenterPID) { pid_t pid; pid = fork(); if(pid < 0) { cerr << "Couldn't create presenter process." << endl; return; } if(pid == 0) { if(execvp(PRESENTER_EXEC, NULL) < 0) { cerr << "Couldn't execvp for presenter" << endl; } } else presenterPID = pid; } void createWorkers(int processCount, vector <pid_t> &workersPIDs, vector <vector<int> > &fds) { pid_t pid; char* argv[3]; for(int i = 0; i < processCount; i++) { argv[0] = (char*)to_string(fds[i][0]).c_str(); argv[1] = (char*)to_string(fds[i][1]).c_str(); argv[2] = NULL; pid = fork(); if(pid < 0) { cerr << "Couldn't create a new worker process." << endl; return; } else if(pid == 0) execvp(WORKER_EXEC, argv); else workersPIDs.push_back(pid); } } bool getFilesOfDir(string name, vector <string> &files) { int len; DIR* dirp; struct dirent *dp; files.clear(); dirp = opendir(name.c_str()); if (dirp == NULL) { cerr << "Cannot open directory " << name << endl; return false; } while ((dp = readdir(dirp)) != NULL) { string fileName = dp->d_name; if(fileName.substr(fileName.find_first_of('.') + 1) == "dms") files.push_back(fileName); } closedir (dirp); return true; } void printData(vector<pair<string, string> > &data) { for (int i = 0; i < data.size(); i++) { cerr << data[i].first << " " << data[i].second << endl; } } void tokenizeInput(string request, vector<pair<string, string> > &data, int &processCount, string &directory) { data.clear(); request.erase(remove(request.begin(), request.end(), ' '), request.end()); string token; while (token != request) { int firstEqual = request.find_first_of(ASSIGN); if (firstEqual != -1) { pair<string, string> field; token = request.substr(0, firstEqual); request = request.substr(firstEqual + 1); field.first = token; token = request.substr(0, request.find_first_of(DELIMITER)); field.second = token; if (field.first == PROCESS_COUNT) processCount = stoi(token); else if (field.first == DIRECTORY) directory = token; else data.push_back(field); } request = request.substr(request.find_first_of(DELIMITER) + 1); } }
#include "medicalej.h" medicalej::medicalej() { }
#pragma once #include "Rect.h" class Chickens : public Rect { protected: bool pos; GLuint nextChange; public: bool anotherLife; Chickens(); Chickens(string); virtual void Update(GLfloat deltaTime); void Attack(); ~Chickens(); };
//$$---- Form HDR ---- //--------------------------------------------------------------------------- #ifndef experimentNotesH #define experimentNotesH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include "MainForm.h" //--------------------------------------------------------------------------- struct markers //структура для циклического динамического массива с метками { AnsiString textMark;//собственно текст метки __int32 pointOnGraph;//номер сигнала на графике, к которому привязан данная метка bool chanN[maxChannels];//номера каналов, которым принадлежит данная метка markers *nextM,//адрес следующей метки в циклическом динамическом массиве *prevM;//адрес предыдущей метки в циклическом динамическом массиве }; class TExpNotes : public TForm { __published: // IDE-managed Components TMemo *usersNotes; TMemo *PIDates; TLabel *mainLinesLbl; TEdit *addUMark; TLabel *addMarkLbl; void __fastcall addUMarkKeyPress(TObject *Sender, char &Key); private: // User declarations public: // User declarations __fastcall TExpNotes(TComponent* Owner); void AddMarker(AnsiString addedMark, __int32 pnG, bool *chN); void CreateAMark(); void DeleteAMark(markers *delM); void DeleteMarkers(); markers *theMarker;//указатель на некую метку в динамическом массиве для меток __int32 npNewRec,//количество сигналов, записанных в предыдущих сеансах сбора данных (дозапись в существующий файл) nmInRec;//количество меток, записанных в предыдущих сеансах сбора данных (дозапись в существующий файл) AnsiString pIDateString;//информацюя о файле }; //--------------------------------------------------------------------------- extern PACKAGE TExpNotes *ExpNotes; //--------------------------------------------------------------------------- #endif
// // Created by fab on 31/05/2020. // #ifndef DUMBERENGINE_VERTEX_HPP #define DUMBERENGINE_VERTEX_HPP #include <glm/glm.hpp> #include <cereal/archives/portable_binary.hpp> struct Vertex { glm::vec3 Position; glm::vec3 Normal; glm::vec2 TexCoords; template<class Archive> void serialize(Archive& archive) { archive(Position.x, Position.y, Position.z, Normal.x, Normal.y, Normal.z, TexCoords.x, TexCoords.y); } }; #endif //DUMBERENGINE_VERTEX_HPP
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; int main(){ int minInd, maxInd, numValid = 0, letterCount; char letter; char password[100]; while(scanf("%d-%d %c: %s", &minInd, &maxInd, &letter, password) > 0){ if((password[minInd - 1] == letter && password[maxInd - 1] != letter) || (password[minInd - 1] != letter && password[maxInd - 1] == letter)){ numValid++; } } cout << numValid << endl; return 0; }
#ifndef GNSMELEMENT_H #define GNSMELEMENT_H GnSmartPointer(Gn2DMeshObject); class GNMESH_ENTRY Gn2DMeshObject : public GnObjectForm { GnDeclareRTTI; GnDeclareFlags( guint16 ); GnDeclareStream; public: enum eSMFlag { VISIBLE_MASK = 0x0001, }; protected: Gn2DMeshObject* mpParent; GnReal2DMesh* mpMesh; Gn2DAVDataPtr mpsAVData; GnVector2 mOriginalPosition; GnVector2 mMeshSize; public: virtual ~Gn2DMeshObject(); static Gn2DMeshObject* CreateFromTextureFile(const gchar* pcFilePath); static Gn2DMeshObject* Create(bool bUseGn2DMeshData); static Gn2DMeshObject* Create(const gchar* pcFilePath, bool bUseGn2DMeshData); static Gn2DMeshObject* CreateFullPath(const gchar* pcFullPath, bool bUseGn2DMeshData); void SetMesh(GnReal2DMesh* pMesh); void SetAVData(Gn2DAVData* val); void AttachParent(Gn2DMeshObject* pParent); void SetScale(float val); void SetPosition(GnVector2 val); void SetFlipX(bool val); virtual void Update(float fTime); virtual Gn2DMeshObjectPtr DetachChild(Gn2DMeshObject* pChild){ return NULL; }; virtual GnObjectForm* GetObjectByName(const GnSimpleString& kName); inline GnReal2DMesh* GetMesh() { return mpMesh; } inline void DetachParent() { mpParent = NULL; } inline void StopAllAnimation() { mpMesh->stopAllActions(); } inline Gn2DAVData* GetAVData() { return mpsAVData; } inline bool IsVisible() { return GetBit( VISIBLE_MASK ); } inline void SetVisible(bool val) { mpMesh->setIsVisible( val ); SetBit( val, VISIBLE_MASK ); } inline GnVector2& GetOriginalPosition() { return mOriginalPosition; } inline void SetOriginalPosition(GnVector2& val) { mOriginalPosition = val; } inline GnVector2& GetPosition() { return mOriginalPosition; } inline GnVector2 GetPositionFromImageCenter() { CCPoint pos = mpMesh->getPosition(); CCSize size = mpMesh->getContentSize(); size.width /= 2; size.height /= 2; if( GetAVData() == NULL ) return GnVector2( pos.x + size.width, pos.y + size.height ); if( mpMesh->isFlipX() ) { return GnVector2( pos.x + size.width, pos.y + size.height );; } return GnVector2( pos.x + size.width, pos.y + size.height );; } inline guchar GetAlpha() { return mpMesh->getOpacity(); } inline void SetAlpha(float val) { mpMesh->setOpacity( (GLubyte)(val * 255) ); } inline void SetAlpha(guchar val) { mpMesh->setOpacity( val ); } inline void SetColor(GnColor cColor) { mpMesh->setColor( ccc3( (GLubyte)(cColor.r * 255), (GLubyte)(cColor.g * 255.0f) , (GLubyte)(cColor.b * 255.0f) ) ); } inline GnColor GetColor() { ccColor3B color = mpMesh->getColor(); return GnColor( (float)color.r / 255.0f , (float)color.g / 255.0f, (float)color.b / 255.0f ) ; } inline float GetScale() { return mpMesh->getScale(); } inline bool GetFlipX() { return mpMesh->isFlipX(); } inline GnVector2 GetSize() { return mMeshSize; } inline void SetSize(GnVector2 cSize) { mpMesh->setContentSize( CCSizeMake( cSize.x, cSize.y ) ); mMeshSize = cSize; } inline gint32 GetZOrder() { return mpMesh->getZOrder(); } inline GnVector2 GetFlipCenter() { if( GetAVData() ) return GetAVData()->GetImageCenter(); return GnVector2( 0.0f, 0.0f ); } protected: Gn2DMeshObject(GnReal2DMesh* pMesh); void SetVectorExtraDataScale(); void SetVectorExtraDataFlipX(); void Create2DAVData(GnVector2 cSize); void SetRootMeshFromTextureAniCtlr(); }; #endif // GNSMELEMENT_H
#include <iostream> #include <fstream> #include <string> #include<streambuf> #include <stdio.h> #include <stdlib.h> #include <cstring> #include <time.h> #include <vector> #include "base64.cpp" //Base64 Library (written by René Nyffenegger) #include "EncryptClass.cpp" #include "DecryptClass.cpp" using namespace std; //Global Constants const bool ENC = true; const bool DEC = false; //PARSING CHECKER bool checkParse(char* argv[],int argc,int i){ const char* OPTIONS[] = { "-e","-encrypt","-d","-decrypt","-msg","-b64","-l","-r","-i","-o","-p","--help","--about"}; const int OPT_LENGTH = sizeof(OPTIONS)/sizeof(*OPTIONS); if (!(argc > (i+1))){ return false; } else { char* parse = argv[i+1]; for (int i = 0; i < OPT_LENGTH; i++){ if (strcmp(parse,OPTIONS[i])== 0){ return false; } } } return true; } //MAKE A COPY OF ANY FILE char* fileCopy(char* file){ //Declare both Files. Copy & Original fstream fileCopy; string copyText; //Open and copy whats in Original to string ifstream TextBuffer(file); TextBuffer.seekg(0, ios::end); copyText.reserve(TextBuffer.tellg()); TextBuffer.seekg(0, ios::beg); copyText.assign((istreambuf_iterator<char>(TextBuffer)),istreambuf_iterator<char>()); //Copy string to copyFile fileCopy.open("OrigCopy.ckt",fstream::out); fileCopy << copyText; fileCopy.close(); return (char*)"OrigCopy.ckt"; } //ARGUMENT PARSER int argumentparser(int argc, char*argv[]) { char* inFile = (char*)""; char* outFile = (char*)"cypher.txt"; char* transFile = (char*)""; char* inFileOriginal = inFile; bool RemoveOrigin = false; bool onTheGo = false; int repeat = 0; string password = ""; bool mode = ENC; bool modeGiven = false; bool inFileGiven = false; bool outFileGiven = true; bool passGiven = false; bool b64 = false; bool print = false; bool loud = false; bool pDisplacement = false; bool header = false; ///THIS IS THE PUBLISHED VERSION ///THEREFORE IT IS ONLY NATURAL THAT THE ENCRYPTION PROTOCOL SHOULD BE THE BEST POSSIBLE modeGiven = true; b64 = true; repeat = 2; pDisplacement = true; header = true; ////////////////////// for(int i = 1; i < argc; i++) { if (strcmp(argv[i],"--help")==0){ return 5; } else if (strcmp(argv[i],"--about")==0){ return 6; } else if (strcmp(argv[i],"--easter")==0){ return 7; } //CHECK MODE else if (strcmp(argv[i],"-e")==0) { mode = ENC; modeGiven = true; } else if (strcmp(argv[i],"-encrypt")==0) { mode = ENC; modeGiven= true; } else if (strcmp(argv[i],"-d")==0) { mode = DEC; modeGiven=true; } else if (strcmp(argv[i],"-decrypt")==0) { mode = DEC; modeGiven = true; } //CHECK OPTIONS //-Repeat else if (strcmp(argv[i],"-r")==0) { if (checkParse(argv,argc,i)){ i++; repeat = atoi(argv[i]); if (repeat == 0){ return 9; } if (repeat == 1){ repeat = 0; //Because 1 causes a bug. } } else { return 9;} } //-Loud else if (strcmp(argv[i],"-l")==0) { loud = true; } //-Delete Original else if (strcmp(argv[i],"-del")==0) { RemoveOrigin = true; } //-Base64 Encoding else if (strcmp(argv[i],"-b64")==0) { if (checkParse(argv,argc,i)){ i++; b64 = (bool) atoi(argv[i]); } } //-Strong else if (strcmp(argv[i],"-strong")==0) { b64 = true; repeat = 2; pDisplacement = true; header = true; } //-Password Displacement else if (strcmp(argv[i], "-pdis")==0) { if (checkParse(argv,argc,i)){ i++; pDisplacement = (bool) atoi(argv[i]); } } //-Header else if (strcmp(argv[i], "-h")==0) { if (checkParse(argv,argc,i)){ i++; header = (bool) atoi(argv[i]); } } //CHECK FILES else if (strcmp(argv[i],"-i")==0) { if (onTheGo == false){ if (checkParse(argv,argc,i)){ i++; inFile = argv[i]; ifstream testfile(inFile); if (testfile){ inFileGiven = true; } } } else {return 8;} } else if (strcmp(argv[i],"-o")==0) { if (checkParse(argv,argc,i)){ i++; outFile = argv[i]; ifstream testfile(outFile); if (testfile){ outFileGiven = true; } } } //CHECK IF IT IS ON-THE-GO// else if (strcmp(argv[i],"-msg")==0) { if (inFileGiven == false){ onTheGo = true; } else{ return 8;} } //CHECK PASSWORD else if (strcmp(argv[i],"-p")==0) { if (argc > (i+1)){ i++; password = argv[i]; passGiven = true; } } else {cout <<"\nParameter: " << argv[i] << " not recognized.\n"; return 10;} } //ON THE GO ENCRYPTION/DECRYPTION if (onTheGo == true){ string clearText = " "; cout << "\nWrite your message: \n\n"; getline( cin, clearText ); //Create the TempFile inFile = (char*) "TempCKTFile.ckt"; inFileGiven = true; //Fill the File with the cleartext fstream clearFile; clearFile.open(inFile,fstream::out); clearFile << clearText; clearFile.close(); //Makesure it is Erased Eventually. RemoveOrigin = true; } //Print Variable - Do we want to print the enc/dec process? if (loud == true || onTheGo == true){ print = true;} //If everything is parsed and correct then lets enc/dec! if (modeGiven && inFileGiven && outFileGiven && passGiven) { //ENCRYPTION MODE if (mode == ENC) { //Copy Original File - Precaution in case somthing goes wrong. We don't want to damage the original. inFileOriginal = inFile; inFile = fileCopy(inFile); Encryptor message; for (int i = 0; i<=repeat; i++) { //REPEAT, SWITCHING FILES if (i != 0){ transFile = outFile; outFile = inFile; inFile = transFile; } message.Encrypt(password, inFile, outFile, true, b64, pDisplacement, print,header); } } else if (mode == DEC) { //Copy Original File - Precaution in case somthing goes wrong. We don't want to damage the original. inFileOriginal = inFile; inFile = fileCopy(inFile); Decryptor message; for (int i = 0; i<=repeat; i++) { if (i != 0){ transFile = outFile; outFile = inFile; inFile = transFile; } message.Decrypt(password, inFile, outFile, true, b64, pDisplacement, print,header); } } if (RemoveOrigin){ if (remove(inFileOriginal) != 0){cout << "Couldn't delete original file"<<endl;} } } else if (modeGiven !=true){ return 3;} else if (inFileGiven !=true){return 2;} else if (passGiven !=true) {return 4;} else {return 1;} //Loud Printing of Variables for Debuggin Purpose if (loud) { cout << "<>-----------<>\n" << " Mode: " <<mode << endl << " In File: " << inFileOriginal << endl << " Out File: " << outFile << endl << " Password: " << password << endl << " Repeats: " << repeat << endl << " Base64: " << b64 <<endl << " Password Displacement: " << pDisplacement<< endl << " Delete Original: " << RemoveOrigin << endl << " Loud : " << loud << "\n\n"; } return 0; } //EASTER EGG (because all programs should have one!) int easter(){ cout <<"\n" <<" --.` " << endl <<" `o+osso+/:-` " << endl <<" -yssysso++o+- " << endl <<" :ysssysoo+++++ ` " << endl <<" :s+oysy+o++++++ -+ys. " << endl <<" `syyssyo++++++o. /oyo::-. " << endl <<" -yyyyyo+++--+o/ `ss `-//+:` " << endl <<" `+yyyy++o` `` -y: `:/:/: " << endl <<" -+sssso+++ /y` .///+` " << endl <<" `o+sooso++o/ `:/:- ///+. " << endl <<" .o++o++o++os .:/+//` ://+` " << endl <<" .o+oo++++++o+:oo..y/` ./:/ " << endl <<" /++o+++++o+ososs+/y` `/o " << endl <<" o+++oooyssooo+oy++o o` " << endl <<" /o++++o/+s++s+so:y: " << endl <<" -+ooooo+ooo+o.` :y` " << endl <<" /+++++++++++o. +s " << endl <<" +++++++++++++: sy " << endl <<" `o++++++++++++/ `sy` " << endl <<" ++++++++++++++o..sy/ " << endl <<" /ooo++++++++++++o-sss " << endl <<" -+ooo++++++++++++++:oyy. " << endl <<" ...-:/+ooo+++++++++++++++++ooso` " << endl <<" ....`` ``...---------------.` " << endl <<"--------------------------------------------------" <<endl <<" DEAD MAN TELL NO TALE" <<endl <<"--------------------------------------------------" <<endl <<"Special Thanks To: Mom & Pops, Luigi, Ikus, Almojarifazgo,\nand all my cousins around the globe" <<endl; return 0; } //PRINTING META INFORMATION int printMetaInfo(int info){ if (info == 1){ cout<<"\nFile Cyphering:\n casualkrypt -[mode] -[options] -o [OUTfile] -i [INfile] -p [Password]\n\n" <<"On-The-Go Cyphering:\n casualkrypt -[mode] -[options] -o [OUTfile] -p [Password] -msg" <<"\n\n" <<"MODES:\n" <<" -e , -encrypt : Encrypt File\n" <<" -d , -decrypt : Decrypt File" <<"\n\n" <<"OPTIONS:\n" <<" -msg : Let's you type in your own message on the console.\n" <<" -r [x] : (Default: 2) Repeat Enc/Dec [x] amount of times.\n" <<" -l : Prints Data To Screen\n" <<" -del : Deletes input file upon cyphering completion\n" <<" -h : (0-ON, 1-OFF,Default= ON) Adds Encryption Header for added security\n" <<" -pdis : (0-ON, 1-OFF,Default= ON) Password Displacement for added security\n" <<" -b64 : (0-ON, 1-OFF,Default= ON) Use Base64 Encoding\n" <<"\n\n" <<"FILES:\n" <<" -i [INfile] : input file to encrypt or decrypt.\n" <<" -o [OUTfile] : output (enc/dec) processed file.\n" <<" (OPTIONAL - Default: cyphered.txt)\n" <<" -p [Password] : The password.\n\n" <<" (If files/passwords have spaces : write between qoutation marks \"test 1\")\n" <<" (You can reference files on different directories \"C:\\programs\\foo.txt\")" <<"\n\n" <<" --about : information about the program\n" <<" --help : displays this usage screen" <<"\n\n\n"; } else if (info == 2){ cout << "\nCasualKrypt 1.5.0\n" << "Programmed by: Pedro M. Sosa <konukoii@gmail.com>\n" << "Website & Donations: sosavpm.users.sourceforge.net\n\n" << "Licenced under GNU GPL\n" << "(C) 2012 Pedro Sosa\n" << "This is free software; see the source for copying conditions.\n" << "There is NO warranty; not even for MERCHTABILITY or FITNESS FOR A PARTICULAR PURPOSE\n" << "Base64 Encoding programmed by Rene Nyffenegger\n\n"; } else if (info ==3){easter();} return 0; } //ERROR DISPLAY int displayError(int errorCode){ if (errorCode == 0){cout << "\nGreat Success!\n";} if (errorCode == 1){cout << "\nError: Not enough arguments given!\n";} if (errorCode == 2){cout << "\nError: File to Enc/Dec does not exist\n";} if (errorCode == 3){cout << "\nError: No Mode Given!\n";} if (errorCode == 4){cout << "\nError: No Password Given!\n";} if (errorCode == 5){printMetaInfo(1); return 0;} //help if (errorCode == 6){printMetaInfo(2);} //about if (errorCode == 7){printMetaInfo(3);} //easter Egg if (errorCode == 8){cout << "\nInput file given and On-The-Go text recieved! Can't do both at the same time.\n";} if (errorCode == 9){cout << "\n'-r' option given with no valid number given\n";} if (errorCode != 0){cout << "\nTry 'casualkrypt --help' for usage information\n";} return 0; } //MAIN FUNCTION int main(int argc, char*argv[]) { if (argc <= 1){ cout << "\nFile Cyphering:\n casualkrypt -[mode] -[options] -o [OUTfile] -i [INfile] -p [Password]\n\n"; cout << "On-The-Go Cyphering:\n casualkrypt -[mode] -[options] -o [OUTfile] -p [Password] -msg\n"; cout << "\n\nTry 'casualkrypt --help' for more options\n"; } else { int errorcode = 0; errorcode = argumentparser(argc, argv); displayError(errorcode); } //encrypt("PwnSosa",(char*)"TrueT.ckt",(char*)"OutFile1.pms"); //decrypt("PwnSosa",(char*)"OutFile1.pms",(char*)"TheBigDeal.ckt"); //cout << "hit enter!"; //int debug; //cin >> debug; return 0; } //int main(){ //Encrypt(string pass, char* inFileName, char* outFileName, bool RemoveOrigin, bool b64, bool pDisplacement, bool loud,bool header); //Encrypt message1("PwnSosa",(char*)"texto.txt",(char*)"OutFile1.pms",false,true,true,true,true); //Decrypt message("PwnSosa",(char*)"OutFile1.pms",(char*)"OF2.txt",false,true,true,true,true); //return 0; //}
#ifndef TABLERO_H_ #define TABLERO_H_ #include "casillero.h" #define ANCHO 3 #define ALTO 3 typedef struct{ Casillero *** casilleros; int ancho; int alto; } Tablero; Tablero * inicializarTablero(); void imprimirTablero(Tablero * tablero, std::string archivoSalida); void destruirTablero(Tablero * tablero); void asignarFicha(Tablero * tablero, int x, int y, char ficha); void asignarFicha(Casillero * casillero, char ficha); void quitarFicha(Tablero * tablero, int x, int y, char ficha); void quitarFicha(Casillero * casillero, char ficha); void moverFicha(Tablero * tablero, int x, int y, int xInicial, int yInicial, char ficha); bool verificarGanador(Tablero* tablero, int x, int y, char ficha); bool verificarColumna(Tablero* tablero, int x, int y, char ficha); bool verificarFila(Tablero* tablero, int x, int y, char ficha); bool verificarDiagonal(Tablero* tablero, int x, int y, char ficha); bool verificarAntiDiagonal(Tablero* tablero, int x, int y, char ficha); void imprimirGanador(char ficha); #endif /* TABLERO_H_ */
#include <codecvt> #include "fakeit.hpp" // Matcher for wchar_t* and std::wstring template<typename T> struct EqSTRCreator : public fakeit::TypedMatcherCreator<T> { const std::wstring expected; virtual ~EqSTRCreator() = default; EqSTRCreator(const std::wstring &expected) : fakeit::TypedMatcherCreator<T>(), expected(expected) { } struct Matcher : public fakeit::TypedMatcher<T> { const std::wstring expected; Matcher(const std::wstring &expected) : expected(expected) {} std::string format() const override { using convert_typeX = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_typeX, wchar_t> converterX; return converterX.to_bytes(expected); } bool matches(const T &actual) const override { return actual == expected; } }; fakeit::TypedMatcher<T> *createMatcher() const override { return new Matcher(expected); } }; template<typename T> EqSTRCreator<T> EqSTR(const std::wstring &arg) { return EqSTRCreator<T>{arg}; } // Matcher for T* and T template<typename T, typename E = typename std::remove_pointer<T>::type> struct EqPTRCreator : public fakeit::TypedMatcherCreator<T> { const E expected; virtual ~EqPTRCreator() = default; EqPTRCreator(const E &expected) : fakeit::TypedMatcherCreator<T>(), expected(expected) { } struct Matcher : public fakeit::TypedMatcher<T> { const E expected; Matcher(const E &expected) : expected(expected) {} std::string format() const override { return TypeFormatter<E>::format(expected); } bool matches(const T &actual) const override { return *actual == expected; } }; fakeit::TypedMatcher<T> *createMatcher() const override { return new Matcher(expected); } }; template<typename T> EqPTRCreator<T> EqPTR(const typename std::remove_pointer<T>::type &arg) { return EqPTRCreator<T>{arg}; }
#include <iostream> #include "string.hpp" String fun(){ String a; std::cout << "a-num:\t" << a.getNum() << std::endl; return a; } int main() { String str1; String str2 = str1; str1.setNum(90); std::cout << "Num:\t" << str1.getNum() << std::endl; std::cout << "Num:\t" << str2.getNum() << std::endl; // String outher = &fun(); return 0; }
#include <NewPing.h> #include <TridentTD_LineNotify.h> #include <BlynkSimpleEsp8266.h> #include <DHT.h> #include <Adafruit_Sensor.h> #define SONAR_NUM 5 #define MAX_DISTANCE 100 #define DHTPIN D8 #define DHTTYPE DHT22 NewPing sonar[SONAR_NUM] = { // Sensor object array. NewPing(D1, D1, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping. NewPing(D2, D2, MAX_DISTANCE), NewPing(D5, D5, MAX_DISTANCE), NewPing(D6, D6, MAX_DISTANCE), NewPing(D7, D7, MAX_DISTANCE) }; int ul, TotalGrownMushroom, LastTotalGrownMushroom; int freq = 1000; int ref = 10; float Humid, Temp; char auth[] = "API_KEY"; //Blynk api key char ssid[] = "SSID"; //ชื่อ wifi char pass[] = "PASS"; //Wifi password char IP[] = "oasiskit.com"; BLYNK_WRITE(V1) { ref = param.asInt(); } BLYNK_WRITE(V2) { freq = param.asInt(); } DHT dht(DHTPIN, DHTTYPE); void IOTbegin() { WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(200); } Serial.println(WiFi.localIP()); LINE.setToken("LINE_TOKEN");//Line token Blynk.begin(auth, ssid, pass, IP, 8080); } void CheckMushroom() { TotalGrownMushroom = 0; for (int i = 0; i < SONAR_NUM; i++) { ul = sonar[i].ping_cm(); Serial.print(i); Serial.print("="); Serial.print(ul); Serial.print("cm "); if (ul < ref) { TotalGrownMushroom++; } } Serial.println(); if (TotalGrownMushroom != LastTotalGrownMushroom) { Serial.print("GrownMushroom ="); Serial.println(TotalGrownMushroom); LINE.notify(TotalGrownMushroom); Blynk.virtualWrite(V0, TotalGrownMushroom); LastTotalGrownMushroom = TotalGrownMushroom; } } void TestDHT () { Serial.print(F("Humidity: ")); Serial.print(Humid); Serial.print(F("% Temperature: ")); Serial.print(Temp); Serial.println(F("°C ")); } void setup() { Serial.begin(115200); IOTbegin(); dht.begin(); } void loop() { Blynk.run(); Humid = dht.readHumidity(); Temp = dht.readTemperature(); CheckMushroom(); Blynk.virtualWrite(V3, Temp); Blynk.virtualWrite(V4, Humid); delay(freq); }
#include <iostream> #include "polynomials.h" #include <ctype.h> // isdigit() #include <sstream> // stringstream using namespace std; void Wx::isFloat(string &s, float &f, int iI) { int isFlt=0; int decimalCount=0; int stringZero=0; bool isFltBool=false; bool containsSpaces = false; do { getline(cin >> ws, s); for (int i=0; i<s.size(); i++) { if (s[i]=='0') stringZero++; } for (int i=0; i<s.size(); i++) { if (isspace(s[i])) containsSpaces=true; } if (s[0]=='-') { isFlt=1; } if (s[0]=='-' && s[1]=='0' && s[2]=='.' && s.size()-2==stringZero) { isFlt=0; } else if (s[0]=='0' && s[1]=='.' && s.size()-1==stringZero) { isFlt=-1; } else if (s[0]=='0' && s[1]=='0') { isFlt=-1; } else if (s[1]=='0' && s[2]=='0') { isFlt=0; } else if ((s[0]=='0' && isdigit(s[1]))) { isFlt = -1; } stringZero=0; for (int i=0; i<s.size(); i++) { if (isdigit(s[i])) isFlt++; if (s[i]=='.') { decimalCount++; isFlt++; } } if (isFlt==s.size() && containsSpaces==false && (decimalCount==0 || decimalCount==1) && (s[0]!='.' && s[s.size()-1]!='.')) { stringstream str_stream_object(s); str_stream_object>>f; isFltBool=1; } else { cout<<"It is not a floating point numer, try again: "; cout<<endl; cout<<"x^"<<iI<<": "; isFltBool=0; isFlt=0; decimalCount=0; containsSpaces=false; } } while (isFltBool==0); }
// // main.cpp // fraction-to-recurring-decimal // // Created by xiedeping01 on 15/11/12. // Copyright (c) 2015年 xiedeping01. All rights reserved. // #include <iostream> #include <limits> #include <unordered_map> using namespace std; class Solution { public: string fractionToDecimal(int numerator, int denominator) { // 整数部分可以直接除,小数部分需要模拟除法 // 小数部分使用一个map帮助寻找循环的位置。 // 除法一般需要注意几个问题: // 1. 除零错 // 2. 负数 // 3. 溢出 // 避免除零错 if (denominator == 0) return to_string(numeric_limits<int>::max()); if (numerator == 0) return "0"; // 负数转成整数,使用long long避免溢出 long long a = abs((long long)numerator); long long b = abs((long long)denominator); // 分别计算整数部分和小数部分 string integerPart = calcIntegerPart(a, b); string floatPart = calcFloatPart(a, b); // 拼接结果 string result = combineIntegerAndFloat(integerPart, floatPart); // 补充符号 if ((numerator ^ denominator) >> 31) { return "-" + result; } else { return result; } } private: string calcIntegerPart(long long a, long long b) { return to_string(a / b); } string calcFloatPart(long long a, long long b) { a = a % b; // 保存结果 string result; // 保存每次除法中,被除数及商的位置,如果遇到重复的被除数,说明遇到循环,根据对应商的位置,找出循环的起点和终点 unordered_map<long long, int> idxMap; while (a) { // 商 long long d = (10 * a) / b; // 余数 long long r = (10 * a) % b; // 寻找循环 if (idxMap.find(a) != idxMap.end()) { result.insert(idxMap[a], 1, '('); result.push_back(')'); return result; } idxMap[a] = (int)result.length(); result.push_back(d + '0'); a = r; } return result; } string combineIntegerAndFloat(const string &integerPart, const string &floatPart) { if (floatPart.empty()) return integerPart; return integerPart + "." + floatPart; } }; int main(int argc, const char * argv[]) { std::cout << Solution().fractionToDecimal(3, 0) << endl; std::cout << Solution().fractionToDecimal(56, 7) << endl; std::cout << Solution().fractionToDecimal(56, -7) << endl; std::cout << Solution().fractionToDecimal(-56, 7) << endl; std::cout << Solution().fractionToDecimal(-56, -7) << endl; std::cout << Solution().fractionToDecimal(57, 7) << endl; std::cout << Solution().fractionToDecimal(1, 2) << endl; std::cout << Solution().fractionToDecimal(2, 1) << endl; std::cout << Solution().fractionToDecimal(1, 3) << endl; std::cout << Solution().fractionToDecimal(1, 333) << endl; std::cout << Solution().fractionToDecimal(1, 6) << endl; std::cout << Solution().fractionToDecimal(0, -5) << endl; return 0; }
#include "Tick.hh" #include "umlrtinsignal.hh" #include "umlrtobjectclass.hh" #include "umlrtoutsignal.hh" struct UMLRTCommsPort; static UMLRTObject_field fields_tick[] = { #ifdef NEED_NON_FLEXIBLE_ARRAY { 0, 0, 0, 0, 0 } #endif }; static UMLRTObject payload_tick = { 0, #ifdef NEED_NON_FLEXIBLE_ARRAY 1 #else 0 #endif , fields_tick }; Tick::Base::Base( const UMLRTCommsPort * & srcPort ) : UMLRTProtocol( srcPort ) { } UMLRTOutSignal Tick::Base::tick() const { UMLRTOutSignal signal; signal.initialize( "tick", signal_tick, srcPort, &payload_tick ); return signal; } Tick::Conj::Conj( const UMLRTCommsPort * & srcPort ) : UMLRTProtocol( srcPort ) { } UMLRTInSignal Tick::Conj::tick() const { UMLRTInSignal signal; signal.initialize( "tick", signal_tick, srcPort, &payload_tick ); return signal; }
#include <cstdio> #include <sstream> #include <iostream> #include <cmath> #include <math.h> #include <stdlib.h> #include <ctime> #ifdef __APPLE__ # pragma clang diagnostic ignored "-Wdeprecated-declarations" # include <GLUT/glut.h> #else # include <GL/glut.h> #endif using namespace std; // // Rotation constants // static int rotating = 0; // static float y_angle = 0; // //static int y_angle = 0; // static float y_delta = 0.1; // static float x_angle = 0; // //static int x_angle = 0; // static float x_delta = 0.1; // Window handles static int window_cube; static int window_green; static int window_red; static int window_blue; // Display list constants const int cube = 1; const int green = 2; const int red = 3; const int blue = 4; // Color variables static float g = -1.0; static float r = -1.0; static float b = -1.0; static int color_tgl = 1; // main window initial dimensions const int WINDOW_SIZE = 800; // color slider initial dimensions const int SLIDER_HEIGHT = 20; static int green_window_width = 200; static int red_window_width = 200; static int blue_window_width = 200; // void mouse(int btn, int state, int x, int y) // { // if (btn == GLUT_LEFT_BUTTON) // rotating = 1 - rotating; // } // void motion(int x, int y) // { // static int prev_x = 0, prev_y = 0; // if (rotating == 1) // { // if (x > prev_x) // { // y_angle += y_delta; // prev_x = x; // } // else if (x < prev_x) // { // y_angle -= y_delta; // prev_x = x; // } // if (y > prev_y) // { // x_angle += x_delta; // prev_y = y; // } // else if (y < prev_y) // { // x_angle -= x_delta; // prev_y = y; // } // glutPostRedisplay(); // } // } GLUquadricObj *cyl = gluNewQuadric(); GLfloat diffuseMaterial[4] = { 0.2, 0.2, 0.2, 1.0 }; int userChoice = 0; int treeSize = 1; int seasonChoice = 0; char userAx; std::string userRule; float userAngle; std::string mainString; void handleKeys(unsigned char key, int x, int y){ switch(key){ case 'q': // q - quit case 'Q': case 27: // esc - quit exit(0); default: // not a valid key -- just ignore it return; } } void growString(std::string& newString) { std::string buildString; std::string changeString; char newChar = 'z'; for(int i = 0; i < newString.size(); i++) { newChar = newString.at(i); switch(newChar) { // for Celtic Tree case 'a': changeString = "a"; break; case 'b': changeString = "a[rb][lb]"; break; // for fractal tree case 'f': changeString = "ff"; break; case 'x': changeString = "fl[[xy]rxy]rf[rfxy]lx"; break; case 'y': changeString = "y"; break; // Truffula tree case 't': changeString = "tt"; break; case 's': changeString = "[s]r[s]"; break; case 'k': changeString = userRule; break; // rotate calls case 'r': changeString = "r"; break; case 'l': changeString = "l"; break; // push matrix case '[': changeString = "["; break; // pop matrix case ']': changeString = "]"; break; } buildString = buildString + changeString; } newString = buildString; } void drawSwitch(std::string mainString) { float setWidth = static_cast<float>(treeSize); float cylWidth = 0.0; float cylChange = 0.0; float cylHeight = 0.0; float rotateAngle = 0.0; char readChar = 'z'; srand( time(0)); int popCount = 0; bool popSwitch = false; //sets variables for Celtic Tree if (userChoice == 1) { cylWidth = (setWidth/200); cylChange = (cylWidth/(treeSize+1)); cylHeight = 0.2; rotateAngle = 20; } // sets variables for fratal plant if (userChoice == 2) { cylWidth = (setWidth/300); cylHeight = 0.1; rotateAngle = (22.5); } // // sets variable for Truffula tree if (userChoice == 3) { cylWidth = (setWidth/100); cylChange = (cylWidth/19); cylHeight = 0.05; rotateAngle = (360/(setWidth + 1)); } // sets variables for user plant if (userChoice == 4) { cylWidth = (setWidth/300); cylHeight = 0.1; rotateAngle = (userAngle); } for(int i = 0; i < mainString.length(); i++) { float randomNum = 0.0; readChar = mainString.at(i); switch(readChar) { case 'a': //grow Celtic trunk gluCylinder(cyl, (cylWidth+cylChange), cylWidth, cylHeight, 30, 30); glTranslatef(0.0, 0.0, cylHeight); glutSolidSphere(cylWidth, 50, 50); // if (popCount == 0) { // glRotatef(20, 0.0, 0.0, 1.0); // } // if (popCount == 1) { // glRotatef(-20, 0.0, 0.0, 1.0); // } // if (popCount == 2) { // glRotatef(-20, 0.0, 0.0, 1.0); // } // if (popCount == 3) { // glRotatef(20, 0.0, 0.0, 1.0); // popCount = 0; // } // popCount++; break; case 'b': //grow Celtic branches gluCylinder(cyl, (cylWidth+cylChange), cylWidth, cylHeight, 30, 30); glTranslatef(0.0, 0.0, cylHeight); //change leaf color based on season, no leaves for winter if (seasonChoice == 1) { glColor4f(1.0,0.4,0.8,1.0); glutSolidSphere(0.02, 50, 50); } if (seasonChoice == 2) { glColor4f(0.0,0.5,0.09,1.0); glutSolidSphere(0.02, 50, 50); } if (seasonChoice == 3) { glColor4f(1.0,0.4,0.0,1.0); glutSolidSphere(0.02, 50, 50); } glColor4f(0.28,0.14,0.08,1.0); break; case 'x': // fractal trunk and branches gluCylinder(cyl, (cylWidth+cylChange), cylWidth, cylHeight, 30, 30); glTranslatef(0.0, 0.0, cylHeight); glutSolidSphere((cylWidth+cylWidth), 30, 30); break; case 'f': // fractal tips gluCylinder(cyl, (cylWidth+cylChange), cylWidth, cylHeight, 30, 30); glTranslatef(0.0, 0.0, cylHeight); break; case 'y': // fractal flowers glColor4f(0.8,0.8,0.0,1.0); glutSolidSphere((cylWidth*2), 30, 30); glColor4f(1.0,1.0,1.0,1.0); for (int k = 0; k < 12; k++) { gluCylinder(cyl, (cylWidth), 0.0, (cylWidth*6), 30, 30); glRotatef(30, 0.0, 1.0, 0.0); } glColor4f(0.0,0.5,0.09,1.0); break; case 't': //grow truffula trunk if (i % 2 != 0) { glColor4f(1.0,1.0,0.4,1.0); } else { glColor4f(0.2,0.2,0.0,1.0); } glRotatef((50/(treeSize*treeSize)*-1), 0.0, 1.0, 0.0); gluCylinder(cyl, cylWidth, cylWidth, cylHeight, 30, 30); glTranslatef(0.0, 0.0, cylHeight); break; case 's': //grow truffula spiral glColor4f(0.2,0.8,1.0,1.0); cylWidth = (cylWidth*4); glutSolidSphere((cylWidth), 30, 30); for (int k = 0; k < 180; k++) { gluCylinder(cyl, cylWidth, (cylWidth-cylChange), (setWidth*.0015), 30, 30); glutSolidSphere((cylWidth-cylChange), 30, 30); glTranslatef(0.0, 0.0, (setWidth*.0015)); glRotatef(2, 0.0, 1.0, 0.0); cylWidth = (cylWidth-cylChange); } break; case 'k': // user line gluCylinder(cyl, cylWidth, cylWidth, cylHeight, 30, 30); glTranslatef(0.0, 0.0, cylHeight); break; case 'r': glRotatef(rotateAngle, 0.0, 1.0, 0.0); break; case 'l': glRotatef(-(rotateAngle), 0.0, 1.0, 0.0); break; case '[': glPushMatrix(); if (userChoice == 1) { cylWidth = (cylWidth-cylChange); } if (userChoice == 2) { randomNum = ((rand() % 40) - (rand() % 40)); glRotatef(randomNum, 1.0, 0.5, 0.0); } break; case ']': glPopMatrix(); if (userChoice == 1) { cylWidth = (cylWidth+cylChange); } if (userChoice == 3) { cylWidth = (setWidth/100); } break; } } } void drawCeltic() { int growth = 0; int flip = 0; //Set Axiom mainString = "b"; //Grow string as needed while (growth < treeSize) { growString(mainString); growth++; } while (flip < 2) { //tree setup glColor4f(0.28,0.14,0.08,1.0); if (flip == 0) { glRotatef(-90, 1.0, 0.0, 0.0); } if (flip == 1) { glRotatef(180, 1.0, 0.0, 0.0); } glPushMatrix(); drawSwitch(mainString); flip++; } } void drawFractal() { int growth = 0; //Set Axiom mainString = "x"; //Grow string as needed while (growth < treeSize) { growString(mainString); growth++; } //tree setup glRotatef(-90, 1.0, 0.0, 0.0); glTranslatef(0.0, 0.0, -2.0); glColor4f(0.0,0.5,0.09,1.0); drawSwitch(mainString); } void drawTruf() { int growth = 0; //Set Axiom mainString = "ts"; //Grow string as needed while (growth < treeSize) { growString(mainString); growth++; } //tree setup glRotatef(-90, 1.0, 0.0, 0.0); glRotatef(25, 0.0, 1.0, 0.0); glTranslatef(1.0, 0.0, -1.0); drawSwitch(mainString); } void drawUserTree() { int growth = 0; //Set Axiom mainString = "k"; //Grow string as needed while (growth < treeSize) { growString(mainString); growth++; } //tree setup glRotatef(-90, 1.0, 0.0, 0.0); glTranslatef(0.0, 0.0, -2.0); glColor4f(0.0,0.5,0.09,1.0); drawSwitch(mainString); } // Cylinder Window Routine void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); gluQuadricDrawStyle(cyl, GLU_SMOOTH); if (userChoice == 1) { drawCeltic(); } if (userChoice == 2) { drawFractal(); } if (userChoice == 3) { drawTruf(); } if (userChoice == 4) { drawUserTree(); } glutSwapBuffers(); } void init() { GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 }; glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_SMOOTH); glEnable(GL_DEPTH_TEST); glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseMaterial); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialf(GL_FRONT, GL_SHININESS, 98.0); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glColorMaterial(GL_FRONT, GL_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glMatrixMode(GL_PROJECTION); gluPerspective(40.0, 1.0, 1.0, 100.0); glMatrixMode(GL_MODELVIEW); gluLookAt(8.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); } int main(int argc, char **argv) { std::cout << "What type of tree would you like to see?" << std::endl; std::cout << "Select 1 for Celtic Tree of Life, 2 for Fractal Baby's Breath, 3 for Truffula Tree, or select 4 to draw your own" << std::endl; std::cin >> userChoice; if (userChoice == 1) { std::cout << "How many recursions? (1-9)" << std::endl; std::cin >> treeSize; std::cout << "Choose a season: 1=Spring 2=Summer 3=Fall 4=Winter " << std::endl; std::cin >> seasonChoice; } if (userChoice == 2) { std::cout << "How many recursions? (1-4)" << std::endl; std::cin >> treeSize; } if (userChoice == 3) { std::cout << "How many recursions? (1-6)" <<std::endl; std::cin >> treeSize; } if (userChoice == 4) { std::cout << "With the given axiom k, create your own your rule with the characters below. ex. kkl[lkrkrk]r[rklklk]" << std::endl; std::cout << "k = draw a line" << std::endl; std::cout << "y = draw a flower" << std::endl; std::cout << "l = rotate left (you can set rotate angle after writing rule)" << std::endl; std::cout << "r = rotate right (you can set rotate angle after writing rule)" << std::endl; std::cout << "[ = pushes the matrix" << std::endl; std::cout << "[ = pops the matrix" << std::endl; std::cin >> userRule; std::cout << "Set rotate angle (float):" << std::endl; std::cin >> userAngle; std::cout << "How many recursions?" << std::endl; std::cin >> treeSize; } glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); // Create Cube window window_cube = glutCreateWindow("Viewport"); glutDisplayFunc(display); // glutMotionFunc(motion); // glutMouseFunc(mouse); glutReshapeWindow(WINDOW_SIZE, WINDOW_SIZE); glutKeyboardFunc(handleKeys); init(); glutMainLoop(); return 0; }
/* * SpaceShip.cpp * * Created on: Dec 2, 2017 * Author: ryanw */ #include "Spaceship.hpp" Spaceship::Spaceship() { vector<Point*> cp; cp.push_back(new Point(3,0,0)); cp.push_back(new Point(1.5,1,0)); cp.push_back(new Point(0,0,0)); body = new BezierCurve(cp, 50,370,2); body->setDrawingMode(GLSL_SHADE); //body->rotate_mc(0, 1, 0, 90); vector<Point> wingPoints; wingPoints.push_back(Point(0.5, 0, 1.5)); wingPoints.push_back(Point(1, 0, 2)); wingPoints.push_back(Point(1.5, 0, 2)); wingPoints.push_back(Point(2, 0, 1.5)); wingPoints.push_back(Point(1.5, 0, 0)); //wingPoints.push_back(Point(2, 0, 0)); wingPoints.push_back(Point(0.5, 0, 0)); // add the wings rightUpperWing = new Prism(wingPoints, 0.02); leftUpperWing = new Prism(wingPoints, 0.02); leftLowerWing = new Prism(wingPoints, 0.02); rightLowerWing = new Prism(wingPoints, 0.02); rightLowerWing->rotate(1, 0, 0, 20); leftLowerWing->rotate(1, 0, 0, 160); leftUpperWing->rotate(1, 0, 0, 200); rightUpperWing->rotate(1, 0, 0, -20); vy = 0; vz = 0; } Spaceship::~Spaceship() { delete rightUpperWing; delete leftUpperWing; delete body; } void Spaceship::draw() { Matrix tilt; if (vy > 0){ tilt.rotate(0,0,1,20); }else if (vy < 0){ tilt.rotate(0,0,1,-20); } if (vz > 0){ tilt.rotate(1,0,0,20); }else if (vz < 0){ tilt.rotate(1,0,0,-20); } glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, 75); glPushMatrix(); ctm_multiply(); tilt.ctm_multiply(); body->draw(); leftUpperWing->draw(); rightUpperWing->draw(); leftLowerWing->draw(); rightLowerWing->draw(); glPopMatrix(); } void Spaceship::vert(char d) { vy= d*0.00000000003; } void Spaceship::horiz(char d) { vz = d*-0.00000000003; } void Spaceship::tick(DWORD ticks){ if(mc.mat[1][3] > 3){ vy = 0; mc.mat[1][3] = 3; }else if(mc.mat[1][3] < -3){ vy = 0; mc.mat[1][3] = -3; } if (mc.mat[2][3] > 3){ vz = 0; mc.mat[2][3] = 3; }else if (mc.mat[2][3] < -3){ vz = 0; mc.mat[2][3] = -3; } translate(0, vy * ticks, vz * ticks); }
#ifndef CFG_OTHER # error "This source should only be compiled in a non-Debug configuration." #endif #ifdef CFG_DEBUG # error "This source should not be compiled in a Debug configuration." #endif #include "iface.h" int iface_other() { return 0; }
#if !defined(ERROR_HPP) #define ERROR_HPP #include "HttpResponse.hpp" class Error : public HttpResponse { public: Error(ResponseContext&, BufferChain&, int); ~Error(); void handleRead(BufferChain& readChain, BufferChain& writeChain); }; class HeadersError : public HttpResponse { public: HeadersError(ResponseContext&, BufferChain&, int); ~HeadersError(); void handleRead(BufferChain& readChain, BufferChain& writeChain); }; #endif // ERROR_HPP
#include <hpx/hpx_fwd.hpp> #include <hpx/runtime/components/server/managed_component_base.hpp> #include <hpx/runtime/components/server/locking_hook.hpp> #include <hpx/runtime/actions/component_action.hpp> #include "../lib/glm/glm.hpp" #include "table.h" struct serialVec { float x; float y; float z; private: friend class boost::serialization::access; template <typename Archive> void serialize(Archive& ar, const unsigned int version) { ar & x & y & z; } }; bool operator<(const serialVec a, const serialVec b){ if (b.z <= a.z) return false; if (b.y <= a.y) return false; if (b.x <= a.x) return false; return true; } struct block_boilerplate { hpx::id_type GID; serialVec pos; private: friend class boost::serialization::access; template <typename Archive> void serialize(Archive& ar, const unsigned int version) { ar & GID & pos; } }; typedef glm::vec3 vec3; typedef glm::vec2 vec2; typedef vector<float> data; typedef vector<float> cube; typedef int ID; typedef vec2 edge; typedef tuple<serialVec, serialVec> vertexPos; typedef std::map<vertexPos, ID> vertexMap; typedef vector<ID> face; struct Vertex { ID global_ID; vec3 coord; float normalWeight; vec3 normal; }; struct BlockInfo { vector<vertexPos> vertexPosList; vector<Vertex> vertexList; vector<face> faceList; int activeVertexCount; }; int IDtoArrayPos(ID id, int count){ if (id > 0) return id-1; if (id < 0) return count-1 - id; } vec3 computeFaceNormal(Vertex one, Vertex two, Vertex three){ vec3 U = two.coord - one.coord; vec3 V = three.coord - one.coord; vec3 result; result.x = (U.y*V.z) - (U.z*V.y); result.y = (U.z*V.x) - (U.x*V.z); result.z = (U.x*V.y) - (U.y*V.x); return result; } void adjustNormals(Vertex one, Vertex two, Vertex three){ vec3 faceNormal = computeFaceNormal(one, two, three); vec3 a = (one.normalWeight*one.normal) + faceNormal; one.normalWeight++; one.normal = a* (1/one.normalWeight); a = (two.normalWeight*two.normal) + faceNormal; two.normalWeight++; two.normal = a* (1/two.normalWeight); a = (three.normalWeight*three.normal) + faceNormal; three.normalWeight++; three.normal = a* (1/three.normalWeight); } #include <limits> #include <cmath> using namespace std; double mandelbulb( const double z0[3], bool output = false ) { const double power = 8.0f; const int iter = 8; double z[3] = { z0[0], z0[1], z0[2] }; double r = sqrt( z[0]*z[0]+z[1]*z[1]+z[2]*z[2] ); if( r < numeric_limits<double>::epsilon() ) return 0.0; double dr = 1.0; for( int i=0; i<iter && r<2.0; ++i ) { double zo = power * asin( z[2]/r ); double zi = power * atan( z[1]/z[0] ); double zr = pow( r, power-1.0f ); dr = zr*dr*power + 1.0f; zr *= r; z[0] = z0[0] + zr * cos(zo)*cos(zi); z[1] = z0[1] + zr * cos(zo)*sin(zi); z[2] = z0[2] + zr * sin(zo); r = sqrt( z[0]*z[0]+z[1]*z[1]+z[2]*z[2] ); } double v = 0.5*log(r)*r/dr; return v; } namespace server { class block : public hpx::components::managed_component_base<block> { public: block(){ } block(serialVec pos, boost::uint64_t size){ position_ = vec3(pos.x, pos.y, pos.z); m_size = size; printf("Block created\n"); } void initialize(){ printf("loading data\n"); double bmin[3] = { -1.1, -1.1, -1.1 }; double bmax[3] = { 1.1, 1.1, 1.1 }; int res[3] = { m_size, m_size, m_size }; // generate values on regular grid vector<float> values( res[0]*res[1]*res[2] ); for( int k=0; k<res[2]; ++k ) { cerr << k << endl; for( int j=0; j<res[1]; ++j ) { for( int i=0; i<res[0]; ++i ) { double z[3] = { bmin[0] + (i+0.5) * (bmax[0] - bmin[0])/(res[0]-1), bmin[1] + (j+0.5) * (bmax[1] - bmin[1])/(res[1]-1), bmin[2] + (k+0.5) * (bmax[2] - bmin[2])/(res[2]-1), }; values[i + res[0]*(j+k*res[1])] = mandelbulb( z ); } } } m_dat = values; printf("data loaded\n"); } block_boilerplate getBoilerplate(){ block_boilerplate result; result.GID = this->get_gid(); result.pos.x = position_.x; result.pos.y = position_.y; result.pos.z = position_.z; return result; } //findet oder registriert ID für diese Position //IDs werden bei jeder registrierung hochgezählt //IDs passiver Positionen werden unabhängig negativ gezählt //arrayindex entspricht positiver ID - 1 oder getCount - 1 - //negativer ID ID mapGet(vertexPos pos){ if (m_Map.count(pos)){ return m_Map.find(pos)->second; } else { m_Info.activeVertexCount++; m_Map.insert(std::pair<vertexPos, ID>(pos, m_Info.activeVertexCount)); return m_Info.activeVertexCount; } } vector<vertexPos> mapMakeList(){ vector<vertexPos> result; for (vertexMap::iterator it = m_Map.begin(); it != m_Map.end(); ++it){ result.push_back(it->first); } printf("Making MapList with %u Vertices \n", result.size()); return result; } int getCount() { return m_activeVertexCount; } vec3 interpolate(vertexPos pos, float isovalue) { vec3 first(std::get<0>(pos).x, std::get<0>(pos).y, std::get<0>(pos).z); int datapoint = first.z*(m_size*m_size) + first.y*(m_size) + first.x; float firstValue = m_dat.at(datapoint); vec3 second(std::get<1>(pos).x, std::get<1>(pos).y, std::get<1>(pos).z); datapoint = second.z*(m_size*m_size) + second.y*(m_size) + second.x; float secondValue = m_dat.at(datapoint); if (firstValue > secondValue){ float a = firstValue - secondValue; float b = isovalue - secondValue; float ratioA = b/a; float ratioB = (a-b)/a; return second*ratioA + first*ratioB; } else { float a = secondValue - firstValue; float b = isovalue - firstValue; float ratioA = b/a; float ratioB = (a-b)/a; return first*ratioA + second*ratioB; } } int cubeCount(){ int temp = m_size-1; return temp*temp*temp; } cube findCube(unsigned i){ // return marching cube with number i vector<float> result(8); int temp = m_size-1; //cube space coordinates int z = (int)i/(temp*temp); int y = (int)(i % (temp*temp))/temp; int x = (int)(i % temp); int pz = z; int py = y; int px = x; int datapoint = pz*(m_size*m_size) + py*(m_size) + px; result[4] = m_dat.at(datapoint); px++; datapoint = pz*(m_size*m_size) + py*(m_size) + px; result[5] = m_dat.at(datapoint); py++; datapoint = pz*(m_size*m_size) + py*(m_size) + px; result[6] = m_dat.at(datapoint); px--; datapoint = pz*(m_size*m_size) + py*(m_size) + px; result[7] = m_dat.at(datapoint); pz++; datapoint = pz*(m_size*m_size) + py*(m_size) + px; result[3] = m_dat.at(datapoint); py--; datapoint = pz*(m_size*m_size) + py*(m_size) + px; result[0] = m_dat.at(datapoint); px++; datapoint = pz*(m_size*m_size) + py*(m_size) + px; result[1] = m_dat.at(datapoint); py++; datapoint = pz*(m_size*m_size) + py*(m_size) + px; result[2] = m_dat.at(datapoint); return result; } vertexPos findCoords(int i, edge myEdge){ int temp = m_size-1; //cube space coordinates int z = (int)i/(temp*temp); int y = (int)(i % (temp*temp))/temp; int x = (int)(i % temp); int px = x; int py = y; int pz = z; if (myEdge.x == 0){ pz++; } if (myEdge.x == 1){ pz++; px++; } if (myEdge.x == 2){ px++; py++; pz++; } if (myEdge.x == 3){ pz++; py++; } if (myEdge.x == 5){ px++; } if (myEdge.x == 6){ px++; py++; } if (myEdge.x == 7){ py++; } serialVec first; first.x = px; first.y = py; first.z = pz; px = x; py = y; pz = z; if (myEdge.y == 0){ pz++; } if (myEdge.y == 1){ pz++; px++; } if (myEdge.y == 2){ px++; py++; pz++; } if (myEdge.y == 3){ pz++; py++; } if (myEdge.y == 5){ px++; } if (myEdge.y == 6){ px++; py++; } if (myEdge.y == 7){ py++; } serialVec second; second.x = px; second.y = py; second.z = pz; return make_tuple(first, second); } int findInfo(float isovalue){ //printf("Finding Info\n"); for (int i = 0; (i < cubeCount()); i++){ // printf("Find Cube %i ...", i); cube currentCube = findCube(i); // printf("Found Cube. \nExtracting Case ..."); mcCase currentCase(8); for (unsigned char i = 0; (i < 8); i++) { currentCase[i] = (currentCube[i] >= isovalue); } // printf("Found Case. \nLooking up Case..."); vector<edge> mcEdgelist = m_table.lookup(currentCase); printf("Case looked up. Found %u edges.\n", mcEdgelist.size()); int j = 0; face* currentFace; for (edge currentEdge : mcEdgelist){ if (j % 3 == 0) currentFace = new face(); // printf("Finding Edge Coords..."); vertexPos currentPos = findCoords(i, currentEdge); // vec3 first(std::get<0>(currentPos).x, std::get<0>(currentPos).y, std::get<0>(currentPos).z); // vec3 second(std::get<1>(currentPos).x, std::get<1>(currentPos).y, std::get<1>(currentPos).z); // printf("Found Edge Coords %f/%f/%f - %f/%f/%f \nGetting ID from Map...", first.x, first.y, first.z, second.x, second.y, second.z); ID currentID = mapGet(currentPos); // printf("Got ID %i \n", currentID); (*currentFace)[j%3] = currentID; if (j % 3 == 2) { m_Info.faceList.push_back(*currentFace); delete currentFace; } j++; // printf("Next iteration \n"); } } //printf("All iterations done \n"); m_Info.vertexPosList = mapMakeList(); printf("Info Found with %u faces \n", m_Info.faceList.size()); return 0; } int computeBlock(float isovalue){ printf("computing block\n"); vector<Vertex> vertexList(m_Info.vertexPosList.size()); for (int i = 0; (i < m_Info.vertexPosList.size()); i++) { vertexList[i].coord = interpolate(m_Info.vertexPosList[i], isovalue); } for (face currentFace : m_Info.faceList){ Vertex& one = vertexList[IDtoArrayPos(currentFace[0], m_Info.activeVertexCount)]; Vertex& two = vertexList[IDtoArrayPos(currentFace[1], m_Info.activeVertexCount)]; Vertex& three = vertexList[IDtoArrayPos(currentFace[2], m_Info.activeVertexCount)]; adjustNormals(one, two, three); } m_Info.vertexList = vertexList; printf("Block computed\n"); writeOBJ(); return 0; } #include <fstream> void writeOBJ(){ std::ofstream myfile; myfile.open("output.obj"); printf("Writing %u Vertices to File \n", m_Info.vertexList.size()); for (Vertex vertex : m_Info.vertexList){ myfile << "v " << vertex.coord.x << " " << vertex.coord.y << " " << vertex.coord.z << "\n"; } for (Vertex vertex : m_Info.vertexList){ myfile << "vn " << vertex.normal.x << " " << vertex.normal.y << " " << vertex.normal.z << "\n"; } printf("Writing %u Faces to File \n", m_Info.faceList.size()); for (face currentFace : m_Info.faceList){ myfile << "f " << currentFace[0] << "//" << currentFace[0] << " " << currentFace[1] << "//" << currentFace[1] << " " << currentFace[2] << "//" << currentFace[2] << "\n"; } } int communicateGlobalIDs(std::vector<block_boilerplate> globalBlocks){ printf("CommunicateGlobalIDs called \n"); return 0; } int sendPassive(std::vector<block_boilerplate> globalBlocks){ printf("sendPassive called \n"); return 0; } int sendActive(std::vector<block_boilerplate> globalBlocks){ printf("sendActive called \n"); return 0; } HPX_DEFINE_COMPONENT_ACTION(block, initialize); HPX_DEFINE_COMPONENT_ACTION(block, getBoilerplate); HPX_DEFINE_COMPONENT_ACTION(block, findInfo); HPX_DEFINE_COMPONENT_ACTION(block, computeBlock); HPX_DEFINE_COMPONENT_ACTION(block, communicateGlobalIDs); HPX_DEFINE_COMPONENT_ACTION(block, sendPassive); HPX_DEFINE_COMPONENT_ACTION(block, sendActive); private: BlockInfo m_Info; Table m_table; vertexMap m_Map; data m_dat; int m_activeVertexCount; vec3 position_; int m_size; }; } HPX_REGISTER_ACTION_DECLARATION(server::block::initialize_action, block_initialize_action); HPX_REGISTER_ACTION_DECLARATION(server::block::getBoilerplate_action, block_getBoilerplate_action); HPX_REGISTER_ACTION_DECLARATION(server::block::findInfo_action, block_findInfo_action); HPX_REGISTER_ACTION_DECLARATION(server::block::computeBlock_action, block_computeBlock_action); HPX_REGISTER_ACTION_DECLARATION(server::block::communicateGlobalIDs_action, block_communicateGlobalIDs_action); HPX_REGISTER_ACTION_DECLARATION(server::block::sendPassive_action, block_sendPassive_action); HPX_REGISTER_ACTION_DECLARATION(server::block::sendActive_action, block_sendActive_action); #include <hpx/runtime/applier/apply.hpp> #include <hpx/include/async.hpp> #include <hpx/include/components.hpp> class block : public hpx::components::client_base<block, server::block> { typedef hpx::components::client_base<block, server::block> base_type; public: block(){} block(hpx::future<hpx::naming::id_type> && gid) : base_type(std::move(gid)) {} int getBlub() const { return 5; } hpx::id_type getID() const { return this->get_gid(); } void initialize() const { HPX_ASSERT(this->get_gid()); hpx::apply<server::block::initialize_action>(this->get_gid()); } block_boilerplate getBoilerplate() const { HPX_ASSERT(this->get_gid()); return hpx::async<server::block::getBoilerplate_action>(this->get_gid()).get(); } hpx::shared_future<int> findInfo(float isovalue) const { HPX_ASSERT(this->get_gid()); return hpx::async<server::block::findInfo_action>(this->get_gid(), isovalue); } hpx::shared_future<int> computeBlock(float isovalue) const { HPX_ASSERT(this->get_gid()); return hpx::async<server::block::computeBlock_action>(this->get_gid(), isovalue); } hpx::shared_future<int> communicateGlobalIDs(std::vector<block_boilerplate> block_boilerplates) const { HPX_ASSERT(this->get_gid()); return hpx::async<server::block::communicateGlobalIDs_action>(this->get_gid(), block_boilerplates); } hpx::shared_future<int> sendPassive(std::vector<block_boilerplate> block_boilerplates) const { HPX_ASSERT(this->get_gid()); return hpx::async<server::block::sendPassive_action>(this->get_gid(), block_boilerplates); } hpx::shared_future<int> sendActive(std::vector<block_boilerplate> block_boilerplates) const { HPX_ASSERT(this->get_gid()); return hpx::async<server::block::sendActive_action>(this->get_gid(), block_boilerplates); } };
#include "server.h" using namespace std; void run_thread() { while(1) { int client = Server::clientqueue.pop(); // cout << "popping off: " << client << endl; Worker worker(client); worker.handle_client(); close(client); } } Mailbox Server::mailbox; ClientQueue Server::clientqueue; Server::Server() { server = socket(PF_INET,SOCK_STREAM,0); } Server::~Server() {} int Server::get_server() { return server; } void Server::run_server(int port) { struct sockaddr_in server_addr,client_addr; socklen_t clientlen = sizeof(client_addr); // setup socket address structure memset(&server_addr,0,sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr.s_addr = INADDR_ANY; // create socket if (!server) { perror("socket"); exit(-1); } int reuse; // set socket to immediately reuse port when the application closes reuse = 1; if (setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) { perror("setsockopt"); exit(-1); } // call bind to associate the socket with our local address and // port if (bind(server,(const struct sockaddr *)&server_addr,sizeof(server_addr)) < 0) { perror("bind"); exit(-1); } // convert the socket to listen for incoming connections if (listen(server,SOMAXCONN) < 0) { perror("listen"); exit(-1); } int thread_count = 10; for(int i = 0; i < thread_count; i++) { //make new thread, pass in run thread function as param thread* t = new thread(&run_thread); } while(1) { int client = accept(server,(struct sockaddr *)&client_addr,&clientlen); if(client > 0) { // cout << "pushing on: " << client << endl; clientqueue.push(client); } } } int main(int argc, char **argv) { int option, port; // setup default arguments port = 5000; // process command line options using getopt() // see "man 3 getopt" while ((option = getopt(argc,argv,"p:d::")) != -1) { switch (option) { case 'p': port = atoi(optarg); break; case 'd': cout << "debug flag on for server" << endl; default: cout << "server [-p port]" << endl; exit(EXIT_FAILURE); } } Server server; server.run_server(port); close(server.get_server()); }
#pragma once #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> class DepthFrame { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW DepthFrame(const double &timestamp, const pcl::PointCloud<pcl::PointXYZ>::Ptr &point_cloud, const Eigen::Matrix4d &pose); DepthFrame(const pcl::PointCloud<pcl::PointXYZ>::Ptr &point_cloud, const Eigen::Matrix4d &pose); ~DepthFrame() {} double timestamp() { return timestamp_; } pcl::PointCloud<pcl::PointXYZ>::Ptr point_cloud() { return point_cloud_;} pcl::PointCloud<pcl::Normal>::Ptr normals() { return normals_; } Eigen::Vector3d *translation() { return &translation_; } Eigen::Quaterniond *rotation() { return &rotation_; } double *mutable_translation() { return translation_.data(); } double *mutable_rotation() { return rotation_.coeffs().data(); } void get_pose(Eigen::Matrix4d &pose); void transformed_point_cloud(const pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud); void transformed_normals(const pcl::PointCloud<pcl::Normal>::Ptr &normals); void filter(); void compute_normal(const int k_nearest_neighbor); void compute_normal_using_unfiltered(const int k_nearest_neighbor); bool find_closest_point(const pcl::PointXYZ &target_point, pcl::PointXYZ &closest_point, pcl::Normal &normal); bool find_closest_point(const pcl::PointXYZ &target_point, const pcl::Normal &target_normal, pcl::PointXYZ &closest_point, pcl::Normal &normal); private: double timestamp_; pcl::PointCloud<pcl::PointXYZ>::Ptr unfiltered_cloud_; pcl::PointCloud<pcl::PointXYZ>::Ptr point_cloud_; pcl::PointCloud<pcl::Normal>::Ptr normals_; Eigen::Vector3d translation_; Eigen::Quaterniond rotation_; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2002 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Alexander Remen (alexr) */ #include "core/pch.h" #include "InsertHTMLDialog.h" #include "adjunct/quick_toolkit/widgets/Dialog.h" #include "modules/widgets/WidgetContainer.h" #include "modules/widgets/OpMultiEdit.h" #ifdef M2_SUPPORT void InsertHTMLDialog::Init(DesktopWindow* parent_window, RichTextEditor *rich_text_editor) { m_rich_text_editor = rich_text_editor; Dialog::Init(parent_window); }; void InsertHTMLDialog::OnInit() { OpMultilineEdit *edit = static_cast<OpMultilineEdit*>(GetWidgetByName("HTML_multiline_edit")); if (edit) edit->SetColoured(TRUE); } UINT32 InsertHTMLDialog::OnOk() { OpString source_code; GetWidgetText("HTML_multiline_edit",source_code); m_rich_text_editor->InsertHTML(source_code); return 0; } #endif // M2_SUPPORT
/*Heap sort implementation.*/ #include "cc/algo/sorting/heap_sort.h" #include "cc/shared/generic_array.h" #include "cc/shared/common.h" using cc_shared::GenericArray; namespace cc_algo_sorting { namespace { size_t parent_index(size_t index) { RT_ASSERT_GT(index, 0); // TODO: Add unit tests for this. // 1 -> 0, 2 -> 0 // 3 -> 1, 4 -> 1 // 5 -> 2, 6 -> 2 // 7 -> 3, 8 -> 3 return (((index + (index % 2)) >> 1) - 1); } size_t left_child_index(size_t index) { // Assume index is small and there would be no overflow. // TODO: Add unit tests for this. return ((index << 1) + 1); } size_t right_child_index(size_t index) { // Assume index is small and there would be no overflow. // TODO: Add unit tests for this. return ((index << 1) + 2); } void sift_up(size_t new_index, GenericArray* generic) { while (new_index > 0) { size_t parent = parent_index(new_index); if (generic->greater_than(new_index, parent)) { generic->swap(new_index, parent); new_index = parent; } else { break; } } } void sift_down(size_t total, GenericArray* generic) { size_t index = 0; while (index <= total) { // Set left and right child indices. size_t lc = left_child_index(index); size_t rc = right_child_index(index); // Find if mismatch exists for any direction (left or right). bool lm = (lc <= total) && generic->greater_than(lc, index); bool rm = (rc <= total) && generic->greater_than(rc, index); if (!(lm || rm)) { break; } // Find move direction and next index. bool go_left = (lm && rm) ? generic->less_than(rc, lc) : lm; size_t next_index = go_left ? lc : rc; generic->swap(index, next_index); index = next_index; } } } // namespace void heap_sort(void* base, size_t member_count, size_t member_size, cc_shared::CompareFuncType comparer) { // Parameter validation. if (!(base && (member_count > 1) && member_size && comparer)) { return; } cc_shared::GenericArray generic(base, member_count, member_size, comparer); // Build the max heap assuming [0, .. (i - 1)] already has a heap. for (size_t i = 1; i < member_count; ++i) { sift_up(i, &generic); } for (size_t i = member_count; i >= 1; --i) { // Move the largest element to the end of the array. Then restore the heap // property on reduced array by sifting down (if needed). generic.swap(0, i - 1); if (i >= 2) { sift_down(i - 2, &generic); } } } } // cc_algo_sorting
#include<iostream> #include<cstdio> #include<algorithm> #include<vector> using namespace std; int f[100010]; int find(int x) {vector<int> s; while (x != f[x]) {s.push_back(x); x = f[x]; } while (!s.empty()) {f[s.back()] = x; s.pop_back(); } return x; } int main() {int n,m; while (scanf("%d%d",&n,&m) != EOF) {for (int i = 1;i <= n; i++) f[i] = i; for (int i = 1;i <= m; i++) {int a,b; cin >> a >> b; f[a] = max(f[a],find(f[b])); } for (int i = 1;i < n; i++) printf("%d ",find(f[i])); printf("%d\n",f[n]); } return 0; }
#pragma once #include "CoreMinimal.h" namespace EMessageBoxButton { enum Type { MB_Ok = 0b00000001, MB_Cancel = 0b00000010 }; }
#include "gold.h" Gold::Gold(QObject *parent) : Values(parent) {} Gold::Gold(int x, int y, int width, int height, QObject *parent) : Values(x, y, width, height, ":/images/gold/images/gold/gold.png", 1, parent) {}
#include "Solar.hpp" #include "CelBody.cpp" #include "MultiBodySystem.cpp" #include <fstream> #include <armadillo> using namespace std; using namespace arma; void makeObject(string&, istringstream&, CelBody*, int&, string, double); void makeStatSun(CelBody*); int main(int argc, char const *argv[]){ int steps = stoi(argv[1]); double time = stod(argv[2]); string version = argv[3]; /* Declaration of variables */ string line, name, objects; double mass, beta = 2.; int n_bodies, c_b = 0; string modifier = ""; bool statSun = true, useEuler = false, timing = false; /* Version control, changes some of the values given above */ if (version == "Earth"){ objects = "earth"; modifier = "circular"; n_bodies = 2; timing = true; } if (version == "EarthEuler"){ objects = "earth"; useEuler = true; modifier = "circular"; n_bodies = 2; timing = true; } if (version == "EarthJup"){ objects = "earth jupiter"; n_bodies = 3; } if (version == "EarthMegaJup"){ objects = "earth jupiter"; modifier = "megaJup"; n_bodies = 3; } if (version == "EarthGigaJup"){ objects = "earth jupiter"; modifier = "gigaJup"; n_bodies = 3; } if (version == "EarthBeta"){ int ans; objects = "earth"; n_bodies = 2; cout << "What exponent do you want to use for beta?\n"; cout << "Input: "; cin >> beta; cout << "What type of orbit do you want?\n"; cout << "1: Circular\n"; cout << "2: Elliptical\n"; cout << "Input: "; cin >> ans; if (ans == 2){ modifier = "elliptical"; } } if (version == "EllipticalEarth"){ objects = "earth"; modifier = "elliptical"; n_bodies = 2; } if (version == "All"){ objects = "earth jupiter mars venus saturn mercury uranus neptune sun"; statSun = false; n_bodies = 9; } if (version == "RelMercury"){ objects = "mercury"; n_bodies = 2; modifier = "relativistic"; } CelBody bodies[n_bodies]; if (statSun){ makeStatSun(bodies); c_b++; } /* Reads file */ ifstream inFile("initial_conditions.txt"); getline(inFile,line); while(getline(inFile,line)){ istringstream iss(line); iss >> name; if (objects.find(name) != string::npos){ makeObject(name,iss,bodies,c_b, modifier, beta); } } inFile.close(); MultiBodySystem solarSystem(n_bodies,bodies); string filename = version + ".txt"; solarSystem.simulate(filename,time,steps,useEuler,timing); return 0; } void makeObject(string& name, istringstream& iss, CelBody* bodies, int& n, string modifier, double beta){ /* Makes an object and adds it to the array */ double mass, x, y, z, vx, vy, vz; bool isRel = false; iss >> mass; if (modifier == "relativistic"){ //This only works for mercury isRel = true; x = 0.3075; y = 0; z = 0; vx = 0; vy = 12.44/365.24; vz = 0; } else if (modifier == "circular"){ //This only works for the earth double pi = 3.141592; x = 1; y = 0; z = 0; vx = 0; vz = 0; vy = 2*sqrt(pow(pi,2)/pow(365.24,2)); } else if (modifier == "elliptical"){ //This only works for the earth x = 1; y = 0; z = 0; vx = 0; vz = 0; cout << "What is initial angular velocity for " << name << "? [AU/yr]\n"; cout << "Input: "; cin >> vy; vy /= 365.24; } else{ iss >> x >> y >> z >> vx >> vy >> vz; } if (modifier == "megaJup" && name == "jupiter"){ mass *= 10; } if (modifier == "gigaJup" && name == "jupiter"){ mass *= 1000; } vec r({x,y,z}); vec v({vx,vy,vz}); bodies[n] = CelBody(name,r,v,mass,true,isRel,beta); n++; } void makeStatSun(CelBody* bodies){ double mass = 2e30; vec r({0,0,0}); vec v({0,0,0}); bodies[0] = CelBody("sun",r,v,mass,false); }
#pragma once #include <stdint.h> #include <sys/epoll.h> #include <mutiplex/callbacks.h> namespace muti { typedef std::function<void(uint64_t)> EventCallback; class EventLoop; class EventSource { public: explicit EventSource(int fd, EventLoop* loop) : state_(StateNoEvent), loop_(loop), fd_(fd), interest_ops_(0), ready_ops_(0) { } ~EventSource(); int fd() { return fd_; } void disable_all(); void enable_reading() { enable_ops(EPOLLIN); } void set_reading_callback(const EventCallback& cb) { read_callback_ = cb; } void disable_reading() { disable_ops(EPOLLIN); } void enable_writing() { enable_ops(EPOLLOUT); } void set_writing_callback(const EventCallback& cb) { write_callback_ = cb; } void disable_writing() { disable_ops(EPOLLOUT); } void set_close_callback(const EventCallback& cb) { close_callback_ = cb; } void set_error_callback(const EventCallback& cb) { error_callback_ = cb; } void handle_events(uint64_t timestamp) { if (ready_ops_ & EPOLLERR && error_callback_) { error_callback_(timestamp); disable_all(); return; } if (ready_ops_ & EPOLLHUP && close_callback_) { close_callback_(timestamp); disable_all(); return; } if (ready_ops_ & EPOLLIN && read_callback_) { read_callback_(timestamp); } if (ready_ops_ & EPOLLOUT && write_callback_) { write_callback_(timestamp); } } uint32_t ready_ops() const { return ready_ops_; } void ready_ops(uint32_t ops) { ready_ops_ = ops; } uint32_t interest_ops() const { return interest_ops_; } void interest_ops(uint32_t ops) { interest_ops_ = ops; } private: void enable_ops(uint32_t op); void disable_ops(uint32_t op); enum State { StateNoEvent = 0, StateRegistered = 1, }; uint8_t state_; EventLoop* loop_; int fd_; uint32_t interest_ops_; uint32_t ready_ops_; EventCallback read_callback_; EventCallback write_callback_; EventCallback close_callback_; EventCallback error_callback_; }; }
#include "wiring.c" // Unit size in milliseconds #define UNIT 75 void setup() { Serial.begin(9600); pinMode(2, OUTPUT); pinMode(14, OUTPUT); } void loop(){ digitalWrite(14, LOW); morse_string("hello world"); digitalWrite(14, HIGH); delay_LPM1(2000); } // modify the delay function to void delay_LPM1(uint32_t milliseconds) { uint32_t wakeTime = wdtCounter + (milliseconds * WDT_TICKS_PER_MILISECOND); while(wdtCounter < wakeTime) /* Wait for WDT interrupt in LMP1 */ __bis_status_register(LPM1_bits+GIE); } void long_blink(){ digitalWrite(2, HIGH); delay_LPM1(UNIT * 3); digitalWrite(2, LOW); delay_LPM1(UNIT); } void short_blink(){ digitalWrite(2, HIGH); delay_LPM1(UNIT); digitalWrite(2, LOW); delay_LPM1(UNIT); } void no_blink(){ delay_LPM1(UNIT * 3); } void word_space(){ delay_LPM1(UNIT*4); // Three unit delay_LPM1 in every letter } void morse_string(String message){ for(int i = 0; i < message.length(); i++){ morse_letter(message[i]); } } void morse_letter(char letter){ noInterrupts(); if(letter == ' '){ word_space(); return; } switch(letter){ case 'a': // .- case 'A': short_blink(); long_blink(); no_blink(); break; case 'b': // -... case 'B': long_blink(); short_blink(); short_blink(); short_blink(); no_blink(); break; case 'c': // -.-. case 'C': long_blink(); short_blink(); long_blink(); short_blink(); no_blink(); break; case 'd': // -.. case 'D': long_blink(); short_blink(); short_blink(); no_blink(); break; case 'e': // . case 'E': short_blink(); no_blink(); break; case 'f': // ..-. case 'F': short_blink(); short_blink(); long_blink(); short_blink(); no_blink(); break; case 'g': // --. case 'G': long_blink(); long_blink(); short_blink(); no_blink(); break; case 'h': // .... case 'H': short_blink(); short_blink(); short_blink(); short_blink(); no_blink(); break; case 'i': // .. case 'I': short_blink(); short_blink(); no_blink(); break; case 'j': // .--- case 'J': short_blink(); long_blink(); long_blink(); long_blink(); no_blink(); break; case 'k': // -.- case 'K': long_blink(); short_blink(); long_blink(); no_blink(); break; case 'l': // .-.. case 'L': short_blink(); long_blink(); short_blink(); short_blink(); no_blink(); break; case 'm': // -- case 'M': long_blink(); long_blink(); no_blink(); break; case 'n': // -. case 'N': long_blink(); short_blink(); no_blink(); break; case 'o': // --- case 'O': long_blink(); long_blink(); long_blink(); no_blink(); break; case 'p': // .--. case 'P': short_blink(); long_blink(); long_blink(); short_blink(); no_blink(); break; case 'q': // --.- case 'Q': long_blink(); long_blink(); short_blink(); long_blink(); no_blink(); break; case 'r': // .-. case 'R': short_blink(); long_blink(); short_blink(); no_blink(); break; case 's': // ... case 'S': short_blink(); short_blink(); short_blink(); no_blink(); break; case 't': // - case 'T': long_blink; no_blink(); break; case 'u': // ..- case 'U': short_blink(); short_blink(); long_blink(); no_blink(); break; case 'v': // ...- case 'V': short_blink(); short_blink(); short_blink(); long_blink(); no_blink(); break; case 'w': // .-- case 'W': short_blink(); long_blink(); long_blink(); no_blink(); break; case 'x': // -..- case 'X': long_blink(); short_blink(); short_blink(); long_blink(); no_blink(); break; case 'y': // -.-- case 'Y': long_blink(); short_blink(); long_blink(); long_blink(); no_blink(); break; case 'z': // --.. case 'Z': long_blink(); long_blink(); short_blink(); short_blink(); no_blink(); break; case '0': // ----- long_blink(); long_blink(); long_blink(); long_blink(); long_blink(); no_blink(); break; case '1': // .---- short_blink(); long_blink(); long_blink(); long_blink(); long_blink(); no_blink(); break; case '2': // ..--- short_blink(); short_blink(); long_blink(); long_blink(); long_blink(); no_blink(); break; case '3': // ...-- short_blink(); short_blink(); short_blink(); long_blink(); long_blink(); no_blink(); break; case '4': // ....- short_blink(); short_blink(); short_blink(); short_blink(); long_blink(); no_blink(); break; case '5': // ..... short_blink(); short_blink(); short_blink(); short_blink(); short_blink(); no_blink(); break; case '6': // -.... long_blink(); short_blink(); short_blink(); short_blink(); short_blink(); no_blink(); break; case '7': // --... long_blink(); long_blink(); short_blink(); short_blink(); short_blink(); no_blink(); break; case '8': // ---.. long_blink(); long_blink(); long_blink(); short_blink(); short_blink(); no_blink(); break; case '9': // ----. long_blink(); long_blink(); long_blink(); long_blink(); short_blink(); no_blink(); break; } interrupts(); }
#pragma once #include <boost/filesystem.hpp> #include <gsl/span> #include "SphinxModel.h" namespace PticaGovorun { class KaldiModelBuilder { struct AssignedPhaseAudioSegmentAndUttId { const AssignedPhaseAudioSegment* SegRef; std::string UttId; }; boost::filesystem::path outDirPath_; std::function<auto (boost::wstring_view)->boost::wstring_view> pronCodeDisplayTrain_; std::function<auto (boost::wstring_view)->boost::wstring_view> pronCodeDisplayTest_; public: KaldiModelBuilder(const boost::filesystem::path& outDirPath, std::function<auto (boost::wstring_view)->boost::wstring_view> pronCodeDisplayTrain, std::function<auto (boost::wstring_view)->boost::wstring_view> pronCodeDisplayTest); bool generate(gsl::span<const AssignedPhaseAudioSegment> segsRefs, ErrMsgList* errMsg) const; /// Kaldi's wav.scp (uttId->wav file path), utt2spk, text (uttId->transcription) use utterance id as the first token in a line. /// UttId should start with speakerId (is it mandatory?) so when all utterances are sorted, they become ordered by speakerId. static void createUtteranceId(const AssignedPhaseAudioSegment& segRef, std::string* uttId); static void createSpkIdToUttIdListMap(gsl::span<const AssignedPhaseAudioSegmentAndUttId> segsRefs, ResourceUsagePhase targetPhase, std::map<boost::string_view, std::vector<boost::string_view>>* spkId2UttIdList); bool writeUttId2SpeakerId(gsl::span<const AssignedPhaseAudioSegmentAndUttId> segsRefs, ResourceUsagePhase targetPhase, const boost::filesystem::path& filePath, ErrMsgList* errMsg) const; bool writeUttId2WavPathAbs(gsl::span<const AssignedPhaseAudioSegmentAndUttId> segsRefs, ResourceUsagePhase targetPhase, const boost::filesystem::path& filePath, ErrMsgList* errMsg) const; bool writeUttId2Transcription(gsl::span<const AssignedPhaseAudioSegmentAndUttId> segsRefs, ResourceUsagePhase targetPhase, std::function<auto (boost::wstring_view)->boost::wstring_view> pronCodeDisplay, const boost::filesystem::path& filePath, ErrMsgList* errMsg) const; bool writeSpkId2UttIdList(const std::map<boost::string_view, std::vector<boost::string_view>>& spkId2UttIdList, const boost::filesystem::path& filePath, ErrMsgList* errMsg) const; }; }
/** * Copyright (c) 2014, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or otherlist materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file log_accel.hh */ #ifndef log_accel_h #define log_accel_h #include <cmath> #include <stdint.h> #include "base/lnav_log.hh" /** * Helper class for figuring out changes in the log message rate. */ class log_accel { public: /*< The direction of the message rate: steady, accelerating, or decelerating */ enum direction_t { A_STEADY, A_DECEL, A_ACCEL, }; /** * Add a time point that will be used to compute velocity and then * acceleration. Points should be added in reverse order, from most * recent to oldest. * * @param point The point in time. * @return True if more points can be added. */ bool add_point(int64_t point); /** * Get the average acceleration based on the time points we've received. * * @return The average message acceleration. */ double get_avg_accel() const; /** * Compute the message rate direction. If the average acceleration is less * than a certain threshold, then we consider the rate to be steady. * Otherwise, the message rate is increasing or decreasing. * * @return The direction of the message rate. */ direction_t get_direction() const; private: /** * The amount of historical data to include in the average acceleration * computation. */ static const int HISTORY_SIZE = 8; /** * The minimum range of velocities seen. This value should limit false- * positives for small millisecond level fluctuations. */ static const double MIN_RANGE; static const double THRESHOLD; int64_t la_last_point{0}; bool la_last_point_set{false}; int64_t la_min_velocity{INT64_MAX}; int64_t la_max_velocity{INT64_MIN}; int64_t la_velocity[HISTORY_SIZE]; int la_velocity_size{0}; }; #endif
#include <reactor/net/EventLoop.h> #include <signal.h> #include <reactor/base/SimpleLogger.h> #include <reactor/net/Channel.h> #include <reactor/net/PollPoller.h> #include <reactor/net/TimerId.h> #include <reactor/net/TimerQueue.h> namespace reactor { namespace net { namespace { #pragma GCC diagnostic ignored "-Wold-style-cast" class IgnoreSigPipe { public: IgnoreSigPipe() { ::signal(SIGPIPE, SIG_IGN); // LOG_TRACE << "Ignore SIGPIPE"; } }; #pragma GCC diagnostic error "-Wold-style-cast" IgnoreSigPipe initObj; } EventLoop::EventLoop(): poller_(new PollPoller()), timerq_(new TimerQueue(this)), quit_(false), handling_(false), qevents_() { } EventLoop::~EventLoop() { } void EventLoop::loop() { while (!quit_) { poller_->poll(&active_channels_); handle_active_channels(); handle_queue_events(); } } void EventLoop::handle_active_channels() { handling_ = true; for (Channel *channel : active_channels_) { channel->handle_events(); } handling_ = false; } void EventLoop::handle_queue_events() { assert(!handling_); while (!qevents_.empty()) { auto event = qevents_.front(); qevents_.pop(); event(); } } void EventLoop::add_channel(Channel *channel) { poller_->update_channel(channel); } void EventLoop::remove_channel(Channel *channel) { poller_->remove_channel(channel); } void EventLoop::update_channel(Channel *channel) { poller_->update_channel(channel); } void EventLoop::cancel_timer(const TimerId &id) { timerq_->cancel(id); } TimerId EventLoop::run_after(double delay, const TimerCallback &cb) { int64_t delay_us = static_cast<int64_t>(delay * 1000000); return run_at(Timestamp::current().add_microseconds(delay_us), cb); } TimerId EventLoop::run_at(const Timestamp &time, const TimerCallback &cb) { return timerq_->add_timer(time, cb, 0.0); } TimerId EventLoop::run_every(double interval, const TimerCallback &cb) { int64_t delay_us = static_cast<int64_t>(interval * 1000000); Timestamp first(Timestamp::current().add_microseconds(delay_us)); return timerq_->add_timer(first, cb, interval); } } // namespace net } // namespace reactor
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/crostini/crostini_share_path.h" #include "base/barrier_closure.h" #include "base/bind.h" #include "base/files/file_util.h" #include "base/optional.h" #include "chrome/browser/chromeos/crostini/crostini_manager.h" #include "chrome/browser/chromeos/crostini/crostini_pref_names.h" #include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/chromeos/file_manager/path_util.h" #include "chrome/browser/profiles/profile.h" #include "chromeos/chromeos_switches.h" #include "chromeos/dbus/concierge/service.pb.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/seneschal_client.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/browser_thread.h" namespace { void OnSeneschalSharePathResponse( base::FilePath path, base::OnceCallback<void(bool, std::string)> callback, base::Optional<vm_tools::seneschal::SharePathResponse> response) { if (!response) { std::move(callback).Run(false, "System error"); return; } std::move(callback).Run(response.value().success(), response.value().failure_reason()); } void CallSeneschalSharePath( Profile* profile, std::string vm_name, const base::FilePath path, bool save_to_prefs, base::OnceCallback<void(bool, std::string)> callback) { // Verify path is in one of the allowable mount points. // This logic is similar to DownloadPrefs::SanitizeDownloadTargetPath(). // TODO(joelhockey): Seneschal currently only support sharing directories // under Downloads. if (!path.IsAbsolute()) { std::move(callback).Run(false, "Path must be absolute"); return; } base::FilePath downloads = file_manager::util::GetDownloadsFolderForProfile(profile); base::FilePath relative_path; if (!downloads.AppendRelativePath(path, &relative_path)) { std::move(callback).Run(false, "Path must be under Downloads"); return; } // Path must be a valid directory. if (!base::DirectoryExists(path)) { std::move(callback).Run(false, "Path is not a valid directory"); return; } // Even if VM is not running, save to prefs now. if (save_to_prefs) { PrefService* pref_service = profile->GetPrefs(); ListPrefUpdate update(pref_service, crostini::prefs::kCrostiniSharedPaths); base::ListValue* shared_paths = update.Get(); shared_paths->Append(std::make_unique<base::Value>(path.value())); } // VM must be running. base::Optional<vm_tools::concierge::VmInfo> vm_info = crostini::CrostiniManager::GetForProfile(profile)->GetVmInfo( std::move(vm_name)); if (!vm_info) { std::move(callback).Run(false, "VM not running"); return; } vm_tools::seneschal::SharePathRequest request; request.set_handle(vm_info->seneschal_server_handle()); request.mutable_shared_path()->set_path(relative_path.value()); request.mutable_shared_path()->set_writable(true); request.set_storage_location( vm_tools::seneschal::SharePathRequest::DOWNLOADS); request.set_owner_id(crostini::CryptohomeIdForProfile(profile)); chromeos::DBusThreadManager::Get()->GetSeneschalClient()->SharePath( request, base::BindOnce(&OnSeneschalSharePathResponse, std::move(path), std::move(callback))); } void SharePathLogErrorCallback(std::string path, base::RepeatingClosure barrier, bool success, std::string failure_reason) { barrier.Run(); if (!success) { LOG(ERROR) << "Error SharePath=" << path << ", FailureReason=" << failure_reason; } } } // namespace namespace crostini { void SharePath(Profile* profile, std::string vm_name, const base::FilePath& path, base::OnceCallback<void(bool, std::string)> callback) { DCHECK(profile); DCHECK(callback); if (!base::CommandLine::ForCurrentProcess()->HasSwitch( chromeos::switches::kCrostiniFiles)) { std::move(callback).Run(false, "Flag crostini-files not enabled"); } CallSeneschalSharePath(profile, vm_name, path, true, std::move(callback)); } void UnsharePath(Profile* profile, std::string vm_name, const base::FilePath& path, base::OnceCallback<void(bool, std::string)> callback) { PrefService* pref_service = profile->GetPrefs(); ListPrefUpdate update(pref_service, crostini::prefs::kCrostiniSharedPaths); base::ListValue* shared_paths = update.Get(); shared_paths->Remove(base::Value(path.value()), nullptr); // TODO(joelhockey): Call to seneschal once UnsharePath is supported, // and update FilesApp to watch for changes. std::move(callback).Run(true, ""); } std::vector<std::string> GetSharedPaths(Profile* profile) { DCHECK(profile); std::vector<std::string> result; if (!base::CommandLine::ForCurrentProcess()->HasSwitch( chromeos::switches::kCrostiniFiles)) { return result; } const base::ListValue* shared_paths = profile->GetPrefs()->GetList(prefs::kCrostiniSharedPaths); for (const auto& path : *shared_paths) { result.emplace_back(path.GetString()); } return result; } void ShareAllPaths(Profile* profile, base::OnceCallback<void()> callback) { DCHECK(profile); std::vector<std::string> paths = GetSharedPaths(profile); base::RepeatingClosure barrier = base::BarrierClosure(paths.size(), std::move(callback)); for (const auto& path : paths) { CallSeneschalSharePath( profile, kCrostiniDefaultVmName, base::FilePath(path), false, base::BindOnce(&SharePathLogErrorCallback, std::move(path), barrier)); } } } // namespace crostini
#include "Globals.h" #include "Application.h" #include "ModuleTextures.h" #include "ModuleInput.h" #include "ModuleParticles.h" #include "ModuleRender.h" #include "ModuleCollision.h" #include "ModuleFadeToBlack.h" #include "ModuleSceneTemple.h" #include "ModuleAyin.h" #include "ModuleAyinArrow.h" #include "ModuleUI.h" #include "ModuleEnemies.h" #include "ModuleAyinUltimate.h" #include "SDL\include\SDL_timer.h" ModuleAyinUltimate::ModuleAyinUltimate() { graphics = nullptr; current_animation = nullptr; //PHASE 1 phase1.PushBack({222, 287, 32, 39}); //PHASE 2 phase2.PushBack({256, 277, 49, 57}); //PHASE 3 phase3.PushBack({306, 267, 63, 65}); } ModuleAyinUltimate::~ModuleAyinUltimate() { //destroyer } bool ModuleAyinUltimate::Start() { LOG("Loading partner textures"); graphics = App->textures->Load("assets/sprites/characters/ayin/Ayin_SpriteSheet2.png"); if (graphics == nullptr) { LOG("Could not load arrow textures") return false; } exist = false; aux = 0; spot1 = 0; spot2 = 0; spot3 = 0; spot4 = 0; position.x = App->ayin->position.x - 20; position.y = App->ayin->position.y + 20; return true; } bool ModuleAyinUltimate::CleanUp() { LOG("Unloading player"); App->textures->Unload(graphics); graphics = nullptr; if (graphics != nullptr) { LOG("Could not unload partner textures") return false; } return true; } update_status ModuleAyinUltimate::Update() { CheckState(); PerformActions(); if (App->input->keyboard[SDL_SCANCODE_M] == KEY_STATE::KEY_DOWN) { App->ayin->ulti++; } if (App->input->keyboard[SDL_SCANCODE_N] == KEY_STATE::KEY_DOWN) { App->ayin->ulti--; } //Draw partner SDL_Rect r = current_animation->GetCurrentFrame(); SDL_Rect r1 = current_animation_2->GetCurrentFrame(); /*SDL_Rect r2 = current_animation_3->GetCurrentFrame();*/ //SDL_Rect r3 = current_animation_4->GetCurrentFrame(); //Set position position.x = App->ayin->position.x - 20; position.y = App->ayin->position.y - 20; if (exist) { //ULTI 1 if (state == FIRST_PHASE) App->render->Blit(graphics, position.x + spot1, position.y + 30 - r.h, &r); else if (state == SECOND_PHASE) App->render->Blit(graphics, position.x + spot1, position.y + 30 - r.h, &r); else if (state == THIRD_PHASE) App->render->Blit(graphics, position.x + spot1, position.y + 30 - r.h, &r); //else if (state == SHOT_PHASE) App->render->Blit(graphics, position.x + spot1, position.y + 30 - r.h, &r); if (state2 == FIRST_PHASE) App->render->Blit(graphics, position.x + spot2, position.y + 30 - r.h, &r1); else if (state2 == SECOND_PHASE) App->render->Blit(graphics,position.x + spot2 , position.y + 30 - r.h, &r1); else if (state2 == THIRD_PHASE) App->render->Blit(graphics, position.x + spot2 , position.y + 30 - r.h, &r1); //ULTI 3 /*else if (state3 == FIRST_PHASE) App->render->Blit(graphics, position.x + spot3, position.y + 30 - r.h, &r2); else if (state3 == SECOND_PHASE) App->render->Blit(graphics, position.x + spot3, position.y + 30 - r.h, &r2); else if (state3 == THIRD_PHASE) App->render->Blit(graphics, position.x + spot3, position.y + 30 - r.h, &r2);*/ ////ULTI 4 //else if (state4 == FIRST_PHASE) App->render->Blit(graphics, position.x + spot4, position.y + 30 - r.h, &r3); //else if (state4 == SECOND_PHASE) App->render->Blit(graphics, position.x + spot4, position.y + 30 - r.h, &r3); //else if (state4 == THIRD_PHASE) App->render->Blit(graphics, position.x + spot4, position.y + 30 - r.h, &r3); if (App->input->keyboard[SDL_SCANCODE_U] == KEY_STATE::KEY_DOWN) { App->ayin->state = ULTI_AYIN; state = FIRST_PHASE; active = true; } if (active) { if (spot1 > 80) { state2 = FIRST_PHASE; active = false; //active2 = true; } } /*if (active2) { if (spot1 > 80) { state3 = FIRST_PHASE; active2 = false; } }*/ /*if (active) { if (shot_delay) { shot_entry = SDL_GetTicks(); shot_delay = false; active = false; } shot_current = SDL_GetTicks() - shot_entry; if (shot_current == 140) { state2 = FIRST_PHASE; } if (shot_current == 300) { state3 = FIRST_PHASE; } if (shot_current == 450) { state4 = FIRST_PHASE; shot_delay = true; } }*/ } //if (exist2) { ////ULTI 2 // if (state2 == FIRST_PHASE) App->render->Blit(graphics, position.x +spot2 , position.y + 30 - r.h, &r1); //else if (state2 == SECOND_PHASE) App->render->Blit(graphics,position.x + spot2 , position.y + 30 - r.h, &r1); //else if (state2 == THIRD_PHASE) App->render->Blit(graphics, position.x + spot2 , position.y + 30 - r.h, &r1); //state2 = FIRST_PHASE; // if (shot_delay) // { // shot_entry = SDL_GetTicks(); // shot_delay = false; // // //} // // shot_current = SDL_GetTicks() - shot_entry; // // if (shot_current >= 500) { // state2 = FIRST_PHASE; // //shot_delay = true; // //shot_entry = SDL_GetTicks(); // // } //if (App->input->keyboard[SDL_SCANCODE_U] == KEY_STATE::KEY_DOWN) { // state2 = FIRST_PHASE; // //active = true; //} /*}*/ return UPDATE_CONTINUE; } void ModuleAyinUltimate::CheckState() { //ULTI 1 switch (state) { case NO_ULTI: if (App->ayin->ulti > 0) { exist = true; spot1 = 0; } break; case FIRST_PHASE: spot1 = spot1 + 2; if (spot1 >= 30) { state =SECOND_PHASE; } break; case SECOND_PHASE: spot1 = spot1 + 2; if (spot1 >= 60) { state = THIRD_PHASE; } break; case THIRD_PHASE: spot1 = spot1 + 2; if (spot1 >= 90) { state = SHOT_PHASE; ulti = true; } break; case SHOT_PHASE: /*if (App->particles->ulti_ayin.position.x > App->particles->ulti_ayin.position.x + SCREEN_WIDTH) {*/ state = NO_ULTI; /*}*/ break; } //ULTI 2 switch (state2) { case NO_ULTI: if (App->ayin->ulti > 0) { spot2 = 0; } break; case FIRST_PHASE: spot2 = spot2 + 2; if (spot2 >= 30) { state2 = SECOND_PHASE; } break; case SECOND_PHASE: spot2 = spot2 + 2; if (spot2 >= 60) { state2 = THIRD_PHASE; } break; case THIRD_PHASE: spot2 = spot2 + 2; if (spot2 >= 90) { state2 = SHOT_PHASE; ulti2 = true; } break; case SHOT_PHASE: /*if (App->particles->ulti_ayin.position.x > App->particles->ulti_ayin.position.x + SCREEN_WIDTH) {*/ state2 = NO_ULTI; /*}*/ break; } //switch (state3) //{ //case NO_ULTI: // if (App->ayin->ulti > 0) { // spot3 = 0; // } // break; //case FIRST_PHASE: // spot3 = spot3 + 2; // if (spot3 >= 30) { // state3 = SECOND_PHASE; // } // break; //case SECOND_PHASE: // spot3 = spot3 + 2; // if (spot3 >= 60) { // state3 = THIRD_PHASE; // } // break; //case THIRD_PHASE: // spot3 = spot3 + 2; // if (spot3 >= 90) { // state3 = SHOT_PHASE; // ulti = true; // } // break; //case SHOT_PHASE: // /*if (App->particles->ulti_ayin.position.x > App->particles->ulti_ayin.position.x + SCREEN_WIDTH) {*/ // state3 = NO_ULTI; // /*}*/ // break; //} ////ULTI 4 //switch (state4) //{ //case NO_ULTI: // if (App->ayin->ulti > 0) { // exist = true; // spot4 = 0; // } // break; //case FIRST_PHASE: // spot4 = spot4 + 2; // if (spot4 >= 30) { // state4 = SECOND_PHASE; // } // break; //case SECOND_PHASE: // spot4 = spot4 + 2; // if (spot4 >= 60) { // state4 = THIRD_PHASE; // } // break; //case THIRD_PHASE: // spot4 = spot4 + 2; // if (spot4 >= 90) { // state4 = SHOT_PHASE; // ulti = true; // } // break; //case SHOT_PHASE: // /*if (App->particles->ulti_ayin.position.x > App->particles->ulti_ayin.position.x + SCREEN_WIDTH) {*/ // state4 = NO_ULTI; // /*}*/ // break; //} } void ModuleAyinUltimate::PerformActions() { //ULTI 1 switch (state) { case NO_ULTI: current_animation = &phase1; break; case FIRST_PHASE: current_animation = &phase1; break; case SECOND_PHASE: current_animation = &phase2; break; case THIRD_PHASE: current_animation = &phase3; break; case SHOT_PHASE: if (ulti) { App->particles->AddParticle(App->particles->ulti_ayin, position.x + spot1, position.y - 30, COLLIDER_PLAYER_AYIN_ULTI); ulti = false; } break; } //ULTI 2 switch (state2) { case NO_ULTI: current_animation_2 = &phase1; break; case FIRST_PHASE: current_animation_2 = &phase1; break; case SECOND_PHASE: current_animation_2 = &phase2; break; case THIRD_PHASE: current_animation_2 = &phase3; break; case SHOT_PHASE: if (ulti2) { App->particles->AddParticle(App->particles->ulti_ayin, position.x + spot2 , position.y - 30, COLLIDER_PLAYER_AYIN_ULTI); ulti2 = false; } break; } //ULTI 3 /*switch (state3) { case NO_ULTI: current_animation_3 = &phase1; break; case FIRST_PHASE: current_animation_3 = &phase1; break; case SECOND_PHASE: current_animation_3 = &phase2; break; case THIRD_PHASE: current_animation_3 = &phase3; break; case SHOT_PHASE: if (ulti) { App->particles->AddParticle(App->particles->ulti_ayin, position.x + spot3, position.y - 30, COLLIDER_PLAYER_AYIN_ULTI); ulti = false; } break; }*/ ////ULTI 4 //switch (state4) { //case NO_ULTI: // current_animation_4 = &phase1; // break; //case FIRST_PHASE: // current_animation_4 = &phase1; // break; //case SECOND_PHASE: // current_animation_4 = &phase2; // break; //case THIRD_PHASE: // current_animation_4 = &phase3; // break; //case SHOT_PHASE: // if (ulti) { // App->particles->AddParticle(App->particles->ulti_ayin, position.x + spot4, position.y - 30, COLLIDER_PLAYER_AYIN_ULTI); // ulti = false; // } // break; //} }
#pragma once #include "VirtualMemoryChunk.h" #include <cassert> namespace keng::memory { template<typename T> class VirtualVector { public: VirtualVector(size_t capacity, size_t resizeValue = 1) : m_resizeValue(resizeValue), m_capacity(capacity), m_memory(m_capacity * sizeof(T), m_resizeValue * sizeof(T)) {} T& operator[](size_t index) { assert(index < m_size); return ((T*)m_memory.GetData())[index]; } bool OwnsThisPointer(void* pointer) const { auto poolAddress = reinterpret_cast<size_t>(m_memory.GetData()); auto pointerAddress = reinterpret_cast<size_t>(pointer); if (pointerAddress < poolAddress) { return false; } auto delta = (pointerAddress - poolAddress); auto index = delta / sizeof(T); return index < m_size; } size_t GetSize() const { return m_size; } size_t GetStartAddress() const { return (size_t)m_memory.GetData(); } bool Resize(size_t size) { if (size > m_size) { if (size > m_capacity) { return false; } m_memory.Commit(size * sizeof(T)); } m_size = size; return true; } private: size_t m_size = 0; size_t m_resizeValue = 1; size_t m_capacity; VirtualMemoryChunk m_memory; }; }
#include<iostream> #include<vector> using namespace std; bool palindrome(string word){ string dummy=""; int i; if(word.size()==1){ dummy+=word; } for(i=word.size()-1;i>=0;i--){ dummy+=word[i]; } if(dummy == word){ return true; } return false; } int main(){ string str; int len,counter=0; vector<string>words(10); getline(cin,str); cout<<str<<endl; len = str.length(); for(int i=0;i<len;i++){ if(str[i]==' '){ counter++; }else{ words[counter] +=str[i]; } } for(int i=0;i<=counter;i++){ //cout<<words[i]<<endl; if(palindrome(words[i])){ words.erase(words.begin()+i); } } for(int i=0;i<=counter;i++){ cout<<words[i]<<' '; } cout<<endl; return 0; }
#ifndef SFR_OBJECT_H #define SFR_OBJECT_H #include <QObject> class SFR_Object : public QObject { Q_OBJECT public: explicit SFR_Object(QObject *parent = 0); signals: public slots: }; #endif // SFR_OBJECT_H
#include <stdio.h> // - Just for some ASCII messages #include "visuals.h" // Header file for our OpenGL functions #include <time.h> #include "GL/glut.h" // - An interface and windows management library int main(int argc, char* argv[]) { // initialize GLUT library state glutInit(&argc, argv); // Set up the display using the GLUT functions to // get rid of the window setup details: // - Use true RGB colour mode ( and transparency ) // - Enable double buffering for faster window update // - Allocate a Depth-Buffer in the system memory or // in the video memory if 3D acceleration available //RGBA//DEPTH BUFFER//DOUBLE BUFFER// glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE); // Define the main window size and initial position // ( upper left corner, boundaries included ) glutInitWindowSize(1200,1200); glutInitWindowPosition(50,50); // Create and label the main window glutCreateWindow("Planet Simulation"); // Configure various properties of the OpenGL rendering context Setup(); // Callbacks for the GL and GLUT events: // The rendering function glutDisplayFunc(Render); glutReshapeFunc(Resize); glutIdleFunc(Idle); glutKeyboardFunc(Keyboard); glutMouseFunc(Mouse); //Enter main event handling loop glutMainLoop(); return 0; }
#include<iostream> #include<vector> #include<algorithm> #include <unistd.h> #include<stdio.h> using namespace std; struct process { int pid, at, bt, wt, tt, c; }; bool compare(process p1, process p2) { return p1.at < p2.at; } void arrange(vector<process> &arr) { sort(arr.begin(), arr.end(), compare); } void findWaitingTime(vector<process> &arr, int n) { for (int i = 1; i < n ; i++ ) arr[i].wt = arr[i - 1].bt + arr[i - 1].wt; } void findTurnAroundTime(vector<process> &arr, int n) { for (int i = 0; i < n ; i++) arr[i].tt = arr[i].bt + arr[i].wt; } void findavgTime(vector<process> &arr, int n){ findWaitingTime(arr, n); findTurnAroundTime(arr, n); int total_wt = 0, total_tat = 0; int cnt = 0, i = 0, time = arr[0].at; while(i < n) { cout << "Press Enter to Continue"; cin.ignore(); system("clear"); cout<<"\nReady Queue at time "<<time<<"\n\n\t\t"; for(int j = 0; arr[j].at <= time; j++) { if(j == n) break; cout<<arr[j].pid<<" | "; } cout<<"\n\t\t"; for(int k = 0; k < cnt; k++) cout<<" "; cnt++; printf("\u2191"); cout<<"\n"; cout<<"Process "<<arr[i].pid<<" is chosen"; cout<<"\n"; time += arr[i].bt; i++; } cout<<"Process ID\tArrival Time\tBurst Time\tWaiting Time\tTurnaround Time\n"; for (int i=0; i<n; i++) { total_wt = total_wt + arr[i].wt; total_tat = total_tat + arr[i].tt; //cout << " " <<arr[i].pid<< "\t\t" <<arr[i].bt <<"\t "<<arr[i].wt<<"\t\t " <<arr[i].tt<<endl; cout<<arr[i].pid<<"\t\t"<<arr[i].at<<"\t\t"<<arr[i].bt<<"\t\t"<<arr[i].wt<<"\t\t"<<arr[i].tt<<"\n"; } cout << "Average waiting time = "<< (float)total_wt / (float)n; cout << "\nAverage turn around time = "<< (float)total_tat / (float)n<<"\n\n"; } int main() { int n; system("clear"); cout<<"\tWELCOME TO VISUALIZATION OF FCFS SCHEDULING ALGORITHM\n"; cout<<"\nEnter the number of processes: "; cin>>n; vector<process> arr; for(int i=0; i<n; i++) { process p; cout<<"Process "<<i+1<<"\n"; cout<<"Enter Process Id: "; cin>>p.pid; cout<<"Enter Arrival Time: "; cin>>p.at; cout<<"Enter Burst Time: "; cin>>p.bt; arr.push_back(p); } vector<process> arr1 = arr; arrange(arr); arr[0].wt = 0; findavgTime(arr, n); return 0; }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #include "Scene.h" #include "model/IModel.h" #include "model/manager/IModelManager.h" #include "events/types/UpdateEvent.h" #include "model/layout/LayerProperties.h" #include "model/IBox.h" #include "model/IGroup.h" #include "Config.h" #include "events/EventIdex.h" #include "events/PointerInsideIndex.h" #include "tween/Manager.h" #include "events/types/ManagerEvent.h" #include "util/UpdateContext.h" namespace Util { namespace M = Model; struct Scene::Impl { Impl () : model (NULL), modelManager (NULL), config (NULL) {} M::IModel *model; M::IModelManager *modelManager; Config *config; Event::EventIndex eventIndex; Event::PointerInsideIndex pointerInsideIndex; Util::UpdateContext updateContext; }; /****************************************************************************/ Scene::Scene (M::IModelManager *m, Config *c, View::GLContext *gl) : impl (new Impl) { impl->modelManager = m; impl->config = c; impl->updateContext.config = c; impl->updateContext.glContext = gl; } /****************************************************************************/ Scene::~Scene () { delete impl; } /****************************************************************************/ void Scene::onStep (Event::UpdateEvent *updateEvent) { bool newModelLoaded = impl->modelManager->run (this); if (newModelLoaded) { assert (impl->model); updateLayout (); } impl->model->update (updateEvent, &impl->updateContext); } /****************************************************************************/ void Scene::setModel (Model::IModel *m) { impl->model = m; impl->eventIndex.clear (); impl->pointerInsideIndex.clear (); impl->eventIndex.add (0xFFFFu & ~Event::MOUSE_EVENTS, m); if (m->isGroup ()) { Model::IGroup *g = dynamic_cast <Model::IGroup *> (m); g->setIndices (&impl->eventIndex, &impl->pointerInsideIndex); } } /****************************************************************************/ Model::IModel *Scene::getModel () { return impl->model; } /****************************************************************************/ void Scene::reset () { impl->eventIndex.clear (); impl->pointerInsideIndex.clear (); } /****************************************************************************/ void Scene::onManagerLoadModel () { M::IModel *m = impl->model; Event::ManagerEvent event; if (m && m->getController () && m->getController ()->getEventMask () & Event::MANAGER_EVENT) { m->getController ()->onManagerLoad (&event, m, m->getView ()); } } /****************************************************************************/ void Scene::onManagerUnloadModel () { Tween::Manager::getMain ()->killAll (); M::IModel *m = impl->model; Event::ManagerEvent event; if (m && m->getController () && m->getController ()->getEventMask () & Event::MANAGER_EVENT) { m->getController ()->onManagerUnload (&event, m, m->getView ()); } } /****************************************************************************/ void Scene::updateLayout () { M::IGroupProperties const *props = impl->model->getGroupProps (); if (!props) { return; } M::LayerProperties const *scrProps = dynamic_cast <M::LayerProperties const *> (props); if (!scrProps) { return; } Model::IBox *box = dynamic_cast <Model::IBox *> (impl->model); if (!box) { return; } if (scrProps->fillW) { box->setWidth (impl->config->projectionWidth); } if (scrProps->fillH) { box->setHeight (impl->config->projectionHeight); } if (!scrProps->centerGroup || !impl->model->isGroup ()) { return; } M::IGroup *group = dynamic_cast <M::IGroup *> (impl->model); if (group->getCoordinateSystemOrigin () == M::IGroup::BOTTOM_LEFT) { Geometry::Point t; t.x = -box->getWidth () / 2.0; t.y = -box->getHeight () / 2.0; impl->model->setTranslate (t); } else { impl->model->setTranslate (Geometry::ZERO_POINT); } } /****************************************************************************/ Event::EventIndex *Scene::getEventIndex () { return &impl->eventIndex; } /****************************************************************************/ Event::PointerInsideIndex *Scene::getPointerInsideIndex () { return &impl->pointerInsideIndex; } } /* namespace Util */
// Info taken from these sites: // http://www.learncpp.com/cpp-tutorial/19-header-files/ // http://www.umich.edu/~eecs381/handouts/CppHeaderFileGuidelines.pdf // This is start of the header guard. #ifndef FSTREAM_I #define FSTREAM_I #include <fstream> #endif #ifndef IOSTREAM_I #define IOSTREAM_I #include <iostream> #endif #ifndef STRING_I #define STRING_I #include <string> #endif #ifndef VECTOR_I #define VECTOR_I #include <vector> #endif /* #ifndef WEIGHT_H // not sure how to do this, one site says not to... #define WEIGHT_H #include "../lib/weight.cpp" #endif */ // ***_H can be any unique name. By convention, we use the name of the header file. #ifndef BOARDGEN_H #define BOARDGEN_H // This is the content of the .h file, which is where the declarations go Board boardGen(); vector<Tile> rackGen(); // This is the end of the header guard #endif
#include <Wire.h> #include <ZumoMotors.h> #include <Pushbutton.h> #include <ZumoBuzzer.h> #include <LSM303.h> ZumoMotors motors; ZumoBuzzer buzzer; Pushbutton button(ZUMO_BUTTON); LSM303 compass; #define SPEED 120 // default motor speed float red_G, green_G, blue_G; // RGB values int zoneNumber_G; // zone number int mode_G; // mode in each zone unsigned long timeInit_G, timeNow_G; // start time, current time, int motorR_G, motorL_G; // input values to the motors unsigned long zone_start_time_G; float azimuth = 0, start_angle=0; // 角度 /********* zone4 **********/ const int trig = 2; const int echo = 4; const int power = 13; /**************************/ void setup() { Serial.begin(57600); Wire.begin(); button.waitForButton(); setupColorSensor(); // カラーセンサーのsetup CalibrationColorSensor(); // カラーセンサーのキャリブレーション setupCompass(); // 地磁気センサーのsetup CalibrationCompass(); // 地磁気センサーのキャリブレーション buzzer.play(">g32>>c32"); zoneNumber_G = 0; mode_G = 0; timeInit_G = millis(); button.waitForButton(); } void loop() { compass.read(); azimuth = averageHeading(); readRGB(); clearInterrupt(); timeNow_G = millis() - timeInit_G; motors.setSpeeds(motorL_G, motorR_G); sendData(); zoneNumber_G = 6; switch ( zoneNumber_G ) { case 0: startToZone(); // start to zone break; case 1: // zone(); // zone 1 break; case 2: // zone(); // zone 2 break; case 3: // zone(); // zone 3 break; case 4: zone4(); // zone 4 break; case 5: // zone(); // zone 5 break; case 6: zone6(); // zone 6 break; case 7: // zone(); // finish zone break; case 8: zoneToZone(); // zone to zone break; default: break; } // Serial.println(azimuth); // 20s経過していたらゾーンを移動 /*if(timeNow_G - zone_start_time_G >= 20000){ mode_G = 5; }*/ } void sendData() { static unsigned long timePrev = 0; if ( timeNow_G - timePrev > 50 ) { // 50msごとにデータ送信 /* Serial.write('H'); Serial.write(zoneNumber_G); Serial.write(mode_G); Serial.write((int)red_G); Serial.write((int)green_G); Serial.write((int)blue_G); */ //Serial.println(zoneNumber_G); /* Serial.print(red_G); Serial.print(green_G); Serial.println(blue_G); Serial.println((red_G + green_G + blue_G) /3 ); */ if(zoneNumber_G == 6){ if(Serial.read() == 'A') { int angle = int(azimuth - start_angle); if(angle < 0) angle += 360; Serial.write('H'); Serial.write((int)angle >> 8); Serial.write((int)angle & 255); Serial.write((int)(motorR_G)); Serial.write((int)(motorL_G)); Serial.write((int)red_G); Serial.write((int)green_G); Serial.write((int)blue_G); timePrev = timeNow_G; } } } }
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include <stdint.h> #include "codegen/il2cpp-codegen.h" #include "il2cpp-object-internals.h" // System.Char[] struct CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2; // System.String struct String_t; // System.Void struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Object // System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF : public RuntimeObject { public: public: }; // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_com { }; // Unity.Jobs.IJobParallelForExtensions struct IJobParallelForExtensions_tE5A9098E3E7E5F5617857743A369E9BFF53A5479 : public RuntimeObject { public: public: }; // System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521 : public ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF { public: public: }; struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_StaticFields { public: // System.Char[] System.Enum::enumSeperatorCharArray CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* ___enumSeperatorCharArray_0; public: inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_StaticFields, ___enumSeperatorCharArray_0)); } inline CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; } inline CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; } inline void set_enumSeperatorCharArray_0(CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* value) { ___enumSeperatorCharArray_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___enumSeperatorCharArray_0), (void*)value); } }; // Native definition for P/Invoke marshalling of System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_marshaled_com { }; // System.Int32 struct Int32_t585191389E07734F19F3156FF88FB3EF4800D102 { public: // System.Int32 System.Int32::m_value int32_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int32_t585191389E07734F19F3156FF88FB3EF4800D102, ___m_value_0)); } inline int32_t get_m_value_0() const { return ___m_value_0; } inline int32_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(int32_t value) { ___m_value_0 = value; } }; // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; // System.Void struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017 { public: union { struct { }; uint8_t Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017__padding[1]; }; public: }; // Unity.Collections.Allocator struct Allocator_t62A091275262E7067EAAD565B67764FA877D58D6 { public: // System.Int32 Unity.Collections.Allocator::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(Allocator_t62A091275262E7067EAAD565B67764FA877D58D6, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // Unity.Jobs.JobHandle struct JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 { public: // System.IntPtr Unity.Jobs.JobHandle::jobGroup intptr_t ___jobGroup_0; // System.Int32 Unity.Jobs.JobHandle::version int32_t ___version_1; public: inline static int32_t get_offset_of_jobGroup_0() { return static_cast<int32_t>(offsetof(JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1, ___jobGroup_0)); } inline intptr_t get_jobGroup_0() const { return ___jobGroup_0; } inline intptr_t* get_address_of_jobGroup_0() { return &___jobGroup_0; } inline void set_jobGroup_0(intptr_t value) { ___jobGroup_0 = value; } inline static int32_t get_offset_of_version_1() { return static_cast<int32_t>(offsetof(JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1, ___version_1)); } inline int32_t get_version_1() const { return ___version_1; } inline int32_t* get_address_of_version_1() { return &___version_1; } inline void set_version_1(int32_t value) { ___version_1 = value; } }; // Unity.Jobs.LowLevel.Unsafe.ScheduleMode struct ScheduleMode_t83F3C482EFD55A9D2FA6F84D626EF24DFACB2E37 { public: // System.Int32 Unity.Jobs.LowLevel.Unsafe.ScheduleMode::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(ScheduleMode_t83F3C482EFD55A9D2FA6F84D626EF24DFACB2E37, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // Unity.Collections.NativeArray`1<UnityEngine.Quaternion> struct NativeArray_1_t9C70B1A7759D3AEB5D78FECCCDB8DCDEB9CCA684 { public: // System.Void* Unity.Collections.NativeArray`1::m_Buffer void* ___m_Buffer_0; // System.Int32 Unity.Collections.NativeArray`1::m_Length int32_t ___m_Length_1; // Unity.Collections.Allocator Unity.Collections.NativeArray`1::m_AllocatorLabel int32_t ___m_AllocatorLabel_2; public: inline static int32_t get_offset_of_m_Buffer_0() { return static_cast<int32_t>(offsetof(NativeArray_1_t9C70B1A7759D3AEB5D78FECCCDB8DCDEB9CCA684, ___m_Buffer_0)); } inline void* get_m_Buffer_0() const { return ___m_Buffer_0; } inline void** get_address_of_m_Buffer_0() { return &___m_Buffer_0; } inline void set_m_Buffer_0(void* value) { ___m_Buffer_0 = value; } inline static int32_t get_offset_of_m_Length_1() { return static_cast<int32_t>(offsetof(NativeArray_1_t9C70B1A7759D3AEB5D78FECCCDB8DCDEB9CCA684, ___m_Length_1)); } inline int32_t get_m_Length_1() const { return ___m_Length_1; } inline int32_t* get_address_of_m_Length_1() { return &___m_Length_1; } inline void set_m_Length_1(int32_t value) { ___m_Length_1 = value; } inline static int32_t get_offset_of_m_AllocatorLabel_2() { return static_cast<int32_t>(offsetof(NativeArray_1_t9C70B1A7759D3AEB5D78FECCCDB8DCDEB9CCA684, ___m_AllocatorLabel_2)); } inline int32_t get_m_AllocatorLabel_2() const { return ___m_AllocatorLabel_2; } inline int32_t* get_address_of_m_AllocatorLabel_2() { return &___m_AllocatorLabel_2; } inline void set_m_AllocatorLabel_2(int32_t value) { ___m_AllocatorLabel_2 = value; } }; // Unity.Collections.NativeArray`1<UnityEngine.Vector2> struct NativeArray_1_t86AEDFC03CDAC131E54ED6A68B102EBD947A3F71 { public: // System.Void* Unity.Collections.NativeArray`1::m_Buffer void* ___m_Buffer_0; // System.Int32 Unity.Collections.NativeArray`1::m_Length int32_t ___m_Length_1; // Unity.Collections.Allocator Unity.Collections.NativeArray`1::m_AllocatorLabel int32_t ___m_AllocatorLabel_2; public: inline static int32_t get_offset_of_m_Buffer_0() { return static_cast<int32_t>(offsetof(NativeArray_1_t86AEDFC03CDAC131E54ED6A68B102EBD947A3F71, ___m_Buffer_0)); } inline void* get_m_Buffer_0() const { return ___m_Buffer_0; } inline void** get_address_of_m_Buffer_0() { return &___m_Buffer_0; } inline void set_m_Buffer_0(void* value) { ___m_Buffer_0 = value; } inline static int32_t get_offset_of_m_Length_1() { return static_cast<int32_t>(offsetof(NativeArray_1_t86AEDFC03CDAC131E54ED6A68B102EBD947A3F71, ___m_Length_1)); } inline int32_t get_m_Length_1() const { return ___m_Length_1; } inline int32_t* get_address_of_m_Length_1() { return &___m_Length_1; } inline void set_m_Length_1(int32_t value) { ___m_Length_1 = value; } inline static int32_t get_offset_of_m_AllocatorLabel_2() { return static_cast<int32_t>(offsetof(NativeArray_1_t86AEDFC03CDAC131E54ED6A68B102EBD947A3F71, ___m_AllocatorLabel_2)); } inline int32_t get_m_AllocatorLabel_2() const { return ___m_AllocatorLabel_2; } inline int32_t* get_address_of_m_AllocatorLabel_2() { return &___m_AllocatorLabel_2; } inline void set_m_AllocatorLabel_2(int32_t value) { ___m_AllocatorLabel_2 = value; } }; // Unity.Collections.NativeArray`1<UnityEngine.Vector3> struct NativeArray_1_t20B0E97D613353CCC2889E9B3D97A5612374FE74 { public: // System.Void* Unity.Collections.NativeArray`1::m_Buffer void* ___m_Buffer_0; // System.Int32 Unity.Collections.NativeArray`1::m_Length int32_t ___m_Length_1; // Unity.Collections.Allocator Unity.Collections.NativeArray`1::m_AllocatorLabel int32_t ___m_AllocatorLabel_2; public: inline static int32_t get_offset_of_m_Buffer_0() { return static_cast<int32_t>(offsetof(NativeArray_1_t20B0E97D613353CCC2889E9B3D97A5612374FE74, ___m_Buffer_0)); } inline void* get_m_Buffer_0() const { return ___m_Buffer_0; } inline void** get_address_of_m_Buffer_0() { return &___m_Buffer_0; } inline void set_m_Buffer_0(void* value) { ___m_Buffer_0 = value; } inline static int32_t get_offset_of_m_Length_1() { return static_cast<int32_t>(offsetof(NativeArray_1_t20B0E97D613353CCC2889E9B3D97A5612374FE74, ___m_Length_1)); } inline int32_t get_m_Length_1() const { return ___m_Length_1; } inline int32_t* get_address_of_m_Length_1() { return &___m_Length_1; } inline void set_m_Length_1(int32_t value) { ___m_Length_1 = value; } inline static int32_t get_offset_of_m_AllocatorLabel_2() { return static_cast<int32_t>(offsetof(NativeArray_1_t20B0E97D613353CCC2889E9B3D97A5612374FE74, ___m_AllocatorLabel_2)); } inline int32_t get_m_AllocatorLabel_2() const { return ___m_AllocatorLabel_2; } inline int32_t* get_address_of_m_AllocatorLabel_2() { return &___m_AllocatorLabel_2; } inline void set_m_AllocatorLabel_2(int32_t value) { ___m_AllocatorLabel_2 = value; } }; // Unity.Collections.NativeArray`1<UnityEngine.Vector4> struct NativeArray_1_t32E6297AF854BD125529357115F7C02BA25C4C96 { public: // System.Void* Unity.Collections.NativeArray`1::m_Buffer void* ___m_Buffer_0; // System.Int32 Unity.Collections.NativeArray`1::m_Length int32_t ___m_Length_1; // Unity.Collections.Allocator Unity.Collections.NativeArray`1::m_AllocatorLabel int32_t ___m_AllocatorLabel_2; public: inline static int32_t get_offset_of_m_Buffer_0() { return static_cast<int32_t>(offsetof(NativeArray_1_t32E6297AF854BD125529357115F7C02BA25C4C96, ___m_Buffer_0)); } inline void* get_m_Buffer_0() const { return ___m_Buffer_0; } inline void** get_address_of_m_Buffer_0() { return &___m_Buffer_0; } inline void set_m_Buffer_0(void* value) { ___m_Buffer_0 = value; } inline static int32_t get_offset_of_m_Length_1() { return static_cast<int32_t>(offsetof(NativeArray_1_t32E6297AF854BD125529357115F7C02BA25C4C96, ___m_Length_1)); } inline int32_t get_m_Length_1() const { return ___m_Length_1; } inline int32_t* get_address_of_m_Length_1() { return &___m_Length_1; } inline void set_m_Length_1(int32_t value) { ___m_Length_1 = value; } inline static int32_t get_offset_of_m_AllocatorLabel_2() { return static_cast<int32_t>(offsetof(NativeArray_1_t32E6297AF854BD125529357115F7C02BA25C4C96, ___m_AllocatorLabel_2)); } inline int32_t get_m_AllocatorLabel_2() const { return ___m_AllocatorLabel_2; } inline int32_t* get_address_of_m_AllocatorLabel_2() { return &___m_AllocatorLabel_2; } inline void set_m_AllocatorLabel_2(int32_t value) { ___m_AllocatorLabel_2 = value; } }; // Unity.Jobs.LowLevel.Unsafe.JobsUtility_JobScheduleParameters struct JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F { public: // Unity.Jobs.JobHandle Unity.Jobs.LowLevel.Unsafe.JobsUtility_JobScheduleParameters::Dependency JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 ___Dependency_0; // System.Int32 Unity.Jobs.LowLevel.Unsafe.JobsUtility_JobScheduleParameters::ScheduleMode int32_t ___ScheduleMode_1; // System.IntPtr Unity.Jobs.LowLevel.Unsafe.JobsUtility_JobScheduleParameters::ReflectionData intptr_t ___ReflectionData_2; // System.IntPtr Unity.Jobs.LowLevel.Unsafe.JobsUtility_JobScheduleParameters::JobDataPtr intptr_t ___JobDataPtr_3; public: inline static int32_t get_offset_of_Dependency_0() { return static_cast<int32_t>(offsetof(JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F, ___Dependency_0)); } inline JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 get_Dependency_0() const { return ___Dependency_0; } inline JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 * get_address_of_Dependency_0() { return &___Dependency_0; } inline void set_Dependency_0(JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 value) { ___Dependency_0 = value; } inline static int32_t get_offset_of_ScheduleMode_1() { return static_cast<int32_t>(offsetof(JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F, ___ScheduleMode_1)); } inline int32_t get_ScheduleMode_1() const { return ___ScheduleMode_1; } inline int32_t* get_address_of_ScheduleMode_1() { return &___ScheduleMode_1; } inline void set_ScheduleMode_1(int32_t value) { ___ScheduleMode_1 = value; } inline static int32_t get_offset_of_ReflectionData_2() { return static_cast<int32_t>(offsetof(JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F, ___ReflectionData_2)); } inline intptr_t get_ReflectionData_2() const { return ___ReflectionData_2; } inline intptr_t* get_address_of_ReflectionData_2() { return &___ReflectionData_2; } inline void set_ReflectionData_2(intptr_t value) { ___ReflectionData_2 = value; } inline static int32_t get_offset_of_JobDataPtr_3() { return static_cast<int32_t>(offsetof(JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F, ___JobDataPtr_3)); } inline intptr_t get_JobDataPtr_3() const { return ___JobDataPtr_3; } inline intptr_t* get_address_of_JobDataPtr_3() { return &___JobDataPtr_3; } inline void set_JobDataPtr_3(intptr_t value) { ___JobDataPtr_3 = value; } }; // UnityEngine.XR.ARKit.ARKitXRDepthSubsystem_TransformPositionsJob struct TransformPositionsJob_t4BCA4844CF5EFB6C0A19B9E5059390B2E499E283 { public: // Unity.Collections.NativeArray`1<UnityEngine.Quaternion> UnityEngine.XR.ARKit.ARKitXRDepthSubsystem_TransformPositionsJob::positionsIn NativeArray_1_t9C70B1A7759D3AEB5D78FECCCDB8DCDEB9CCA684 ___positionsIn_0; // Unity.Collections.NativeArray`1<UnityEngine.Vector3> UnityEngine.XR.ARKit.ARKitXRDepthSubsystem_TransformPositionsJob::positionsOut NativeArray_1_t20B0E97D613353CCC2889E9B3D97A5612374FE74 ___positionsOut_1; public: inline static int32_t get_offset_of_positionsIn_0() { return static_cast<int32_t>(offsetof(TransformPositionsJob_t4BCA4844CF5EFB6C0A19B9E5059390B2E499E283, ___positionsIn_0)); } inline NativeArray_1_t9C70B1A7759D3AEB5D78FECCCDB8DCDEB9CCA684 get_positionsIn_0() const { return ___positionsIn_0; } inline NativeArray_1_t9C70B1A7759D3AEB5D78FECCCDB8DCDEB9CCA684 * get_address_of_positionsIn_0() { return &___positionsIn_0; } inline void set_positionsIn_0(NativeArray_1_t9C70B1A7759D3AEB5D78FECCCDB8DCDEB9CCA684 value) { ___positionsIn_0 = value; } inline static int32_t get_offset_of_positionsOut_1() { return static_cast<int32_t>(offsetof(TransformPositionsJob_t4BCA4844CF5EFB6C0A19B9E5059390B2E499E283, ___positionsOut_1)); } inline NativeArray_1_t20B0E97D613353CCC2889E9B3D97A5612374FE74 get_positionsOut_1() const { return ___positionsOut_1; } inline NativeArray_1_t20B0E97D613353CCC2889E9B3D97A5612374FE74 * get_address_of_positionsOut_1() { return &___positionsOut_1; } inline void set_positionsOut_1(NativeArray_1_t20B0E97D613353CCC2889E9B3D97A5612374FE74 value) { ___positionsOut_1 = value; } }; // UnityEngine.XR.ARKit.ARKitXRPlaneSubsystem_ARKitProvider_TransformBoundaryPositionsJob struct TransformBoundaryPositionsJob_t1AEFA76DC77740E7CA334DC8C60612BF6D6FA872 { public: // Unity.Collections.NativeArray`1<UnityEngine.Vector4> UnityEngine.XR.ARKit.ARKitXRPlaneSubsystem_ARKitProvider_TransformBoundaryPositionsJob::positionsIn NativeArray_1_t32E6297AF854BD125529357115F7C02BA25C4C96 ___positionsIn_0; // Unity.Collections.NativeArray`1<UnityEngine.Vector2> UnityEngine.XR.ARKit.ARKitXRPlaneSubsystem_ARKitProvider_TransformBoundaryPositionsJob::positionsOut NativeArray_1_t86AEDFC03CDAC131E54ED6A68B102EBD947A3F71 ___positionsOut_1; public: inline static int32_t get_offset_of_positionsIn_0() { return static_cast<int32_t>(offsetof(TransformBoundaryPositionsJob_t1AEFA76DC77740E7CA334DC8C60612BF6D6FA872, ___positionsIn_0)); } inline NativeArray_1_t32E6297AF854BD125529357115F7C02BA25C4C96 get_positionsIn_0() const { return ___positionsIn_0; } inline NativeArray_1_t32E6297AF854BD125529357115F7C02BA25C4C96 * get_address_of_positionsIn_0() { return &___positionsIn_0; } inline void set_positionsIn_0(NativeArray_1_t32E6297AF854BD125529357115F7C02BA25C4C96 value) { ___positionsIn_0 = value; } inline static int32_t get_offset_of_positionsOut_1() { return static_cast<int32_t>(offsetof(TransformBoundaryPositionsJob_t1AEFA76DC77740E7CA334DC8C60612BF6D6FA872, ___positionsOut_1)); } inline NativeArray_1_t86AEDFC03CDAC131E54ED6A68B102EBD947A3F71 get_positionsOut_1() const { return ___positionsOut_1; } inline NativeArray_1_t86AEDFC03CDAC131E54ED6A68B102EBD947A3F71 * get_address_of_positionsOut_1() { return &___positionsOut_1; } inline void set_positionsOut_1(NativeArray_1_t86AEDFC03CDAC131E54ED6A68B102EBD947A3F71 value) { ___positionsOut_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // System.Void Unity.Jobs.LowLevel.Unsafe.JobsUtility/JobScheduleParameters::.ctor(System.Void*,System.IntPtr,Unity.Jobs.JobHandle,Unity.Jobs.LowLevel.Unsafe.ScheduleMode) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void JobScheduleParameters__ctor_m09A522B620ED79BDFD86DE2544175159B6179E48 (JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F * __this, void* ___i_jobData0, intptr_t ___i_reflectionData1, JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 ___i_dependency2, int32_t ___i_scheduleMode3, const RuntimeMethod* method); // Unity.Jobs.JobHandle Unity.Jobs.LowLevel.Unsafe.JobsUtility::ScheduleParallelFor(Unity.Jobs.LowLevel.Unsafe.JobsUtility/JobScheduleParameters&,System.Int32,System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 JobsUtility_ScheduleParallelFor_mD0B7FD9589FB242D9C4E21F93054C526FA6B1DBF (JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F * ___parameters0, int32_t ___arrayLength1, int32_t ___innerloopBatchCount2, const RuntimeMethod* method); // Unity.Jobs.JobHandle Unity.Jobs.IJobParallelForExtensions::Schedule<UnityEngine.XR.ARKit.ARKitXRDepthSubsystem_TransformPositionsJob>(T,System.Int32,System.Int32,Unity.Jobs.JobHandle) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 IJobParallelForExtensions_Schedule_TisTransformPositionsJob_t4BCA4844CF5EFB6C0A19B9E5059390B2E499E283_mC9224B9B04CFAD8D88AE139FA6C5A527E1AEC6DB_gshared (TransformPositionsJob_t4BCA4844CF5EFB6C0A19B9E5059390B2E499E283 ___jobData0, int32_t ___arrayLength1, int32_t ___innerloopBatchCount2, JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 ___dependsOn3, const RuntimeMethod* method) { JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F V_0; memset((&V_0), 0, sizeof(V_0)); JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 V_1; memset((&V_1), 0, sizeof(V_1)); { void* L_0 = (( void* (*) (TransformPositionsJob_t4BCA4844CF5EFB6C0A19B9E5059390B2E499E283 *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)->methodPointer)((TransformPositionsJob_t4BCA4844CF5EFB6C0A19B9E5059390B2E499E283 *)(TransformPositionsJob_t4BCA4844CF5EFB6C0A19B9E5059390B2E499E283 *)(&___jobData0), /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)); intptr_t L_1 = (( intptr_t (*) (const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)->methodPointer)(/*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)); JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 L_2 = ___dependsOn3; JobScheduleParameters__ctor_m09A522B620ED79BDFD86DE2544175159B6179E48((JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F *)(JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F *)(&V_0), (void*)(void*)L_0, (intptr_t)L_1, (JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 )L_2, (int32_t)1, /*hidden argument*/NULL); int32_t L_3 = ___arrayLength1; int32_t L_4 = ___innerloopBatchCount2; JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 L_5 = JobsUtility_ScheduleParallelFor_mD0B7FD9589FB242D9C4E21F93054C526FA6B1DBF((JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F *)(JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F *)(&V_0), (int32_t)L_3, (int32_t)L_4, /*hidden argument*/NULL); V_1 = (JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 )L_5; goto IL_0022; } IL_0022: { JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 L_6 = V_1; return L_6; } } // Unity.Jobs.JobHandle Unity.Jobs.IJobParallelForExtensions::Schedule<UnityEngine.XR.ARKit.ARKitXRPlaneSubsystem_ARKitProvider_TransformBoundaryPositionsJob>(T,System.Int32,System.Int32,Unity.Jobs.JobHandle) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 IJobParallelForExtensions_Schedule_TisTransformBoundaryPositionsJob_t1AEFA76DC77740E7CA334DC8C60612BF6D6FA872_mEFD98E2FA8598E542B584F49614EEA56224DDDC8_gshared (TransformBoundaryPositionsJob_t1AEFA76DC77740E7CA334DC8C60612BF6D6FA872 ___jobData0, int32_t ___arrayLength1, int32_t ___innerloopBatchCount2, JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 ___dependsOn3, const RuntimeMethod* method) { JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F V_0; memset((&V_0), 0, sizeof(V_0)); JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 V_1; memset((&V_1), 0, sizeof(V_1)); { void* L_0 = (( void* (*) (TransformBoundaryPositionsJob_t1AEFA76DC77740E7CA334DC8C60612BF6D6FA872 *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)->methodPointer)((TransformBoundaryPositionsJob_t1AEFA76DC77740E7CA334DC8C60612BF6D6FA872 *)(TransformBoundaryPositionsJob_t1AEFA76DC77740E7CA334DC8C60612BF6D6FA872 *)(&___jobData0), /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)); intptr_t L_1 = (( intptr_t (*) (const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)->methodPointer)(/*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)); JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 L_2 = ___dependsOn3; JobScheduleParameters__ctor_m09A522B620ED79BDFD86DE2544175159B6179E48((JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F *)(JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F *)(&V_0), (void*)(void*)L_0, (intptr_t)L_1, (JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 )L_2, (int32_t)1, /*hidden argument*/NULL); int32_t L_3 = ___arrayLength1; int32_t L_4 = ___innerloopBatchCount2; JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 L_5 = JobsUtility_ScheduleParallelFor_mD0B7FD9589FB242D9C4E21F93054C526FA6B1DBF((JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F *)(JobScheduleParameters_t55DC8564D72859191CE4E81639EFD25F6C6A698F *)(&V_0), (int32_t)L_3, (int32_t)L_4, /*hidden argument*/NULL); V_1 = (JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 )L_5; goto IL_0022; } IL_0022: { JobHandle_tDA498A2E49AEDE014468F416A8A98A6B258D73D1 L_6 = V_1; return L_6; } }
#include <VirtualWire.h> void setup() { vw_set_ptt_inverted(true); // Required by the RF module vw_setup(2000); // bps connection speed vw_set_tx_pin(3); // Arduino pin to connect the receiver data pin } void loop() { //Message to send: const char *msg = "HELLO WORLD"; vw_send((uint8_t *)msg, strlen(msg)); vw_wait_tx(); // We wait to finish sending the message delay(200); // We wait to send the message again }
// // main.cpp // course-schedule // // Created by xiedeping01 on 15/11/8. // Copyright (c) 2015年 xiedeping01. All rights reserved. // #include <iostream> #include <vector> using namespace std; class DirectedGraph { public: DirectedGraph(int n) : adj(n) {} void addEdge(int from, int to) { adj[from].push_back(to); } bool detectCycle() { int n = (int)adj.size(); vector<bool> visited(n); // 记录哪些节点已经被访问,遇到重复的节点则跳过处理 vector<bool> inpath(n); // 记录DFS路径上出现过的节点,遇到重复的节点则说明有环 for (int i = 0; i < n; i++) { // 不一定是连通图,每个点都要作为起点DFS一次 if (detectCycleUtil(i, visited, inpath)) return true; } return false; } private: bool detectCycleUtil(int root, vector<bool> &visited, vector<bool> &inpath) { if (visited[root]) return false; // 遇到被访问过的重复节点,跳过 if (inpath[root]) return true; // 遇到在dfs路径上的重复节点,说明出现环 inpath[root] = true; for (const auto next : adj[root]) { if (detectCycleUtil(next, visited, inpath)) return true; } inpath[root] = false; visited[root] = true; // 必须在最后设置visited return false; } private: vector<vector<int>> adj; }; class Solution { public: bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { // 本质上,相当于判断有向图中是否有环 // 如果有环,则不能完成所有课程 // corner case if (numCourses <= 0) return true; // build the graph DirectedGraph graph = buildGraph(numCourses, prerequisites); // detect cycle return !graph.detectCycle(); } private: DirectedGraph buildGraph(int n, vector<pair<int, int>> &edges) { DirectedGraph graph(n); for (const auto edge : edges) { graph.addEdge(edge.first, edge.second); } return graph; } }; int main(int argc, const char * argv[]) { int numCourses = 2; vector<pair<int, int>> prerequisites; prerequisites.push_back(make_pair(1, 0)); prerequisites.push_back(make_pair(0, 1)); std::cout << Solution().canFinish(numCourses, prerequisites); return 0; }
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// // Простая программа для запоминания таблицы умножения. // Simple program for storing multiplication tables. // V 2.3 beta refactoring // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// #include<iostream> #include "functions.h" int main() { using namespace std; cout.setf(ios::boolalpha); // Для вывода слов true/false char userSelection{'y'}; // Для продолжения или выхода из программы float allTry{}; // Подсчёт попыток float allFalse{}; // Подсчёт неудач cout << "Testing knowledge of the multiplication table" << endl; while (userSelection != 'n') { ++allTry; cout << randNums1() << " x " << randNums2() << " ? " << endl; int check{}; // Для сравнения check = randNums1() * randNums2(); // Вычисление int num{}; // Для ввода ответа пользователем cin >> num; if (cin.fail()) { // Проверка ввода числа cin.clear(); // Сброс состояния cout << "Insert the number!" << endl; break; } else { const bool answer{false}; // Для вывода результата if (num == check) { cout << !answer << endl; } else { cout << answer << endl; ++allFalse; } cout << "Press (y) to replay or any other key to exit" << endl; cin >> userSelection; // Проверка корректности ввода символа if (userSelection == 'y') { continue; } else { break; } } } computation(allTry, allFalse); return 0; } //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-// // END FILE //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
/* * audio.cpp * * Created on: Apr 14, 2012 * Author: edge87 */ #include <iostream> #include <SFML/Audio.hpp> #include "audio.hpp" sf::SoundBuffer Buffer1; sf::SoundBuffer Buffer2; sf::Sound Sound; void playTest(){ Sound.Stop(); if (!Buffer1.LoadFromFile("/home/teamheck/exec/media/sound/effect/boomattack.oga")) { std::cout << "Sound failed to load\n"; } Sound.SetBuffer(Buffer1); // Buffer is a sf::SoundBuffer Sound.Play(); }; void scream(){ Sound.Stop(); if (!Buffer2.LoadFromFile("/home/teamheck/exec/media/sound/effect/wilhelm.ogg")) { std::cout << "Sound failed to load\n"; } Sound.SetBuffer(Buffer2); // Buffer is a sf::SoundBuffer Sound.Play(); };
#pragma once /** * @file * @copyright (C) 2020 Anton Frolov johnjocoo@gmail.com */ #include "FreeRTOS/portable.h" void* os_raw_alloc(const unsigned int bytes) { return pvPortMalloc(bytes); } void os_raw_dealloc(void* mem) { if (mem == nullptr) { return; } vPortFree(mem); } template <typename T> T* os_alloc_n(const unsigned int number) { void* mem = pvPortMalloc(number * sizeof(T) + sizeof(unsigned int)); if (mem == nullptr) { return nullptr; } (*((unsigned int*)mem)) = number; mem = (void*)(((unsigned int*)mem) + 1); for (unsigned int i = 0; i < number; ++i) { new (((T*)mem) + i) T(); } return (T*)mem; } template <typename T, typename... Args> T* os_alloc(Args... args) { void* mem = pvPortMalloc(sizeof(T)); if (mem == nullptr) { return nullptr; } new ((T*)mem) T(args...); return (T*)mem; } template <typename T> void os_dealloc_n(T* objects) { if (objects == nullptr) { return; } const unsigned int number = *(((unsigned int*)objects) - 1); for (unsigned int i = number; i > 0; --i) { (objects + (i - 1))->~T(); } vPortFree((((unsigned int*)objects) - 1)); } template <typename T> void os_dealloc(T* object) { if (object == nullptr) { return; } object->~T(); vPortFree(object); }
/* * Copyright 2019 LogMeIn * * 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 * * http://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. * * SPDX-License-Identifier: Apache-2.0 */ #pragma once #include <memory> #include <string> #include "asyncly/ExecutorTypes.h" #include "asyncly/scheduler/SchedulerThread.h" namespace asyncly { namespace test { class SchedulerProviderNone { public: ISchedulerPtr get_scheduler() const { return ISchedulerPtr(); } }; template <class SchedulerImpl> class SchedulerProviderExternal { public: SchedulerProviderExternal() { schedulerThread_ = std::make_shared<SchedulerThread>( ThreadInitFunction{}, std::make_shared<SchedulerImpl>()); } virtual ~SchedulerProviderExternal() { if (schedulerThread_) { schedulerThread_->finish(); } } ISchedulerPtr get_scheduler() const { return schedulerThread_->get_scheduler(); } private: std::shared_ptr<SchedulerThread> schedulerThread_; }; } }
#include "Hooks.h" #include "framework.h" Hook* instance; Hook::Hook() { } Hook* Hook::getHook() { if (!instance) { instance = new Hook(); } return instance; } typedef void(WINAPI* AVKeyItem)(uint64_t key, bool isDown); AVKeyItem _AVKeyItem; const char* te = "48 89 5C 24 18 55 56 57 41 54 41 55 41 56 41 57 48 8D AC 24 E0 FE FF FF 48 81 EC 20 02 00 00 48 8B 05 AA"; void KeyItemCallback(uint64_t key, bool isDown) { bool cancel = false; Hook::getHook()->keys[key] = isDown; if (!cancel) _AVKeyItem(key, isDown); } typedef void(__fastcall* ChatHook)(void*, void*); ChatHook _ChatHook; uintptr_t ae = 0; void ChatCallback(void* a1, void* a2) { bool cancelSend = false; TextHolder* messageHolder = reinterpret_cast<TextHolder*>(a2); Command(messageHolder, &cancelSend); if (!cancelSend) _ChatHook(a1, messageHolder); } void Hook::Install() { MH_Initialize(); uintptr_t sigAddr = Mem::getMem()->findSig("48 89 5C 24 ?? ?? 48 83 EC ?? 8B 05 ?? ?? ?? ?? 8B DA"); if (sigAddr) { if (MH_CreateHook((void*)sigAddr, &KeyItemCallback, reinterpret_cast<LPVOID*>(&_AVKeyItem)) == MH_OK) { MH_EnableHook((void*)sigAddr); } else { } } sigAddr = Mem::getMem()->findSig(te); if (sigAddr) { if (MH_CreateHook((void*)sigAddr, &ChatCallback, reinterpret_cast<LPVOID*>(&_ChatHook)) == MH_OK) { MH_EnableHook((void*)sigAddr); } else { } } else { } } void Hook::Disable() { uintptr_t sigAddr = Mem::getMem()->findSig("48 89 5C 24 ?? ?? 48 83 EC ?? 8B 05 ?? ?? ?? ?? 8B DA"); MH_RemoveHook((LPVOID)sigAddr); sigAddr = Mem::getMem()->findSig(te); MH_RemoveHook((LPVOID)sigAddr); MH_Uninitialize(); }
#include <iostream> #include <stack> using namespace std; typedef long long ll; int n; ll x = 0, m, cnt; char c; stack <int> a; int main() { cin >> n; while(n--) { cin >> c; if(c == 'f') { cin >> m; if(a.empty()) { a.push(m); //printf("m = %lld\n", m); } else { cnt = a.top() * m; a.push(cnt); //printf("cnt = %lld\n", cnt); } } if(c == 'e' && !a.empty()) { a.pop(); //printf("x = %d\n", x); } if(c == '+') { if(!a.empty()) x = x + a.top(); else x++; //printf("CX = %lld\n", x); } } if(x >= 10000000) printf("Go Out!!!\n"); else printf("%lld\n", x); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- ** ** Copyright (C) 2007-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include <stdio.h> #include <sys/stat.h> #include <openssl/bio.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/x509.h> #include <openssl/pem.h> /* Main controller of the certificate repository builder */ #include "modules/rootstore/server/types.h" #include "modules/rootstore/server/api.h" #if !defined(ENABLE_V1_REPOSITORY) && defined IS_TEST_SERVER #define ENABLE_V1_REPOSITORY #endif #ifdef ENABLE_V1_REPOSITORY /* Configuration for version and key for v1 (debug) folder */ #define VERSION_1 "01" #define VERSION_NUM_1 0x01 #define VERSION_KEY_1 "tools/key.pem" #endif /* Configuration for version and key for v2 folder */ #define VERSION_2 "02" #define VERSION_NUM_2 0x02 #define VERSION_KEY_2 "tools/version02.key.pem" /* Configuration for version and key for v3 (default) folder, uses v2 key*/ #define VERSION_3 "03" #define VERSION_NUM_3 0x03 #define VERSION_KEY_3 "tools/version02.key.pem" // Target folder names #define FOLDER_TREE(VERSION) \ "output/" VERSION, \ "output/" VERSION "/roots", \ "output/" VERSION "/untrusted" // Target folders, expanded const char *folders[] = { "output", #ifdef ENABLE_V1_REPOSITORY FOLDER_TREE(VERSION_1), #endif FOLDER_TREE(VERSION_2), FOLDER_TREE(VERSION_3), NULL }; // Configuration of repository, version, keys and methods const struct config_list_st { const char *version_text; int version_num; const char *key_name; int sign_nid; } config_list[] = { #ifdef ENABLE_V1_REPOSITORY {VERSION_1, VERSION_NUM_1, VERSION_KEY_1, NID_sha256WithRSAEncryption}, #endif {VERSION_2, VERSION_NUM_2, VERSION_KEY_2, NID_sha256WithRSAEncryption}, {VERSION_3, VERSION_NUM_3, VERSION_KEY_3, NID_sha256WithRSAEncryption}, {NULL, 0, NULL, 0} }; /** Build the repositor */ int main() { OpenSSL_add_all_algorithms(); if(ERR_get_error()) return FALSE; BOOL ret = FALSE; EVP_PKEY *pkey = NULL; BIO *source = NULL; // Create target folders const char **fldrs = folders; while(*fldrs) { if(mkdir(*fldrs, 0755) != 0 && errno != EEXIST) return FALSE; fldrs++; } // For each configuration const config_list_st *cfg = config_list; while(cfg->key_name != NULL) { ret = FALSE; // Read the key file source = BIO_new_file(cfg->key_name, "r"); if(!source) break;; pkey = PEM_read_bio_PrivateKey(source, NULL, NULL, NULL); BIO_free(source); source = NULL; if(pkey == NULL) break; // Create the repository if(!CreateRepository(cfg->version_text, cfg->version_num, pkey, cfg->sign_nid)) break; // Produce the EV OID list if(!ProduceEVOID_XML_File(cfg->version_text, pkey, cfg->sign_nid)) break; if(ERR_get_error()) break; // Cleanup BIO_free(source); EVP_PKEY_free(pkey); source = NULL; pkey = NULL; printf ("Finished %s %s\n", cfg->version_text, cfg->key_name); ret = TRUE; cfg++; } // Clean up if(source) BIO_free(source); if(pkey) EVP_PKEY_free(pkey); EVP_cleanup(); return (ret ? 0 : 1); // 0 is OK in shell scripts }
#if OCAML_MINOR >= 8 let attributeTxt = (x: Parsetree.attribute) => x.attr_name.txt; #else let attributeTxt = (x: Parsetree.attribute) => fst(x).txt; #endif
/* * Copyright (c) 2015-2021 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_DETAIL_INPLACE_MERGE_H_ #define CPPSORT_DETAIL_INPLACE_MERGE_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <algorithm> #include <cstddef> #include <iterator> #include <utility> #include <cpp-sort/utility/as_function.h> #include "iterator_traits.h" #include "memory.h" #include "recmerge_bidirectional.h" #include "recmerge_forward.h" #include "symmerge.h" #include "type_traits.h" namespace cppsort { namespace detail { //////////////////////////////////////////////////////////// // Forward algorithm using recmerge template<typename ForwardIterator, typename RandomAccessIterator, typename Compare, typename Projection> auto inplace_merge(ForwardIterator first, ForwardIterator middle, ForwardIterator, Compare compare, Projection projection, difference_type_t<ForwardIterator> len1, difference_type_t<ForwardIterator> len2, RandomAccessIterator buff, std::ptrdiff_t buff_size, std::forward_iterator_tag) -> void { recmerge(std::move(first), len1, std::move(middle), len2, buff, buff_size, std::move(compare), std::move(projection)); } //////////////////////////////////////////////////////////// // Bidirectional algorithm using recmerge template<typename BidirectionalIterator, typename RandomAccessIterator, typename Compare, typename Projection> auto inplace_merge(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare compare, Projection projection, difference_type_t<BidirectionalIterator> len1, difference_type_t<BidirectionalIterator> len2, RandomAccessIterator buff, std::ptrdiff_t buff_size, std::bidirectional_iterator_tag tag) -> void { recmerge(std::move(first), std::move(middle), std::move(last), std::move(compare), std::move(projection), len1, len2, buff, buff_size, tag); } //////////////////////////////////////////////////////////// // Random-access algorithm using symmerge template<typename RandomAccessIterator1, typename RandomAccessIterator2, typename Compare, typename Projection> auto inplace_merge(RandomAccessIterator1 first, RandomAccessIterator1 middle, RandomAccessIterator1 last, Compare compare, Projection projection, difference_type_t<RandomAccessIterator1> len1, difference_type_t<RandomAccessIterator1> len2, RandomAccessIterator2 buff, std::ptrdiff_t buff_size, std::random_access_iterator_tag) -> void { symmerge(first, 0, middle - first, last - first, std::move(compare), std::move(projection), len1, len2, buff, buff_size); } //////////////////////////////////////////////////////////// // Intermediate functions allocating the memory buffer if // one wasn't passed template<typename ForwardIterator, typename Compare, typename Projection> auto inplace_merge(ForwardIterator first, ForwardIterator middle, ForwardIterator last, Compare compare, Projection projection, std::forward_iterator_tag) -> void { auto&& comp = utility::as_function(compare); auto&& proj = utility::as_function(projection); // Shrink the problem size on the left side, makes the // size computation potentially cheaper while (first != middle && not comp(proj(*middle), proj(*first))) { ++first; } if (first == middle) return; auto n0 = std::distance(first, middle); auto n1 = std::distance(middle, last); auto buffer = temporary_buffer<rvalue_type_t<ForwardIterator>>((std::max)(n0, n1)); recmerge(std::move(first), n0, std::move(middle), n1, buffer.data(), buffer.size(), std::move(compare), std::move(projection)); } template<typename BidirectionalIterator, typename Compare, typename Projection> auto inplace_merge(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare compare, Projection projection, difference_type_t<BidirectionalIterator> len1, difference_type_t<BidirectionalIterator> len2, std::bidirectional_iterator_tag) -> void { temporary_buffer<rvalue_type_t<BidirectionalIterator>> buffer((std::min)(len1, len2)); using category = iterator_category_t<BidirectionalIterator>; inplace_merge(std::move(first), std::move(middle), std::move(last), std::move(compare), std::move(projection), len1, len2, buffer.data(), buffer.size(), category{}); } template<typename BidirectionalIterator, typename Compare, typename Projection> auto inplace_merge(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare compare, Projection projection, std::bidirectional_iterator_tag) -> void { using category = iterator_category_t<BidirectionalIterator>; auto&& comp = utility::as_function(compare); auto&& proj = utility::as_function(projection); // Shrink the problem size on the left side, makes the // size computation potentially cheaper while (first != middle && not comp(proj(*middle), proj(*first))) { ++first; } if (first == middle) return; auto len1 = std::distance(first, middle); auto len2 = std::distance(middle, last); temporary_buffer<rvalue_type_t<BidirectionalIterator>> buffer((std::min)(len1, len2)); inplace_merge(std::move(first), std::move(middle), std::move(last), std::move(compare), std::move(projection), len1, len2, buffer.data(), buffer.size(), category{}); } //////////////////////////////////////////////////////////// // Generic inplace_merge interfaces // Unbuffered overload, defers the buffer allocation to a specific // function depending on the iterator category template<typename ForwardIterator, typename Compare, typename Projection> auto inplace_merge(ForwardIterator first, ForwardIterator middle, ForwardIterator last, Compare compare, Projection projection) -> void { using category = iterator_category_t<ForwardIterator>; inplace_merge(std::move(first), std::move(middle), std::move(last), std::move(compare), std::move(projection), category{}); } template<typename BidirectionalIterator, typename Compare, typename Projection> auto inplace_merge(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare compare, Projection projection, difference_type_t<BidirectionalIterator> len1, difference_type_t<BidirectionalIterator> len2) -> void { using category = iterator_category_t<BidirectionalIterator>; inplace_merge(std::move(first), std::move(middle), std::move(last), std::move(compare), std::move(projection), len1, len2, category{}); } // Buffered overload, which also happens to take the length of the // subranges, allowing not to cross the whole range to compute them // from time to time template<typename ForwardIterator, typename RandomAccessIterator, typename Compare, typename Projection> auto inplace_merge(ForwardIterator first, ForwardIterator middle, ForwardIterator last, Compare compare, Projection projection, difference_type_t<ForwardIterator> len1, difference_type_t<ForwardIterator> len2, RandomAccessIterator buff, std::ptrdiff_t buff_size) -> void { using category = iterator_category_t<ForwardIterator>; inplace_merge(std::move(first), std::move(middle), std::move(last), std::move(compare), std::move(projection), len1, len2, buff, buff_size, category{}); } }} #endif // CPPSORT_DETAIL_INPLACE_MERGE_H_