hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
db2b3ad9178c762b697722051647f74d045c27f5
2,196
cpp
C++
solutions/1198/memory_allocating.cpp
buptlxb/hihoCoder
1995bdfda29d4dab98c002870ef0bc138bc37ce7
[ "Apache-2.0" ]
44
2016-05-11T06:41:14.000Z
2021-12-20T13:45:41.000Z
solutions/1198/memory_allocating.cpp
buptlxb/hihoCoder
1995bdfda29d4dab98c002870ef0bc138bc37ce7
[ "Apache-2.0" ]
null
null
null
solutions/1198/memory_allocating.cpp
buptlxb/hihoCoder
1995bdfda29d4dab98c002870ef0bc138bc37ce7
[ "Apache-2.0" ]
10
2016-06-25T08:55:20.000Z
2018-07-06T05:52:53.000Z
#include <iostream> #include <vector> #include <cassert> #include <algorithm> using namespace std; struct Chunk{ int key; int length; Chunk *prev; Chunk *next; Chunk(int k=0, int len=0) : key(k), length(len), prev(nullptr), next(nullptr) {} } *head; void init(int m) { Chunk *t = new Chunk(0, m); t->next = new Chunk(-1, 0); t->prev = new Chunk(-1, 0); t->next->prev = t; t->prev->next = t; head = t->prev; } Chunk *find_empty(int len) { Chunk *p = head->next; for (Chunk *p = head->next; p->key != -1; p = p->next) { if (p->key == 0 && p->length >= len) return p; } return nullptr; } void insert(Chunk *p, int key, int len) { assert(p->key == 0 && p->length >= len); if (p->length == len) p->key = key; else { Chunk *t = new Chunk(0, p->length-len); t->prev = p; t->next = p->next; t->next->prev = t; p->next = t; p->key = key; p->length = len; } } void release(Chunk *p) { Chunk *t = p->prev; if (t->key == 0) { p->length += t->length; p->prev = t->prev; p->prev->next = p; delete t; } t = p->next; if (t->key == 0) { p->length += t->length; p->next = t->next; p->next->prev = p; delete t; } p->key = 0; } int main(void) { int n, m; cin >> n >> m; init(m); vector<Chunk *> pos(n+1); for (int i = 1, last = 1; i <= n; ++i) { int k; cin >> k; while (true) { Chunk *p = find_empty(k); if (p) { insert(p, i, k); pos[i] = p; break; } else { release(pos[last]); pos[last++] = nullptr; } } } vector<pair<int, int>> res; int last = 0; for (Chunk *p = head->next; p->key != -1; p = p->next) { if (p->key) res.push_back(make_pair(p->key, last)); last += p->length; } sort(res.begin(), res.end()); for (auto &pr : res) cout << pr.first << " " << pr.second << '\n'; cout << flush; return 0; }
20.523364
84
0.435337
buptlxb
db2b633908571f8cbac6a03474dfd7c0878540d1
4,816
cpp
C++
core/ir/Input.cpp
p1x31/TRTorch
f99a6ca763eb08982e8b7172eb948a090bcbf11c
[ "BSD-3-Clause" ]
944
2020-03-13T22:50:32.000Z
2021-11-09T05:39:28.000Z
core/ir/Input.cpp
p1x31/TRTorch
f99a6ca763eb08982e8b7172eb948a090bcbf11c
[ "BSD-3-Clause" ]
434
2020-03-18T03:00:29.000Z
2021-11-09T00:26:36.000Z
core/ir/Input.cpp
p1x31/TRTorch
f99a6ca763eb08982e8b7172eb948a090bcbf11c
[ "BSD-3-Clause" ]
106
2020-03-18T02:20:21.000Z
2021-11-08T18:58:58.000Z
#include "core/ir/ir.h" #include "core/util/prelude.h" namespace trtorch { namespace core { namespace ir { bool valid_dtype_format_combo(nvinfer1::DataType dtype, nvinfer1::TensorFormat format) { switch (dtype) { case nvinfer1::DataType::kINT8: // Supports just Linear (NCHW) switch (format) { case nvinfer1::TensorFormat::kLINEAR: return true; case nvinfer1::TensorFormat::kHWC: default: return false; } case nvinfer1::DataType::kINT32: // Supports just Linear (NCHW) switch (format) { case nvinfer1::TensorFormat::kLINEAR: return true; case nvinfer1::TensorFormat::kHWC: default: return false; } case nvinfer1::DataType::kHALF: // Supports just Linear (NCHW) switch (format) { case nvinfer1::TensorFormat::kLINEAR: return true; case nvinfer1::TensorFormat::kHWC: default: return false; } case nvinfer1::DataType::kFLOAT: // Supports both Linear (NCHW) and channel last (NHWC) switch (format) { case nvinfer1::TensorFormat::kLINEAR: return true; case nvinfer1::TensorFormat::kHWC: return true; default: return false; } default: return false; } } bool valid_input_dtype(nvinfer1::DataType dtype) { switch (dtype) { case nvinfer1::DataType::kBOOL: return false; case nvinfer1::DataType::kFLOAT: return true; case nvinfer1::DataType::kHALF: return true; case nvinfer1::DataType::kINT8: return true; case nvinfer1::DataType::kINT32: return true; default: return false; } } Input::Input( std::vector<int64_t> shape, nvinfer1::DataType dtype, nvinfer1::TensorFormat format, bool dtype_is_user_defined) { if (shape.size() > 5) { LOG_WARNING("Verify that this dim size is accepted"); } opt = util::toDims(shape); min = util::toDims(shape); max = util::toDims(shape); input_shape = util::toDims(shape); input_is_dynamic = false; TRTORCH_CHECK(valid_input_dtype(dtype), "Unsupported input data type: " << dtype); this->dtype = dtype; TRTORCH_CHECK( valid_dtype_format_combo(dtype, format), "Unsupported combination of dtype and tensor format: (" << dtype << ", " << format << "), TRTorch only supports contiguous format (NCHW) except with input type Float32 where channel last (NHWC) is also supported"); this->format = format; this->dtype_is_user_defined = dtype_is_user_defined; } Input::Input( std::vector<int64_t> min_shape, std::vector<int64_t> opt_shape, std::vector<int64_t> max_shape, nvinfer1::DataType dtype, nvinfer1::TensorFormat format, bool dtype_is_user_defined) { if (min_shape.size() > 5 || opt_shape.size() > 5 || max_shape.size() > 5) { LOG_WARNING("Verify that this dim size is accepted"); } std::set<size_t> sizes; sizes.insert(min_shape.size()); sizes.insert(opt_shape.size()); sizes.insert(max_shape.size()); if (sizes.size() != 1) { LOG_ERROR( "Expected all input sizes have the same dimensions, but found dimensions: min(" << min_shape.size() << "), opt(" << opt_shape.size() << "), max(" << max_shape.size() << ")"); } min = util::toDims(min_shape); opt = util::toDims(opt_shape); max = util::toDims(max_shape); std::vector<int64_t> dyn_shape; for (size_t i = 0; i < opt_shape.size(); i++) { std::set<uint64_t> dim; dim.insert(min_shape[i]); dim.insert(opt_shape[i]); dim.insert(max_shape[i]); if (dim.size() != 1) { dyn_shape.push_back(-1); input_is_dynamic = true; } else { dyn_shape.push_back(opt_shape[i]); } } input_shape = util::toDims(dyn_shape); TRTORCH_CHECK(valid_input_dtype(dtype), "Unsupported input data type: " << dtype); this->dtype = dtype; TRTORCH_CHECK( valid_dtype_format_combo(dtype, format), "Unsupported combination of dtype and tensor format: (" << dtype << ", " << format << "), TRTorch only supports contiguous format (NCHW) except with input type Float32 where channel last (NHWC) is also supported"); this->format = format; this->dtype_is_user_defined = dtype_is_user_defined; } std::ostream& operator<<(std::ostream& os, const Input& input) { if (!input.input_is_dynamic) { os << "Input(shape: " << input.input_shape << ", dtype: " << input.dtype << ", format: " << input.format << ')'; } else { os << "Input(shape: " << input.input_shape << ", min: " << input.min << ", opt: " << input.opt << ", max: " << input.max << ", dtype: " << input.dtype << ", format: " << input.format << ')'; } return os; } } // namespace ir } // namespace core } // namespace trtorch
30.871795
141
0.628322
p1x31
db2ce47578fab663169f7642a491179678fadcf2
361
cpp
C++
2018/src/j1.cpp
Kytabyte/CCC
6f98e81c7fef38bf70e68188db38863cc0cba2f4
[ "Apache-2.0" ]
8
2020-12-13T01:29:14.000Z
2022-02-15T09:02:27.000Z
2018/src/j1.cpp
Kytabyte/CCC
6f98e81c7fef38bf70e68188db38863cc0cba2f4
[ "Apache-2.0" ]
null
null
null
2018/src/j1.cpp
Kytabyte/CCC
6f98e81c7fef38bf70e68188db38863cc0cba2f4
[ "Apache-2.0" ]
2
2021-02-05T19:59:33.000Z
2021-09-14T23:25:52.000Z
#include <bits/stdc++.h> using namespace std; /** * Marks: 15/15 */ int digits[4]; int main() { for (int i = 0; i < 4; i++) { scanf("%d", &digits[i]); } if (digits[0] != 8 && digits[0] != 9 || digits[3] != 8 && digits[3] != 9 || digits[1] != digits[2]) { cout << "answer" << endl; } else { cout << "ignore" << endl; } return 0; }
15.695652
103
0.470914
Kytabyte
db2f038fba09c6f17406382ca0b25affad1a7e03
797
cpp
C++
Merge Nodes in Between Zeros.cpp
dishanp/Coding-In-C-and-C-
889985ac136826cf9be88d6c5455f79fd805a069
[ "BSD-2-Clause" ]
2
2021-10-01T04:20:04.000Z
2021-10-01T04:20:06.000Z
Merge Nodes in Between Zeros.cpp
dishanp/Coding-In-C-and-C-
889985ac136826cf9be88d6c5455f79fd805a069
[ "BSD-2-Clause" ]
null
null
null
Merge Nodes in Between Zeros.cpp
dishanp/Coding-In-C-and-C-
889985ac136826cf9be88d6c5455f79fd805a069
[ "BSD-2-Clause" ]
8
2021-10-01T04:20:38.000Z
2022-03-19T17:05:05.000Z
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeNodes(ListNode* head) { ListNode* p=head; p=p->next; ListNode* l=new ListNode(0); ListNode* res=l; int sum=0; while(p){ if(p->val!=0) { sum+=p->val; } else{ ListNode* temp=new ListNode(sum); l->next=temp; l=l->next; sum=0; } p=p->next; } return res->next; } };
22.771429
62
0.430364
dishanp
db2f6ebce9b568be81e7fa60d41c9646f0761a96
3,627
cpp
C++
app/main.cpp
KPO-2020-2021/zad4-KrystianCyga
f055e0f13052646f8b55bc6a4b1f94ebce9db84a
[ "Unlicense" ]
null
null
null
app/main.cpp
KPO-2020-2021/zad4-KrystianCyga
f055e0f13052646f8b55bc6a4b1f94ebce9db84a
[ "Unlicense" ]
null
null
null
app/main.cpp
KPO-2020-2021/zad4-KrystianCyga
f055e0f13052646f8b55bc6a4b1f94ebce9db84a
[ "Unlicense" ]
null
null
null
#include <iostream> #include <iomanip> #include <fstream> #include "vector.hh" #include "matrix.hh" #include "Prostopadloscian.hh" #include "lacze_do_gnuplota.hh" #include <string> #include <unistd.h> #include <stdlib.h> Vector<double, 3> VecPrzesu; Matrix<3> MROT; Prostopadloscian<double> cuboid; PzG::LaczeDoGNUPlota Lacze; void menu(); int main() { if (!cuboid.wczytaj("../datasets/orginalny.dat")) { std::cerr << "Nie udalo sie wczytac prostopadloscianu!!!\n"; } cuboid.boki(); cuboid.zapis("../datasets/anim.dat"); Lacze.DodajNazwePliku("../datasets/anim.dat", PzG::RR_Ciagly, 2); Lacze.ZmienTrybRys(PzG::TR_3D); Lacze.UstawZakresY(-155, 155); Lacze.UstawZakresX(-155, 155); Lacze.UstawZakresZ(-155, 155); Lacze.Rysuj(); std::cout << "Naciśnij ENTER, aby kontynuowac" << std::endl; std::cin.ignore(10000, '\n'); menu(); } void menu() { char wyb; std::cout << "\n" << "************************MENU************************\n"; std::cout << " o-obrot bryly o zadany kat wzgledem danej osi\n"; std::cout << " p-przesuniecie o dany wektor\n"; std::cout << " w-wyswietlenie wspolrzednych wierzcholkow\n"; std::cout << " m-powrot do menu\n"; std::cout << " k-koniec dzialania programu\n"; std::cout << " r-Rysuj prostokat w Gnuplocie\n"; std::cout << " t-wyswietlenie macierzy rotacji\n"; std::cout << " Twoj wybor -> :"; std::cin >> wyb; std::cout << "\n"; switch (wyb) { case 'o': char os; double kat, ilosc; std::cout << "Podaj kat obrotu: "; std::cin >> kat; std::cout << "Podaj ilosc operacji: "; std::cin >> ilosc; std::cout << "Podaj os operacji: "; std::cin >> os; MROT.Mobrot3D_tworzenie(kat, os); if (ilosc > 1 && ilosc <= 720) { Lacze.Rysuj(); usleep(2000000); for (int i = 0; i < ilosc; i++) { cuboid.obrot(kat, 1, os); cuboid.zapis("../datasets/anim.dat"); Lacze.Rysuj(); int czas = 10000000 / ilosc; usleep(czas); } } else { cuboid.obrot(kat, ilosc, os); cuboid.zapis("../datasets/anim.dat"); Lacze.Rysuj(); } break; case 'p': std::cout << "Podaj wektor przesuniecia (x) (y) (z): "; std::cin >> VecPrzesu; cuboid.owektor(VecPrzesu); std::cout << cuboid; break; case 'w': std::cout << cuboid; break; case 'r': cuboid.boki(); cuboid.zapis("../datasets/anim.dat"); Lacze.Rysuj(); break; case 't': std::cout << MROT; break; case 'm': return menu(); break; case 'k': std::cout << "Koniec dzialania programu.\n "; return; break; default: std::cout << "Zly wybor !!! \n"; std::cout << "Mozliwe to o,r,p,w,m,k,t\n"; break; } return menu(); }
25.723404
77
0.435897
KPO-2020-2021
db3228a6c5035e62578eb8bff186b13d000858bf
1,746
cpp
C++
main.cpp
CaptainDreamcast/Torchbearer
144a1d8eca66e994dc832fc4116431ea267e00d9
[ "MIT" ]
null
null
null
main.cpp
CaptainDreamcast/Torchbearer
144a1d8eca66e994dc832fc4116431ea267e00d9
[ "MIT" ]
null
null
null
main.cpp
CaptainDreamcast/Torchbearer
144a1d8eca66e994dc832fc4116431ea267e00d9
[ "MIT" ]
null
null
null
#include <prism/framerateselectscreen.h> #include <prism/physics.h> #include <prism/file.h> #include <prism/drawing.h> #include <prism/log.h> #include <prism/wrapper.h> #include <prism/system.h> #include <prism/stagehandler.h> #include <prism/logoscreen.h> #include <prism/mugentexthandler.h> #include <prism/debug.h> #include "gamescreen.h" #include "datingscreen.h" #include "bars.h" #include "storyhandler.h" #include "storyscreen.h" #ifdef DREAMCAST KOS_INIT_FLAGS(INIT_DEFAULT); extern uint8 romdisk[]; KOS_INIT_ROMDISK(romdisk); #endif // #define DEVELOP void exitGame() { shutdownPrismWrapper(); #ifdef DEVELOP if (isOnDreamcast()) { abortSystem(); } else { returnToMenu(); } #else returnToMenu(); #endif } int main(int argc, char** argv) { (void)argc; (void)argv; #ifdef DEVELOP setDevelopMode(); #endif setGameName("OlympicTorchCarrier"); setScreenSize(320, 240); initPrismWrapperWithConfigFile("data/config.cfg"); setFont("$/rd/fonts/segoe.hdr", "$/rd/fonts/segoe.pkg"); addMugenFont(-1, "font/f4x6.fnt"); addMugenFont(1, "font/f6x9.fnt"); addMugenFont(2, "font/jg.fnt"); logg("Check framerate"); FramerateSelectReturnType framerateReturnType = selectFramerate(); if (framerateReturnType == FRAMERATE_SCREEN_RETURN_ABORT) { exitGame(); } if(isInDevelopMode()) { ScreenSize sz = getScreenSize(); // setDisplayedScreenSize(sz.x, sz.y); disableWrapperErrorRecovery(); setMinimumLogType(LOG_TYPE_NORMAL); } else { setMinimumLogType(LOG_TYPE_NONE); } resetBarValues(); setScreenAfterWrapperLogoScreen(getLogoScreenFromWrapper()); setStoryHandlerPath("story/1.def"); setCurrentStoryDefinitionFile("INTRO"); startScreenHandling(getStoryScreen()); exitGame(); return 0; }
19.186813
67
0.733677
CaptainDreamcast
db392ef179cff39ac26e263071c12e1e08373dc6
1,792
cpp
C++
src/VPetLCD/Screens/ProgressBarScreen.cpp
Perchindroid/DigimonVPet
75ae638fb19a5b5d7073589734aa43f8a20813a4
[ "MIT" ]
23
2021-02-17T06:37:42.000Z
2022-03-31T23:16:39.000Z
src/VPetLCD/Screens/ProgressBarScreen.cpp
Perchindroid/DigimonVPet
75ae638fb19a5b5d7073589734aa43f8a20813a4
[ "MIT" ]
3
2021-03-09T14:39:48.000Z
2022-03-22T12:27:52.000Z
src/VPetLCD/Screens/ProgressBarScreen.cpp
Perchindroid/DigimonVPet
75ae638fb19a5b5d7073589734aa43f8a20813a4
[ "MIT" ]
13
2021-03-23T05:35:32.000Z
2022-03-21T12:01:38.000Z
///////////////////////////////////////////////////////////////// /* Created by Berat Özdemir, January 24 , 2021. */ ///////////////////////////////////////////////////////////////// #include "ProgressBarScreen.h" V20::ProgressBarScreen::ProgressBarScreen(char _text[], uint16_t _barLength, uint16_t _fillPercentage){ int textlength = strlen(_text); char *buf = new char[textlength+1]; strcpy(buf,_text); text=buf; barLength=_barLength; fillPercentage=_fillPercentage; }; void V20::ProgressBarScreen::draw(VPetLCD *lcd){ lcd->drawCharArrayOnLCD(text, screenX, 0, pixelColor); lcd->drawPixelOnLCD( screenX, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 1, pixelColor); lcd->drawPixelOnLCD( screenX + barLength / 2 + 1, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 1, pixelColor); lcd->drawPixelOnLCD( screenX + barLength + 1, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 1, pixelColor); for (int i = 1; i <= barLength; i++) { lcd->drawPixelOnLCD(i + screenX, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 2, pixelColor); lcd->drawPixelOnLCD(i + screenX, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 2 + 5, pixelColor); } for (int i = 0; i < 4; i++) { lcd->drawPixelOnLCD( screenX, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 3 + i, pixelColor); lcd->drawPixelOnLCD( screenX + barLength + 1, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 3 + i, pixelColor); } uint16_t maxFill = barLength / 2; uint16_t percentageBars = fillPercentage * maxFill / 100; for (int i = 1; i <= percentageBars; i++) { lcd->drawPixelOnLCD( screenX + i * 2, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 4, pixelColor); lcd->drawPixelOnLCD( screenX + i * 2, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 5, pixelColor); } }
35.84
115
0.661272
Perchindroid
db3eef4d69ec56893bb291897520af8ad9d5b3e5
6,892
hh
C++
python/dune/xt/functions/interfaces/grid-function.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
2
2020-02-08T04:08:52.000Z
2020-08-01T18:54:14.000Z
python/dune/xt/functions/interfaces/grid-function.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
35
2019-08-19T12:06:35.000Z
2020-03-27T08:20:39.000Z
python/dune/xt/functions/interfaces/grid-function.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
1
2020-02-08T04:09:34.000Z
2020-02-08T04:09:34.000Z
// This file is part of the dune-xt project: // https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt // Copyright 2009-2021 dune-xt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2020) // René Fritze (2020) // // (http://opensource.org/licenses/BSD-2-Clause) #ifndef PYTHON_DUNE_XT_FUNCTIONS_INTERFACES_GRID_FUNCTION_HH #define PYTHON_DUNE_XT_FUNCTIONS_INTERFACES_GRID_FUNCTION_HH #include <dune/pybindxi/pybind11.h> #include <dune/xt/common/string.hh> #include <dune/xt/functions/interfaces/grid-function.hh> #include <dune/xt/functions/visualization.hh> #include <dune/xt/grid/gridprovider/provider.hh> #include <python/dune/xt/common/parameter.hh> namespace Dune::XT::Functions::bindings { template <class G, class E, size_t r = 1, size_t rC = 1, class R = double> class GridFunctionInterface { using GP = XT::Grid::GridProvider<G>; static constexpr size_t d = G::dimension; template <bool vector = (r != 1 && rC == 1), bool matrix = (rC != 1), bool anything = false> struct product_helper // <true, false, ...> { template <class T, typename... options> static void addbind(pybind11::class_<T, options...>& c) { namespace py = pybind11; c.def( "__mul__", [](const T& self, const Functions::GridFunctionInterface<E, r, 1, R>& other) { return std::make_unique<decltype(self * other)>(self * other); }, py::is_operator()); } }; template <bool anything> struct product_helper<false, true, anything> { template <class T, typename... options> static void addbind(pybind11::class_<T, options...>& c) { namespace py = pybind11; c.def( "__mul__", [](const T& self, const Functions::GridFunctionInterface<E, rC, 1, R>& other) { return std::make_unique<decltype(self * other)>(self * other); }, py::is_operator()); c.def( "__mul__", [](const T& self, const Functions::GridFunctionInterface<E, rC, 2, R>& other) { return std::make_unique<decltype(self * other)>(self * other); }, py::is_operator()); c.def( "__mul__", [](const T& self, const Functions::GridFunctionInterface<E, rC, 3, R>& other) { return std::make_unique<decltype(self * other)>(self * other); }, py::is_operator()); } }; template <bool scalar = (r == 1 && rC == 1), bool anything = false> struct fraction_helper // <true, ...> { template <class T, typename... options> static void addbind(pybind11::class_<T, options...>& c) { namespace py = pybind11; c.def( "__truediv__", [](const T& self, const type& other) { return std::make_unique<decltype(other / self)>(other / self); }, py::is_operator()); } }; template <bool anything> struct fraction_helper<false, anything> { template <class T, typename... options> static void addbind(pybind11::class_<T, options...>& /*c*/) {} }; public: using type = Functions::GridFunctionInterface<E, r, rC, R>; using bound_type = pybind11::class_<type>; static std::string class_name(const std::string& grid_id, const std::string& layer_id, const std::string& class_id) { std::string ret = class_id; ret += "_" + grid_id; if (!layer_id.empty()) ret += "_" + layer_id; ret += "_to_" + Common::to_string(r); if (rC > 1) ret += "x" + Common::to_string(rC); ret += "d"; if (!std::is_same<R, double>::value) ret += "_" + Common::Typename<R>::value(/*fail_wo_typeid=*/true); return ret; } // ... class_name(...) template <class T, typename... options> static void addbind_methods(pybind11::class_<T, options...>& c) { namespace py = pybind11; using namespace pybind11::literals; // our methods c.def( "visualize", [](const T& self, const GP& grid_provider, const std::string& filename, const bool subsampling) { Functions::visualize(self, grid_provider.leaf_view(), filename, subsampling); }, "grid"_a, "filename"_a, "subsampling"_a = true); // our operators c.def( "__add__", [](const T& self, const type& other) { return std::make_unique<decltype(self + other)>(self + other); }, py::is_operator()); c.def( "__sub__", [](const T& self, const type& other) { return std::make_unique<decltype(self - other)>(self - other); }, py::is_operator()); // we can always multiply with a scalar from the right ... c.def( "__mul__", [](const T& self, const Functions::GridFunctionInterface<E, 1, 1, R>& other) { return std::make_unique<decltype(self * other)>(self * other); }, py::is_operator()); // .. and with lots of other dims product_helper<>::addbind(c); fraction_helper<>::addbind(c); if constexpr (r == 1 && rC == 1) c.def( "__pow__", [](const T& self) { return std::make_unique<decltype(self * self)>(self * self); }, py::is_operator()); // ParametricInterface methods c.def( "parse_parameter", [](const T& self, const Common::Parameter& mu) { return self.parse_parameter(mu); }, "mu"_a); } // ... addbind_methods(...) static bound_type bind(pybind11::module& m, const std::string& grid_id, const std::string& layer_id = "", const std::string& class_id = "grid_function_interface") { using namespace pybind11::literals; const auto ClassName = Common::to_camel_case(class_name(grid_id, layer_id, class_id)); bound_type c(m, ClassName.c_str(), Common::to_camel_case(class_id).c_str()); // our properties c.def_property_readonly("dim_domain", [](type&) { return size_t(d); }); if (rC == 1) c.def_property_readonly("dim_range", [](type&) { return size_t(r); }); else c.def_property_readonly("dim_range", [](type&) { return std::make_pair(size_t(r), size_t(rC)); }); c.def_property_readonly("name", [](type& self) { return self.name(); }); // ParametricInterface properties c.def_property_readonly("is_parametric", [](type& self) { return self.is_parametric(); }); c.def_property_readonly("parameter_type", [](type& self) { return self.parameter_type(); }); addbind_methods(c); return c; } }; // class GridFunctionInterface } // namespace Dune::XT::Functions::bindings #endif // PYTHON_DUNE_XT_FUNCTIONS_INTERFACES_GRID_FUNCTION_HH
34.633166
120
0.613755
dune-community
b9cc6a75f6fc587a1942fd227445cd200057bad5
1,492
cpp
C++
027-occlusion-query/HUD027.cpp
michalbb1/opengl4-tutorials-mbsoftworks
ddd5ac157173ccbac5baf864afa34ecb372e2f8a
[ "MIT" ]
51
2018-06-01T05:05:20.000Z
2022-03-03T16:10:20.000Z
027-occlusion-query/HUD027.cpp
michalbb1/opengl4-tutorials-mbsoftworks
ddd5ac157173ccbac5baf864afa34ecb372e2f8a
[ "MIT" ]
null
null
null
027-occlusion-query/HUD027.cpp
michalbb1/opengl4-tutorials-mbsoftworks
ddd5ac157173ccbac5baf864afa34ecb372e2f8a
[ "MIT" ]
16
2019-04-03T04:35:29.000Z
2022-02-16T01:27:00.000Z
// STL #include <mutex> // Project #include "HUD027.h" #include "../common_classes/ostreamUtils.h" using namespace ostream_utils; HUD027::HUD027(const OpenGLWindow& window) : HUD(window) { static std::once_flag prepareOnceFlag; std::call_once(prepareOnceFlag, []() { FreeTypeFontManager::getInstance().loadSystemFreeTypeFont(DEFAULT_FONT_KEY, "arial.ttf", 24); }); } void HUD027::renderHUD(size_t numObjects, size_t numVisibleObjects, bool isWireframeModeOn, bool visualizeOccluders) const { printBuilder().print(10, 10, "FPS: {}", _window.getFPS()); printBuilder().print(10, 40, "Vertical Synchronization: {} (Press F3 to toggle)", _window.isVerticalSynchronizationEnabled() ? "On" : "Off"); // Calculate percentage of visible objects auto visiblePercentage = 0.0f; if(numObjects > 0) { visiblePercentage = 100.0f * static_cast<float>(numVisibleObjects) / numObjects; } // Print information about wireframe mode and occlusion query statistics printBuilder().print(10, 70, "Wireframe mode: {} (Press 'X' to toggle)", isWireframeModeOn ? "On" : "Off"); printBuilder().print(10, 100, "Visualize occluders: {} (Press 'C' to toggle)", visualizeOccluders ? "On" : "Off"); printBuilder().print(10, 130, " - Visible / total objects: {} / {} ({}%)", numVisibleObjects, numObjects, visiblePercentage); printBuilder() .fromRight() .fromBottom() .print(10, 10, "www.mbsoftworks.sk"); }
34.697674
145
0.677614
michalbb1
b9cd0c71089bfd47e0d6072a1b5a08fd60a346f6
2,982
cpp
C++
src/core/shadow/DirectionalShadow.cpp
Dreambee0123/render-engine
a82b79dd39f12c3dbaacbd1ac700fb6969532f4c
[ "MIT" ]
1
2021-11-25T11:15:37.000Z
2021-11-25T11:15:37.000Z
src/core/shadow/DirectionalShadow.cpp
Dreambee0123/render-engine
a82b79dd39f12c3dbaacbd1ac700fb6969532f4c
[ "MIT" ]
null
null
null
src/core/shadow/DirectionalShadow.cpp
Dreambee0123/render-engine
a82b79dd39f12c3dbaacbd1ac700fb6969532f4c
[ "MIT" ]
6
2020-03-09T12:37:26.000Z
2020-04-01T16:55:33.000Z
// // Created by Krisu on 2020/3/13. // #include "DirectionalShadow.hpp" #include "Renderer.hpp" #include "Mesh.hpp" #include "Scene.hpp" #include "Transform.hpp" DirectionalShadow::DirectionalShadow(const int map_width, const int map_height) : width(map_width), height(map_height) { glGenFramebuffers(1, &depthMapFBO); glGenTextures(1, &depthMap); glBindTexture(GL_TEXTURE_2D, depthMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0); glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { throw std::runtime_error("Shadow map frame buffer not complete"); } } void DirectionalShadow::GenerateShadowMap(const glm::vec3 &position, const glm::vec3 &direction, float cone_in_degree) { glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO); glViewport(0, 0, width, height); glClear(GL_DEPTH_BUFFER_BIT); static Shader shadowGenShader {"shader/shadow-mapping/directional-shadow.vert", "shader/shadow-mapping/directional-shadow.frag"}; glm::mat4 lightProjection = glm::ortho<float>( -10, 10, -10, 10, 1.0, 100 ); static const glm::vec3 global_up {0, 1, 0}; glm::vec3 right = glm::cross(direction, global_up); glm::vec3 up = glm::cross(right, direction); glm::mat4 lightView = glm::lookAt(position, direction, up); this->lightSpaceTransform = lightProjection * lightView; shadowGenShader.UseShaderProgram(); shadowGenShader.Set("lightSpaceTransform", lightSpaceTransform); glCullFace(GL_FRONT); // fix peter panning /* Rendering scene at light's space */ auto& scene = Engine::GetInstance().GetCurrentScene(); for (auto& up_game_obj : scene.GetListOfObeject()) { try { auto& mesh = up_game_obj->GetComponent<Mesh>(); auto& transform = up_game_obj->GetComponent<Transform>(); shadowGenShader.Set("model", transform.GetMatrix()); mesh.DrawCall(); } catch (NoComponent &) { continue; } } glCullFace(GL_BACK); glBindFramebuffer(GL_FRAMEBUFFER, 0); Engine::GetInstance().GetRenderer().ResetViewport(); } DirectionalShadow::~DirectionalShadow() { glDeleteBuffers(1, &depthMapFBO); glDeleteTextures(1, &depthMap); }
35.927711
91
0.680751
Dreambee0123
b9cd2302411dfa98e87b197b88213cb543802202
5,637
hpp
C++
src/3rd party/boost/boost/limits.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/3rd party/boost/boost/limits.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
1
2018-01-09T10:08:18.000Z
2018-01-09T10:08:18.000Z
src/3rd party/boost/boost/limits.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
// (C) Copyright Boost.org 1999. Permission to copy, use, modify, sell and // distribute this software is granted provided this copyright notice appears // in all copies. This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // // use this header as a workaround for missing <limits> // See http://www.boost.org/libs/utility/limits.html for documentation. #ifndef BOOST_LIMITS #define BOOST_LIMITS #include <boost/config.hpp> #ifdef BOOST_NO_LIMITS # include <boost/detail/limits.hpp> #else # include <limits> #endif #if (defined(BOOST_HAS_LONG_LONG) && defined(BOOST_NO_LONG_LONG_NUMERIC_LIMITS)) \ || (defined(BOOST_HAS_MS_INT64) && defined(BOOST_NO_MS_INT64_NUMERIC_LIMITS)) // Add missing specializations for numeric_limits: #ifdef BOOST_HAS_MS_INT64 # define BOOST_LLT __int64 #else # define BOOST_LLT long long #endif namespace std { template<> class numeric_limits<BOOST_LLT> { public: BOOST_STATIC_CONSTANT(bool, is_specialized = true); #ifdef BOOST_HAS_MS_INT64 static BOOST_LLT min(){ return 0x8000000000000000i64; } static BOOST_LLT max(){ return 0x7FFFFFFFFFFFFFFFi64; } #elif defined(LLONG_MAX) static BOOST_LLT min(){ return LLONG_MIN; } static BOOST_LLT max(){ return LLONG_MAX; } #elif defined(LONGLONG_MAX) static BOOST_LLT min(){ return LONGLONG_MIN; } static BOOST_LLT max(){ return LONGLONG_MAX; } #else static BOOST_LLT min(){ return 1LL << (sizeof(BOOST_LLT) * CHAR_BIT - 1); } static BOOST_LLT max(){ return ~min(); } #endif BOOST_STATIC_CONSTANT(int, digits = sizeof(BOOST_LLT) * CHAR_BIT -1); BOOST_STATIC_CONSTANT(int, digits10 = (CHAR_BIT * sizeof (BOOST_LLT) - 1) * 301L / 1000); BOOST_STATIC_CONSTANT(bool, is_signed = true); BOOST_STATIC_CONSTANT(bool, is_integer = true); BOOST_STATIC_CONSTANT(bool, is_exact = true); BOOST_STATIC_CONSTANT(int, radix = 2); static BOOST_LLT epsilon() throw() { return 0; }; static BOOST_LLT round_error() throw() { return 0; }; BOOST_STATIC_CONSTANT(int, min_exponent = 0); BOOST_STATIC_CONSTANT(int, min_exponent10 = 0); BOOST_STATIC_CONSTANT(int, max_exponent = 0); BOOST_STATIC_CONSTANT(int, max_exponent10 = 0); BOOST_STATIC_CONSTANT(bool, has_infinity = false); BOOST_STATIC_CONSTANT(bool, has_quiet_NaN = false); BOOST_STATIC_CONSTANT(bool, has_signaling_NaN = false); BOOST_STATIC_CONSTANT(bool, has_denorm = false); BOOST_STATIC_CONSTANT(bool, has_denorm_loss = false); static BOOST_LLT infinity() throw() { return 0; }; static BOOST_LLT quiet_NaN() throw() { return 0; }; static BOOST_LLT signaling_NaN() throw() { return 0; }; static BOOST_LLT denorm_min() throw() { return 0; }; BOOST_STATIC_CONSTANT(bool, is_iec559 = false); BOOST_STATIC_CONSTANT(bool, is_bounded = false); BOOST_STATIC_CONSTANT(bool, is_modulo = false); BOOST_STATIC_CONSTANT(bool, traps = false); BOOST_STATIC_CONSTANT(bool, tinyness_before = false); BOOST_STATIC_CONSTANT(float_round_style, round_style = round_toward_zero); }; template<> class numeric_limits<unsigned BOOST_LLT> { public: BOOST_STATIC_CONSTANT(bool, is_specialized = true); #ifdef BOOST_HAS_MS_INT64 static unsigned BOOST_LLT min(){ return 0ui64; } static unsigned BOOST_LLT max(){ return 0xFFFFFFFFFFFFFFFFui64; } #elif defined(ULLONG_MAX) && defined(ULLONG_MIN) static unsigned BOOST_LLT min(){ return ULLONG_MIN; } static unsigned BOOST_LLT max(){ return ULLONG_MAX; } #elif defined(ULONGLONG_MAX) && defined(ULONGLONG_MIN) static unsigned BOOST_LLT min(){ return ULONGLONG_MIN; } static unsigned BOOST_LLT max(){ return ULONGLONG_MAX; } #else static unsigned BOOST_LLT min(){ return 0uLL; } static unsigned BOOST_LLT max(){ return ~0uLL; } #endif BOOST_STATIC_CONSTANT(int, digits = sizeof(BOOST_LLT) * CHAR_BIT); BOOST_STATIC_CONSTANT(int, digits10 = (CHAR_BIT * sizeof (BOOST_LLT)) * 301L / 1000); BOOST_STATIC_CONSTANT(bool, is_signed = false); BOOST_STATIC_CONSTANT(bool, is_integer = true); BOOST_STATIC_CONSTANT(bool, is_exact = true); BOOST_STATIC_CONSTANT(int, radix = 2); static unsigned BOOST_LLT epsilon() throw() { return 0; }; static unsigned BOOST_LLT round_error() throw() { return 0; }; BOOST_STATIC_CONSTANT(int, min_exponent = 0); BOOST_STATIC_CONSTANT(int, min_exponent10 = 0); BOOST_STATIC_CONSTANT(int, max_exponent = 0); BOOST_STATIC_CONSTANT(int, max_exponent10 = 0); BOOST_STATIC_CONSTANT(bool, has_infinity = false); BOOST_STATIC_CONSTANT(bool, has_quiet_NaN = false); BOOST_STATIC_CONSTANT(bool, has_signaling_NaN = false); BOOST_STATIC_CONSTANT(bool, has_denorm = false); BOOST_STATIC_CONSTANT(bool, has_denorm_loss = false); static unsigned BOOST_LLT infinity() throw() { return 0; }; static unsigned BOOST_LLT quiet_NaN() throw() { return 0; }; static unsigned BOOST_LLT signaling_NaN() throw() { return 0; }; static unsigned BOOST_LLT denorm_min() throw() { return 0; }; BOOST_STATIC_CONSTANT(bool, is_iec559 = false); BOOST_STATIC_CONSTANT(bool, is_bounded = false); BOOST_STATIC_CONSTANT(bool, is_modulo = false); BOOST_STATIC_CONSTANT(bool, traps = false); BOOST_STATIC_CONSTANT(bool, tinyness_before = false); BOOST_STATIC_CONSTANT(float_round_style, round_style = round_toward_zero); }; } #endif #endif
39.697183
95
0.712258
OLR-xray
b9d3f077eea00bb84395dbc78a804d41fe2a91fb
1,863
hh
C++
test/geometry/LinearPropagator.test.hh
amandalund/celeritas
c631594b00c040d5eb4418fa2129f88c01e29316
[ "Apache-2.0", "MIT" ]
null
null
null
test/geometry/LinearPropagator.test.hh
amandalund/celeritas
c631594b00c040d5eb4418fa2129f88c01e29316
[ "Apache-2.0", "MIT" ]
null
null
null
test/geometry/LinearPropagator.test.hh
amandalund/celeritas
c631594b00c040d5eb4418fa2129f88c01e29316
[ "Apache-2.0", "MIT" ]
null
null
null
//----------------------------------*-C++-*----------------------------------// // Copyright 2020 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file LinearPropagator.test.hh //---------------------------------------------------------------------------// #pragma once #include <vector> #include "base/Assert.hh" #include "geometry/GeoInterface.hh" namespace celeritas_test { using celeritas::MemSpace; using celeritas::Ownership; using GeoParamsCRefDevice = celeritas::GeoParamsData<Ownership::const_reference, MemSpace::device>; using GeoStateRefDevice = celeritas::GeoStateData<Ownership::reference, MemSpace::device>; //---------------------------------------------------------------------------// // TESTING INTERFACE //---------------------------------------------------------------------------// using LinPropTestInit = celeritas::GeoTrackInitializer; //! Input data struct LinPropTestInput { std::vector<LinPropTestInit> init; int max_segments = 0; GeoParamsCRefDevice params; GeoStateRefDevice state; }; //---------------------------------------------------------------------------// //! Output results struct LinPropTestOutput { std::vector<int> ids; std::vector<double> distances; }; //---------------------------------------------------------------------------// //! Run on device and return results LinPropTestOutput linprop_test(LinPropTestInput); #if !CELERITAS_USE_CUDA LinPropTestOutput linprop_test(LinPropTestInput) { CELER_NOT_CONFIGURED("CUDA"); } #endif //---------------------------------------------------------------------------// } // namespace celeritas_test
31.576271
79
0.482555
amandalund
b9d65eeb1f513c29f10ba8d2620b97fbe032b6ea
946
cpp
C++
Arrays-Insertion Sort.cpp
Apoorv0001/HackerBlogs-Practice-Questions
52c95f9d0ade3f38596821c979604c0aa23c78cb
[ "MIT" ]
null
null
null
Arrays-Insertion Sort.cpp
Apoorv0001/HackerBlogs-Practice-Questions
52c95f9d0ade3f38596821c979604c0aa23c78cb
[ "MIT" ]
null
null
null
Arrays-Insertion Sort.cpp
Apoorv0001/HackerBlogs-Practice-Questions
52c95f9d0ade3f38596821c979604c0aa23c78cb
[ "MIT" ]
null
null
null
/* Given an array A of size N , write a function that implements insertion sort on the array. Print the elements of sorted array. Input Format First line contains a single integer N denoting the size of the array. Next line contains N space seperated integers where ith integer is the ith element of the array. Constraints 1 <= N <= 1000 |Ai| <= 1000000 Output Format Output N space seperated integers of the sorted array in a single line. Sample Input 4 3 4 2 1 Sample Output 1 2 3 4 Explanation For each test case, write insertion sort to sort the array. */ #include<iostream> using namespace std; int main() { int size, arr[1001], i, j, temp; cout<<" "; cin>>size; for(i=0; i<size; i++) { cin>>arr[i]; } cout<<" "; for(i=1; i<size; i++) { temp=arr[i]; j=i-1; while((temp<arr[j]) && (j>=0)) { arr[j+1]=arr[j]; j=j-1; } arr[j+1]=temp; } cout<<" "; for(i=0; i<size; i++) { cout<<arr[i]<<" "; } return 0; }
18.54902
167
0.647992
Apoorv0001
b9d694961356006758cb892928111d86b7976fd6
933
cpp
C++
test/runtime/23_threads_heap.cpp
ste-lam/TypeART
e563d3d1cd28245301f5f6d87f7f55d2b13d610a
[ "BSD-3-Clause" ]
17
2020-04-23T14:51:32.000Z
2022-03-30T08:41:45.000Z
test/runtime/23_threads_heap.cpp
ste-lam/TypeART
e563d3d1cd28245301f5f6d87f7f55d2b13d610a
[ "BSD-3-Clause" ]
94
2020-09-03T12:26:17.000Z
2022-02-28T14:56:17.000Z
test/runtime/23_threads_heap.cpp
ste-lam/TypeART
e563d3d1cd28245301f5f6d87f7f55d2b13d610a
[ "BSD-3-Clause" ]
6
2020-10-07T22:06:17.000Z
2021-12-06T12:07:08.000Z
// clang-format off // RUN: %run %s --thread 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN // RUN: %run %s --thread 2>&1 | FileCheck %s // REQUIRES: thread && softcounter // clang-format on #include <stdlib.h> #include <thread> #include <stdio.h> void repeat_alloc_free(unsigned n) { for (int i = 0; i < n; i++) { double* d = (double*)malloc(sizeof(double) * n); free(d); } } int main(int argc, char** argv) { constexpr unsigned n = 1000; // CHECK: [Trace] TypeART Runtime Trace std::thread t1(repeat_alloc_free, n); std::thread t2(repeat_alloc_free, n); std::thread t3(repeat_alloc_free, n); t1.join(); t2.join(); t3.join(); // CHECK-TSAN-NOT: ThreadSanitizer // CHECK-NOT: Error // CHECK: Allocation type detail (heap, stack, global) // CHECK: 6 : 3000 , 0 , 0 , double // CHECK: Free allocation type detail (heap, stack) // CHECK: 6 : 3000 , 0 , double return 0; }
22.214286
70
0.619507
ste-lam
b9d8e7dc999ba3064bee7105eff0f9553d825df8
9,818
cpp
C++
src/slave/containerizer/mesos/isolators/xfs/utils.cpp
m4rvin/Mesos_DRFH
212486a9349cbec91724d13e6bbc82f1215706aa
[ "Apache-2.0" ]
4
2016-03-15T14:54:34.000Z
2018-01-03T13:52:10.000Z
src/slave/containerizer/mesos/isolators/xfs/utils.cpp
m4rvin/Mesos_DRFH
212486a9349cbec91724d13e6bbc82f1215706aa
[ "Apache-2.0" ]
null
null
null
src/slave/containerizer/mesos/isolators/xfs/utils.cpp
m4rvin/Mesos_DRFH
212486a9349cbec91724d13e6bbc82f1215706aa
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. // The XFS API headers come from the xfsprogs package. xfsprogs versions // earlier than 4.5 contain various internal macros that conflict with // libstdc++. // If ENABLE_GETTEXT is not defined, then the XFS headers will define // textdomain() to a while(0) loop. When C++ standard headers try to // use textdomain(), compilation errors ensue. #define ENABLE_GETTEXT #include <xfs/xfs.h> #include <xfs/xqm.h> #undef ENABLE_GETTEXT // xfs/platform_defs-x86_64.h defines min() and max() macros which conflict // with various min() and max() function definitions. #undef min #undef max #include <fts.h> #include <blkid/blkid.h> #include <linux/quota.h> #include <sys/quota.h> #include <stout/check.hpp> #include <stout/error.hpp> #include <stout/numify.hpp> #include <stout/path.hpp> #include <stout/fs.hpp> #include <stout/os.hpp> #include "slave/containerizer/mesos/isolators/xfs/utils.hpp" using std::string; // Manually define this for old kernels. Compatible with the one in // <linux/quota.h>. #ifndef PRJQUOTA #define PRJQUOTA 2 #endif namespace mesos { namespace internal { namespace xfs { // The quota API defines space limits in terms of in basic // blocks (512 bytes). static constexpr Bytes BASIC_BLOCK_SIZE = Bytes(512u); // Although XFS itself doesn't define any invalid project IDs, // we need a way to know whether or not a project ID was assigned // so we use 0 as our sentinel value. static constexpr prid_t NON_PROJECT_ID = 0u; static Error nonProjectError() { return Error("Invalid project ID '0'"); } static Try<int> openPath( const string& path, const struct stat& stat) { int flags = O_NOFOLLOW | O_RDONLY | O_CLOEXEC; // Directories require O_DIRECTORY. flags |= S_ISDIR(stat.st_mode) ? O_DIRECTORY : 0; return os::open(path, flags); } static Try<Nothing> setAttributes( int fd, struct fsxattr& attr) { if (::xfsctl(nullptr, fd, XFS_IOC_FSSETXATTR, &attr) == -1) { return ErrnoError(); } return Nothing(); } static Try<struct fsxattr> getAttributes(int fd) { struct fsxattr attr; if (::xfsctl(nullptr, fd, XFS_IOC_FSGETXATTR, &attr) == -1) { return ErrnoError(); } return attr; } // Return the path of the device backing the filesystem containing // the given path. static Try<string> getDeviceForPath(const string& path) { struct stat statbuf; if (::lstat(path.c_str(), &statbuf) == -1) { return ErrnoError("Unable to access '" + path + "'"); } char* name = blkid_devno_to_devname(statbuf.st_dev); if (name == nullptr) { return ErrnoError("Unable to get device for '" + path + "'"); } string devname(name); free(name); return devname; } namespace internal { static Try<Nothing> setProjectQuota( const string& path, prid_t projectId, Bytes limit) { Try<string> devname = getDeviceForPath(path); if (devname.isError()) { return Error(devname.error()); } fs_disk_quota_t quota = {0}; quota.d_version = FS_DQUOT_VERSION; // Specify that we are setting a project quota for this ID. quota.d_id = projectId; quota.d_flags = XFS_PROJ_QUOTA; // Set both the hard and the soft limit to the same quota, just // for consistency. Functionally all we need is the hard quota. quota.d_fieldmask = FS_DQ_BSOFT | FS_DQ_BHARD; quota.d_blk_hardlimit = limit.bytes() / BASIC_BLOCK_SIZE.bytes(); quota.d_blk_softlimit = limit.bytes() / BASIC_BLOCK_SIZE.bytes(); if (::quotactl(QCMD(Q_XSETQLIM, PRJQUOTA), devname.get().c_str(), projectId, reinterpret_cast<caddr_t>(&quota)) == -1) { return ErrnoError("Failed to set quota for project ID " + stringify(projectId)); } return Nothing(); } static Try<Nothing> setProjectId( const string& path, const struct stat& stat, prid_t projectId) { Try<int> fd = openPath(path, stat); if (fd.isError()) { return Error("Failed to open '" + path + "': " + fd.error()); } Try<struct fsxattr> attr = getAttributes(fd.get()); if (attr.isError()) { os::close(fd.get()); return Error("Failed to get XFS attributes for '" + path + "': " + attr.error()); } attr->fsx_projid = projectId; if (projectId == NON_PROJECT_ID) { attr->fsx_xflags &= ~XFS_XFLAG_PROJINHERIT; } else { attr->fsx_xflags |= XFS_XFLAG_PROJINHERIT; } Try<Nothing> status = setAttributes(fd.get(), attr.get()); os::close(fd.get()); if (status.isError()) { return Error("Failed to set XFS attributes for '" + path + "': " + status.error()); } return Nothing(); } } // namespace internal { Result<QuotaInfo> getProjectQuota( const string& path, prid_t projectId) { if (projectId == NON_PROJECT_ID) { return nonProjectError(); } Try<string> devname = getDeviceForPath(path); if (devname.isError()) { return Error(devname.error()); } fs_disk_quota_t quota = {0}; quota.d_version = FS_DQUOT_VERSION; quota.d_id = projectId; quota.d_flags = XFS_PROJ_QUOTA; // In principle, we should issue a Q_XQUOTASYNC to get an accurate accounting. // However, we don't want to affect performance by continually syncing the // disks, so we accept that the quota information will be slightly out of // date. if (::quotactl(QCMD(Q_XGETQUOTA, PRJQUOTA), devname.get().c_str(), projectId, reinterpret_cast<caddr_t>(&quota)) == -1) { return ErrnoError("Failed to get quota for project ID " + stringify(projectId)); } // Zero quota means that no quota is assigned. if (quota.d_blk_hardlimit == 0 && quota.d_bcount == 0) { return None(); } QuotaInfo info; info.limit = BASIC_BLOCK_SIZE * quota.d_blk_hardlimit; info.used = BASIC_BLOCK_SIZE * quota.d_bcount; return info; } Try<Nothing> setProjectQuota( const string& path, prid_t projectId, Bytes limit) { if (projectId == NON_PROJECT_ID) { return nonProjectError(); } // A 0 limit deletes the quota record. Since the limit is in basic // blocks that effectively means > 512 bytes. if (limit < BASIC_BLOCK_SIZE) { return Error("Quota limit must be >= " + stringify(BASIC_BLOCK_SIZE)); } return internal::setProjectQuota(path, projectId, limit); } Try<Nothing> clearProjectQuota( const string& path, prid_t projectId) { if (projectId == NON_PROJECT_ID) { return nonProjectError(); } return internal::setProjectQuota(path, projectId, Bytes(0)); } Result<prid_t> getProjectId( const string& directory) { struct stat stat; if (::lstat(directory.c_str(), &stat) == -1) { return ErrnoError("Failed to access '" + directory); } Try<int> fd = openPath(directory, stat); if (fd.isError()) { return Error("Failed to open '" + directory + "': " + fd.error()); } Try<struct fsxattr> attr = getAttributes(fd.get()); os::close(fd.get()); if (attr.isError()) { return Error("Failed to get XFS attributes for '" + directory + "': " + attr.error()); } if (attr->fsx_projid == NON_PROJECT_ID) { return None(); } return attr->fsx_projid; } static Try<Nothing> setProjectIdRecursively( const string& directory, prid_t projectId) { if (os::stat::islink(directory) || !os::stat::isdir(directory)) { return Error(directory + " is not a directory"); } char* directory_[] = {const_cast<char*>(directory.c_str()), nullptr}; FTS* tree = ::fts_open( directory_, FTS_NOCHDIR | FTS_PHYSICAL | FTS_XDEV, nullptr); if (tree == nullptr) { return ErrnoError("Failed to open '" + directory + "'"); } for (FTSENT *node = ::fts_read(tree); node != nullptr; node = ::fts_read(tree)) { if (node->fts_info == FTS_D || node->fts_info == FTS_F) { Try<Nothing> status = internal::setProjectId( node->fts_path, *node->fts_statp, projectId); if (status.isError()) { ::fts_close(tree); return Error(status.error()); } } } if (errno != 0) { Error error = ErrnoError(); ::fts_close(tree); return error; } if (::fts_close(tree) != 0) { return ErrnoError("Failed to stop traversing file system"); } return Nothing(); } Try<Nothing> setProjectId( const string& directory, prid_t projectId) { if (projectId == NON_PROJECT_ID) { return nonProjectError(); } return setProjectIdRecursively(directory, projectId); } Try<Nothing> clearProjectId( const string& directory) { return setProjectIdRecursively(directory, NON_PROJECT_ID); } Option<Error> validateProjectIds(const IntervalSet<prid_t>& projectRange) { if (projectRange.contains(NON_PROJECT_ID)) { return Error("XFS project ID range contains illegal " + stringify(NON_PROJECT_ID) + " value"); } return None(); } bool pathIsXfs(const string& path) { return ::platform_test_xfs_path(path.c_str()) == 1; } } // namespace xfs { } // namespace internal { } // namespace mesos {
24.483791
80
0.666735
m4rvin
b9e86fddafa3ddc8ecfebd6c1bc4b3a69df8aa9e
1,888
cpp
C++
bitcoinPoSTdisplay/libraries/ArduinoJson/extras/tests/JsonArray/remove.cpp
adrienlacombe-ledger/bitcoinPoS
2a4701c445c7eeec88c8abc2bd7940916899e79c
[ "MIT" ]
81
2022-01-22T17:35:01.000Z
2022-03-08T09:59:02.000Z
bitcoinPoSTdisplay/libraries/ArduinoJson/extras/tests/JsonArray/remove.cpp
adrienlacombe-ledger/bitcoinPoS
2a4701c445c7eeec88c8abc2bd7940916899e79c
[ "MIT" ]
6
2022-01-25T20:23:08.000Z
2022-03-07T23:50:32.000Z
bitcoinPoSTdisplay/libraries/ArduinoJson/extras/tests/JsonArray/remove.cpp
adrienlacombe-ledger/bitcoinPoS
2a4701c445c7eeec88c8abc2bd7940916899e79c
[ "MIT" ]
14
2022-01-22T18:16:11.000Z
2022-03-07T21:32:41.000Z
// ArduinoJson - https://arduinojson.org // Copyright © 2014-2022, Benoit BLANCHON // MIT License #include <ArduinoJson.h> #include <catch.hpp> TEST_CASE("JsonArray::remove()") { DynamicJsonDocument doc(4096); JsonArray array = doc.to<JsonArray>(); array.add(1); array.add(2); array.add(3); SECTION("remove first by index") { array.remove(0); REQUIRE(2 == array.size()); REQUIRE(array[0] == 2); REQUIRE(array[1] == 3); } SECTION("remove middle by index") { array.remove(1); REQUIRE(2 == array.size()); REQUIRE(array[0] == 1); REQUIRE(array[1] == 3); } SECTION("remove last by index") { array.remove(2); REQUIRE(2 == array.size()); REQUIRE(array[0] == 1); REQUIRE(array[1] == 2); } SECTION("remove first by iterator") { JsonArray::iterator it = array.begin(); array.remove(it); REQUIRE(2 == array.size()); REQUIRE(array[0] == 2); REQUIRE(array[1] == 3); } SECTION("remove middle by iterator") { JsonArray::iterator it = array.begin(); ++it; array.remove(it); REQUIRE(2 == array.size()); REQUIRE(array[0] == 1); REQUIRE(array[1] == 3); } SECTION("remove last bty iterator") { JsonArray::iterator it = array.begin(); ++it; ++it; array.remove(it); REQUIRE(2 == array.size()); REQUIRE(array[0] == 1); REQUIRE(array[1] == 2); } SECTION("In a loop") { for (JsonArray::iterator it = array.begin(); it != array.end(); ++it) { if (*it == 2) array.remove(it); } REQUIRE(2 == array.size()); REQUIRE(array[0] == 1); REQUIRE(array[1] == 3); } SECTION("remove by index on unbound reference") { JsonArray unboundArray; unboundArray.remove(20); } SECTION("remove by iterator on unbound reference") { JsonArray unboundArray; unboundArray.remove(unboundArray.begin()); } }
20.977778
75
0.585275
adrienlacombe-ledger
b9e94ed79ea8e9220e2f2cba68b0f7f827fa3549
845
cc
C++
Cplusplus/Bootcamp/03_MoreBasics/Casting.cc
Kreijeck/learning
eaffee08e61f2a34e01eb8f9f04519aac633f48c
[ "MIT" ]
null
null
null
Cplusplus/Bootcamp/03_MoreBasics/Casting.cc
Kreijeck/learning
eaffee08e61f2a34e01eb8f9f04519aac633f48c
[ "MIT" ]
null
null
null
Cplusplus/Bootcamp/03_MoreBasics/Casting.cc
Kreijeck/learning
eaffee08e61f2a34e01eb8f9f04519aac633f48c
[ "MIT" ]
null
null
null
#include <iomanip> #include <iostream> // 1a. C++: static_cast<> - converts object from type to another // 1b. C: (newDtype)(varName) int main() { double number = 3.14; std::cout << std::setprecision(20) << number << std::endl; int num2 = number; std::cout << num2 << std::endl; //C-Casting // groß nach klein verliert genauigkeit float number3 = (float)(number); std::cout << number3 << std::endl; // klein nach Groß. alles prima! float number4 = (double)(number3); std::cout << number3 << std::endl; //C++-Casting // groß nach klein verliert genauigkeit float number5 = static_cast<float>(number); std::cout << number5 << std::endl; // klein nach Groß. alles prima! float number6 = static_cast<double>(number3); std::cout << number6 << std::endl; return 0; }
24.142857
64
0.611834
Kreijeck
b9f0203c850126067cadb83bfd52a4dc74919861
24,190
cpp
C++
modules/attention_segmentation/src/algo.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
2
2021-02-22T11:36:33.000Z
2021-07-20T11:31:08.000Z
modules/attention_segmentation/src/algo.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
null
null
null
modules/attention_segmentation/src/algo.cpp
v4r-tuwien/v4r
ff3fbd6d2b298b83268ba4737868bab258262a40
[ "BSD-1-Clause", "BSD-2-Clause" ]
3
2018-10-19T10:39:23.000Z
2021-04-07T13:39:03.000Z
/**************************************************************************** ** ** Copyright (C) 2017 TU Wien, ACIN, Vision 4 Robotics (V4R) group ** Contact: v4r.acin.tuwien.ac.at ** ** This file is part of V4R ** ** V4R is distributed under dual licenses - GPLv3 or closed source. ** ** GNU General Public License Usage ** V4R is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published ** by the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** V4R is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** Please review the following information to ensure the GNU General Public ** License requirements will be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** ** Commercial License Usage ** If GPL is not suitable for your project, you must purchase a commercial ** license to use V4R. Licensees holding valid commercial V4R licenses may ** use this file in accordance with the commercial license agreement ** provided with the Software or, alternatively, in accordance with the ** terms contained in a written agreement between you and TU Wien, ACIN, V4R. ** For licensing terms and conditions please contact office<at>acin.tuwien.ac.at. ** ** ** The copyright holder additionally grants the author(s) of the file the right ** to use, copy, modify, merge, publish, distribute, sublicense, and/or ** sell copies of their contributions without any restrictions. ** ****************************************************************************/ #include "v4r/attention_segmentation/algo.h" #include "v4r/attention_segmentation/AttentionModuleErrors.h" #include <Eigen/Dense> namespace v4r { void filterGaussian(cv::Mat &input, cv::Mat &output, cv::Mat &mask) { float kernel[5] = {1.0, 4.0, 6.0, 4.0, 1.0}; cv::Mat temp = cv::Mat_<float>::zeros(input.rows, input.cols); for (int i = 0; i < input.rows; ++i) { for (int j = 0; j < input.cols; j = j + 2) { if (mask.at<float>(i, j) > 0) { float value = 0; float kernel_sum = 0; for (int k = 0; k < 5; ++k) { int jj = j + (k - 2); if ((jj >= 0) && (jj < input.cols)) { if (mask.at<float>(i, jj) > 0) { value += kernel[k] * input.at<float>(i, jj); kernel_sum += kernel[k]; } } } if (kernel_sum > 0) { temp.at<float>(i, j) = value / kernel_sum; } } } } cv::Mat temp2 = cv::Mat_<float>::zeros(temp.rows, temp.cols); for (int i = 0; i < temp.rows; i = i + 2) { for (int j = 0; j < temp.cols; j = j + 2) { if (mask.at<float>(i, j) > 0) { float value = 0; float kernel_sum = 0; for (int k = 0; k < 5; ++k) { int ii = i + (k - 2); if ((ii >= 0) && (ii < temp.rows)) { if (mask.at<float>(ii, j) > 0) { value += kernel[k] * temp.at<float>(ii, j); kernel_sum += kernel[k]; } } } if (kernel_sum > 0) { temp2.at<float>(i, j) = value / kernel_sum; } } } } int new_width = input.cols / 2; int new_height = input.rows / 2; cv::Mat mask_output = cv::Mat_<float>::zeros(new_height, new_width); output = cv::Mat_<float>::zeros(new_height, new_width); for (int i = 0; i < new_height; ++i) { for (int j = 0; j < new_width; ++j) { if (mask.at<float>(2 * i, 2 * j) > 0) { mask_output.at<float>(i, j) = 1.0; output.at<float>(i, j) = temp2.at<float>(2 * i, 2 * j); } } } mask_output.copyTo(mask); } void buildDepthPyramid(cv::Mat &image, std::vector<cv::Mat> &pyramid, cv::Mat &mask, unsigned int levelNumber) { pyramid.resize(levelNumber + 1); image.copyTo(pyramid.at(0)); cv::Mat oldMask; mask.copyTo(oldMask); for (unsigned int i = 1; i <= levelNumber; ++i) { cv::Mat tempImage; filterGaussian(pyramid.at(i - 1), tempImage, oldMask); tempImage.copyTo(pyramid.at(i)); } } int createPointCloudPyramid(std::vector<cv::Mat> &pyramidX, std::vector<cv::Mat> &pyramidY, std::vector<cv::Mat> &pyramidZ, std::vector<cv::Mat> &pyramidIndices, std::vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> &pyramidCloud) { assert(pyramidX.size() == pyramidY.size()); assert(pyramidX.size() == pyramidZ.size()); assert(pyramidX.size() == pyramidIndices.size()); if (pyramidX.size() != pyramidY.size() && pyramidX.size() != pyramidZ.size() && pyramidX.size() != pyramidIndices.size()) return AM_DIFFERENTSIZES; unsigned int num_levels = pyramidX.size(); pyramidCloud.resize(num_levels); for (unsigned int idx = 0; idx < num_levels; ++idx) { assert(pyramidX.at(idx).rows == pyramidY.at(idx).rows); assert(pyramidX.at(idx).cols == pyramidY.at(idx).cols); assert(pyramidX.at(idx).rows == pyramidZ.at(idx).rows); assert(pyramidX.at(idx).cols == pyramidZ.at(idx).cols); assert(pyramidX.at(idx).rows == pyramidIndices.at(idx).rows); assert(pyramidX.at(idx).cols == pyramidIndices.at(idx).cols); pyramidCloud.at(idx) = pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>()); unsigned int cur_height = pyramidX.at(idx).rows; unsigned int cur_width = pyramidX.at(idx).cols; pyramidCloud.at(idx)->points.resize(cur_height * cur_width); pyramidCloud.at(idx)->width = cur_width; pyramidCloud.at(idx)->height = cur_height; for (unsigned int i = 0; i < cur_height; ++i) { for (unsigned int j = 0; j < cur_width; ++j) { pcl::PointXYZRGB p_cur; p_cur.x = pyramidX.at(idx).at<float>(i, j); p_cur.y = pyramidY.at(idx).at<float>(i, j); p_cur.z = pyramidZ.at(idx).at<float>(i, j); int p_idx = i * cur_width + j; pyramidCloud.at(idx)->points.at(p_idx) = p_cur; } } } return AM_OK; } void createNormalPyramid(std::vector<cv::Mat> &pyramidNx, std::vector<cv::Mat> &pyramidNy, std::vector<cv::Mat> &pyramidNz, std::vector<cv::Mat> &pyramidIndices, std::vector<pcl::PointCloud<pcl::Normal>::Ptr> &pyramidNormal) { assert(pyramidNx.size() == pyramidNy.size()); assert(pyramidNx.size() == pyramidNz.size()); assert(pyramidIndices.size() == pyramidNz.size()); unsigned int num_levels = pyramidNx.size(); pyramidNormal.resize(num_levels); for (unsigned int idx = 0; idx < num_levels; ++idx) { assert(pyramidNx.at(idx).rows == pyramidNy.at(idx).rows); assert(pyramidNx.at(idx).cols == pyramidNy.at(idx).cols); assert(pyramidNx.at(idx).rows == pyramidNz.at(idx).rows); assert(pyramidNx.at(idx).cols == pyramidNz.at(idx).cols); assert(pyramidNx.at(idx).rows == pyramidIndices.at(idx).rows); assert(pyramidNx.at(idx).cols == pyramidIndices.at(idx).cols); pyramidNormal.at(idx) = pcl::PointCloud<pcl::Normal>::Ptr(new pcl::PointCloud<pcl::Normal>()); unsigned int cur_height = pyramidNx.at(idx).rows; unsigned int cur_width = pyramidNx.at(idx).cols; pyramidNormal.at(idx)->points.clear(); for (unsigned int i = 0; i < cur_height; ++i) { for (unsigned int j = 0; j < cur_width; ++j) { if (pyramidIndices.at(idx).at<float>(i, j) > 0) { pcl::Normal p_cur; p_cur.normal[0] = pyramidNx.at(idx).at<float>(i, j); p_cur.normal[1] = pyramidNy.at(idx).at<float>(i, j); p_cur.normal[2] = pyramidNz.at(idx).at<float>(i, j); pyramidNormal.at(idx)->points.push_back(p_cur); } } } pyramidNormal.at(idx)->width = pyramidNormal.at(idx)->points.size(); pyramidNormal.at(idx)->height = 1; } } void createIndicesPyramid(std::vector<cv::Mat> &pyramidIndices, std::vector<pcl::PointIndices::Ptr> &pyramidIndiceSets) { unsigned int num_levels = pyramidIndices.size(); pyramidIndiceSets.resize(num_levels); for (unsigned int idx = 0; idx < num_levels; ++idx) { pyramidIndiceSets.at(idx) = pcl::PointIndices::Ptr(new pcl::PointIndices()); unsigned int cur_height = pyramidIndices.at(idx).rows; unsigned int cur_width = pyramidIndices.at(idx).cols; pyramidIndiceSets.at(idx)->indices.clear(); for (unsigned int i = 0; i < cur_height; ++i) { for (unsigned int j = 0; j < cur_width; ++j) { if (pyramidIndices.at(idx).at<float>(i, j) > 0) { int p_idx = i * cur_width + j; pyramidIndiceSets.at(idx)->indices.push_back(p_idx); } } } } } void upscaleImage(cv::Mat &input, cv::Mat &output, unsigned int width, unsigned int height) { assert(width >= (unsigned int)(2 * input.cols)); assert(height >= (unsigned int)(2 * input.rows)); output = cv::Mat_<float>::zeros(height, width); for (unsigned int i = 0; i < (unsigned int)input.rows; ++i) { for (unsigned int j = 0; j < (unsigned int)input.cols; ++j) { output.at<float>(2 * i, 2 * j) = input.at<float>(i, j); } } for (unsigned int i = 0; i < (unsigned int)output.rows; i = i + 2) { for (unsigned int j = 1; j < (unsigned int)output.cols - 1; j = j + 2) { output.at<float>(i, j) = (output.at<float>(i, j - 1) + output.at<float>(i, j + 1)) / 2.0; } } for (unsigned int i = 1; i < (unsigned int)output.rows - 1; i = i + 2) { for (unsigned int j = 0; j < (unsigned int)output.cols; j = j + 2) { output.at<float>(i, j) = (output.at<float>(i - 1, j) + output.at<float>(i + 1, j)) / 2.0; } } for (unsigned int i = 1; i < (unsigned int)output.rows - 1; i = i + 2) { for (unsigned int j = 1; j < (unsigned int)output.cols - 1; j = j + 2) { output.at<float>(i, j) = (output.at<float>(i - 1, j - 1) + output.at<float>(i - 1, j + 1) + output.at<float>(i + 1, j - 1) + output.at<float>(i + 1, j + 1)) / 4.0; } } } void downscaleImage(cv::Mat &input, cv::Mat &output, unsigned int width, unsigned int height) { assert(2 * width <= (unsigned int)(input.cols)); assert(2 * height <= (unsigned int)(input.rows)); output = cv::Mat_<float>::zeros(height, width); for (unsigned int i = 0; i < (unsigned int)output.rows; ++i) { for (unsigned int j = 0; j < (unsigned int)output.cols; ++j) { output.at<float>(i, j) = input.at<float>(2 * i, 2 * j); } } } void scaleImage(std::vector<cv::Mat> &inputPyramid, cv::Mat &input, cv::Mat &output, int inLevel, int outLevel) { assert(input.cols == inputPyramid.at(inLevel).cols); assert(input.rows == inputPyramid.at(inLevel).rows); if (inLevel < outLevel) { input.copyTo(output); for (int l = inLevel + 1; l <= outLevel; ++l) { cv::Mat temp; downscaleImage(output, temp, inputPyramid.at(l).cols, inputPyramid.at(l).rows); temp.copyTo(output); } } else if (inLevel > outLevel) { input.copyTo(output); for (int l = inLevel - 1; l >= outLevel; --l) { cv::Mat temp; upscaleImage(output, temp, inputPyramid.at(l).cols, inputPyramid.at(l).rows); temp.copyTo(output); } } else { input.copyTo(output); } } bool inPoly(std::vector<cv::Point> &poly, cv::Point p) { cv::Point newPoint; cv::Point oldPoint; cv::Point p1, p2; bool inside = false; if (poly.size() < 3) { return (false); } oldPoint = poly.at(poly.size() - 1); for (unsigned int i = 0; i < poly.size(); i++) { newPoint = poly.at(i); if (newPoint.y > oldPoint.y) { p1 = oldPoint; p2 = newPoint; } else { p1 = newPoint; p2 = oldPoint; } if ((newPoint.y < p.y) == (p.y <= oldPoint.y) /* edge "open" at one end */ && ((long)p.x - (long)p1.x) * (long)(p2.y - p1.y) < ((long)p2.x - (long)p1.x) * (long)(p.y - p1.y)) { inside = !inside; } oldPoint = newPoint; } return (inside); } void buildPolygonMap(cv::Mat &polygonMap, std::vector<std::vector<cv::Point>> &polygons) { for (int i = 0; i < polygonMap.rows; ++i) { for (int j = 0; j < polygonMap.cols; ++j) { unsigned int k = 0; while ((polygonMap.at<uchar>(i, j) == 0) && (k < polygons.size())) { if (inPoly(polygons.at(k), cv::Point(j, i))) polygonMap.at<uchar>(i, j) = k + 1; k += 1; } } } } void buildCountourMap(cv::Mat &polygonMap, std::vector<std::vector<cv::Point>> &polygons, cv::Scalar color) { for (unsigned int i = 0; i < polygons.size(); ++i) { for (unsigned int j = 0; j < polygons.at(i).size(); ++j) { cv::line(polygonMap, polygons.at(i).at(j), polygons.at(i).at((j + 1) % polygons.at(i).size()), color, 2); } } } float normPDF(float x, float mean, float stddev) { float val = exp(-(x - mean) * (x - mean) / (2 * stddev * stddev)); val /= sqrt(2 * 3.14) * stddev; return val; } float normPDF(std::vector<float> x, std::vector<float> mean, cv::Mat stddev) { int dim = mean.size(); EIGEN_ALIGN16 Eigen::MatrixXf _stddev = Eigen::MatrixXf::Zero(dim, dim); EIGEN_ALIGN16 Eigen::VectorXf _x = Eigen::VectorXf::Zero(dim); for (int i = 0; i < dim; ++i) { _x[i] = x.at(i) - mean.at(i); for (int j = 0; j < dim; ++j) { _stddev(i, j) = stddev.at<float>(i, j); } } float value = (_x.transpose()) * _stddev * _x; value /= -2; value = exp(value); float det = _stddev.determinant(); value /= sqrt(pow(2 * 3.14, dim) * det); return (value); } void addNoise(cv::Mat &image, cv::Mat &nImage, cv::RNG &rng, float min, float max) { nImage = cv::Mat_<float>::zeros(image.rows, image.cols); for (int i = 0; i < image.rows; ++i) { for (int j = 0; j < image.cols; ++j) { float val = image.at<float>(i, j) + rng.uniform(min, max); nImage.at<float>(i, j) = (val < 0 ? 0 : (val > 1 ? 1 : val)); } } } void normPDF(cv::Mat &mat, float mean, float stddev, cv::Mat &res) { res = cv::Mat_<float>::zeros(mat.rows, mat.cols); res = mat - mean; res = res.mul(res); float b = -1.0f / (2 * stddev * stddev); res = res * b; cv::exp(res, res); float a = 1.0f / (stddev * sqrt(2 * M_PI)); res = res * a; } void normalizeDist(std::vector<float> &dist) { float total_sum = 0; for (unsigned int i = 0; i < dist.size(); ++i) { total_sum += dist.at(i); } for (unsigned int i = 0; i < dist.size(); ++i) { dist.at(i) /= total_sum; } } float getMean(std::vector<float> dist, float total_num) { float mean = 0; for (unsigned int i = 0; i < dist.size(); ++i) { mean += (dist.at(i) / total_num) * i; } return mean; } float getStd(std::vector<float> dist, float mean, float total_num) { float stdDev = 0; for (unsigned int i = 0; i < dist.size(); ++i) { stdDev += (i - mean) * (i - mean) * (dist.at(i) / total_num); } stdDev = sqrt(stdDev); return stdDev; } long commulativeFunctionArgValue(float x, std::vector<float> &A) { long min = 0; long max = A.size() - 1; while (max != min + 1) { long mid = (min + max) / 2; if (x <= A.at(mid)) { max = mid; } else { min = mid; } } if (A.at(min) >= x) return (min); else return (max); } void createContoursFromMasks(std::vector<cv::Mat> &masks, std::vector<std::vector<cv::Point>> &contours) { contours.clear(); contours.resize(masks.size()); for (unsigned int i = 0; i < masks.size(); ++i) { std::vector<std::vector<cv::Point>> temp; cv::Mat temp_image; masks.at(i).copyTo(temp_image); cv::findContours(temp_image, temp, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); if (temp.size()) { long totalPointsNum = 0; for (unsigned int j = 0; j < temp.size(); ++j) { totalPointsNum += temp.at(j).size(); } contours.at(i).resize(totalPointsNum); totalPointsNum = 0; for (unsigned int j = 0; j < temp.size(); ++j) { for (unsigned int k = 0; k < temp.at(j).size(); ++k) { contours.at(i).at(totalPointsNum) = temp.at(j).at(k); totalPointsNum += 1; } } } } } uchar Num01Transitions(cv::Mat s, int j, int i) { uchar p2 = s.at<uchar>(j - 1, i); uchar p3 = s.at<uchar>(j - 1, i + 1); uchar p4 = s.at<uchar>(j, i + 1); uchar p5 = s.at<uchar>(j + 1, i + 1); uchar p6 = s.at<uchar>(j + 1, i); uchar p7 = s.at<uchar>(j + 1, i - 1); uchar p8 = s.at<uchar>(j, i - 1); uchar p9 = s.at<uchar>(j - 1, i - 1); uchar Nt = 0; if ((p3 - p2) == 1) Nt++; if ((p4 - p3) == 1) Nt++; if ((p5 - p4) == 1) Nt++; if ((p6 - p5) == 1) Nt++; if ((p7 - p6) == 1) Nt++; if ((p8 - p7) == 1) Nt++; if ((p9 - p8) == 1) Nt++; if ((p2 - p9) == 1) Nt++; return Nt; } void MConnectivity(cv::Mat &s, uchar *element) { for (int i = 1; i < s.rows - 1; ++i) { for (int j = 1; j < s.cols - 1; ++j) { if (s.at<uchar>(i, j) > 0) { bool remove = true; for (int p = 0; p < 8; ++p) { int new_x = j + dx8[p]; int new_y = i + dy8[p]; uchar value = s.at<uchar>(new_y, new_x); if (element[p] < 2) { if (value != element[p]) { remove = false; } } } if (remove) { s.at<uchar>(i, j) = 0; } } } } } V4R_EXPORTS void Skeleton(cv::Mat a, cv::Mat &s) { int width = a.cols; int height = a.rows; a.copyTo(s); cv::Scalar prevsum(0); while (true) { cv::Mat m = cv::Mat_<uchar>::ones(height, width); for (int j = 1; j < height - 1; ++j) { for (int i = 1; i < width - 1; ++i) { if (s.at<uchar>(j, i) == 1) { uchar p2 = s.at<uchar>(j - 1, i); uchar p3 = s.at<uchar>(j - 1, i + 1); uchar p4 = s.at<uchar>(j, i + 1); uchar p5 = s.at<uchar>(j + 1, i + 1); uchar p6 = s.at<uchar>(j + 1, i); uchar p7 = s.at<uchar>(j + 1, i - 1); uchar p8 = s.at<uchar>(j, i - 1); uchar p9 = s.at<uchar>(j - 1, i - 1); uchar condA = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9; uchar condB = Num01Transitions(s, j, i); uchar condC = p2 * p4 * p6; uchar condD = p4 * p6 * p8; if ((condA >= 2) && (condA <= 6) && (condB == 1) && (condC == 0) && (condD == 0)) m.at<uchar>(j, i) = 0; } } } for (int j = 1; j < height - 1; ++j) { for (int i = 1; i < width - 1; ++i) { s.at<uchar>(j, i) = s.at<uchar>(j, i) * m.at<uchar>(j, i); } } m = cv::Mat_<uchar>::ones(height, width); for (int j = 1; j < height - 1; ++j) { for (int i = 1; i < width - 1; ++i) { if (s.at<uchar>(j, i) == 1) { uchar p2 = s.at<uchar>(j - 1, i); uchar p3 = s.at<uchar>(j - 1, i + 1); uchar p4 = s.at<uchar>(j, i + 1); uchar p5 = s.at<uchar>(j + 1, i + 1); uchar p6 = s.at<uchar>(j + 1, i); uchar p7 = s.at<uchar>(j + 1, i - 1); uchar p8 = s.at<uchar>(j, i - 1); uchar p9 = s.at<uchar>(j - 1, i - 1); uchar condA = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9; uchar condB = Num01Transitions(s, j, i); uchar condC = p2 * p4 * p8; uchar condD = p2 * p6 * p8; if ((condA >= 2) && (condA <= 6) && (condB == 1) && (condC == 0) && (condD == 0)) m.at<uchar>(j, i) = 0; } } } for (int j = 1; j < height - 1; ++j) { for (int i = 1; i < width - 1; ++i) { s.at<uchar>(j, i) = s.at<uchar>(j, i) * m.at<uchar>(j, i); } } cv::Scalar newsum = cv::sum(s); if (newsum(0) == prevsum(0)) break; prevsum = newsum; } prevsum = cv::sum(s); uchar e1[8] = {2, 1, 2, 1, 2, 0, 0, 0}; uchar e2[8] = {2, 1, 2, 0, 0, 0, 2, 1}; uchar e3[8] = {0, 0, 2, 1, 2, 1, 2, 0}; uchar e4[8] = {2, 0, 0, 0, 2, 1, 2, 1}; while (true) { MConnectivity(s, e1); MConnectivity(s, e2); MConnectivity(s, e3); MConnectivity(s, e4); cv::Scalar newsum = cv::sum(s); if (newsum(0) == prevsum(0)) break; prevsum = newsum; } } float calculateDistance(cv::Point center, cv::Point point) { float distance = sqrt((center.x - point.x) * (center.x - point.x) + (center.y - point.y) * (center.y - point.y)); return (distance); } float calculateDistance(cv::Point center, cv::Point point, float sigma) { float distance = (center.x - point.x) * (center.x - point.x) + (center.y - point.y) * (center.y - point.y); distance = exp(-distance / (2 * sigma * sigma)); return (distance); } void calculateObjectCenter(cv::Mat mask, cv::Point &center) { assert(mask.type() == CV_8UC1); float x_cen = 0; float y_cen = 0; cv::Scalar area = cv::sum(mask); for (int i = 0; i < mask.rows; ++i) { for (int j = 0; j < mask.cols; ++j) { uchar value = mask.at<uchar>(i, j); if (value > 0) { x_cen = x_cen + ((float)j) / area(0); y_cen = y_cen + ((float)i) / area(0); } } } if (mask.at<uchar>(y_cen, x_cen) == 0) { // search for closes 4-neighbour point std::list<cv::Point> points; points.push_back(cv::Point(x_cen, y_cen)); cv::Mat used = cv::Mat_<uchar>::zeros(mask.rows, mask.cols); used.at<uchar>(y_cen, x_cen) = 1; while (points.size()) { cv::Point p = points.front(); points.pop_front(); if (mask.at<uchar>(p.y, p.x) > 0) { x_cen = p.x; y_cen = p.y; break; } for (int i = 0; i < 8; ++i) { int new_x = p.x + dx8[i]; int new_y = p.y + dy8[i]; if ((new_x < 0) || (new_y < 0) || (new_x >= used.cols) || (new_y >= used.rows)) continue; if (used.at<uchar>(new_y, new_x) <= 0) { points.push_back(cv::Point(new_x, new_y)); used.at<uchar>(new_y, new_x) = 1; } } } } center.x = x_cen; center.y = y_cen; } void calculateObjectCenter(std::vector<cv::Point> contour, cv::Mat mask, cv::Point &center) { float x_cen = 0; float y_cen = 0; for (unsigned int i = 0; i < contour.size(); ++i) { x_cen = x_cen + ((float)contour.at(i).x) / contour.size(); y_cen = y_cen + ((float)contour.at(i).y) / contour.size(); } if (mask.at<uchar>(y_cen, x_cen) == 0) { // search for closes 4-neighbour point std::list<cv::Point> points; points.push_back(cv::Point(x_cen, y_cen)); cv::Mat used = cv::Mat_<uchar>::zeros(mask.rows, mask.cols); used.at<uchar>(y_cen, x_cen) = 1; while (points.size()) { cv::Point p = points.front(); points.pop_front(); if (mask.at<uchar>(p.y, p.x) > 0) { x_cen = p.x; y_cen = p.y; break; } for (int i = 0; i < 8; ++i) { int new_x = p.x + dx8[i]; int new_y = p.y + dy8[i]; if ((new_x < 0) || (new_y < 0) || (new_x >= used.cols) || (new_y >= used.rows)) continue; if (used.at<uchar>(new_y, new_x) <= 0) { points.push_back(cv::Point(new_x, new_y)); used.at<uchar>(new_y, new_x) = 1; } } } } center.x = x_cen; center.y = y_cen; } void get2DNeighbors(const cv::Mat &patches, cv::Mat &neighbors, int patchesNumber) { neighbors = cv::Mat_<bool>(patchesNumber, patchesNumber); neighbors.setTo(false); int dr[4] = {-1, 0, -1}; int dc[4] = {0, -1, -1}; for (int r = 1; r < patches.rows - 1; r++) { for (int c = 1; c < patches.cols - 1; c++) { // if the patch exist if (patches.at<int>(r, c) != -1) { int patchIdx = patches.at<int>(r, c); //@ep: why we did not use 1,-1 shift??? for (int i = 0; i < 3; ++i) //@ep: TODO 3->4 { int nr = r + dr[i]; int nc = c + dc[i]; int currentPatchIdx = patches.at<int>(nr, nc); if (currentPatchIdx == -1) continue; if (patchIdx != currentPatchIdx) { neighbors.at<bool>(currentPatchIdx, patchIdx) = true; neighbors.at<bool>(patchIdx, currentPatchIdx) = true; } } } } } } } // namespace v4r
30.504414
115
0.545763
v4r-tuwien
b9f4361c00fd88d61e84092afce6d01d8ea21d5e
36,075
cpp
C++
Userland/Libraries/LibUnicode/CodeGenerators/GenerateUnicodeData.cpp
Blocky-studio/serenity
8337e6cb52076e7f3e2cb5f9a5fd270141e8bbfe
[ "BSD-2-Clause" ]
2
2021-06-25T13:20:28.000Z
2021-08-19T11:00:54.000Z
Userland/Libraries/LibUnicode/CodeGenerators/GenerateUnicodeData.cpp
Blocky-studio/serenity
8337e6cb52076e7f3e2cb5f9a5fd270141e8bbfe
[ "BSD-2-Clause" ]
null
null
null
Userland/Libraries/LibUnicode/CodeGenerators/GenerateUnicodeData.cpp
Blocky-studio/serenity
8337e6cb52076e7f3e2cb5f9a5fd270141e8bbfe
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2021, Tim Flynn <[email protected]> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/AllOf.h> #include <AK/Array.h> #include <AK/CharacterTypes.h> #include <AK/HashMap.h> #include <AK/Optional.h> #include <AK/QuickSort.h> #include <AK/SourceGenerator.h> #include <AK/String.h> #include <AK/StringUtils.h> #include <AK/Types.h> #include <AK/Vector.h> #include <LibCore/ArgsParser.h> #include <LibCore/File.h> // Some code points are excluded from UnicodeData.txt, and instead are part of a "range" of code // points, as indicated by the "name" field. For example: // 3400;<CJK Ideograph Extension A, First>;Lo;0;L;;;;;N;;;;; // 4DBF;<CJK Ideograph Extension A, Last>;Lo;0;L;;;;;N;;;;; struct CodePointRange { u32 first; u32 last; }; // SpecialCasing source: https://www.unicode.org/Public/13.0.0/ucd/SpecialCasing.txt // Field descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#SpecialCasing.txt struct SpecialCasing { u32 index { 0 }; u32 code_point { 0 }; Vector<u32> lowercase_mapping; Vector<u32> uppercase_mapping; Vector<u32> titlecase_mapping; String locale; String condition; }; // PropList source: https://www.unicode.org/Public/13.0.0/ucd/PropList.txt // Property descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#PropList.txt // https://www.unicode.org/reports/tr44/tr44-13.html#WordBreakProperty.txt using PropList = HashMap<String, Vector<CodePointRange>>; // PropertyAliases source: https://www.unicode.org/Public/13.0.0/ucd/PropertyAliases.txt struct Alias { String property; String alias; }; // UnicodeData source: https://www.unicode.org/Public/13.0.0/ucd/UnicodeData.txt // Field descriptions: https://www.unicode.org/reports/tr44/tr44-13.html#UnicodeData.txt // https://www.unicode.org/reports/tr44/#General_Category_Values struct CodePointData { u32 code_point { 0 }; String name; String general_category; u8 canonical_combining_class { 0 }; String bidi_class; String decomposition_type; Optional<i8> numeric_value_decimal; Optional<i8> numeric_value_digit; Optional<i8> numeric_value_numeric; bool bidi_mirrored { false }; String unicode_1_name; String iso_comment; Optional<u32> simple_uppercase_mapping; Optional<u32> simple_lowercase_mapping; Optional<u32> simple_titlecase_mapping; Vector<u32> special_casing_indices; Vector<StringView> prop_list; StringView script; Vector<StringView> script_extensions; StringView word_break_property; }; struct UnicodeData { Vector<SpecialCasing> special_casing; u32 largest_casing_transform_size { 0 }; u32 largest_special_casing_size { 0 }; Vector<String> locales; Vector<String> conditions; Vector<CodePointData> code_point_data; Vector<CodePointRange> code_point_ranges; // The Unicode standard defines General Category values which are not in any UCD file. These // values are simply unions of other values. // https://www.unicode.org/reports/tr44/#GC_Values_Table Vector<String> general_categories; Vector<Alias> general_category_unions { { "Ll | Lu | Lt"sv, "LC"sv }, { "Lu | Ll | Lt | Lm | Lo"sv, "L"sv }, { "Mn | Mc | Me"sv, "M"sv }, { "Nd | Nl | No"sv, "N"sv }, { "Pc | Pd | Ps | Pe | Pi | Pf | Po"sv, "P"sv }, { "Sm | Sc | Sk | So"sv, "S"sv }, { "Zs | Zl | Zp"sv, "Z"sv }, { "Cc | Cf | Cs | Co"sv, "C"sv }, // FIXME: This union should also contain "Cn" (Unassigned), which we don't parse yet. }; Vector<Alias> general_category_aliases; // The Unicode standard defines additional properties (Any, Assigned, ASCII) which are not in // any UCD file. Assigned is set as the default enum value 0 so "property & Assigned == Assigned" // is always true. Any is not assigned code points here because this file only parses assigned // code points, whereas Any will include unassigned code points. // https://unicode.org/reports/tr18/#General_Category_Property PropList prop_list { { "Any"sv, {} }, { "ASCII"sv, { { 0, 0x7f } } }, }; Vector<Alias> prop_aliases; PropList script_list { { "Unknown"sv, {} }, }; Vector<Alias> script_aliases; PropList script_extensions; u32 largest_script_extensions_size { 0 }; PropList word_break_prop_list; }; static constexpr auto s_desired_fields = Array { "general_category"sv, "simple_uppercase_mapping"sv, "simple_lowercase_mapping"sv, }; static void write_to_file_if_different(Core::File& file, StringView contents) { auto const current_contents = file.read_all(); if (StringView { current_contents.bytes() } == contents) return; VERIFY(file.seek(0)); VERIFY(file.truncate(0)); VERIFY(file.write(contents)); } static void parse_special_casing(Core::File& file, UnicodeData& unicode_data) { auto parse_code_point_list = [&](auto const& line) { Vector<u32> code_points; auto segments = line.split(' '); for (auto const& code_point : segments) code_points.append(AK::StringUtils::convert_to_uint_from_hex<u32>(code_point).value()); return code_points; }; while (file.can_read_line()) { auto line = file.read_line(); if (line.is_empty() || line.starts_with('#')) continue; if (auto index = line.find('#'); index.has_value()) line = line.substring(0, *index); auto segments = line.split(';', true); VERIFY(segments.size() == 5 || segments.size() == 6); SpecialCasing casing {}; casing.index = static_cast<u32>(unicode_data.special_casing.size()); casing.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value(); casing.lowercase_mapping = parse_code_point_list(segments[1]); casing.titlecase_mapping = parse_code_point_list(segments[2]); casing.uppercase_mapping = parse_code_point_list(segments[3]); if (auto condition = segments[4].trim_whitespace(); !condition.is_empty()) { auto conditions = condition.split(' ', true); VERIFY(conditions.size() == 1 || conditions.size() == 2); if (conditions.size() == 2) { casing.locale = move(conditions[0]); casing.condition = move(conditions[1]); } else if (all_of(conditions[0], is_ascii_lower_alpha)) { casing.locale = move(conditions[0]); } else { casing.condition = move(conditions[0]); } casing.locale = casing.locale.to_uppercase(); casing.condition.replace("_", "", true); if (!casing.locale.is_empty() && !unicode_data.locales.contains_slow(casing.locale)) unicode_data.locales.append(casing.locale); if (!casing.condition.is_empty() && !unicode_data.conditions.contains_slow(casing.condition)) unicode_data.conditions.append(casing.condition); } unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.lowercase_mapping.size()); unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.titlecase_mapping.size()); unicode_data.largest_casing_transform_size = max(unicode_data.largest_casing_transform_size, casing.uppercase_mapping.size()); unicode_data.special_casing.append(move(casing)); } } static void parse_prop_list(Core::File& file, PropList& prop_list, bool multi_value_property = false) { while (file.can_read_line()) { auto line = file.read_line(); if (line.is_empty() || line.starts_with('#')) continue; if (auto index = line.find('#'); index.has_value()) line = line.substring(0, *index); auto segments = line.split_view(';', true); VERIFY(segments.size() == 2); auto code_point_range = segments[0].trim_whitespace(); Vector<StringView> properties; if (multi_value_property) properties = segments[1].trim_whitespace().split_view(' '); else properties = { segments[1].trim_whitespace() }; for (auto const& property : properties) { auto& code_points = prop_list.ensure(property.trim_whitespace()); if (code_point_range.contains(".."sv)) { segments = code_point_range.split_view(".."sv); VERIFY(segments.size() == 2); auto begin = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value(); auto end = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[1]).value(); code_points.append({ begin, end }); } else { auto code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(code_point_range).value(); code_points.append({ code_point, code_point }); } } } } static void parse_alias_list(Core::File& file, PropList const& prop_list, Vector<Alias>& prop_aliases) { String current_property; auto append_alias = [&](auto alias, auto property) { // Note: The alias files contain lines such as "Hyphen = Hyphen", which we should just skip. if (alias == property) return; // FIXME: We will, eventually, need to find where missing properties are located and parse them. if (!prop_list.contains(property)) return; prop_aliases.append({ property, alias }); }; while (file.can_read_line()) { auto line = file.read_line(); if (line.is_empty() || line.starts_with('#')) { if (line.ends_with("Properties"sv)) current_property = line.substring(2); continue; } // Note: For now, we only care about Binary Property aliases for Unicode property escapes. if (current_property != "Binary Properties"sv) continue; auto segments = line.split_view(';', true); VERIFY((segments.size() == 2) || (segments.size() == 3)); auto alias = segments[0].trim_whitespace(); auto property = segments[1].trim_whitespace(); append_alias(alias, property); if (segments.size() == 3) { alias = segments[2].trim_whitespace(); append_alias(alias, property); } } } static void parse_value_alias_list(Core::File& file, StringView desired_category, Vector<String> const& value_list, Vector<Alias> const& prop_unions, Vector<Alias>& prop_aliases, bool primary_value_is_first = true) { VERIFY(file.seek(0)); auto append_alias = [&](auto alias, auto value) { // Note: The value alias file contains lines such as "Ahom = Ahom", which we should just skip. if (alias == value) return; // FIXME: We will, eventually, need to find where missing properties are located and parse them. if (!value_list.contains_slow(value) && !any_of(prop_unions, [&](auto const& u) { return value == u.alias; })) return; prop_aliases.append({ value, alias }); }; while (file.can_read_line()) { auto line = file.read_line(); if (line.is_empty() || line.starts_with('#')) continue; if (auto index = line.find('#'); index.has_value()) line = line.substring(0, *index); auto segments = line.split_view(';', true); auto category = segments[0].trim_whitespace(); if (category != desired_category) continue; VERIFY((segments.size() == 3) || (segments.size() == 4)); auto value = primary_value_is_first ? segments[1].trim_whitespace() : segments[2].trim_whitespace(); auto alias = primary_value_is_first ? segments[2].trim_whitespace() : segments[1].trim_whitespace(); append_alias(alias, value); if (segments.size() == 4) { alias = segments[3].trim_whitespace(); append_alias(alias, value); } } } static void parse_unicode_data(Core::File& file, UnicodeData& unicode_data) { Optional<u32> code_point_range_start; auto assign_code_point_property = [&](u32 code_point, auto const& list, auto& property, StringView default_) { using PropertyType = RemoveCVReference<decltype(property)>; constexpr bool is_single_item = IsSame<PropertyType, StringView>; auto assign_property = [&](auto const& item) { if constexpr (is_single_item) property = item; else property.append(item); }; for (auto const& item : list) { for (auto const& range : item.value) { if ((range.first <= code_point) && (code_point <= range.last)) { assign_property(item.key); break; } } if constexpr (is_single_item) { if (!property.is_empty()) break; } } if (property.is_empty() && !default_.is_empty()) assign_property(default_); }; while (file.can_read_line()) { auto line = file.read_line(); if (line.is_empty()) continue; auto segments = line.split(';', true); VERIFY(segments.size() == 15); CodePointData data {}; data.code_point = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[0]).value(); data.name = move(segments[1]); data.general_category = move(segments[2]); data.canonical_combining_class = AK::StringUtils::convert_to_uint<u8>(segments[3]).value(); data.bidi_class = move(segments[4]); data.decomposition_type = move(segments[5]); data.numeric_value_decimal = AK::StringUtils::convert_to_int<i8>(segments[6]); data.numeric_value_digit = AK::StringUtils::convert_to_int<i8>(segments[7]); data.numeric_value_numeric = AK::StringUtils::convert_to_int<i8>(segments[8]); data.bidi_mirrored = segments[9] == "Y"sv; data.unicode_1_name = move(segments[10]); data.iso_comment = move(segments[11]); data.simple_uppercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[12]); data.simple_lowercase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[13]); data.simple_titlecase_mapping = AK::StringUtils::convert_to_uint_from_hex<u32>(segments[14]); if (data.name.starts_with("<"sv) && data.name.ends_with(", First>")) { VERIFY(!code_point_range_start.has_value()); code_point_range_start = data.code_point; data.name = data.name.substring(1, data.name.length() - 9); } else if (data.name.starts_with("<"sv) && data.name.ends_with(", Last>")) { VERIFY(code_point_range_start.has_value()); unicode_data.code_point_ranges.append({ *code_point_range_start, data.code_point }); data.name = data.name.substring(1, data.name.length() - 8); code_point_range_start.clear(); } for (auto const& casing : unicode_data.special_casing) { if (casing.code_point == data.code_point) data.special_casing_indices.append(casing.index); } assign_code_point_property(data.code_point, unicode_data.prop_list, data.prop_list, "Assigned"sv); assign_code_point_property(data.code_point, unicode_data.script_list, data.script, "Unknown"sv); assign_code_point_property(data.code_point, unicode_data.script_extensions, data.script_extensions, {}); assign_code_point_property(data.code_point, unicode_data.word_break_prop_list, data.word_break_property, "Other"sv); unicode_data.largest_special_casing_size = max(unicode_data.largest_special_casing_size, data.special_casing_indices.size()); unicode_data.largest_script_extensions_size = max(unicode_data.largest_script_extensions_size, data.script_extensions.size()); if (!unicode_data.general_categories.contains_slow(data.general_category)) unicode_data.general_categories.append(data.general_category); unicode_data.code_point_data.append(move(data)); } } static void generate_unicode_data_header(Core::File& file, UnicodeData& unicode_data) { StringBuilder builder; SourceGenerator generator { builder }; generator.set("casing_transform_size", String::number(unicode_data.largest_casing_transform_size)); generator.set("special_casing_size", String::number(unicode_data.largest_special_casing_size)); generator.set("script_extensions_size", String::number(unicode_data.largest_script_extensions_size)); auto generate_enum = [&](StringView name, StringView default_, Vector<String> values, Vector<Alias> unions = {}, Vector<Alias> aliases = {}, bool as_bitmask = false) { VERIFY(!as_bitmask || (values.size() <= 64)); quick_sort(values); quick_sort(unions, [](auto& union1, auto& union2) { return union1.alias < union2.alias; }); quick_sort(aliases, [](auto& alias1, auto& alias2) { return alias1.alias < alias2.alias; }); generator.set("name", name); generator.set("underlying", String::formatted("{}UnderlyingType", name)); if (as_bitmask) { generator.append(R"~~~( using @underlying@ = u64; enum class @name@ : @underlying@ {)~~~"); } else { generator.append(R"~~~( enum class @name@ {)~~~"); } if (!default_.is_empty()) { generator.set("default", default_); generator.append(R"~~~( @default@,)~~~"); } u8 index = 0; for (auto const& value : values) { generator.set("value", value); if (as_bitmask) { generator.set("index", String::number(index++)); generator.append(R"~~~( @value@ = static_cast<@underlying@>(1) << @index@,)~~~"); } else { generator.append(R"~~~( @value@,)~~~"); } } for (auto const& union_ : unions) { generator.set("union", union_.alias); generator.set("value", union_.property); generator.append(R"~~~( @union@ = @value@,)~~~"); } for (auto const& alias : aliases) { generator.set("alias", alias.alias); generator.set("value", alias.property); generator.append(R"~~~( @alias@ = @value@,)~~~"); } generator.append(R"~~~( }; )~~~"); if (as_bitmask) { generator.append(R"~~~( constexpr @name@ operator&(@name@ value1, @name@ value2) { return static_cast<@name@>(static_cast<@underlying@>(value1) & static_cast<@underlying@>(value2)); } constexpr @name@ operator|(@name@ value1, @name@ value2) { return static_cast<@name@>(static_cast<@underlying@>(value1) | static_cast<@underlying@>(value2)); } )~~~"); } }; generator.append(R"~~~( #pragma once #include <AK/Optional.h> #include <AK/Types.h> #include <LibUnicode/Forward.h> namespace Unicode { )~~~"); generate_enum("Locale"sv, "None"sv, move(unicode_data.locales)); generate_enum("Condition"sv, "None"sv, move(unicode_data.conditions)); generate_enum("GeneralCategory"sv, "None"sv, unicode_data.general_categories, unicode_data.general_category_unions, unicode_data.general_category_aliases, true); generate_enum("Property"sv, "Assigned"sv, unicode_data.prop_list.keys(), {}, unicode_data.prop_aliases, true); generate_enum("Script"sv, {}, unicode_data.script_list.keys(), {}, unicode_data.script_aliases); generate_enum("WordBreakProperty"sv, "Other"sv, unicode_data.word_break_prop_list.keys()); generator.append(R"~~~( struct SpecialCasing { u32 code_point { 0 }; u32 lowercase_mapping[@casing_transform_size@]; u32 lowercase_mapping_size { 0 }; u32 uppercase_mapping[@casing_transform_size@]; u32 uppercase_mapping_size { 0 }; u32 titlecase_mapping[@casing_transform_size@]; u32 titlecase_mapping_size { 0 }; Locale locale { Locale::None }; Condition condition { Condition::None }; }; struct UnicodeData { u32 code_point;)~~~"); auto append_field = [&](StringView type, StringView name) { if (!s_desired_fields.span().contains_slow(name)) return; generator.set("type", type); generator.set("name", name); generator.append(R"~~~( @type@ @name@;)~~~"); }; // Note: For compile-time performance, only primitive types are used. append_field("char const*"sv, "name"sv); append_field("GeneralCategory"sv, "general_category"sv); append_field("u8"sv, "canonical_combining_class"sv); append_field("char const*"sv, "bidi_class"sv); append_field("char const*"sv, "decomposition_type"sv); append_field("i8"sv, "numeric_value_decimal"sv); append_field("i8"sv, "numeric_value_digit"sv); append_field("i8"sv, "numeric_value_numeric"sv); append_field("bool"sv, "bidi_mirrored"sv); append_field("char const*"sv, "unicode_1_name"sv); append_field("char const*"sv, "iso_comment"sv); append_field("u32"sv, "simple_uppercase_mapping"sv); append_field("u32"sv, "simple_lowercase_mapping"sv); append_field("u32"sv, "simple_titlecase_mapping"sv); generator.append(R"~~~( SpecialCasing const* special_casing[@special_casing_size@] {}; u32 special_casing_size { 0 }; Property properties { Property::Assigned }; Script script { Script::Unknown }; Script script_extensions[@script_extensions_size@]; u32 script_extensions_size { 0 }; WordBreakProperty word_break_property { WordBreakProperty::Other }; }; namespace Detail { Optional<UnicodeData> unicode_data_for_code_point(u32 code_point); Optional<Property> property_from_string(StringView const& property); Optional<GeneralCategory> general_category_from_string(StringView const& general_category); Optional<Script> script_from_string(StringView const& script); } } )~~~"); write_to_file_if_different(file, generator.as_string_view()); } static void generate_unicode_data_implementation(Core::File& file, UnicodeData const& unicode_data) { StringBuilder builder; SourceGenerator generator { builder }; generator.set("special_casing_size", String::number(unicode_data.special_casing.size())); generator.set("code_point_data_size", String::number(unicode_data.code_point_data.size())); generator.append(R"~~~( #include <AK/Array.h> #include <AK/CharacterTypes.h> #include <AK/HashMap.h> #include <AK/StringView.h> #include <LibUnicode/UnicodeData.h> namespace Unicode { )~~~"); auto append_list_and_size = [&](auto const& list, StringView format) { if (list.is_empty()) { generator.append(", {}, 0"); return; } bool first = true; generator.append(", {"); for (auto const& item : list) { generator.append(first ? " " : ", "); generator.append(String::formatted(format, item)); first = false; } generator.append(String::formatted(" }}, {}", list.size())); }; generator.append(R"~~~( static constexpr Array<SpecialCasing, @special_casing_size@> s_special_casing { {)~~~"); for (auto const& casing : unicode_data.special_casing) { generator.set("code_point", String::formatted("{:#x}", casing.code_point)); generator.append(R"~~~( { @code_point@)~~~"); constexpr auto format = "0x{:x}"sv; append_list_and_size(casing.lowercase_mapping, format); append_list_and_size(casing.uppercase_mapping, format); append_list_and_size(casing.titlecase_mapping, format); generator.set("locale", casing.locale.is_empty() ? "None" : casing.locale); generator.append(", Locale::@locale@"); generator.set("condition", casing.condition.is_empty() ? "None" : casing.condition); generator.append(", Condition::@condition@"); generator.append(" },"); } generator.append(R"~~~( } }; static constexpr Array<UnicodeData, @code_point_data_size@> s_unicode_data { {)~~~"); auto append_field = [&](StringView name, String value) { if (!s_desired_fields.span().contains_slow(name)) return; generator.set("value", move(value)); generator.append(", @value@"); }; for (auto const& data : unicode_data.code_point_data) { generator.set("code_point", String::formatted("{:#x}", data.code_point)); generator.append(R"~~~( { @code_point@)~~~"); append_field("name", String::formatted("\"{}\"", data.name)); append_field("general_category", String::formatted("GeneralCategory::{}", data.general_category)); append_field("canonical_combining_class", String::number(data.canonical_combining_class)); append_field("bidi_class", String::formatted("\"{}\"", data.bidi_class)); append_field("decomposition_type", String::formatted("\"{}\"", data.decomposition_type)); append_field("numeric_value_decimal", String::number(data.numeric_value_decimal.value_or(-1))); append_field("numeric_value_digit", String::number(data.numeric_value_digit.value_or(-1))); append_field("numeric_value_numeric", String::number(data.numeric_value_numeric.value_or(-1))); append_field("bidi_mirrored", String::formatted("{}", data.bidi_mirrored)); append_field("unicode_1_name", String::formatted("\"{}\"", data.unicode_1_name)); append_field("iso_comment", String::formatted("\"{}\"", data.iso_comment)); append_field("simple_uppercase_mapping", String::formatted("{:#x}", data.simple_uppercase_mapping.value_or(data.code_point))); append_field("simple_lowercase_mapping", String::formatted("{:#x}", data.simple_lowercase_mapping.value_or(data.code_point))); append_field("simple_titlecase_mapping", String::formatted("{:#x}", data.simple_titlecase_mapping.value_or(data.code_point))); append_list_and_size(data.special_casing_indices, "&s_special_casing[{}]"sv); bool first = true; for (auto const& property : data.prop_list) { generator.append(first ? ", " : " | "); generator.append(String::formatted("Property::{}", property)); first = false; } generator.append(String::formatted(", Script::{}", data.script)); append_list_and_size(data.script_extensions, "Script::{}"sv); generator.append(String::formatted(", WordBreakProperty::{}", data.word_break_property)); generator.append(" },"); } generator.append(R"~~~( } }; static HashMap<u32, UnicodeData const*> const& ensure_code_point_map() { static HashMap<u32, UnicodeData const*> code_point_to_data_map; code_point_to_data_map.ensure_capacity(s_unicode_data.size()); for (auto const& unicode_data : s_unicode_data) code_point_to_data_map.set(unicode_data.code_point, &unicode_data); return code_point_to_data_map; } static Optional<u32> index_of_code_point_in_range(u32 code_point) {)~~~"); for (auto const& range : unicode_data.code_point_ranges) { generator.set("first", String::formatted("{:#x}", range.first)); generator.set("last", String::formatted("{:#x}", range.last)); generator.append(R"~~~( if ((code_point > @first@) && (code_point < @last@)) return @first@;)~~~"); } generator.append(R"~~~( return {}; } namespace Detail { Optional<UnicodeData> unicode_data_for_code_point(u32 code_point) { static auto const& code_point_to_data_map = ensure_code_point_map(); VERIFY(is_unicode(code_point)); if (auto data = code_point_to_data_map.get(code_point); data.has_value()) return *(data.value()); if (auto index = index_of_code_point_in_range(code_point); index.has_value()) { auto data_for_range = *(code_point_to_data_map.get(*index).value()); data_for_range.simple_uppercase_mapping = code_point; data_for_range.simple_lowercase_mapping = code_point; return data_for_range; } return {}; } Optional<Property> property_from_string(StringView const& property) { if (property == "Assigned"sv) return Property::Assigned;)~~~"); for (auto const& property : unicode_data.prop_list) { generator.set("property", property.key); generator.append(R"~~~( if (property == "@property@"sv) return Property::@property@;)~~~"); } for (auto const& alias : unicode_data.prop_aliases) { generator.set("property", alias.alias); generator.append(R"~~~( if (property == "@property@"sv) return Property::@property@;)~~~"); } generator.append(R"~~~( return {}; } Optional<GeneralCategory> general_category_from_string(StringView const& general_category) {)~~~"); for (auto const& general_category : unicode_data.general_categories) { generator.set("general_category", general_category); generator.append(R"~~~( if (general_category == "@general_category@"sv) return GeneralCategory::@general_category@;)~~~"); } for (auto const& union_ : unicode_data.general_category_unions) { generator.set("general_category", union_.alias); generator.append(R"~~~( if (general_category == "@general_category@"sv) return GeneralCategory::@general_category@;)~~~"); } for (auto const& alias : unicode_data.general_category_aliases) { generator.set("general_category", alias.alias); generator.append(R"~~~( if (general_category == "@general_category@"sv) return GeneralCategory::@general_category@;)~~~"); } generator.append(R"~~~( return {}; } Optional<Script> script_from_string(StringView const& script) {)~~~"); for (auto const& script : unicode_data.script_list) { generator.set("script", script.key); generator.append(R"~~~( if (script == "@script@"sv) return Script::@script@;)~~~"); } for (auto const& alias : unicode_data.script_aliases) { generator.set("script", alias.alias); generator.append(R"~~~( if (script == "@script@"sv) return Script::@script@;)~~~"); } generator.append(R"~~~( return {}; } } } )~~~"); write_to_file_if_different(file, generator.as_string_view()); } int main(int argc, char** argv) { char const* generated_header_path = nullptr; char const* generated_implementation_path = nullptr; char const* unicode_data_path = nullptr; char const* special_casing_path = nullptr; char const* prop_list_path = nullptr; char const* derived_core_prop_path = nullptr; char const* derived_binary_prop_path = nullptr; char const* prop_alias_path = nullptr; char const* prop_value_alias_path = nullptr; char const* scripts_path = nullptr; char const* script_extensions_path = nullptr; char const* word_break_path = nullptr; char const* emoji_data_path = nullptr; Core::ArgsParser args_parser; args_parser.add_option(generated_header_path, "Path to the Unicode Data header file to generate", "generated-header-path", 'h', "generated-header-path"); args_parser.add_option(generated_implementation_path, "Path to the Unicode Data implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path"); args_parser.add_option(unicode_data_path, "Path to UnicodeData.txt file", "unicode-data-path", 'u', "unicode-data-path"); args_parser.add_option(special_casing_path, "Path to SpecialCasing.txt file", "special-casing-path", 's', "special-casing-path"); args_parser.add_option(prop_list_path, "Path to PropList.txt file", "prop-list-path", 'p', "prop-list-path"); args_parser.add_option(derived_core_prop_path, "Path to DerivedCoreProperties.txt file", "derived-core-prop-path", 'd', "derived-core-prop-path"); args_parser.add_option(derived_binary_prop_path, "Path to DerivedBinaryProperties.txt file", "derived-binary-prop-path", 'b', "derived-binary-prop-path"); args_parser.add_option(prop_alias_path, "Path to PropertyAliases.txt file", "prop-alias-path", 'a', "prop-alias-path"); args_parser.add_option(prop_value_alias_path, "Path to PropertyValueAliases.txt file", "prop-value-alias-path", 'v', "prop-value-alias-path"); args_parser.add_option(scripts_path, "Path to Scripts.txt file", "scripts-path", 'r', "scripts-path"); args_parser.add_option(script_extensions_path, "Path to ScriptExtensions.txt file", "script-extensions-path", 'x', "script-extensions-path"); args_parser.add_option(word_break_path, "Path to WordBreakProperty.txt file", "word-break-path", 'w', "word-break-path"); args_parser.add_option(emoji_data_path, "Path to emoji-data.txt file", "emoji-data-path", 'e', "emoji-data-path"); args_parser.parse(argc, argv); auto open_file = [&](StringView path, StringView flags, Core::OpenMode mode = Core::OpenMode::ReadOnly) { if (path.is_empty()) { warnln("{} is required", flags); args_parser.print_usage(stderr, argv[0]); exit(1); } auto file_or_error = Core::File::open(path, mode); if (file_or_error.is_error()) { warnln("Failed to open {}: {}", path, file_or_error.release_error()); exit(1); } return file_or_error.release_value(); }; auto generated_header_file = open_file(generated_header_path, "-h/--generated-header-path", Core::OpenMode::ReadWrite); auto generated_implementation_file = open_file(generated_implementation_path, "-c/--generated-implementation-path", Core::OpenMode::ReadWrite); auto unicode_data_file = open_file(unicode_data_path, "-u/--unicode-data-path"); auto special_casing_file = open_file(special_casing_path, "-s/--special-casing-path"); auto prop_list_file = open_file(prop_list_path, "-p/--prop-list-path"); auto derived_core_prop_file = open_file(derived_core_prop_path, "-d/--derived-core-prop-path"); auto derived_binary_prop_file = open_file(derived_binary_prop_path, "-b/--derived-binary-prop-path"); auto prop_alias_file = open_file(prop_alias_path, "-a/--prop-alias-path"); auto prop_value_alias_file = open_file(prop_value_alias_path, "-v/--prop-value-alias-path"); auto scripts_file = open_file(scripts_path, "-r/--scripts-path"); auto script_extensions_file = open_file(script_extensions_path, "-x/--script-extensions-path"); auto word_break_file = open_file(word_break_path, "-w/--word-break-path"); auto emoji_data_file = open_file(emoji_data_path, "-e/--emoji-data-path"); UnicodeData unicode_data {}; parse_special_casing(special_casing_file, unicode_data); parse_prop_list(prop_list_file, unicode_data.prop_list); parse_prop_list(derived_core_prop_file, unicode_data.prop_list); parse_prop_list(derived_binary_prop_file, unicode_data.prop_list); parse_prop_list(emoji_data_file, unicode_data.prop_list); parse_alias_list(prop_alias_file, unicode_data.prop_list, unicode_data.prop_aliases); parse_prop_list(scripts_file, unicode_data.script_list); parse_prop_list(script_extensions_file, unicode_data.script_extensions, true); parse_prop_list(word_break_file, unicode_data.word_break_prop_list); parse_unicode_data(unicode_data_file, unicode_data); parse_value_alias_list(prop_value_alias_file, "gc"sv, unicode_data.general_categories, unicode_data.general_category_unions, unicode_data.general_category_aliases); parse_value_alias_list(prop_value_alias_file, "sc"sv, unicode_data.script_list.keys(), {}, unicode_data.script_aliases, false); generate_unicode_data_header(generated_header_file, unicode_data); generate_unicode_data_implementation(generated_implementation_file, unicode_data); return 0; }
40.083333
214
0.662564
Blocky-studio
b9f64e7519efdf9f94327dbbc6d2229ed1017bdf
2,405
cpp
C++
samples/cpp/3_2_1/3_2_1.cpp
971586331/opencv-2.4.9
d0ecc6013340ce505bade94a61946ba7654e381d
[ "BSD-3-Clause" ]
null
null
null
samples/cpp/3_2_1/3_2_1.cpp
971586331/opencv-2.4.9
d0ecc6013340ce505bade94a61946ba7654e381d
[ "BSD-3-Clause" ]
null
null
null
samples/cpp/3_2_1/3_2_1.cpp
971586331/opencv-2.4.9
d0ecc6013340ce505bade94a61946ba7654e381d
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------【头文件、命名空间包含部分】------------------------------- // 描述:包含程序所使用的头文件和命名空间 //------------------------------------------------------------------------------------------------- #include <stdio.h> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; //-----------------------------------【宏定义部分】-------------------------------------------- // 描述:定义一些辅助宏 //------------------------------------------------------------------------------------------------ #define WINDOW_NAME "【滑动条的创建&线性混合示例】" //为窗口标题定义的宏 //-----------------------------------【全局变量声明部分】-------------------------------------- // 描述:全局变量声明 //----------------------------------------------------------------------------------------------- const int g_nMaxAlphaValue = 100;//Alpha值的最大值 int g_nAlphaValueSlider;//滑动条对应的变量 double g_dAlphaValue; double g_dBetaValue; //声明存储图像的变量 Mat g_srcImage1; Mat g_srcImage2; Mat g_dstImage; //-----------------------------------【on_Trackbar( )函数】-------------------------------- // 描述:响应滑动条的回调函数 //------------------------------------------------------------------------------------------ void on_Trackbar( int, void* ) { //求出当前alpha值相对于最大值的比例 g_dAlphaValue = (double) g_nAlphaValueSlider/g_nMaxAlphaValue ; //则beta值为1减去alpha值 g_dBetaValue = ( 1.0 - g_dAlphaValue ); //根据alpha和beta值进行线性混合 addWeighted( g_srcImage1, g_dAlphaValue, g_srcImage2, g_dBetaValue, 0.0, g_dstImage); //显示效果图 imshow( WINDOW_NAME, g_dstImage ); } //--------------------------------------【main( )函数】----------------------------------------- // 描述:控制台应用程序的入口函数,我们的程序从这里开始执行 //----------------------------------------------------------------------------------------------- int main( int argc, char** argv ) { //加载图像 (两图像的尺寸需相同) g_srcImage1 = imread("1.jpg"); g_srcImage2 = imread("2.jpg"); if( !g_srcImage1.data ) { printf("读取第一幅图片错误,请确定目录下是否有imread函数指定图片存在~! \n"); return -1; } if( !g_srcImage2.data ) { printf("读取第二幅图片错误,请确定目录下是否有imread函数指定图片存在~!\n"); return -1; } //设置滑动条初值为70 g_nAlphaValueSlider = 70; //创建窗体 namedWindow(WINDOW_NAME, 1); //在创建的窗体中创建一个滑动条控件 char TrackbarName[50]; sprintf( TrackbarName, "透明值 %d", g_nMaxAlphaValue ); createTrackbar( TrackbarName, WINDOW_NAME, &g_nAlphaValueSlider, g_nMaxAlphaValue, on_Trackbar ); //结果在回调函数中显示 on_Trackbar( g_nAlphaValueSlider, 0 ); //按任意键退出 waitKey(0); return 0; }
30.833333
99
0.469439
971586331
b9fbc29db558bb43b7156b6602d6b5a171bb5e7b
370
cpp
C++
src/crossserver/crossserver/protocal/msgcpp.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
3
2021-12-16T13:57:28.000Z
2022-03-26T07:50:08.000Z
src/crossserver/crossserver/protocal/msgcpp.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
null
null
null
src/crossserver/crossserver/protocal/msgcpp.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
1
2022-03-26T07:50:11.000Z
2022-03-26T07:50:11.000Z
#include "servercommon/userprotocal/msgheader.h" #include "servercommon/userprotocal/systemmsgcode.h" #include "servercommon/userprotocal/crossmsgcode.h" #include "servercommon/userprotocal/msgsystem.h" #include "msgcross.h" namespace Protocol { SCNoticeNum::SCNoticeNum():header(MT_SYSTEM_NOTICE_CODE_SC){} SCSystemMsg::SCSystemMsg():header(MT_SYSTEM_MSG_SC){} }
24.666667
62
0.810811
mage-game
b9fd7d8c1bf20e8968297aae72ed825276e13430
24,061
cpp
C++
robot/common/Body/jhcManusBody.cpp
jconnell11/ALIA
f7a6c9dfd775fbd41239051aeed7775adb878b0a
[ "Apache-2.0" ]
null
null
null
robot/common/Body/jhcManusBody.cpp
jconnell11/ALIA
f7a6c9dfd775fbd41239051aeed7775adb878b0a
[ "Apache-2.0" ]
null
null
null
robot/common/Body/jhcManusBody.cpp
jconnell11/ALIA
f7a6c9dfd775fbd41239051aeed7775adb878b0a
[ "Apache-2.0" ]
null
null
null
// jhcManusBody.cpp : basic control of Manus small forklift robot // // Written by Jonathan H. Connell, [email protected] // /////////////////////////////////////////////////////////////////////////// // // Copyright 2019-2020 IBM Corporation // Copyright 2020 Etaoin Systems // // 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. // /////////////////////////////////////////////////////////////////////////// #include <math.h> #include "Interface/jhcMessage.h" // common video #include "Interface/jms_x.h" #include "Video/jhcOcv3VSrc.h" #include "Body/jhcManusBody.h" /////////////////////////////////////////////////////////////////////////// // Creation and Initialization // /////////////////////////////////////////////////////////////////////////// //= Default destructor does necessary cleanup. jhcManusBody::~jhcManusBody () { ser.Close(); if (wifi > 0) delete vid; } //= Default constructor initializes certain values. // large transaction pod send to servo control for best speed // ask = 4 channel target commands (4*4 = 16) // 1 channel speed command (1*4 = 4) // 6 channel position request (6*2 = 12) jhcManusBody::jhcManusBody () { UC8 *req = ask + 20; int i; // prepare multiple target commands (start at 0, 4, 8, 12) for (i = 0; i < 16; i += 4) ask[i] = 0x84; ask[1] = LFW; ask[5] = LIFT; ask[9] = RTW; ask[13] = HAND; // prepare multiple position requests (all 6 channels) for (i = 0; i < 12; i += 2) { req[i] = 0x90; req[i + 1] = (UC8)(i / 2); } // expect external video source to be bound now.SetSize(640, 360, 3); vid = NULL; wifi = 0; // default robot ID and serial port port0 = 10; id = 0; // set processing parameters and initial state Defaults(); clr_state(); } //= Set image sizes directly. void jhcManusBody::SetSize (int x, int y) { jhcManusX::SetSize(x, y); now.SetSize(frame); } /////////////////////////////////////////////////////////////////////////// // Processing Parameters // /////////////////////////////////////////////////////////////////////////// //= Parameters describing camera warping and pose. int jhcManusBody::cam_params (const char *fname) { jhcParam *ps = &cps; int ok; ps->SetTag("man_cam", 0); ps->NextSpecF( &w2, -3.0, "R^2 warp coefficient"); ps->NextSpecF( &w4, 6.5, "R^4 warp coefficient"); ps->NextSpecF( &mag, 0.9, "Magnification"); ps->NextSpecF( &roll, -1.0, "Roll (deg)"); ok = ps->LoadDefs(fname); ps->RevertAll(); return ok; } //= Parameters for distance sensor and miscellaneous reporting. int jhcManusBody::range_params (const char *fname) { jhcParam *ps = &rps; int ok; ps->SetTag("man_rng", 0); ps->NextSpec4( &v0, 426, "Sensor close value"); ps->NextSpecF( &r0, 0.0, "Close range (in)"); ps->NextSpec4( &v4, 106, "Sensor middle val"); ps->NextSpecF( &r4, 4.0, "Middle range (in)"); ps->NextSpec4( &v12, 64, "Sensor far value"); ps->NextSpecF( &r12, 6.0, "Far range (in)"); ok = ps->LoadDefs(fname); ps->RevertAll(); return ok; } //= Parameters used for interpreting gripper width. int jhcManusBody::width_params (const char *fname) { jhcParam *ps = &wps; int ok; ps->SetTag("man_wid", 0); ps->NextSpecF( &vmax, 23.0, "Full open val (us)"); ps->NextSpecF( &vfat, 99.0, "Holding fat val (us)"); ps->NextSpecF( &vmed, 121.5, "Holding medium val (us)"); ps->NextSpecF( &vmin, 125.0, "Full close val (us)"); ps->NextSpecF( &wfat, 1.7, "Fat object (in)"); ps->NextSpecF( &wmed, 1.4, "Medium object (in)"); ps->NextSpecF( &wsm, 0.94, "Decrease for inner pads (in)"); ok = ps->LoadDefs(fname); ps->RevertAll(); return ok; } //= Parameters used for controlling wheel motion. int jhcManusBody::drive_params (const char *fname) { jhcParam *ps = &dps; int ok; ps->SetTag("man_drive", 0); ps->NextSpec4( &lf0, 1484, "Left zero value (us)"); ps->NextSpec4( &rt0, 1484, "Right zero value (us)"); ps->NextSpecF( &vcal, 9.0, "Calibrated speed (ips)"); // cal 18" @ 9 ips ps->NextSpec4( &ccal, 339, "Diff cmd for speed (us)"); ps->NextSpecF( &bal, 0.0, "Right vs. left balance"); ps->NextSpecF( &sep, 4.2, "Virtual turn circle (in)"); // cal 180 degs @ 9 ips ps->NextSpec4( &dacc, 40, "Acceleration limit"); ok = ps->LoadDefs(fname); ps->RevertAll(); return ok; } //= Parameters used for controlling forklift stage. int jhcManusBody::lift_params (const char *fname) { jhcParam *ps = &lps; int ok; ps->SetTag("man_lift", 0); ps->NextSpec4( &ldef, 1780, "Default lift value (us)"); ps->NextSpecF( &hdef, 0.3, "Default height (in)"); ps->NextSpec4( &lout, 1320, "Horizontal lift val (us)"); ps->NextSpecF( &hout, 2.0, "Horizontal height (in)"); ps->NextSpecF( &arm, 2.5, "Lift arm length (in)"); ps->Skip(); ps->NextSpec4( &lsp, 100, "Lift speed limit"); // was 50 ps->NextSpec4( &lacc, 15, "Lift acceleration"); ok = ps->LoadDefs(fname); ps->RevertAll(); return ok; } //= Parameters used for controlling gripper. int jhcManusBody::grip_params (const char *fname) { jhcParam *ps = &gps; int ok; ps->SetTag("man_grip", 0); ps->NextSpec4( &gmax, 433, "Open gripper value (us)"); ps->NextSpec4( &gmin, 2282, "Closed gripper value (us)"); ps->Skip(); ps->NextSpecF( &wtol, 0.1, "Offset for closed test (in)"); ps->NextSpecF( &wprog, 0.05, "Insignificant change (in)"); ps->NextSpec4( &wstop, 5, "Count for no motion"); ps->NextSpec4( &gsp, 100, "Grip speed limit"); ok = ps->LoadDefs(fname); ps->RevertAll(); return ok; } /////////////////////////////////////////////////////////////////////////// // Parameter Bundles // /////////////////////////////////////////////////////////////////////////// //= Read all relevant defaults variable values from a file. int jhcManusBody::Defaults (const char *fname) { int ok = 1; ok &= cam_params(fname); ok &= range_params(fname); ok &= width_params(fname); ok &= drive_params(fname); ok &= lift_params(fname); ok &= grip_params(fname); return ok; } //= Write current processing variable values to a file. int jhcManusBody::SaveVals (const char *fname) const { int ok = 1; ok &= cps.SaveVals(fname); ok &= rps.SaveVals(fname); ok &= wps.SaveVals(fname); ok &= dps.SaveVals(fname); ok &= lps.SaveVals(fname); ok &= gps.SaveVals(fname); return ok; } //= Possibly change robot ID number then reload calibration parameters. int jhcManusBody::LoadCfg (const char *dir, int robot, int noisy) { if (robot > 0) id = robot; CfgName(dir); jprintf(1, noisy, "Reading robot calibration from: %s\n", cfile); return Defaults(cfile); } //= Save values to standard file name. int jhcManusBody::SaveCfg (const char *dir) { return SaveVals(CfgName(dir)); } //= Get canonical name of configuration file based on retrieved ID. // can optionally preface name with supplied path // returns pointer to internal string const char *jhcManusBody::CfgName (const char *dir) { if (dir != NULL) sprintf_s(cfile, "%s/Manus-%d.cfg", dir, id); else sprintf_s(cfile, "Manus-%d.cfg", id); return cfile; } /////////////////////////////////////////////////////////////////////////// // Camera Connection // /////////////////////////////////////////////////////////////////////////// //= Bind an external video source to be used. void jhcManusBody::BindVideo (jhcVideoSrc *v) { if (wifi > 0) delete vid; wifi = 0; vid = v; if (vid != NULL) vid->SizeFor(frame); } //= Bind the SQ13 WiFi cube camera for image acquistion. int jhcManusBody::SetWifiCam (int rpt) { jhcOcv3VSrc *v; // make sure not already bound if (wifi > 0) return 1; // try connecting if (rpt > 0) jprintf("Connecting to wifi camera ...\n"); if ((v = new jhcOcv3VSrc("ttp://192.168.25.1:8080/?action=stream.ocv3")) == NULL) { if (rpt >= 2) Complain("Could not connect to SQ13 camera"); else if (rpt > 0) jprintf(">>> Could not connect to SQ13 camera !\n"); return 0; } // configure images if (rpt > 0) jprintf(" ** good **\n\n"); BindVideo(v); wifi = 1; return 1; } /////////////////////////////////////////////////////////////////////////// // Main Functions // /////////////////////////////////////////////////////////////////////////// //= Reset state for the beginning of a sequence. // will also automatically read in correct calibration file from "dir" // returns 1 if connected, 0 or negative for problem int jhcManusBody::Reset (int noisy, const char *dir, int prefer) { UC8 pod[2]; int com = 0; // try to connect to particular robot if (prefer > 0) com = find_robot(prefer, noisy); // set up conversion factors and gripper state chan_coefs(); v2d_eqn(); clr_state(); lvel = 0.0; // no translation or rotation rvel = 0.0; wcmd = wmax; // fully open pgrip = 0; // reconnect serial port and clear any controller errors mok = 0; if (com > 0) if (ser.Xmit(0xA1) > 0) { // get response but ignore details (wait required) jms_sleep(30); if (ser.RxArray(pod, 2) >= 2) mok = 1; // set up initial pose then wait for it to be achieved servo_defs(); rcv_all(); jms_sleep(500); req_all(); // request positions for first Update } // create image rectification pattern and rewind video (if file) wp.InitSize(frame.XDim(), frame.YDim(), 3); wp.Rectify(w2, w4, mag, roll); if (vid != NULL) if (vid->Rewind() <= 0) return 0; return mok; } //= Look for the preferred robot then set the valid port and id. // if prefer = 0 then scans all standard serial ports // returns 1 something found, 0 for no robots available int jhcManusBody::find_robot (int prefer, int noisy) { int rid, rnum = prefer; // try port associated with preferred robot or scan all if (prefer > 0) rid = test_port(rnum, noisy); else for (rnum = 1; rnum <= 9; rnum++) if ((rid = test_port(rnum, noisy)) > 0) break; // save parameters if robot actually found if (rid > 0) { id = rid; return 1; } // failure jprintf(1, noisy, ">>> Could not talk to robot!\n"); return 0; } //= Try connecting to robot on given serial port. // returns hardware ID if successful (and leaves port open) int jhcManusBody::test_port (int n, int noisy) { UC8 pod[2]; int i, p = port0 + n; // see if connection exists jprintf(1, noisy, "Looking for robot on serial port %d ...\n", p); if (ser.SetSource(p, 230400) <= 0) return 0; ser.wtime = 0.2; // for HC-05 Bluetooth latency // make sure a robot is there if (ser.Xmit(0xA1) > 0) if (ser.RxArray(pod, 2) >= 2) { // try to get ID number if (test_id(n)) return n; for (i = 1; i < 256; i++) if (i != n) if (test_id(i)) return i; // assume given number was correct jprintf(1, noisy, ">>> Unable to determine robot ID!\n\n"); return n; } // close port if no response to basic probe ser.Close(); return 0; } //= See if the robot responds to the given hardware ID. bool jhcManusBody::test_id (int i) { UC8 pod[3] = {0xAA, (UC8) i, 0x21}; if (ser.TxArray(pod, 3) < 3) return false; return(ser.RxArray(pod, 2) >= 2); } //= Precompute coefficients for turning commands into pulse widths. void jhcManusBody::chan_coefs () { // fork rate at 50 Hz based on change from default to straight out lsf = 4.0 * abs(lout - ldef) / (50.0 * (hout - hdef)); // width sensor conversion wsc = (wfat - wmed) / (vfat - vmed); wmin = get_grip(vmin); wmax = get_grip(vmax); // position command conversion factors msc = ccal / vcal; tsc = msc * PI * 0.5 * sep / 180.0; lsc = (ldef - lout) / asin((hdef - hout) / arm); gsc = (gmax - gmin) / (wmax - wmin); } //= Precompute values for turning voltage into distance. // distance is roughly proportional to inverse voltage // <pre> // r = rsc / (v + voff) + roff // v = rsc / (r - roff) - voff // // (v0 - v4) = rsc * [ 1 / (r0 - roff) - 1 / (r4 - roff) ] // = rsc * [ (r4 - roff) - (r0 - roff) ] / (r0 - roff) * (r4 - roff) // = rsc * (r4 - r0) / (r0 - roff) * (r4 - roff) // // rsc = (v0 - v4) * (r0 - roff) * (r4 - roff) / (r4 - r0) // = [ (v0 - v4) / (r4 - r0) ] * (r0 - roff) * (r4 - roff) // = S * (r0 - roff) * (r4 - roff) where S = (v0 - v4) / (r4 - r0) // // rsc = T * (r0 - roff) * (r12 - roff) where T = (v0 - v12) / (r12 - r0) // // S * (r0 - roff) * (r4 - roff) = T * (r0 - roff) * (r12 - roff) // S * (r4 - roff) = T * (r12 - roff) // S * r4 - S * roff = T * r12 - T * roff // (T - S) * roff = T * r12 - S * r4 // roff = (T * r12 - S * r4) / (T - S) // // (v0 - v4) = rsc * [ 1 / (r0 - roff) - 1 / (r4 - roff) ] // rsc = (v0 - v4) / [ 1 / (r0 - roff) - 1 / (r4 - roff) ] // // v12 = rsc / (r12 - roff) - voff // voff = rsc / (r12 - roff) - v12 // // </pre> void jhcManusBody::v2d_eqn () { double S = (v0 - v4) / (r4 - r0), T = (v0 - v12) / (r12 - r0); roff = (T * r12 - S * r4) / (T - S); rsc = (v0 - v4) / (1.0 / (r0 - roff) - 1.0 / (r4 - roff)); voff = rsc / (r12 - roff) - v12; } //= Set initial servo positions and motion profiling parameters. void jhcManusBody::servo_defs () { // set servo max speeds and accelerations set_speed(HAND, gsp, 1); set_speed(LIFT, lsp, 1); set_accel(LIFT, lacc); set_speed(LFW, dacc, 1); // really acceleration set_speed(RTW, dacc, 1); // set initial targets (in microseconds) set_target(LFW, lf0); set_target(RTW, rt0); set_target(LIFT, ldef); set_target(HAND, gmax); req_all(); } //= Freezes all motion servos, sets hand to passive. void jhcManusBody::Stop () { // set up actuator commands send_wheels(0.0, 0.0); send_lift(0.0); send_grip(0); // send to robot (skip getting sensors) if (mok > 0) { ser.TxArray(ask, 20); jms_sleep(100); } // always kill comm link (must be re-established later) ser.Close(); mok = 0; } /////////////////////////////////////////////////////////////////////////// // Rough Odometry // /////////////////////////////////////////////////////////////////////////// //= Reset odometry so current direction is angle zero and path length zero. // also resets Cartesian coordinates to (0, 0) and x axis points forward void jhcManusBody::Zero () { } /////////////////////////////////////////////////////////////////////////// // Core Interaction // /////////////////////////////////////////////////////////////////////////// //= Read and interpret base odometry as well as grip force and distance. // assumes req_all() has already been called to prompt status return // automatically resets "lock" for new bids and specifies default motion // HC-05 Bluetooth has an instrinsic latency of 36 +/- 10ms so 27 Hz max // returns 1 for okay, 0 or negative for problem int jhcManusBody::Update (int img) { int rc = 0; // wait until next video frame is ready then rectify if (img > 0) if ((rc = UpdateImg(1)) < 0) return -1; // check for sensors on Bluetooth if (rcv_all() > 0) { // record sensor values lvel = get_lf(pos[LFW]); rvel = get_rt(pos[RTW]); ht = get_lift(pos[LIFT]); wid = get_grip(pos[WID]); dist = get_dist(pos[DIST]); // do additional interpretation inc_odom(jms_now()); } // set up for next cycle cmd_defs(); return mok; } //= Load new image from video source and possibly rectify. // sometimes useful for debugging vison (robot sensors are irrelevant) // can forego rectification in order to leave shared images unlocked // returns 1 if okay, 0 or negative for problem // NOTE: always blocks until new frame is ready int jhcManusBody::UpdateImg (int rect) { got = 0; if (vid == NULL) return 0; if (vid->Get(now) <= 0) // only affected image return -1; if (rect > 0) Rectify(); return 1; } //= Correct lens distortion in recently acquired image. void jhcManusBody::Rectify () { wp.Warp(frame, now); got = 1; } //= Compute likely speed of left wheel based on current servo set points. // assume wheel's actual velocity is zero if zero microseconds reported double jhcManusBody::get_lf (double us) const { if (us == 0.0) return 0.0; return((us - lf0) / ((1.0 - bal) * msc)); } //= Compute likely speed of right wheel based on current servo set points. // assume wheel's actual velocity is zero if zero microseconds reported double jhcManusBody::get_rt (double us) const { if (us == 0.0) return 0.0; return((rt0 - us) / ((1.0 + bal) * msc)); } //= Determine actual position of lift stage. double jhcManusBody::get_lift (double us) const { return(hout + arm * sin((us - lout) / lsc)); } //= Determine width of gripper. // converts of A/D reading to actual separation in inches double jhcManusBody::get_grip (double ad) const { return(wsc * (ad - vmed) + wmed); } //= Determine forward distance to obstacle. double jhcManusBody::get_dist (double ad) const { double d = roff + rsc / (4.0 * ad + voff); return __max(0.0, d); // 2cm min } //= Update odometry based on wheel speeds over last time interval. // uses saved values "lvel" and "rvel" void jhcManusBody::inc_odom (UL32 tnow) { UL32 t0 = tlast; double secs, ins, degs, mid; // set up for next cycle then find elapsed time tlast = tnow; if (t0 == 0) return; secs = jms_secs(tnow, t0); // find length of recent segment and change in direction ins = 0.5 * (rvel + lvel) * secs; degs = 0.5 * (rvel - lvel) * secs / tsc; // update inferred global Cartesian position mid = D2R * (head + 0.5 * degs); xpos += ins * cos(mid); ypos += ins * sin(mid); // update path length and current global orientation trav += ins; head += degs; //jprintf("[%3.1 %3.1] -> dist %4.2f, turn %4.2f -> x = %3.1f, y = %3.1f\n", lvel, rvel, ins, degs, xpos, ypos); } //= Send wheel speeds, desired forklift height, and adjust gripper. // assumes Update has already been called to get gripper force // returns 1 if successful, 0 or negative for problem int jhcManusBody::Issue () { // send motor commands send_wheels(move, turn); send_lift(fork); send_grip(grip); // update local state and request new sensor data inc_odom(jms_now()); req_all(); return mok; } //= Compute wheel speeds based on commands and send to robot. // relies on digital servo's deadband (will keep moving otherwise) void jhcManusBody::send_wheels (double ips, double dps) { double mv = msc * ips, tv = tsc * dps; set_target(LFW, lf0 + (1.0 - bal) * (mv - tv)); set_target(RTW, rt0 - (1.0 + bal) * (mv + tv)); } //= Compute lift setting and send to robot. // assumes Update already called to provide current height void jhcManusBody::send_lift (double ips) { double hcmd = ht, dead = 0.25, stop = 4.0; // inches per second int fvel = ROUND(lsf * fabs(ips)); if (ips > dead) hcmd = 4.0; else if (ips < -dead) hcmd = 0.0; else fvel = ROUND(lsf * stop); set_target(LIFT, lout + lsc * asin((hcmd - hout) / arm)); set_speed(LIFT, __max(1, fvel), 0); } //= Compute grip setting and send to robot. // 1 = active close, -1 = active open, 0 = finish last action void jhcManusBody::send_grip (int dir) { // zero stability if active motion changes if ((dir != 0) && (dir != pgrip)) wcnt = 0; //jprintf("grip dir %d vs prev %d -> wcnt = %d\n", dir, pgrip, wcnt); pgrip = dir; // open or close gripper, else remember single stable width (no drift) if (dir != 0) wcmd = ((dir > 0) ? 2500.0 : 500.0); else if (wcnt == wstop) wcmd = gmin + gsc * (wid - wmin); //jprintf(" hand target: %4.2f\n", wcmd); set_target(HAND, wcmd); } /////////////////////////////////////////////////////////////////////////// // Low Level Serial // /////////////////////////////////////////////////////////////////////////// //= Set the target position for some channel to given number of microseconds. // part of single large "ask" packet, initialized in constructor // NOTE: commands only transmitted when req_all() called void jhcManusBody::set_target (int ch, double us) { int off[5] = {0, 4, 0, 8, 12}; int v = ROUND(4.0 * us); UC8 *pod; if ((ch < LFW) || (ch == DIST) || (ch > HAND)) return; pod = ask + off[ch]; // where channel packet starts pod[2] = v & 0x7F; pod[3] = (v >> 7) & 0x7F; } //= Set the maximum speed for changing position of servo toward target. // typically updates pulse width by inc_t / 4 microseconds at 50 Hz // if "imm" > 0 then sends command right now, else waits for req_all() void jhcManusBody::set_speed (int ch, int inc_t, int imm) { UC8 *pod = ask + 16; // same slot for all (usually LIFT) if ((ch < LFW) || (ch == DIST) || (ch > HAND) || (mok <= 0)) return; pod[0] = 0x87; pod[1] = (UC8) ch; pod[2] = inc_t & 0x7F; pod[3] = (inc_t >> 7) & 0x7F; if (imm > 0) if (ser.TxArray(pod, 4) < 4) mok = 0; } //= Set the maximum acceleration for changing speed of target position. // typically updates speed by inc_v at 50 Hz void jhcManusBody::set_accel (int ch, int inc_v) { UC8 pod[4]; if ((ch < LFW) || (ch == DIST) || (ch > HAND) || (mok <= 0)) return; pod[0] = 0x89; pod[1] = (UC8) ch; pod[2] = inc_v & 0x7F; pod[3] = (inc_v >> 7) & 0x7F; if (ser.TxArray(pod, 4) < 4) mok = 0; } //= Ask for positions of all channels (but do not wait for response). int jhcManusBody::req_all () { if (mok <= 0) return mok; if (ser.TxArray(ask, 32) < 32) // should just instantly queue mok = 0; return mok; } //= Read position of all channels in terms of microseconds. // assumes servo controller has already been prompted with req_all() // returns 1 if okay, 0 or negative for error // NOTE: always blocks until all data received int jhcManusBody::rcv_all () { int i; // get full response from robot if (mok > 0) { // convert 16 bit values to milliseconds if (ser.RxArray(pod, 12) < 12) mok = 0; else for (i = 0; i < 12; i += 2) pos[i / 2] = 0.25 * ((pod[i + 1] << 8) | pod[i]); } return mok; } /* // non-blocking version int jhcManusBody::rcv_all () { int i; // sanity check if (mok <= 0) return mok; if (fill >= 12) return 1; // read as many bytes as currently available while (ser.Check() > 0) { // save each byte in "pod" array if ((i = ser.Rcv()) < 0) { mok = 0; return -1; } pod[fill++] = (UC8) i; // if all received, convert 16 bit values to milliseconds if (fill >= 12) { for (i = 0; i < 12; i += 2) pos[i / 2] = 0.25 * ((pod[i + 1] << 8) | pod[i]); return 1; } } // still more to go return 0; } */
25.651386
113
0.560866
jconnell11
6a05ff7974763bd852c606a70952678ea5240868
1,208
cpp
C++
src/symUtilities.cpp
SyrtcevVadim/SymCalc
28051768cd7c24e6b906939a61cb8f208226cfd3
[ "Apache-2.0" ]
null
null
null
src/symUtilities.cpp
SyrtcevVadim/SymCalc
28051768cd7c24e6b906939a61cb8f208226cfd3
[ "Apache-2.0" ]
null
null
null
src/symUtilities.cpp
SyrtcevVadim/SymCalc
28051768cd7c24e6b906939a61cb8f208226cfd3
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 Syrtcev Vadim Igorevich 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. */ #include"symUtilities.h" #include"SymHelper.h" #include<sstream> #include<string> using std::string; using std::stringstream; using std::to_string; string trim(string str) { stringstream ss{ str }; ss >> str; return str; } string removeSpaces(string str) { stringstream ss{ str }; string result{ "" }; while (!ss.eof()) { string current; ss >> current; result += current; } return result; } string numberToString(double number) { stringstream ss; ss << number; string result; ss >> result; return result; } double stringToNumber(string str) { stringstream ss{ str }; double result; ss >> result; return result; }
20.133333
72
0.738411
SyrtcevVadim
6a0632b74e975b3c93cdee13444e82df8f40ffbd
18,039
cpp
C++
src/replay.cpp
quazm/GHOST_CB_DOTS
603b9f979628ddaa3ccbcb3c0163b124ae1e0551
[ "Apache-2.0" ]
null
null
null
src/replay.cpp
quazm/GHOST_CB_DOTS
603b9f979628ddaa3ccbcb3c0163b124ae1e0551
[ "Apache-2.0" ]
null
null
null
src/replay.cpp
quazm/GHOST_CB_DOTS
603b9f979628ddaa3ccbcb3c0163b124ae1e0551
[ "Apache-2.0" ]
null
null
null
/* Copyright [2008] [Trevor Hogan] 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. CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/ */ #include "replay.h" #include "gameprotocol.h" #include "ghost.h" #include "util.h" #include "gameslot.h" // // CReplay // CReplay::CReplay() : CPacked() { m_HostPID = 0; m_PlayerCount = 0; m_MapGameType = 0; m_RandomSeed = 0; m_SelectMode = 0; m_StartSpotCount = 0; m_CompiledBlocks.reserve(262144); } CReplay::~CReplay() { } void CReplay::AddLeaveGame(uint32_t reason, unsigned char PID, uint32_t result) { BYTEARRAY Block; Block.push_back(REPLAY_LEAVEGAME); UTIL_AppendByteArray(Block, reason, false); Block.push_back(PID); UTIL_AppendByteArray(Block, result, false); UTIL_AppendByteArray(Block, (uint32_t)1, false); m_CompiledBlocks += std::string(Block.begin(), Block.end()); } void CReplay::AddLeaveGameDuringLoading(uint32_t reason, unsigned char PID, uint32_t result) { BYTEARRAY Block; Block.push_back(REPLAY_LEAVEGAME); UTIL_AppendByteArray(Block, reason, false); Block.push_back(PID); UTIL_AppendByteArray(Block, result, false); UTIL_AppendByteArray(Block, (uint32_t)1, false); m_LoadingBlocks.push(Block); } void CReplay::AddTimeSlot2(std::queue<CIncomingAction *> actions) { BYTEARRAY Block; Block.push_back(REPLAY_TIMESLOT2); UTIL_AppendByteArray(Block, (uint16_t)0, false); UTIL_AppendByteArray(Block, (uint16_t)0, false); while (!actions.empty()) { CIncomingAction *Action = actions.front(); actions.pop(); Block.push_back(Action->GetPID()); UTIL_AppendByteArray(Block, (uint16_t)Action->GetAction()->size(), false); UTIL_AppendByteArrayFast(Block, *Action->GetAction()); } // assign length BYTEARRAY LengthBytes = UTIL_CreateByteArray((uint16_t)(Block.size() - 3), false); Block[1] = LengthBytes[0]; Block[2] = LengthBytes[1]; m_CompiledBlocks += std::string(Block.begin(), Block.end()); } void CReplay::AddTimeSlot(uint16_t timeIncrement, std::queue<CIncomingAction *> actions) { BYTEARRAY Block; Block.push_back(REPLAY_TIMESLOT); UTIL_AppendByteArray(Block, (uint16_t)0, false); UTIL_AppendByteArray(Block, timeIncrement, false); while (!actions.empty()) { CIncomingAction *Action = actions.front(); actions.pop(); Block.push_back(Action->GetPID()); UTIL_AppendByteArray(Block, (uint16_t)Action->GetAction()->size(), false); UTIL_AppendByteArrayFast(Block, *Action->GetAction()); } // assign length BYTEARRAY LengthBytes = UTIL_CreateByteArray((uint16_t)(Block.size() - 3), false); Block[1] = LengthBytes[0]; Block[2] = LengthBytes[1]; m_CompiledBlocks += std::string(Block.begin(), Block.end()); m_ReplayLength += timeIncrement; } void CReplay::AddChatMessage(unsigned char PID, unsigned char flags, uint32_t chatMode, std::string message) { BYTEARRAY Block; Block.push_back(REPLAY_CHATMESSAGE); Block.push_back(PID); UTIL_AppendByteArray(Block, (uint16_t)0, false); Block.push_back(flags); UTIL_AppendByteArray(Block, chatMode, false); UTIL_AppendByteArrayFast(Block, message); // assign length BYTEARRAY LengthBytes = UTIL_CreateByteArray((uint16_t)(Block.size() - 4), false); Block[2] = LengthBytes[0]; Block[3] = LengthBytes[1]; m_CompiledBlocks += std::string(Block.begin(), Block.end()); } void CReplay::AddLoadingBlock(BYTEARRAY &loadingBlock) { m_LoadingBlocks.push(loadingBlock); } void CReplay::BuildReplay(std::string gameName, std::string statString, uint32_t war3Version, uint16_t buildNumber) { m_War3Version = war3Version; m_BuildNumber = buildNumber; m_Flags = 32768; CONSOLE_Print("[REPLAY] building replay"); uint32_t LanguageID = 0x0012F8B0; BYTEARRAY Replay; Replay.push_back(16); // Unknown (4.0) Replay.push_back(1); // Unknown (4.0) Replay.push_back(0); // Unknown (4.0) Replay.push_back(0); // Unknown (4.0) Replay.push_back(0); // Host RecordID (4.1) Replay.push_back(m_HostPID); // Host PlayerID (4.1) UTIL_AppendByteArrayFast(Replay, m_HostName); // Host PlayerName (4.1) Replay.push_back(1); // Host AdditionalSize (4.1) Replay.push_back(0); // Host AdditionalData (4.1) UTIL_AppendByteArrayFast(Replay, gameName); // GameName (4.2) Replay.push_back(0); // Null (4.0) UTIL_AppendByteArrayFast(Replay, statString); // StatString (4.3) UTIL_AppendByteArray(Replay, (uint32_t)m_Slots.size(), false); // PlayerCount (4.6) UTIL_AppendByteArray(Replay, m_MapGameType, false); // GameType (4.7) UTIL_AppendByteArray(Replay, LanguageID, false); // LanguageID (4.8) // PlayerList (4.9) for (std::vector<PIDPlayer>::iterator i = m_Players.begin(); i != m_Players.end(); i++) { if ((*i).first != m_HostPID) { Replay.push_back(22); // Player RecordID (4.1) Replay.push_back((*i).first); // Player PlayerID (4.1) UTIL_AppendByteArrayFast(Replay, (*i).second); // Player PlayerName (4.1) Replay.push_back(1); // Player AdditionalSize (4.1) Replay.push_back(0); // Player AdditionalData (4.1) UTIL_AppendByteArray(Replay, (uint32_t)0, false); // Unknown } } // GameStartRecord (4.10) Replay.push_back(25); // RecordID (4.10) UTIL_AppendByteArray(Replay, (uint16_t)(7 + m_Slots.size() * 9), false); // Size (4.10) Replay.push_back(m_Slots.size()); // NumSlots (4.10) for (unsigned char i = 0; i < m_Slots.size(); i++) UTIL_AppendByteArray(Replay, m_Slots[i].GetByteArray()); UTIL_AppendByteArray(Replay, m_RandomSeed, false); // RandomSeed (4.10) Replay.push_back(m_SelectMode); // SelectMode (4.10) Replay.push_back(m_StartSpotCount); // StartSpotCount (4.10) // ReplayData (5.0) Replay.push_back(REPLAY_FIRSTSTARTBLOCK); UTIL_AppendByteArray(Replay, (uint32_t)1, false); Replay.push_back(REPLAY_SECONDSTARTBLOCK); UTIL_AppendByteArray(Replay, (uint32_t)1, false); // leavers during loading need to be stored between the second and third start blocks while (!m_LoadingBlocks.empty()) { UTIL_AppendByteArray(Replay, m_LoadingBlocks.front()); m_LoadingBlocks.pop(); } Replay.push_back(REPLAY_THIRDSTARTBLOCK); UTIL_AppendByteArray(Replay, (uint32_t)1, false); // done m_Decompressed = std::string(Replay.begin(), Replay.end()); m_Decompressed += m_CompiledBlocks; } #define READB(x, y, z) (x).read((char *)(y), (z)) #define READSTR(x, y) getline((x), (y), '\0') void CReplay::ParseReplay(bool parseBlocks) { m_HostPID = 0; m_HostName.clear(); m_GameName.clear(); m_StatString.clear(); m_PlayerCount = 0; m_MapGameType = 0; m_Players.clear(); m_Slots.clear(); m_RandomSeed = 0; m_SelectMode = 0; m_StartSpotCount = 0; m_LoadingBlocks = std::queue<BYTEARRAY>(); m_Blocks = std::queue<BYTEARRAY>(); m_CheckSums = std::queue<uint32_t>(); if (m_Flags != 32768) { CONSOLE_Print("[REPLAY] invalid replay (flags mismatch)"); m_Valid = false; return; } std::istringstream ISS(m_Decompressed); unsigned char Garbage1; uint32_t Garbage4; std::string GarbageString; unsigned char GarbageData[65535]; READB(ISS, &Garbage4, 4); // Unknown (4.0) if (Garbage4 != 272) { CONSOLE_Print("[REPLAY] invalid replay (4.0 Unknown mismatch)"); m_Valid = false; return; } READB(ISS, &Garbage1, 1); // Host RecordID (4.1) if (Garbage1 != 0) { CONSOLE_Print("[REPLAY] invalid replay (4.1 Host RecordID mismatch)"); m_Valid = false; return; } READB(ISS, &m_HostPID, 1); if (m_HostPID > 15) { CONSOLE_Print("[REPLAY] invalid replay (4.1 Host PlayerID is invalid)"); m_Valid = false; return; } READSTR(ISS, m_HostName); // Host PlayerName (4.1) READB(ISS, &Garbage1, 1); // Host AdditionalSize (4.1) if (Garbage1 != 1) { CONSOLE_Print("[REPLAY] invalid replay (4.1 Host AdditionalSize mismatch)"); m_Valid = false; return; } READB(ISS, &Garbage1, 1); // Host AdditionalData (4.1) if (Garbage1 != 0) { CONSOLE_Print("[REPLAY] invalid replay (4.1 Host AdditionalData mismatch)"); m_Valid = false; return; } AddPlayer(m_HostPID, m_HostName); READSTR(ISS, m_GameName); // GameName (4.2) READSTR(ISS, GarbageString); // Null (4.0) READSTR(ISS, m_StatString); // StatString (4.3) READB(ISS, &m_PlayerCount, 4); // PlayerCount (4.6) if (m_PlayerCount > 12) { CONSOLE_Print("[REPLAY] invalid replay (4.6 PlayerCount is invalid)"); m_Valid = false; return; } READB(ISS, &m_MapGameType, 4); // GameType (4.7) READB(ISS, &Garbage4, 4); // LanguageID (4.8) while (1) { READB(ISS, &Garbage1, 1); // Player RecordID (4.1) if (Garbage1 == 22) { unsigned char PlayerID; std::string PlayerName; READB(ISS, &PlayerID, 1); // Player PlayerID (4.1) if (PlayerID > 15) { CONSOLE_Print("[REPLAY] invalid replay (4.9 Player PlayerID is invalid)"); m_Valid = false; return; } READSTR(ISS, PlayerName); // Player PlayerName (4.1) READB(ISS, &Garbage1, 1); // Player AdditionalSize (4.1) if (Garbage1 != 1) { CONSOLE_Print("[REPLAY] invalid replay (4.9 Player AdditionalSize mismatch)"); m_Valid = false; return; } READB(ISS, &Garbage1, 1); // Player AdditionalData (4.1) if (Garbage1 != 0) { CONSOLE_Print("[REPLAY] invalid replay (4.9 Player AdditionalData mismatch)"); m_Valid = false; return; } READB(ISS, &Garbage4, 4); // Unknown if (Garbage4 != 0) { CONSOLE_Print("[REPLAY] invalid replay (4.9 Unknown mismatch)"); m_Valid = false; return; } AddPlayer(PlayerID, PlayerName); } else if (Garbage1 == 25) break; else { CONSOLE_Print("[REPLAY] invalid replay (4.9 Player RecordID mismatch)"); m_Valid = false; return; } } uint16_t Size; unsigned char NumSlots; READB(ISS, &Size, 2); // Size (4.10) READB(ISS, &NumSlots, 1); // NumSlots (4.10) if (Size != 7 + NumSlots * 9) { CONSOLE_Print("[REPLAY] invalid replay (4.10 Size is invalid)"); m_Valid = false; return; } if (NumSlots == 0 || NumSlots > 12) { CONSOLE_Print("[REPLAY] invalid replay (4.10 NumSlots is invalid)"); m_Valid = false; return; } for (int i = 0; i < NumSlots; i++) { unsigned char SlotData[9]; READB(ISS, SlotData, 9); BYTEARRAY SlotDataBA = UTIL_CreateByteArray(SlotData, 9); m_Slots.push_back(CGameSlot(SlotDataBA)); } READB(ISS, &m_RandomSeed, 4); // RandomSeed (4.10) READB(ISS, &m_SelectMode, 1); // SelectMode (4.10) READB(ISS, &m_StartSpotCount, 1); // StartSpotCount (4.10) if (ISS.eof() || ISS.fail()) { CONSOLE_Print("[SAVEGAME] failed to parse replay header"); m_Valid = false; return; } if (!parseBlocks) return; READB(ISS, &Garbage1, 1); // first start block ID (5.0) if (Garbage1 != CReplay::REPLAY_FIRSTSTARTBLOCK) { CONSOLE_Print("[REPLAY] invalid replay (5.0 first start block ID mismatch)"); m_Valid = false; return; } READB(ISS, &Garbage4, 4); // first start block data (5.0) if (Garbage4 != 1) { CONSOLE_Print("[REPLAY] invalid replay (5.0 first start block data mismatch)"); m_Valid = false; return; } READB(ISS, &Garbage1, 1); // second start block ID (5.0) if (Garbage1 != CReplay::REPLAY_SECONDSTARTBLOCK) { CONSOLE_Print("[REPLAY] invalid replay (5.0 second start block ID mismatch)"); m_Valid = false; return; } READB(ISS, &Garbage4, 4); // second start block data (5.0) if (Garbage4 != 1) { CONSOLE_Print("[REPLAY] invalid replay (5.0 second start block data mismatch)"); m_Valid = false; return; } while (1) { READB(ISS, &Garbage1, 1); // third start block ID *or* loading block ID (5.0) if (ISS.eof() || ISS.fail()) { CONSOLE_Print("[REPLAY] invalid replay (5.0 third start block unexpected end of file found)"); m_Valid = false; return; } if (Garbage1 == CReplay::REPLAY_LEAVEGAME) { READB(ISS, GarbageData, 13); BYTEARRAY LoadingBlock; LoadingBlock.push_back(Garbage1); UTIL_AppendByteArray(LoadingBlock, GarbageData, 13); m_LoadingBlocks.push(LoadingBlock); } else if (Garbage1 == CReplay::REPLAY_THIRDSTARTBLOCK) break; else { CONSOLE_Print("[REPLAY] invalid replay (5.0 third start block ID mismatch)"); m_Valid = false; return; } } READB(ISS, &Garbage4, 4); // third start block data (5.0) if (Garbage4 != 1) { CONSOLE_Print("[REPLAY] invalid replay (5.0 third start block data mismatch)"); m_Valid = false; return; } if (ISS.eof() || ISS.fail()) { CONSOLE_Print("[SAVEGAME] failed to parse replay start blocks"); m_Valid = false; return; } uint32_t ActualReplayLength = 0; while (1) { READB(ISS, &Garbage1, 1); // block ID (5.0) if (ISS.eof() || ISS.fail()) break; else if (Garbage1 == CReplay::REPLAY_LEAVEGAME) { READB(ISS, GarbageData, 13); // reconstruct the block BYTEARRAY Block; Block.push_back(CReplay::REPLAY_LEAVEGAME); UTIL_AppendByteArray(Block, GarbageData, 13); m_Blocks.push(Block); } else if (Garbage1 == CReplay::REPLAY_TIMESLOT) { uint16_t BlockSize; READB(ISS, &BlockSize, 2); READB(ISS, GarbageData, BlockSize); if (BlockSize >= 2) ActualReplayLength += GarbageData[0] | GarbageData[1] << 8; // reconstruct the block BYTEARRAY Block; Block.push_back(CReplay::REPLAY_TIMESLOT); UTIL_AppendByteArray(Block, BlockSize, false); UTIL_AppendByteArray(Block, GarbageData, BlockSize); m_Blocks.push(Block); } else if (Garbage1 == CReplay::REPLAY_CHATMESSAGE) { unsigned char PID; uint16_t BlockSize; READB(ISS, &PID, 1); if (PID > 15) { CONSOLE_Print("[REPLAY] invalid replay (5.0 chatmessage pid is invalid)"); m_Valid = false; return; } READB(ISS, &BlockSize, 2); READB(ISS, GarbageData, BlockSize); // reconstruct the block BYTEARRAY Block; Block.push_back(CReplay::REPLAY_CHATMESSAGE); Block.push_back(PID); UTIL_AppendByteArray(Block, BlockSize, false); UTIL_AppendByteArray(Block, GarbageData, BlockSize); m_Blocks.push(Block); } else if (Garbage1 == CReplay::REPLAY_CHECKSUM) { READB(ISS, &Garbage1, 1); if (Garbage1 != 4) { CONSOLE_Print("[REPLAY] invalid replay (5.0 checksum unknown mismatch)"); m_Valid = false; return; } uint32_t CheckSum; READB(ISS, &CheckSum, 4); m_CheckSums.push(CheckSum); } else { // it's not necessarily an error if we encounter an unknown block ID since replays can contain extra data break; } } if (m_ReplayLength != ActualReplayLength) CONSOLE_Print("[REPLAY] warning - replay length mismatch (" + UTIL_ToString(m_ReplayLength) + "ms/" + UTIL_ToString(ActualReplayLength) + "ms)"); m_Valid = true; }
30.994845
153
0.572371
quazm
6a06b6b983f99fd4eb17f278c6638871729ba00f
612
cpp
C++
DeclareVariableInNamespaceAndClassScope.cpp
haxpor/cpp_st
43d1492266c6e01e6e243c834fba26eedf1ab9f3
[ "MIT" ]
2
2021-06-10T22:05:01.000Z
2021-09-17T08:21:20.000Z
DeclareVariableInNamespaceAndClassScope.cpp
haxpor/cpp_st
43d1492266c6e01e6e243c834fba26eedf1ab9f3
[ "MIT" ]
null
null
null
DeclareVariableInNamespaceAndClassScope.cpp
haxpor/cpp_st
43d1492266c6e01e6e243c834fba26eedf1ab9f3
[ "MIT" ]
1
2020-02-25T04:26:52.000Z
2020-02-25T04:26:52.000Z
/** * Demonstrate that we can initialize non-static data member of namespace, and class scope * without problem. This is possible since c++11 (ref https://web.archive.org/web/20160316174223/https://blogs.oracle.com/pcarlini/entry/c_11_tidbits_non_static). */ #include <cassert> struct StructVar { StructVar(int val): m_val(val) { } int m_val; }; namespace A { namespace B { StructVar myStructVar = StructVar(2); } } class Widget { public: StructVar myStructVar = StructVar(3); }; int main() { assert(A::B::myStructVar.m_val == 2); Widget w; assert(w.myStructVar.m_val == 3); return 0; }
15.692308
162
0.70098
haxpor
6a0c168af224b2c3fe2ea341d32cb6e507bfa6e7
870
cpp
C++
src/test/logical_query_plan/show_columns_node_test.cpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
1
2021-04-14T11:16:52.000Z
2021-04-14T11:16:52.000Z
src/test/logical_query_plan/show_columns_node_test.cpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
null
null
null
src/test/logical_query_plan/show_columns_node_test.cpp
IanJamesMcKay/InMemoryDB
a267d9522926eca9add2ad4512f8ce352daac879
[ "MIT" ]
1
2020-11-30T13:11:04.000Z
2020-11-30T13:11:04.000Z
#include <memory> #include "gtest/gtest.h" #include "base_test.hpp" #include "logical_query_plan/show_columns_node.hpp" namespace opossum { class ShowColumnsNodeTest : public BaseTest { protected: void SetUp() override { _show_columns_node = ShowColumnsNode::make("table_a"); } std::shared_ptr<ShowColumnsNode> _show_columns_node; }; TEST_F(ShowColumnsNodeTest, Description) { EXPECT_EQ(_show_columns_node->description(), "[ShowColumns] Table: 'table_a'"); } TEST_F(ShowColumnsNodeTest, TableName) { EXPECT_EQ(_show_columns_node->table_name(), "table_a"); } TEST_F(ShowColumnsNodeTest, ShallowEquals) { EXPECT_TRUE(_show_columns_node->shallow_equals(*_show_columns_node)); const auto other_show_columns_node = ShowColumnsNode::make("table_b"); EXPECT_FALSE(other_show_columns_node->shallow_equals(*_show_columns_node)); } } // namespace opossum
27.1875
98
0.781609
IanJamesMcKay
6a0d550358cda6b23f9589f30e90ba9de1466bb4
1,656
cpp
C++
Leetcode Daily Challenge/January-2021/14. Minimum Operations to Reduce X to Zero.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
5
2021-08-10T18:47:49.000Z
2021-08-21T15:42:58.000Z
Leetcode Daily Challenge/January-2021/14. Minimum Operations to Reduce X to Zero.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
2
2022-02-25T13:36:46.000Z
2022-02-25T14:06:44.000Z
Leetcode Daily Challenge/January-2021/14. Minimum Operations to Reduce X to Zero.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
1
2022-01-23T22:00:48.000Z
2022-01-23T22:00:48.000Z
/* Minimum Operations to Reduce X to Zero ========================================= You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it's possible, otherwise, return -1. Example 1: Input: nums = [1,1,4,2,3], x = 5 Output: 2 Explanation: The optimal solution is to remove the last two elements to reduce x to zero. Example 2: Input: nums = [5,6,7,8,9], x = 4 Output: -1 Example 3: Input: nums = [3,2,20,1,1,3], x = 10 Output: 5 Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 104 1 <= x <= 109 Hint #1 Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Hint #2 Finding the maximum subarray is standard and can be done greedily. */ class Solution { public: int minOperations(vector<int> &nums, int x) { unordered_map<int, int> left; int res = INT_MAX; for (auto l = 0, sum = 0; l < nums.size() && sum <= x; ++l) { left[sum] = l; sum += nums[l]; } for (int r = nums.size() - 1, sum = 0; r >= 0 && sum <= x; --r) { auto it = left.find(x - sum); if (it != end(left) && r + 1 >= it->second) { res = min(res, (int)nums.size() - r - 1 + it->second); } sum += nums[r]; } return res == INT_MAX ? -1 : res; } };
27.6
239
0.61715
Akshad7829
6a0e1367169fc2943048ee69870dfc52ecec2abd
1,474
hpp
C++
include/lol/def/CollectionsLcdsChampionSkinDTO.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/CollectionsLcdsChampionSkinDTO.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/CollectionsLcdsChampionSkinDTO.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" namespace lol { struct CollectionsLcdsChampionSkinDTO { uint64_t endDate; uint64_t purchaseDate; int32_t winCountRemaining; std::vector<std::string> sources; int32_t championId; bool freeToPlayReward; bool lastSelected; bool owned; int32_t skinId; bool stillObtainable; }; inline void to_json(json& j, const CollectionsLcdsChampionSkinDTO& v) { j["endDate"] = v.endDate; j["purchaseDate"] = v.purchaseDate; j["winCountRemaining"] = v.winCountRemaining; j["sources"] = v.sources; j["championId"] = v.championId; j["freeToPlayReward"] = v.freeToPlayReward; j["lastSelected"] = v.lastSelected; j["owned"] = v.owned; j["skinId"] = v.skinId; j["stillObtainable"] = v.stillObtainable; } inline void from_json(const json& j, CollectionsLcdsChampionSkinDTO& v) { v.endDate = j.at("endDate").get<uint64_t>(); v.purchaseDate = j.at("purchaseDate").get<uint64_t>(); v.winCountRemaining = j.at("winCountRemaining").get<int32_t>(); v.sources = j.at("sources").get<std::vector<std::string>>(); v.championId = j.at("championId").get<int32_t>(); v.freeToPlayReward = j.at("freeToPlayReward").get<bool>(); v.lastSelected = j.at("lastSelected").get<bool>(); v.owned = j.at("owned").get<bool>(); v.skinId = j.at("skinId").get<int32_t>(); v.stillObtainable = j.at("stillObtainable").get<bool>(); } }
36.85
75
0.651967
Maufeat
6a0f3fd051c2d1c78dfc051f67ac9f4cdf1aa854
328
cpp
C++
Before Summer 2017/SummerTrain Archieve/void-pointer.cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
1
2019-12-19T06:51:20.000Z
2019-12-19T06:51:20.000Z
Before Summer 2017/SummerTrain Archieve/void-pointer.cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
null
null
null
Before Summer 2017/SummerTrain Archieve/void-pointer.cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
null
null
null
/* // void-pointer.cpp by Bill Weinman <http://bw.org/> #include <stdio.h> void * func( void * ); int main( int argc, char ** argv ) { printf("this is void-pointer.c\n"); const char * cp = "1234"; int * vp = (int *) func( (void *) cp ); printf("%08x\n", * vp); return 0; } void * func ( void * vp ) { return vp; } */
15.619048
52
0.554878
mohamedGamalAbuGalala
6a1612415a99fcd1a2d8c5cf6965a5dfc091d838
26,619
cpp
C++
Deprecated/Controls/Styles/Win8Styles/GuiWin8StylesCommon.cpp
cameled/GacUI
939856c1045067dc7b78eb80cdb7174ae5c76799
[ "RSA-MD" ]
2,342
2015-04-01T22:12:53.000Z
2022-03-31T07:00:33.000Z
Deprecated/Controls/Styles/Win8Styles/GuiWin8StylesCommon.cpp
vczh2/GacUI
ce100ec13357bbf03ed3d2040c48d6b2b2fefd2f
[ "RSA-MD" ]
68
2015-04-04T15:42:06.000Z
2022-03-29T04:33:51.000Z
Deprecated/Controls/Styles/Win8Styles/GuiWin8StylesCommon.cpp
vczh2/GacUI
ce100ec13357bbf03ed3d2040c48d6b2b2fefd2f
[ "RSA-MD" ]
428
2015-04-02T00:25:48.000Z
2022-03-25T16:37:56.000Z
#include "GuiWin8StylesCommon.h" namespace vl { namespace presentation { namespace win8 { using namespace collections; using namespace elements; using namespace compositions; using namespace controls; /*********************************************************************** Win8ButtonColors ***********************************************************************/ void Win8ButtonColors::SetAlphaWithoutText(unsigned char a) { borderColor.a=a; g1.a=a; g2.a=a; } Win8ButtonColors Win8ButtonColors::Blend(const Win8ButtonColors& c1, const Win8ButtonColors& c2, vint ratio, vint total) { if(ratio<0) ratio=0; else if(ratio>total) ratio=total; Win8ButtonColors result; result.borderColor=BlendColor(c1.borderColor, c2.borderColor, ratio, total); result.g1=BlendColor(c1.g1, c2.g1, ratio, total); result.g2=BlendColor(c1.g2, c2.g2, ratio, total); result.textColor=BlendColor(c1.textColor, c2.textColor, ratio, total); result.bullet=BlendColor(c1.bullet, c2.bullet, ratio, total); return result; } //--------------------------------------------------------- Win8ButtonColors Win8ButtonColors::ButtonNormal() { Win8ButtonColors colors= { Color(172, 172, 172), Color(239, 239, 239), Color(229, 229, 229), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::ButtonActive() { Win8ButtonColors colors= { Color(126, 180, 234), Color(235, 244, 252), Color(220, 236, 252), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::ButtonPressed() { Win8ButtonColors colors= { Color(86, 157, 229), Color(218, 236, 252), Color(196, 224, 252), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::ButtonDisabled() { Win8ButtonColors colors= { Color(173, 178, 181), Color(252, 252, 252), Color(252, 252, 252), Win8GetSystemTextColor(false), }; return colors; } //--------------------------------------------------------- Win8ButtonColors Win8ButtonColors::ItemNormal() { Win8ButtonColors colors= { Color(112, 192, 231, 0), Color(229, 243, 251, 0), Color(229, 243, 251, 0), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::ItemActive() { Win8ButtonColors colors= { Color(112, 192, 231), Color(229, 243, 251), Color(229, 243, 251), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::ItemSelected() { Win8ButtonColors colors= { Color(102, 167, 232), Color(209, 232, 255), Color(209, 232, 255), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::ItemDisabled() { Win8ButtonColors colors= { Color(112, 192, 231, 0), Color(229, 243, 251, 0), Color(229, 243, 251, 0), Win8GetSystemTextColor(false), }; return colors; } //--------------------------------------------------------- Win8ButtonColors Win8ButtonColors::CheckedNormal(bool selected) { Win8ButtonColors colors= { Color(112, 112, 112), Color(255, 255, 255), Color(255, 255, 255), Win8GetSystemTextColor(true), Color(0, 0, 0), }; if(!selected) { colors.bullet.a=0; } return colors; } Win8ButtonColors Win8ButtonColors::CheckedActive(bool selected) { Win8ButtonColors colors= { Color(51, 153, 255), Color(243, 249, 255), Color(243, 249, 255), Win8GetSystemTextColor(true), Color(33, 33, 33), }; if(!selected) { colors.bullet.a=0; } return colors; } Win8ButtonColors Win8ButtonColors::CheckedPressed(bool selected) { Win8ButtonColors colors= { Color(0, 124, 222), Color(217, 236, 255), Color(217, 236, 255), Win8GetSystemTextColor(true), Color(0, 0, 0), }; if(!selected) { colors.bullet.a=0; } return colors; } Win8ButtonColors Win8ButtonColors::CheckedDisabled(bool selected) { Win8ButtonColors colors= { Color(188, 188, 188), Color(230, 230, 230), Color(230, 230, 230), Win8GetSystemTextColor(false), Color(112, 112, 112), }; if(!selected) { colors.bullet.a=0; } return colors; } //--------------------------------------------------------- Win8ButtonColors Win8ButtonColors::ToolstripButtonNormal() { Win8ButtonColors colors= { Win8GetSystemWindowColor(), Win8GetSystemWindowColor(), Win8GetSystemWindowColor(), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::ToolstripButtonActive() { Win8ButtonColors colors= { Color(120, 174, 229), Color(209, 226, 242), Color(209, 226, 242), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::ToolstripButtonPressed() { Win8ButtonColors colors= { Color(96, 161, 226), Color(180, 212, 244), Color(180, 212, 244), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::ToolstripButtonSelected() { Win8ButtonColors colors= { Color(96, 161, 226), Color(233, 241, 250), Color(233, 241, 250), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::ToolstripButtonDisabled() { Win8ButtonColors colors= { Win8GetSystemWindowColor(), Win8GetSystemWindowColor(), Win8GetSystemWindowColor(), Win8GetSystemTextColor(false), }; return colors; } //--------------------------------------------------------- Win8ButtonColors Win8ButtonColors::ScrollHandleNormal() { Win8ButtonColors colors= { Color(205, 205, 205), Color(205, 205, 205), Color(205, 205, 205), }; return colors; } Win8ButtonColors Win8ButtonColors::ScrollHandleActive() { Win8ButtonColors colors= { Color(166, 166, 166), Color(166, 166, 166), Color(166, 166, 166), }; return colors; } Win8ButtonColors Win8ButtonColors::ScrollHandlePressed() { Win8ButtonColors colors= { Color(166, 166, 166), Color(166, 166, 166), Color(166, 166, 166), }; return colors; } Win8ButtonColors Win8ButtonColors::ScrollHandleDisabled() { Win8ButtonColors colors= { Win8GetSystemWindowColor(), Win8GetSystemWindowColor(), Win8GetSystemWindowColor(), }; return colors; } Win8ButtonColors Win8ButtonColors::ScrollArrowNormal() { Win8ButtonColors colors= { Win8GetSystemWindowColor(), Win8GetSystemWindowColor(), Win8GetSystemWindowColor(), Color(96, 96, 96), }; return colors; } Win8ButtonColors Win8ButtonColors::ScrollArrowActive() { Win8ButtonColors colors= { Color(218, 218, 218), Color(218, 218, 218), Color(218, 218, 218), Color(0, 0, 0), }; return colors; } Win8ButtonColors Win8ButtonColors::ScrollArrowPressed() { Win8ButtonColors colors= { Color(96, 96, 96), Color(96, 96, 96), Color(96, 96, 96), Color(255, 255, 255), }; return colors; } Win8ButtonColors Win8ButtonColors::ScrollArrowDisabled() { Win8ButtonColors colors= { Win8GetSystemWindowColor(), Win8GetSystemWindowColor(), Win8GetSystemWindowColor(), Color(191, 191, 191), }; return colors; } //--------------------------------------------------------- Win8ButtonColors Win8ButtonColors::MenuBarButtonNormal() { Win8ButtonColors colors= { Color(245, 246, 247), Color(245, 246, 247), Color(245, 246, 247), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::MenuBarButtonActive() { Win8ButtonColors colors= { Color(122, 177, 232), Color(213, 231, 248), Color(213, 231, 248), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::MenuBarButtonPressed() { Win8ButtonColors colors= { Color(98, 163, 229), Color(184, 216, 249), Color(184, 216, 249), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::MenuBarButtonDisabled() { Win8ButtonColors colors= { Color(245, 246, 247), Color(245, 246, 247), Color(245, 246, 247), Win8GetSystemTextColor(false), }; return colors; } //--------------------------------------------------------- Win8ButtonColors Win8ButtonColors::MenuItemButtonNormal() { Win8ButtonColors colors= { Color(240, 240, 240), Color(240, 240, 240), Color(240, 240, 240), Win8GetSystemTextColor(true), Win8GetMenuSplitterColor(), }; return colors; } Win8ButtonColors Win8ButtonColors::MenuItemButtonNormalActive() { Win8ButtonColors colors= { Color(120, 174, 229), Color(209, 226, 242), Color(209, 226, 242), Win8GetSystemTextColor(true), Color(187, 204, 220), }; return colors; } Win8ButtonColors Win8ButtonColors::MenuItemButtonSelected() { Win8ButtonColors colors= { Color(120, 174, 229), Color(233, 241, 250), Color(233, 241, 250), Win8GetSystemTextColor(true), Color(233, 241, 250), }; return colors; } Win8ButtonColors Win8ButtonColors::MenuItemButtonSelectedActive() { Win8ButtonColors colors= { Color(120, 174, 229), Color(233, 241, 250), Color(233, 241, 250), Win8GetSystemTextColor(true), Color(187, 204, 220), }; return colors; } Win8ButtonColors Win8ButtonColors::MenuItemButtonDisabled() { Win8ButtonColors colors= { Color(240, 240, 240), Color(240, 240, 240), Color(240, 240, 240), Win8GetSystemTextColor(false), Win8GetMenuSplitterColor(), }; return colors; } Win8ButtonColors Win8ButtonColors::MenuItemButtonDisabledActive() { Win8ButtonColors colors= { Color(120, 174, 229), Color(209, 226, 242), Color(209, 226, 242), Win8GetSystemTextColor(false), Win8GetMenuSplitterColor(), }; return colors; } Win8ButtonColors Win8ButtonColors::TabPageHeaderNormal() { Win8ButtonColors colors= { Color(172, 172, 172), Color(239, 239, 239), Color(229, 229, 229), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::TabPageHeaderActive() { Win8ButtonColors colors= { Color(126, 180, 234), Color(236, 244, 252), Color(221, 237, 252), Win8GetSystemTextColor(true), }; return colors; } Win8ButtonColors Win8ButtonColors::TabPageHeaderSelected() { Win8ButtonColors colors= { Color(172, 172, 172), Color(255, 255, 255), Color(255, 255, 255), Win8GetSystemTextColor(true), }; return colors; } /*********************************************************************** Win8ButtonElements ***********************************************************************/ Win8ButtonElements Win8ButtonElements::Create(Alignment horizontal, Alignment vertical) { Win8ButtonElements button; { button.mainComposition=new GuiBoundsComposition; button.mainComposition->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElementAndChildren); } { GuiSolidBorderElement* element=GuiSolidBorderElement::Create(); button.rectBorderElement=element; GuiBoundsComposition* composition=new GuiBoundsComposition; button.mainComposition->AddChild(composition); composition->SetAlignmentToParent(Margin(0, 0, 0, 0)); composition->SetOwnedElement(element); } { GuiGradientBackgroundElement* element=GuiGradientBackgroundElement::Create(); button.backgroundElement=element; element->SetDirection(GuiGradientBackgroundElement::Vertical); element->SetShape(ElementShape::Rectangle); GuiBoundsComposition* composition=new GuiBoundsComposition; button.backgroundComposition=composition; button.mainComposition->AddChild(composition); composition->SetAlignmentToParent(Margin(1, 1, 1, 1)); composition->SetOwnedElement(element); } { Win8CreateSolidLabelElement(button.textElement, button.textComposition, horizontal, vertical); button.mainComposition->AddChild(button.textComposition); } return button; } void Win8ButtonElements::Apply(const Win8ButtonColors& colors) { if(rectBorderElement) { rectBorderElement->SetColor(colors.borderColor); } backgroundElement->SetColors(colors.g1, colors.g2); textElement->SetColor(colors.textColor); } /*********************************************************************** Win8CheckedButtonElements ***********************************************************************/ Win8CheckedButtonElements Win8CheckedButtonElements::Create(elements::ElementShape shape, bool backgroundVisible) { const vint checkSize=13; const vint checkPadding=2; Win8CheckedButtonElements button; { button.mainComposition=new GuiBoundsComposition; button.mainComposition->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElementAndChildren); } { GuiTableComposition* mainTable=new GuiTableComposition; button.mainComposition->AddChild(mainTable); if(backgroundVisible) { GuiSolidBackgroundElement* element=GuiSolidBackgroundElement::Create(); element->SetColor(Win8GetSystemWindowColor()); mainTable->SetOwnedElement(element); } mainTable->SetRowsAndColumns(1, 2); mainTable->SetAlignmentToParent(Margin(0, 0, 0, 0)); mainTable->SetRowOption(0, GuiCellOption::PercentageOption(1.0)); mainTable->SetColumnOption(0, GuiCellOption::AbsoluteOption(checkSize+2*checkPadding)); mainTable->SetColumnOption(1, GuiCellOption::PercentageOption(1.0)); { GuiCellComposition* cell=new GuiCellComposition; mainTable->AddChild(cell); cell->SetSite(0, 0, 1, 1); GuiTableComposition* table=new GuiTableComposition; cell->AddChild(table); table->SetRowsAndColumns(3, 1); table->SetAlignmentToParent(Margin(0, 0, 0, 0)); table->SetRowOption(0, GuiCellOption::PercentageOption(0.5)); table->SetRowOption(1, GuiCellOption::MinSizeOption()); table->SetRowOption(2, GuiCellOption::PercentageOption(0.5)); { GuiCellComposition* checkCell=new GuiCellComposition; table->AddChild(checkCell); checkCell->SetSite(1, 0, 1, 1); { GuiBoundsComposition* borderBounds=new GuiBoundsComposition; checkCell->AddChild(borderBounds); borderBounds->SetAlignmentToParent(Margin(checkPadding, -1, checkPadding, -1)); borderBounds->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElementAndChildren); { GuiSolidBorderElement* element=GuiSolidBorderElement::Create(); button.bulletBorderElement=element; element->SetShape(shape); GuiBoundsComposition* bounds=new GuiBoundsComposition; borderBounds->AddChild(bounds); bounds->SetOwnedElement(element); bounds->SetAlignmentToParent(Margin(0, 0, 0, 0)); bounds->SetBounds(Rect(Point(0, 0), Size(checkSize, checkSize))); } { GuiGradientBackgroundElement* element=GuiGradientBackgroundElement::Create(); button.bulletBackgroundElement=element; element->SetShape(shape); element->SetDirection(GuiGradientBackgroundElement::Vertical); GuiBoundsComposition* bounds=new GuiBoundsComposition; borderBounds->AddChild(bounds); bounds->SetOwnedElement(element); bounds->SetAlignmentToParent(Margin(1, 1, 1, 1)); } } button.bulletCheckElement=0; button.bulletRadioElement=0; if(shape==ElementShape::Rectangle) { button.bulletCheckElement=GuiSolidLabelElement::Create(); { FontProperties font; font.fontFamily=L"Webdings"; font.size=16; font.bold=true; button.bulletCheckElement->SetFont(font); } button.bulletCheckElement->SetText(L"a"); button.bulletCheckElement->SetAlignments(Alignment::Center, Alignment::Center); GuiBoundsComposition* composition=new GuiBoundsComposition; composition->SetOwnedElement(button.bulletCheckElement); composition->SetAlignmentToParent(Margin(0, 0, 0, 0)); checkCell->AddChild(composition); } else { button.bulletRadioElement=GuiSolidBackgroundElement::Create(); button.bulletRadioElement->SetShape(ElementShape::Ellipse); GuiBoundsComposition* composition=new GuiBoundsComposition; composition->SetOwnedElement(button.bulletRadioElement); composition->SetAlignmentToParent(Margin(checkPadding+3, 3, checkPadding+3, 3)); checkCell->AddChild(composition); } } } { GuiCellComposition* textCell=new GuiCellComposition; mainTable->AddChild(textCell); textCell->SetSite(0, 1, 1, 1); { Win8CreateSolidLabelElement(button.textElement, button.textComposition, Alignment::Left, Alignment::Center); textCell->AddChild(button.textComposition); } } } return button; } void Win8CheckedButtonElements::Apply(const Win8ButtonColors& colors) { bulletBorderElement->SetColor(colors.borderColor); bulletBackgroundElement->SetColors(colors.g1, colors.g2); textElement->SetColor(colors.textColor); if(bulletCheckElement) { bulletCheckElement->SetColor(colors.bullet); } if(bulletRadioElement) { bulletRadioElement->SetColor(colors.bullet); } } /*********************************************************************** Win8MenuItemButtonElements ***********************************************************************/ Win8MenuItemButtonElements Win8MenuItemButtonElements::Create() { Win8MenuItemButtonElements button; { button.mainComposition=new GuiBoundsComposition; button.mainComposition->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElementAndChildren); } { GuiSolidBorderElement* element=GuiSolidBorderElement::Create(); button.borderElement=element; GuiBoundsComposition* composition=new GuiBoundsComposition; button.mainComposition->AddChild(composition); composition->SetAlignmentToParent(Margin(0, 0, 0, 0)); composition->SetOwnedElement(element); } { GuiGradientBackgroundElement* element=GuiGradientBackgroundElement::Create(); button.backgroundElement=element; element->SetDirection(GuiGradientBackgroundElement::Vertical); GuiBoundsComposition* composition=new GuiBoundsComposition; button.mainComposition->AddChild(composition); composition->SetAlignmentToParent(Margin(1, 1, 1, 1)); composition->SetOwnedElement(element); } { GuiTableComposition* table=new GuiTableComposition; button.mainComposition->AddChild(table); table->SetAlignmentToParent(Margin(2, 0, 2, 0)); table->SetRowsAndColumns(1, 5); table->SetRowOption(0, GuiCellOption::PercentageOption(1.0)); table->SetColumnOption(0, GuiCellOption::AbsoluteOption(24)); table->SetColumnOption(1, GuiCellOption::AbsoluteOption(1)); table->SetColumnOption(2, GuiCellOption::PercentageOption(1.0)); table->SetColumnOption(3, GuiCellOption::MinSizeOption()); table->SetColumnOption(4, GuiCellOption::AbsoluteOption(10)); { GuiCellComposition* cell=new GuiCellComposition; table->AddChild(cell); cell->SetSite(0, 0, 1, 1); button.splitterComposition=cell; GuiImageFrameElement* element=GuiImageFrameElement::Create(); button.imageElement=element; element->SetStretch(false); element->SetAlignments(Alignment::Center, Alignment::Center); cell->SetOwnedElement(element); } { GuiCellComposition* cell=new GuiCellComposition; table->AddChild(cell); cell->SetSite(0, 1, 1, 1); button.splitterComposition=cell; GuiSolidBorderElement* element=GuiSolidBorderElement::Create(); button.splitterElement=element; cell->SetOwnedElement(element); } { GuiCellComposition* cell=new GuiCellComposition; table->AddChild(cell); cell->SetSite(0, 2, 1, 1); Win8CreateSolidLabelElement(button.textElement, button.textComposition, L"MenuItem-Text", Alignment::Left, Alignment::Center); cell->AddChild(button.textComposition); } { GuiCellComposition* cell=new GuiCellComposition; table->AddChild(cell); cell->SetSite(0, 3, 1, 1); Win8CreateSolidLabelElement(button.shortcutElement, button.shortcutComposition, L"MenuItem-Shortcut", Alignment::Right, Alignment::Center); cell->AddChild(button.shortcutComposition); } { button.subMenuArrowElement=common_styles::CommonFragmentBuilder::BuildRightArrow(); GuiCellComposition* cell=new GuiCellComposition; button.subMenuArrowComposition=cell; cell->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElement); table->AddChild(cell); cell->SetSite(0, 4, 1, 1); cell->SetOwnedElement(button.subMenuArrowElement); cell->SetVisible(false); } } return button; } void Win8MenuItemButtonElements::Apply(const Win8ButtonColors& colors) { borderElement->SetColor(colors.borderColor); backgroundElement->SetColors(colors.g1, colors.g2); splitterElement->SetColor(colors.bullet); textElement->SetColor(colors.textColor); shortcutElement->SetColor(colors.textColor); subMenuArrowElement->SetBackgroundColor(colors.textColor); subMenuArrowElement->SetBorderColor(colors.textColor); } void Win8MenuItemButtonElements::SetActive(bool value) { if(value) { splitterComposition->SetMargin(Margin(0, 1, 0, 2)); } else { splitterComposition->SetMargin(Margin(0, 0, 0, 0)); } } void Win8MenuItemButtonElements::SetSubMenuExisting(bool value) { subMenuArrowComposition->SetVisible(value); } /*********************************************************************** Win8TextBoxColors ***********************************************************************/ Win8TextBoxColors Win8TextBoxColors::Blend(const Win8TextBoxColors& c1, const Win8TextBoxColors& c2, vint ratio, vint total) { if(ratio<0) ratio=0; else if(ratio>total) ratio=total; Win8TextBoxColors result; result.borderColor=BlendColor(c1.borderColor, c2.borderColor, ratio, total); result.backgroundColor=BlendColor(c1.backgroundColor, c2.backgroundColor, ratio, total); return result; } Win8TextBoxColors Win8TextBoxColors::Normal() { Win8TextBoxColors result= { Color(171, 173, 179), Color(255, 255, 255), }; return result; } Win8TextBoxColors Win8TextBoxColors::Active() { Win8TextBoxColors result= { Color(126, 180, 234), Color(255, 255, 255), }; return result; } Win8TextBoxColors Win8TextBoxColors::Focused() { Win8TextBoxColors result= { Color(86, 157, 229), Color(255, 255, 255), }; return result; } Win8TextBoxColors Win8TextBoxColors::Disabled() { Win8TextBoxColors result= { Color(217, 217, 217), Win8GetSystemWindowColor(), }; return result; } /*********************************************************************** Helpers ***********************************************************************/ Color Win8GetSystemWindowColor() { return Color(240, 240, 240); } Color Win8GetSystemTabContentColor() { return Color(255, 255, 255); } Color Win8GetSystemBorderColor() { return Color(171, 173, 179); } Color Win8GetSystemTextColor(bool enabled) { return enabled?Color(0, 0, 0):Color(131, 131, 131); } Color Win8GetMenuBorderColor() { return Color(151, 151, 151); } Color Win8GetMenuSplitterColor() { return Color(215, 215, 215); } void Win8SetFont(GuiSolidLabelElement* element, GuiBoundsComposition* composition, const FontProperties& fontProperties) { vint margin=3; element->SetFont(fontProperties); composition->SetMargin(Margin(margin, margin, margin, margin)); } void Win8CreateSolidLabelElement(GuiSolidLabelElement*& element, GuiBoundsComposition*& composition, Alignment horizontal, Alignment vertical) { element=GuiSolidLabelElement::Create(); element->SetAlignments(horizontal, vertical); composition=new GuiBoundsComposition; composition->SetOwnedElement(element); composition->SetMargin(Margin(0, 0, 0, 0)); composition->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElement); composition->SetAlignmentToParent(Margin(0, 0, 0, 0)); } void Win8CreateSolidLabelElement(elements::GuiSolidLabelElement*& element, compositions::GuiSharedSizeItemComposition*& composition, const WString& group, Alignment horizontal, Alignment vertical) { element=GuiSolidLabelElement::Create(); element->SetAlignments(horizontal, vertical); composition=new GuiSharedSizeItemComposition; composition->SetGroup(group); composition->SetSharedWidth(true); composition->SetOwnedElement(element); composition->SetMargin(Margin(0, 0, 0, 0)); composition->SetMinSizeLimitation(GuiGraphicsComposition::LimitToElement); composition->SetAlignmentToParent(Margin(0, 0, 0, 0)); } elements::text::ColorEntry Win8GetTextBoxTextColor() { elements::text::ColorEntry entry; entry.normal.text=Color(0, 0, 0); entry.normal.background=Color(0, 0, 0, 0); entry.selectedFocused.text=Color(255, 255, 255); entry.selectedFocused.background=Color(51, 153, 255); entry.selectedUnfocused.text=Color(255, 255, 255); entry.selectedUnfocused.background=Color(51, 153, 255); return entry; } } } }
27.301538
199
0.638341
cameled
6a1b8aecfcec3c9417b62bc147408795cf20b728
643
cpp
C++
src/sprite/delete_closet.cpp
Damdoshi/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
38
2016-07-30T09:35:19.000Z
2022-03-04T10:13:48.000Z
src/sprite/delete_closet.cpp
Elania-Marvers/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
15
2017-02-12T19:20:52.000Z
2021-06-09T09:30:52.000Z
src/sprite/delete_closet.cpp
Elania-Marvers/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
12
2016-10-06T09:06:59.000Z
2022-03-04T10:14:00.000Z
// Jason Brillante "Damdoshi" // Hanged Bunny Studio 2014-2018 // // Lapin library #include "lapin_private.h" static void delete_clothe(t_bunny_map *nod, void *param) { t_bunny_clothe *clo; (void)param; if ((clo = bunny_map_data(nod, t_bunny_clothe*)) != NULL) { bunny_free((void*)clo->name); bunny_delete_clipable(&clo->sprite->clipable); bunny_free(clo); } } void bunny_delete_closet(t_bunny_closet *closet) { bunny_map_foreach(closet->clothes, delete_clothe, NULL); bunny_delete_map(closet->clothes); if (closet->name) bunny_free((void*)closet->name); bunny_free(closet); }
20.741935
59
0.676516
Damdoshi
6a21c6ae556f6b8442dbb57c5e506ce1badaefa8
584
hpp
C++
include/mexcppclass/matlab/classid.hpp
rymut/mexcppclass
a6a1873a4c4d4f588490d3dc070cb7500fb82214
[ "ECL-2.0", "Apache-2.0" ]
1
2019-07-28T23:59:48.000Z
2019-07-28T23:59:48.000Z
include/mexcppclass/matlab/classid.hpp
rymut/mexcppclass
a6a1873a4c4d4f588490d3dc070cb7500fb82214
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/mexcppclass/matlab/classid.hpp
rymut/mexcppclass
a6a1873a4c4d4f588490d3dc070cb7500fb82214
[ "ECL-2.0", "Apache-2.0" ]
3
2017-08-25T03:02:36.000Z
2020-04-08T17:02:42.000Z
/// Copyright (C) 2017 by Boguslaw Rymut /// /// This file is distributed under the Apache 2.0 License /// See LICENSE for details. #ifndef MEXCPPCLASS_MATLAB_CLASSID_HPP_ #define MEXCPPCLASS_MATLAB_CLASSID_HPP_ namespace mexcppclass { namespace matlab { enum class ClassId { Single, Double, Char, String, Logical, Int8, Int16, Int32, Int64, Uint8, Uint16, Uint32, Uint64, Numeric, Scalar, Struct, Cell, Table }; } // namespace matlab } // namespace mexcppclass #endif // MEXCPPCLASS_MATLAB_CLASSID_HPP_
15.783784
58
0.664384
rymut
6a242b9f1718c727d87f0c99120d0fffbfcd02cd
823
cpp
C++
opencl/source/xe_hpc_core/gtpin_setup_xe_hpc_core.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
opencl/source/xe_hpc_core/gtpin_setup_xe_hpc_core.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
opencl/source/xe_hpc_core/gtpin_setup_xe_hpc_core.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
/* * Copyright (C) 2021-2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "opencl/source/gtpin/gtpin_hw_helper.h" #include "opencl/source/gtpin/gtpin_hw_helper.inl" #include "opencl/source/gtpin/gtpin_hw_helper_xehp_and_later.inl" #include "ocl_igc_shared/gtpin/gtpin_ocl_interface.h" namespace NEO { extern GTPinHwHelper *gtpinHwHelperFactory[IGFX_MAX_CORE]; using Family = XE_HPC_COREFamily; static const auto gfxFamily = IGFX_XE_HPC_CORE; template class GTPinHwHelperHw<Family>; struct GTPinEnableXeHpcCore { GTPinEnableXeHpcCore() { gtpinHwHelperFactory[gfxFamily] = &GTPinHwHelperHw<Family>::get(); } }; template <> uint32_t GTPinHwHelperHw<Family>::getGenVersion() { return gtpin::GTPIN_XE_HPC_CORE; } static GTPinEnableXeHpcCore gtpinEnable; } // namespace NEO
22.243243
74
0.771567
mattcarter2017
6a2a6457c1b4d0022fefb30b4c5bfa7814284e04
152,503
cpp
C++
src/Scripts.cpp
TijmenUU/VVVVVV
ce6c07c800f3dce98e0bd40f32311b98a01a4cd6
[ "RSA-MD" ]
null
null
null
src/Scripts.cpp
TijmenUU/VVVVVV
ce6c07c800f3dce98e0bd40f32311b98a01a4cd6
[ "RSA-MD" ]
null
null
null
src/Scripts.cpp
TijmenUU/VVVVVV
ce6c07c800f3dce98e0bd40f32311b98a01a4cd6
[ "RSA-MD" ]
null
null
null
#ifndef SCRIPTS_H #define SCRIPTS_H #include <Script.hpp> #include <algorithm> extern scriptclass script; void scriptclass::load(std::string t) { //loads script name t into the array position = 0; scriptlength = 0; running = true; int maxlength = (std::min(int(t.length()), 7)); std::string customstring = ""; for(int i = 0; i < maxlength; i++) { customstring += t[i]; } if(customstring == "custom_") { //this magic function breaks down the custom script and turns into real scripting! std::string cscriptname = ""; for(size_t i = 0; i < t.length(); i++) { if(i >= 7) cscriptname += t[i]; } int scriptstart = -1; int scriptend = -1; std::string tstring; for(size_t i = 0; i < customscript.size(); i++) { if(scriptstart == -1) { //Find start of the script if(script.customscript[i] == cscriptname + ":") { scriptstart = i + 1; } } else if(scriptend == -1) { //Find the end tstring = script.customscript[i]; tstring = tstring[tstring.size() - 1]; if(tstring == ":") { scriptend = i; } } } if(scriptstart > -1) { if(scriptend == -1) { scriptend = customscript.size(); } //Ok, we've got the relavent script segment, we do a pass to assess it, then run it! int customcutscenemode = 0; for(int i = scriptstart; i < scriptend; i++) { tokenize(script.customscript[i]); if(words[0] == "say") { customcutscenemode = 1; } else if(words[0] == "reply") { customcutscenemode = 1; } } if(customcutscenemode == 1) { add("cutscene()"); add("untilbars()"); } int customtextmode = 0; int speakermode = 0; //0, terminal, numbers for crew int squeakmode = 0; //default on //Now run the script for(int i = scriptstart; i < scriptend; i++) { words[0] = "nothing"; //Default! words[1] = "1"; //Default! tokenize(script.customscript[i]); std::transform(words[0].begin(), words[0].end(), words[0].begin(), ::tolower); if(words[0] == "music") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } if(words[1] == "0") { tstring = "stopmusic()"; } else { if(words[1] == "11") { tstring = "play(14)"; } else if(words[1] == "10") { tstring = "play(13)"; } else if(words[1] == "9") { tstring = "play(12)"; } else if(words[1] == "8") { tstring = "play(11)"; } else if(words[1] == "7") { tstring = "play(10)"; } else if(words[1] == "6") { tstring = "play(8)"; } else if(words[1] == "5") { tstring = "play(6)"; } else { tstring = "play(" + words[1] + ")"; } } add(tstring); } else if(words[0] == "playremix") { add("play(15)"); } else if(words[0] == "flash") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } add("flash(5)"); add("shake(20)"); add("playef(9,10)"); } else if(words[0] == "sad" || words[0] == "cry") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } if(words[1] == "player") { add("changemood(player,1)"); } else if(words[1] == "cyan" || words[1] == "viridian" || words[1] == "1") { add("changecustommood(customcyan,1)"); } else if(words[1] == "purple" || words[1] == "violet" || words[1] == "pink" || words[1] == "2") { add("changecustommood(purple,1)"); } else if(words[1] == "yellow" || words[1] == "vitellary" || words[1] == "3") { add("changecustommood(yellow,1)"); } else if(words[1] == "red" || words[1] == "vermilion" || words[1] == "4") { add("changecustommood(red,1)"); } else if(words[1] == "green" || words[1] == "verdigris" || words[1] == "5") { add("changecustommood(green,1)"); } else if(words[1] == "blue" || words[1] == "victoria" || words[1] == "6") { add("changecustommood(blue,1)"); } else if(words[1] == "all" || words[1] == "everybody" || words[1] == "everyone") { add("changemood(player,1)"); add("changecustommood(customcyan,1)"); add("changecustommood(purple,1)"); add("changecustommood(yellow,1)"); add("changecustommood(red,1)"); add("changecustommood(green,1)"); add("changecustommood(blue,1)"); } else { add("changemood(player,1)"); } if(squeakmode == 0) add("squeak(cry)"); } else if(words[0] == "happy") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } if(words[1] == "player") { add("changemood(player,0)"); if(squeakmode == 0) add("squeak(player)"); } else if(words[1] == "cyan" || words[1] == "viridian" || words[1] == "1") { add("changecustommood(customcyan,0)"); if(squeakmode == 0) add("squeak(player)"); } else if(words[1] == "purple" || words[1] == "violet" || words[1] == "pink" || words[1] == "2") { add("changecustommood(purple,0)"); if(squeakmode == 0) add("squeak(purple)"); } else if(words[1] == "yellow" || words[1] == "vitellary" || words[1] == "3") { add("changecustommood(yellow,0)"); if(squeakmode == 0) add("squeak(yellow)"); } else if(words[1] == "red" || words[1] == "vermilion" || words[1] == "4") { add("changecustommood(red,0)"); if(squeakmode == 0) add("squeak(red)"); } else if(words[1] == "green" || words[1] == "verdigris" || words[1] == "5") { add("changecustommood(green,0)"); if(squeakmode == 0) add("squeak(green)"); } else if(words[1] == "blue" || words[1] == "victoria" || words[1] == "6") { add("changecustommood(blue,0)"); if(squeakmode == 0) add("squeak(blue)"); } else if(words[1] == "all" || words[1] == "everybody" || words[1] == "everyone") { add("changemood(player,0)"); add("changecustommood(customcyan,0)"); add("changecustommood(purple,0)"); add("changecustommood(yellow,0)"); add("changecustommood(red,0)"); add("changecustommood(green,0)"); add("changecustommood(blue,0)"); } else { add("changemood(player,0)"); if(squeakmode == 0) add("squeak(player)"); } } else if(words[0] == "squeak") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } if(words[1] == "player") { add("squeak(player)"); } else if(words[1] == "cyan" || words[1] == "viridian" || words[1] == "1") { add("squeak(player)"); } else if(words[1] == "purple" || words[1] == "violet" || words[1] == "pink" || words[1] == "2") { add("squeak(purple)"); } else if(words[1] == "yellow" || words[1] == "vitellary" || words[1] == "3") { add("squeak(yellow)"); } else if(words[1] == "red" || words[1] == "vermilion" || words[1] == "4") { add("squeak(red)"); } else if(words[1] == "green" || words[1] == "verdigris" || words[1] == "5") { add("squeak(green)"); } else if(words[1] == "blue" || words[1] == "victoria" || words[1] == "6") { add("squeak(blue)"); } else if(words[1] == "cry" || words[1] == "sad") { add("squeak(cry)"); } else if(words[1] == "on") { squeakmode = 0; } else if(words[1] == "off") { squeakmode = 1; } } else if(words[0] == "delay") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } add(script.customscript[i]); } else if(words[0] == "flag") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } add(script.customscript[i]); } else if(words[0] == "map") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } add("custom" + script.customscript[i]); } else if(words[0] == "warpdir") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } add(script.customscript[i]); } else if(words[0] == "ifwarp") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } add(script.customscript[i]); } else if(words[0] == "iftrinkets") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } add("custom" + script.customscript[i]); } else if(words[0] == "ifflag") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } add("custom" + script.customscript[i]); } else if(words[0] == "iftrinketsless") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } add("custom" + script.customscript[i]); } else if(words[0] == "destroy") { if(customtextmode == 1) { add("endtext"); customtextmode = 0; } if(words[1] == "gravitylines") { add("destroy(gravitylines)"); } else if(words[1] == "warptokens") { add("destroy(warptokens)"); } else if(words[1] == "platforms") { add("destroy(platforms)"); } } else if(words[0] == "speaker") { speakermode = 0; if(words[1] == "gray" || words[1] == "grey" || words[1] == "terminal" || words[1] == "0") speakermode = 0; if(words[1] == "cyan" || words[1] == "viridian" || words[1] == "player" || words[1] == "1") speakermode = 1; if(words[1] == "purple" || words[1] == "violet" || words[1] == "pink" || words[1] == "2") speakermode = 2; if(words[1] == "yellow" || words[1] == "vitellary" || words[1] == "3") speakermode = 3; if(words[1] == "red" || words[1] == "vermilion" || words[1] == "4") speakermode = 4; if(words[1] == "green" || words[1] == "verdigris" || words[1] == "5") speakermode = 5; if(words[1] == "blue" || words[1] == "victoria" || words[1] == "6") speakermode = 6; } else if(words[0] == "say") { //Speakers! if(words[2] == "terminal" || words[2] == "gray" || words[2] == "grey" || words[2] == "0") speakermode = 0; if(words[2] == "cyan" || words[2] == "viridian" || words[2] == "player" || words[2] == "1") speakermode = 1; if(words[2] == "purple" || words[2] == "violet" || words[2] == "pink" || words[2] == "2") speakermode = 2; if(words[2] == "yellow" || words[2] == "vitellary" || words[2] == "3") speakermode = 3; if(words[2] == "red" || words[2] == "vermilion" || words[2] == "4") speakermode = 4; if(words[2] == "green" || words[2] == "verdigris" || words[2] == "5") speakermode = 5; if(words[2] == "blue" || words[2] == "victoria" || words[2] == "6") speakermode = 6; switch(speakermode) { case 0: if(squeakmode == 0) add("squeak(terminal)"); add("text(gray,0,114," + words[1] + ")"); break; case 1: //NOT THE PLAYER if(squeakmode == 0) add("squeak(cyan)"); add("text(cyan,0,0," + words[1] + ")"); break; case 2: if(squeakmode == 0) add("squeak(purple)"); add("text(purple,0,0," + words[1] + ")"); break; case 3: if(squeakmode == 0) add("squeak(yellow)"); add("text(yellow,0,0," + words[1] + ")"); break; case 4: if(squeakmode == 0) add("squeak(red)"); add("text(red,0,0," + words[1] + ")"); break; case 5: if(squeakmode == 0) add("squeak(green)"); add("text(green,0,0," + words[1] + ")"); break; case 6: if(squeakmode == 0) add("squeak(blue)"); add("text(blue,0,0," + words[1] + ")"); break; } int ti = atoi(words[1].c_str()); if(ti >= 0 && ti <= 50) { for(int ti2 = 0; ti2 < ti; ti2++) { i++; add(script.customscript[i]); } } else { i++; add(script.customscript[i]); } switch(speakermode) { case 0: add("customposition(center)"); break; case 1: add("customposition(cyan,above)"); break; case 2: add("customposition(purple,above)"); break; case 3: add("customposition(yellow,above)"); break; case 4: add("customposition(red,above)"); break; case 5: add("customposition(green,above)"); break; case 6: add("customposition(blue,above)"); break; } add("speak_active"); customtextmode = 1; } else if(words[0] == "reply") { //For this version, terminal only if(squeakmode == 0) add("squeak(player)"); add("text(cyan,0,0," + words[1] + ")"); int ti = atoi(words[1].c_str()); if(ti >= 0 && ti <= 50) { for(int ti2 = 0; ti2 < ti; ti2++) { i++; add(script.customscript[i]); } } else { i++; add(script.customscript[i]); } add("position(player,above)"); add("speak_active"); customtextmode = 1; } } if(customtextmode == 1) { add("endtext"); customtextmode = 0; } if(customcutscenemode == 1) { add("endcutscene()"); add("untilbars()"); } } } else if(t == "intro") { add("ifskip(quickstart)"); //add("createcrewman(232,113,cyan,0,faceright)"); add("createcrewman(96,177,green,0,faceright)"); add("createcrewman(122,177,purple,0,faceleft)"); add("fadein()"); add("untilfade()"); add("delay(90)"); add("flash(5)"); add("shake(20)"); add("playef(9,10)"); add("musicfadeout()"); add("changemood(player,1)"); add("delay(15)"); add("squeak(player)"); add("text(cyan,0,0,1)"); add("Uh oh..."); add("position(player,above)"); //add("backgroundtext"); add("speak_active"); add("squeak(purple)"); add("changeai(purple,followposition,175)"); add("text(purple,145,150,1)"); add("Is everything ok?"); //add("position(purple,above)"); //add("backgroundtext"); add("speak_active"); add("squeak(player)"); add("walk(left,2)"); add("text(cyan,0,0,2)"); add("No! We've hit some"); add("kind of interference..."); add("position(player,above)"); //add("backgroundtext"); add("speak_active"); //add("delay(30)"); add("endtext"); add("flash(5)"); add("shake(50)"); add("playef(9,10)"); add("changemood(green,1)"); add("changemood(purple,1)"); add("alarmon"); add("changedir(player,1)"); add("delay(30)"); add("endtext"); add("squeak(player)"); add("text(cyan,0,0,2)"); add("Something's wrong! We're"); add("going to crash!"); add("position(player,above)"); //add("backgroundtext"); add("speak_active"); //add("delay(100)"); add("endtext"); add("flash(5)"); add("shake(50)"); add("playef(9,10)"); add("changeai(green,followposition,-60)"); add("changeai(purple,followposition,-60)"); add("squeak(player)"); add("text(cyan,70,140,1)"); add("Evacuate!"); add("backgroundtext"); add("speak_active"); add("walk(left,35)"); add("endtextfast"); //Ok, next room! add("flash(5)"); add("shake(50)"); add("playef(9,10)"); add("gotoroom(3,10)"); add("gotoposition(310,177,0)"); add("createcrewman(208,177,green,1,followposition,120)"); add("createcrewman(240,177,purple,1,followposition,120)"); add("createcrewman(10,177,blue,1,followposition,180)"); add("squeak(blue)"); add("text(blue,80,150,1)"); add("Oh no!"); add("backgroundtext"); add("speak_active"); add("walk(left,20)"); add("endtextfast"); //and the next! add("flash(5)"); add("shake(50)"); add("playef(9,10)"); add("gotoroom(3,11)"); add("gotoposition(140,0,0)"); add("createcrewman(90,105,green,1,followblue)"); add("createcrewman(125,105,purple,1,followgreen)"); add("createcrewman(55,105,blue,1,followposition,-200)"); add("createcrewman(120,177,yellow,1,followposition,-200)"); add("createcrewman(240,177,red,1,faceleft)"); add("delay(5)"); add("changeai(red,followposition,-200)"); add("squeak(red)"); add("text(red,100,150,1)"); add("Everyone off the ship!"); add("backgroundtext"); add("speak_active"); add("walk(left,25)"); add("endtextfast"); //final room: add("flash(5)"); add("shake(80)"); add("playef(9,10)"); add("gotoroom(2,11)"); add("gotoposition(265,153,0)"); add("createcrewman(130,153,blue,1,faceleft)"); add("createcrewman(155,153,green,1,faceleft)"); add("createcrewman(180,153,purple,1,faceleft)"); add("createcrewman(205,153,yellow,1,faceleft)"); add("createcrewman(230,153,red,1,faceleft)"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("This shouldn't be happening!"); add("position(yellow,below)"); add("backgroundtext"); add("speak_active"); add("activateteleporter()"); add("delay(10)"); add("changecolour(blue,teleporter)"); add("delay(10)"); add("changecolour(green,teleporter)"); add("delay(10)"); add("changecolour(purple,teleporter)"); add("delay(10)"); add("changecolour(yellow,teleporter)"); add("delay(10)"); add("changecolour(red,teleporter)"); add("delay(10)"); //and teleport! add("endtext"); add("alarmoff"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("blackout()"); add("changemood(player,0)"); add("changedir(player,1)"); add("delay(100)"); add("blackon()"); add("shake(20)"); add("playef(10,10)"); //Finally, appear at the start of the game: add("gotoroom(13,5)"); add("gotoposition(80,96,0)"); add("walk(right,20)"); //add("delay(45)"); add("squeak(player)"); add("text(cyan,0,0,1)"); add("Phew! That was scary!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(cyan,0,0,2)"); add("At least we all"); add("escaped, right guys?"); add("position(player,above)"); add("speak_active"); add("endtext"); add("delay(45)"); add("walk(left,3)"); add("delay(45)"); add("setcheckpoint()"); add("squeak(player)"); add("text(cyan,0,0,1)"); add("...guys?"); add("position(player,above)"); add("speak_active"); add("endtext"); add("delay(25)"); add("changemood(player,1)"); add("squeak(cry)"); add("delay(25)"); add("play(1)"); add("endcutscene()"); add("untilbars()"); add("hideship()"); add("gamestate(4)"); } else if(t == "quickstart") { //Finally, appear at the start of the game: add("gotoroom(13,5)"); add("gotoposition(80,96,0)"); add("walk(right,17)"); add("fadein()"); add("setcheckpoint()"); add("play(1)"); add("endcutscene()"); add("untilbars()"); add("hideship()"); } else if(t == "firststeps") { add("cutscene()"); add("untilbars()"); add("squeak(player)"); add("text(cyan,0,0,2)"); add("I wonder why the ship"); add("teleported me here alone?"); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("text(cyan,0,0,2)"); add("I hope everyone else"); add("got out ok..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "trenchwarfare") { add("cutscene()"); add("untilbars()"); add("iftrinkets(1,newtrenchwarfare)"); add("squeak(player)"); add("text(cyan,0,0,1)"); add("Ohh! I wonder what that is?"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(cyan,0,0,3)"); add("I probably don't really need it,"); add("but it might be nice to take it"); add("back to the ship to study..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "newtrenchwarfare") { add("squeak(player)"); add("text(cyan,0,0,2)"); add("Oh! It's another one of"); add("those shiny things!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(cyan,0,0,3)"); add("I probably don't really need it,"); add("but it might be nice to take it"); add("back to the ship to study..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "trinketcollector") { add("cutscene()"); add("untilbars()"); add("iftrinkets(1,newtrinketcollector)"); add("squeak(player)"); add("text(cyan,0,0,3)"); add("This seems like a good"); add("place to store anything"); add("I find out there..."); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(cyan,0,0,3)"); add("Victoria loves to study the"); add("interesting things we find"); add("on our adventures!"); add("position(player,above)"); add("speak_active"); add("ifcrewlost(5,new2trinketcollector)"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "newtrinketcollector") { add("squeak(player)"); add("text(cyan,0,0,3)"); add("This seems like a good"); add("place to store those"); add("shiny things."); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(cyan,0,0,3)"); add("Victoria loves to study the"); add("interesting things we find"); add("on our adventures!"); add("position(player,above)"); add("speak_active"); add("ifcrewlost(5,new2trinketcollector)"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "new2trinketcollector") { add("squeak(cry)"); add("changemood(player,1)"); add("text(cyan,0,0,1)"); add("I hope she's ok..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("changemood(player,0)"); add("endcutscene()"); add("untilbars()"); return; } if(t == "communicationstation") { add("ifskip(communicationstationskip)"); add("cutscene()"); add("untilbars()"); add("changemood(player,0)"); add("tofloor"); add("play(5)"); add("delay(10)"); add("squeak(player)"); add("text(cyan,0,0,1)"); add("Violet! Is that you?"); add("position(player,above)"); add("speak_active"); add("endtext"); add("squeak(purple)"); add("text(purple,45,18,1)"); add("Captain! You're ok!"); add("speak_active"); add("squeak(cry)"); add("text(purple,20,16,3)"); add("Something has gone"); add("horribly wrong with the"); add("ship's teleporter!"); add("speak_active"); add("squeak(purple)"); add("text(purple,8,14,3)"); add("I think everyone has been"); add("teleported away randomly!"); add("They could be anywhere!"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(cyan,0,0,1)"); add("Oh no!"); add("position(player,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,10,19,2)"); add("I'm on the ship - it's damaged"); add("badly, but it's still intact!"); add("speak_active"); add("squeak(purple)"); add("text(purple,10,15,1)"); add("Where are you, Captain?"); add("speak_active"); add("squeak(player)"); add("changemood(player,0)"); add("text(cyan,0,0,3)"); add("I'm on some sort of"); add("space station... It"); add("seems pretty modern..."); add("position(player,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,15,16,2)"); add("There seems to be some sort of"); add("interference in this dimension..."); add("speak_active"); add("hideteleporters()"); add("endtextfast"); add("delay(10)"); //add map mode here and wrap up... add("gamemode(teleporter)"); add("delay(20)"); add("squeak(purple)"); add("text(purple,25,205,2)"); add("I'm broadcasting the coordinates"); add("of the ship to you now."); add("speak_active"); add("endtext"); add("squeak(terminal)"); add("showship()"); add("delay(10)"); add("hideship()"); add("delay(10)"); add("showship()"); add("delay(10)"); add("hideship()"); add("delay(10)"); add("showship()"); add("delay(20)"); add("squeak(purple)"); add("text(purple,10,200,1)"); add("I can't teleport you back, but..."); add("speak_active"); add("squeak(purple)"); add("text(purple,25,195,3)"); add("If YOU can find a teleporter"); add("anywhere nearby, you should be"); add("able to teleport back to me!"); add("speak_active"); add("endtext"); add("squeak(terminal)"); add("delay(20)"); add("showteleporters()"); add("delay(10)"); add("hideteleporters()"); add("delay(10)"); add("showteleporters()"); add("delay(10)"); add("hideteleporters()"); add("delay(10)"); add("showteleporters()"); add("delay(20)"); add("squeak(player)"); add("text(cyan,20,190,1)"); add("Ok! I'll try to find one!"); add("speak_active"); add("endtext"); add("delay(20)"); add("gamemode(game)"); add("delay(20)"); add("squeak(purple)"); add("text(purple,40,22,1)"); add("Good luck, Captain!"); add("speak_active"); add("endtext"); add("squeak(purple)"); add("text(purple,10,19,2)"); add("I'll keep trying to find"); add("the rest of the crew..."); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("play(1)"); } else if(t == "communicationstationskip") { add("changemood(player,0)"); add("delay(10)"); add("endtext"); //add map mode here and wrap up... add("gamemode(teleporter)"); add("delay(5)"); add("squeak(terminal)"); add("showship()"); add("showteleporters()"); add("delay(10)"); add("hideship()"); add("hideteleporters()"); add("delay(10)"); add("showship()"); add("showteleporters()"); add("delay(10)"); add("hideship()"); add("hideteleporters()"); add("delay(10)"); add("showship()"); add("showteleporters()"); add("delay(20)"); add("gamemode(game)"); } else if(t == "teleporterback") { add("cutscene()"); add("untilbars()"); add("squeak(player)"); add("text(cyan,0,0,1)"); add("A teleporter!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(cyan,0,0,2)"); add("I can get back to the"); add("ship with this!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("teleportscript(levelonecomplete)"); add("endcutscene()"); add("untilbars()"); } else if(t == "levelonecomplete") { add("nocontrol()"); add("createcrewman(230,153,purple,0,faceleft)"); add("cutscene()"); add("untilbars()"); add("delay(30)"); add("rescued(purple)"); add("delay(10)"); add("gamestate(4090)"); } else if(t == "levelonecomplete_ending") { add("squeak(purple)"); add("text(purple,0,0,1)"); add("Captain!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("nocontrol()"); add("endcutscene()"); add("untilbars()"); add("gamestate(3050)"); } else if(t == "levelonecompleteskip") { add("nocontrol()"); add("gamestate(3050)"); } else if(t == "bigopenworld") { add("play(5)"); add("cutscene()"); add("untilbars()"); add("gotoroom(4,10)"); add("gotoposition(100,177,0)"); add("createcrewman(150,177,purple,0,faceleft)"); //set all the crew as rescued to avoid companion issues! add("rescued(red)"); add("rescued(green)"); add("rescued(blue)"); add("rescued(yellow)"); add("fadein()"); add("untilfade()"); add("delay(15)"); add("squeak(player)"); add("text(player,0,0,2)"); add("So, Doctor - have you any"); add("idea what caused the crash?"); add("position(player,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,3)"); add("There's some sort of bizarre"); add("signal here that's interfering"); add("with our equipment..."); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,3)"); add("It caused the ship to lose"); add("its quantum position, collapsing"); add("us into this dimension!"); add("position(purple,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("Oh no!"); add("position(player,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("But I think we should be able to fix"); add("the ship and get out of here..."); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("... as long as we can"); add("find the rest of the crew."); add("position(purple,above)"); add("speak_active"); add("endtext"); //Cut to Red add("fadeout()"); add("untilfade()"); add("changeplayercolour(red)"); add("gotoroom(10,4)"); add("gotoposition(200,185,0)"); add("hideplayer()"); add("createcrewman(200,185,red,1,panic)"); add("fadein()"); add("untilfade()"); //add("walk(right,10)"); add("squeak(purple)"); add("text(purple,60,40,2)"); add("We really don't know anything"); add("about this place..."); add("speak_active"); add("endtext"); add("delay(15)"); //Cut to Green add("fadeout()"); add("untilfade()"); add("showplayer()"); add("changeplayercolour(green)"); add("gotoroom(13,0)"); add("gotoposition(143,20,0)"); add("fadein()"); add("untilfade()"); add("squeak(purple)"); add("text(purple,40,30,2)"); add("Our friends could be anywhere - they"); add("could be lost, or in danger!"); add("speak_active"); add("endtext"); add("delay(15)"); //Cut to Blue add("fadeout()"); add("untilfade()"); add("changeplayercolour(blue)"); add("gotoroom(3,4)"); add("gotoposition(190,177,0)"); add("fadein()"); add("untilfade()"); add("squeak(player)"); add("text(player,10,60,1)"); add("Can they teleport back here?"); add("speak_active"); add("squeak(purple)"); add("text(purple,50,80,2)"); add("Not unless they find some way"); add("to communicate with us!"); add("speak_active"); add("squeak(purple)"); add("text(purple,30,100,3)"); add("We can't pick up their signal and"); add("they can't teleport here unless"); add("they know where the ship is..."); add("speak_active"); add("endtext"); add("delay(15)"); //Cut to Yellow add("fadeout()"); add("untilfade()"); add("changeplayercolour(yellow)"); add("gotoroom(15,9)"); //(6*8)-21 add("gotoposition(300,27,0)"); add("hideplayer()"); add("createcrewman(280,25,yellow,1,panic)"); //add("hascontrol()"); //add("walk(left,4)"); add("fadein()"); add("untilfade()"); add("squeak(player)"); add("text(player,25,60,1)"); add("So what do we do?"); add("speak_active"); add("squeak(purple)"); add("text(purple,80,125,4)"); add("We need to find them! Head"); add("out into the dimension and"); add("look for anywhere they might"); add("have ended up..."); add("speak_active"); add("endtext"); add("delay(15)"); //Back to ship add("fadeout()"); add("untilfade()"); add("showplayer()"); add("missing(red)"); add("missing(green)"); add("missing(blue)"); add("missing(yellow)"); add("changeplayercolour(cyan)"); add("changemood(player,0)"); add("gotoroom(4,10)"); add("gotoposition(90,177,0)"); add("walk(right,2)"); add("createcrewman(150,177,purple,0,faceleft)"); add("fadein()"); add("untilfade()"); add("squeak(player)"); add("text(player,0,0,1)"); add("Ok! Where do we start?"); add("position(player,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("Well, I've been trying to find"); add("them with the ship's scanners!"); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("It's not working, but I did"); add("find something..."); add("position(purple,above)"); add("speak_active"); add("endtext"); add("delay(15)"); add("hidecoordinates(10,4)"); add("hidecoordinates(13,0)"); add("hidecoordinates(3,4)"); add("hidecoordinates(15,9)"); add("showteleporters()"); //Cut to map //add map mode here and wrap up... add("gamemode(teleporter)"); add("delay(20)"); add("squeak(terminal)"); add("showtargets()"); add("delay(10)"); add("hidetargets()"); add("delay(10)"); add("showtargets()"); add("delay(10)"); add("hidetargets()"); add("delay(10)"); add("showtargets()"); add("delay(20)"); add("squeak(purple)"); add("text(purple,25,205,2)"); add("These points show up on our scans"); add("as having high energy patterns!"); add("speak_active"); add("endtext"); add("squeak(purple)"); add("text(purple,35,185,4)"); add("There's a good chance they're"); add("teleporters - which means"); add("they're probably built near"); add("something important..."); add("speak_active"); add("squeak(purple)"); add("text(purple,25,205,2)"); add("They could be a very good"); add("place to start looking."); add("speak_active"); add("endtext"); add("delay(20)"); add("gamemode(game)"); add("delay(20)"); //And finally, back to the ship! add("squeak(player)"); add("text(player,0,0,2)"); add("Ok! I'll head out and see"); add("what I can find!"); add("position(player,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("I'll be right here if"); add("you need any help!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("rescued(purple)"); add("play(4)"); add("endcutscene()"); add("untilbars()"); add("hascontrol()"); add("createactivityzone(purple)"); } else if(t == "bigopenworldskip") { add("gotoroom(4,10)"); add("gotoposition(100,177,0)"); add("createcrewman(150,177,purple,0,faceleft)"); add("fadein()"); add("untilfade()"); add("hidecoordinates(10,4)"); add("hidecoordinates(13,0)"); add("hidecoordinates(3,4)"); add("hidecoordinates(15,9)"); add("showteleporters()"); //Cut to map //add map mode here and wrap up... add("gamemode(teleporter)"); add("delay(20)"); add("squeak(terminal)"); add("showtargets()"); add("delay(10)"); add("hidetargets()"); add("delay(10)"); add("showtargets()"); add("delay(10)"); add("hidetargets()"); add("delay(10)"); add("showtargets()"); add("delay(20)"); add("gamemode(game)"); add("delay(20)"); //And finally, back to the ship! add("squeak(purple)"); add("text(purple,0,0,2)"); add("I'll be right here if"); add("you need any help!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("rescued(purple)"); add("play(4)"); add("endcutscene()"); add("untilbars()"); add("hascontrol()"); add("createactivityzone(purple)"); } else if(t == "rescueblue") { add("ifskip(skipblue)"); add("cutscene()"); add("tofloor()"); add("changeai(blue,followplayer)"); add("untilbars()"); add("rescued(blue)"); add("squeak(blue)"); add("text(blue,0,0,2)"); add("Oh no! Captain! Are you"); add("stuck here too?"); add("position(blue,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("It's ok - I'm here to rescue you!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Let me explain everything..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("fadeout()"); add("untilfade()"); add("delay(30)"); add("fadein()"); add("untilfade()"); add("squeak(cry)"); add("text(blue,0,0,2)"); add("What? I didn't understand"); add("any of that!"); add("position(blue,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Oh... well, don't worry."); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("Follow me! Everything"); add("will be alright!"); add("position(player,above)"); add("speak_active"); add("squeak(blue)"); add("changemood(blue,0)"); add("text(blue,0,0,1)"); add("Sniff... Really?"); add("position(blue,above)"); add("speak_active"); add("squeak(blue)"); add("text(blue,0,0,1)"); add("Ok then!"); add("position(blue,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("companion(8)"); add("setcheckpoint()"); } else if(t == "skipblue") { add("changeai(blue,followplayer)"); add("squeak(blue)"); add("changemood(blue,0)"); add("companion(8)"); add("rescued(blue)"); add("setcheckpoint()"); } else if(t == "rescueyellow") { add("ifskip(skipyellow)"); add("cutscene()"); add("changeai(yellow,followplayer)"); add("changetile(yellow,6)"); add("untilbars()"); add("rescued(yellow)"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("Ah, Viridian! You got off"); add("the ship alright too? "); add("position(yellow,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("It's good to see you're"); add("alright, Professor!"); add("position(player,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("Is the ship ok?"); add("position(yellow,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("It's badly damaged, but Violet's"); add("been working on fixing it."); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("We could really use your help..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("fadeout()"); add("untilfade()"); add("delay(30)"); add("fadein()"); add("untilfade()"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("Ah, of course!"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,4)"); add("The background interference"); add("in this dimension prevented"); add("the ship from finding a"); add("teleporter when we crashed!"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("We've all been teleported"); add("to different locations!"); add("position(yellow,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Er, that sounds about right!"); add("position(player,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("Let's get back to"); add("the ship, then!"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("After you, Captain!"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("companion(7)"); add("endcutscene()"); add("untilbars()"); } else if(t == "skipyellow") { add("changeai(yellow,followplayer)"); add("changetile(yellow,6)"); add("squeak(yellow)"); add("rescued(yellow)"); add("companion(7)"); } else if(t == "rescuegreen") { add("ifskip(skipgreen)"); add("cutscene()"); add("tofloor()"); add("changemood(green,0)"); add("untilbars()"); add("rescued(green)"); add("squeak(green)"); add("text(green,0,0,1)"); add("Captain! I've been so worried!"); add("position(green,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Chief Verdigris! You're ok!"); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(green,1)"); add("text(green,0,0,2)"); add("I've been trying to get out, but"); add("I keep going around in circles..."); add("position(green,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("I've come from the ship. I'm here"); add("to teleport you back to it."); add("position(player,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,2)"); add("Is everyone else"); add("alright? Is Violet..."); add("position(green,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("She's fine - she's back on the ship!"); add("position(player,above)"); add("speak_active"); add("squeak(green)"); add("changemood(green,0)"); add("text(green,0,0,2)"); add("Oh! Great - Let's"); add("get going, then!"); add("position(green,above)"); add("speak_active"); add("endtext"); add("companion(6)"); add("endcutscene()"); add("untilbars()"); add("changeai(green,followplayer)"); } else if(t == "skipgreen") { add("changeai(green,followplayer)"); add("squeak(green)"); add("rescued(green)"); add("changemood(green,0)"); add("companion(6)"); } else if(t == "rescuered") { add("ifskip(skipred)"); add("cutscene()"); add("tofloor()"); add("changemood(red,0)"); add("untilbars()"); add("rescued(red)"); add("squeak(red)"); add("text(red,0,0,1)"); add("Captain!"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,3)"); add("Am I ever glad to see you!"); add("I thought I was the only"); add("one to escape the ship..."); add("position(red,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Vermilion! I knew you'd be ok!"); add("position(player,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,1)"); add("So, what's the situation?"); add("position(red,above)"); add("speak_active"); add("endtext"); add("fadeout()"); add("untilfade()"); add("delay(30)"); add("fadein()"); add("untilfade()"); add("squeak(red)"); add("text(red,0,0,2)"); add("I see! Well, we'd better"); add("get back then."); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("There's a teleporter"); add("in the next room."); add("position(red,above)"); add("speak_active"); add("endtext"); add("companion(9)"); add("endcutscene()"); add("untilbars()"); add("changeai(red,followplayer)"); } else if(t == "skipred") { add("changeai(red,followplayer)"); add("squeak(red)"); add("rescued(red)"); add("changemood(red,0)"); add("companion(9)"); } else if(t == "startexpolevel_station1") { //For the Eurogamer EXPO! Scrap later. add("fadeout()"); add("musicfadeout()"); add("untilfade()"); add("cutscene()"); add("untilbars()"); add("resetgame"); add("gotoroom(4,10)"); add("gotoposition(232,113,0)"); add("setcheckpoint()"); add("changedir(player,1)"); add("fadein()"); add("play(5)"); add("loadscript(intro)"); } else if(t == "startexpolevel_lab") { //For the Eurogamer EXPO! Scrap later. add("fadeout()"); add("musicfadeout()"); add("untilfade()"); add("delay(30)"); add("resetgame"); add("gotoroom(2,16)"); add("gotoposition(58,193,0)"); add("setcheckpoint()"); add("changedir(player,1)"); add("fadein()"); add("stopmusic()"); add("play(3)"); } else if(t == "startexpolevel_warp") { //For the Eurogamer EXPO! Scrap later. add("fadeout()"); add("musicfadeout()"); add("untilfade()"); add("delay(30)"); add("resetgame"); add("gotoroom(14,1)"); add("gotoposition(45,73,0)"); add("setcheckpoint()"); add("changedir(player,1)"); add("fadein()"); add("stopmusic()"); add("play(3)"); } else if(t == "startexpolevel_tower") { //For the Eurogamer EXPO! Scrap later. add("fadeout()"); add("musicfadeout()"); add("untilfade()"); add("delay(30)"); add("resetgame"); add("gotoroom(8,9)"); add("gotoposition(95,193,0)"); add("setcheckpoint()"); add("changedir(player,1)"); add("fadein()"); add("stopmusic()"); add("play(2)"); } else if(t == "skipint1") { add("finalmode(41,56)"); add("gotoposition(52,89,0)"); add("changedir(player,1)"); add("setcheckpoint()"); add("delay(15)"); add("flash(5)"); add("shake(20)"); add("playef(9,10)"); add("showplayer()"); add("play(8)"); add("hascontrol()"); add("befadein()"); } else if(t == "intermission_1") { add("ifskip(skipint1)"); add("finalmode(41,56)"); add("gotoposition(52,89,0)"); add("changedir(player,1)"); add("setcheckpoint()"); add("cutscene()"); add("delay(15)"); add("flash(5)"); add("shake(20)"); add("playef(9,10)"); add("delay(35)"); add("flash(5)"); add("shake(20)"); add("playef(9,10)"); add("delay(25)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("showplayer()"); add("play(8)"); add("befadein()"); add("iflast(2,int1yellow_1)"); add("iflast(3,int1red_1)"); add("iflast(4,int1green_1)"); add("iflast(5,int1blue_1)"); } else if(t == "int1blue_1") { add("delay(45)"); add("squeak(cry)"); add("text(blue,0,0,1)"); add("Waaaa!"); add("position(blue,above)"); add("speak_active"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("text(blue,0,0,1)"); add("Captain! Are you ok?"); add("position(blue,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("I'm ok... this..."); add("this isn't the ship..."); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Where are we?"); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("text(blue,0,0,1)"); add("Waaaa!"); add("position(blue,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("Something's gone wrong... We"); add("should look for a way back!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("telesave()"); add("endcutscene()"); add("untilbars()"); add("gamestate(14)"); } else if(t == "int1blue_2") { add("cutscene()"); add("untilbars()"); add("squeak(player)"); add("text(player,0,0,1)"); add("Follow me! I'll help you!"); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("text(blue,0,0,1)"); add("Promise you won't leave without me!"); add("position(blue,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("I promise! Don't worry!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("gamestate(11)"); } else if(t == "int1blue_3") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(player)"); add("text(player,0,0,1)"); add("Are you ok down there, Doctor?"); add("position(player,below)"); add("speak_active"); add("squeak(cry)"); add("text(blue,0,0,1)"); add("I wanna go home!"); add("position(blue,above)"); add("speak_active"); add("squeak(blue)"); add("text(blue,0,0,2)"); add("Where are we? How did"); add("we even get here?"); add("position(blue,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,4)"); add("Well, Violet did say that the"); add("interference in the dimension"); add("we crashed in was causing"); add("problems with the teleporters..."); add("position(player,below)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("I guess something went wrong..."); add("position(player,below)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,3)"); add("But if we can find another"); add("teleporter, I think we can"); add("get back to the ship!"); add("position(player,below)"); add("speak_active"); add("squeak(blue)"); add("text(blue,0,0,1)"); add("Sniff..."); add("position(blue,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1blue_4") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(cry)"); add("text(blue,0,0,1)"); add("Captain! Captain! Wait for me!"); add("position(blue,above)"); add("speak_active"); add("squeak(blue)"); add("text(blue,0,0,2)"); add("Please don't leave me behind!"); add("I don't mean to be a burden!"); add("position(blue,above)"); add("speak_active"); add("squeak(cry)"); add("text(blue,0,0,1)"); add("I'm scared!"); add("position(blue,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("Oh... don't worry Victoria,"); add("I'll look after you!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1blue_5") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(cry)"); add("text(blue,0,0,2)"); add("We're never going to get"); add("out of here, are we?"); add("position(blue,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("I.. I don't know..."); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("text(player,0,0,2)"); add("I don't know where we are or"); add("how we're going to get out..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1blue_6") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(cry)"); add("text(blue,0,0,1)"); add("We're going to be lost forever!"); add("position(blue,above)"); add("speak_active"); add("squeak(player)"); add("changemood(player,0)"); add("text(player,0,0,2)"); add("Ok, come on... Things"); add("aren't that bad."); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("I have a feeling that"); add("we're nearly home!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("We can't be too far"); add("from another teleporter!"); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("text(blue,0,0,1)"); add("I hope you're right, captain..."); add("position(blue,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1blue_7") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("text(blue,0,0,2"); add("Captain! You were right!"); add("It's a teleporter!"); add("position(blue,above)"); add("speak_active"); add("squeak(player)"); add("changemood(player,0)"); add("text(player,0,0,3)"); add("Phew! You had me worried for a"); add("while there... I thought we"); add("were never going to find one."); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(blue,1)"); add("text(blue,0,0,1"); add("What? Really?"); add("position(blue,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("Anyway, let's go"); add("back to the ship."); add("position(player,above)"); add("speak_active"); add("changemood(blue,0)"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1green_1") { add("delay(45)"); add("squeak(green)"); add("text(green,0,0,1)"); add("Huh? This isn't the ship..."); add("position(green,above)"); add("speak_active"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,1)"); add("Captain! What's going on?"); add("position(green,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1"); add("text(player,0,0,1)"); add("I... I don't know!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Where are we?"); add("position(player,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,3)"); add("Uh oh, this isn't good..."); add("Something must have gone"); add("wrong with the teleporter!"); add("position(green,above)"); add("speak_active"); add("squeak(player)"); add("changemood(player,0"); add("text(player,0,0,1)"); add("Ok... no need to panic!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("changemood(player,0"); add("text(player,0,0,1)"); add("Let's look for another teleporter!"); add("There's bound to be one around"); add("here somewhere!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("telesave()"); add("endcutscene()"); add("untilbars()"); add("gamestate(14)"); } else if(t == "int1green_2") { add("cutscene()"); add("untilbars()"); add("squeak(player)"); add("text(player,0,0,1)"); add("Let's go this way!"); add("position(player,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,1)"); add("After you, Captain!"); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("gamestate(11)"); } else if(t == "int1green_3") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,2)"); add("So Violet's back on the"); add("ship? She's really ok?"); add("position(green,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("She's fine! She helped"); add("me find my way back!"); add("position(player,below)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,1)"); add("Oh, phew! I was worried about her."); add("position(green,above)"); add("speak_active"); add("endtext"); add("delay(45)"); add("squeak(green)"); add("text(green,0,0,1)"); add("Captain, I have a secret..."); add("position(green,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(green,1)"); add("text(green,0,0,1)"); add("I really like Violet!"); add("position(green,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Is that so?"); add("position(player,below)"); add("speak_active"); add("squeak(green)"); add("changemood(green,0)"); add("text(green,0,0,2)"); add("Please promise you"); add("won't tell her!"); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1green_4") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,1)"); add("Hey again!"); add("position(green,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Hey!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Are you doing ok?"); add("position(player,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,3)"); add("I think so! I really"); add("hope we can find a way"); add("back to the ship..."); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1green_5") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,1)"); add("So, about Violet..."); add("position(green,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Um, yeah?"); add("position(player,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,1)"); add("Do you have any advice?"); add("position(green,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Oh!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("delay(45)"); add("squeak(player)"); add("text(player,0,0,1)"); add("Hmm..."); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Um... you should... be yourself!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("delay(15)"); add("squeak(green)"); add("text(green,0,0,1)"); add("Oh."); add("position(green,above)"); add("speak_active"); add("endtext"); add("delay(75)"); add("squeak(green)"); add("text(green,0,0,1)"); add("Thanks Captain!"); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1green_6") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(player)"); add("text(player,0,0,2)"); add("So, do you think you'll"); add("be able to fix the ship?"); add("position(player,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,2)"); add("Depends on how bad it "); add("is... I think so, though!"); add("position(green,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,5)"); add("It's not very hard, really. The"); add("basic dimensional warping engine"); add("design is pretty simple, and if we"); add("can get that working we shouldn't"); add("have any trouble getting home."); add("position(green,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Oh! Good!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1green_7") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,1)"); add("Finally! A teleporter!"); add("position(green,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,2)"); add("I was getting worried"); add("we wouldn't find one..."); add("position(green,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Let's head back to the ship!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1red_1") { add("cutscene()"); add("untilbars()"); add("squeak(red)"); add("text(red,0,0,1)"); add("Wow! Where are we?"); add("position(red,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,3)"); add("This... isn't right..."); add("Something must have gone"); add("wrong with the teleporter!"); add("position(player,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,3)"); add("Oh well... We can work"); add("it out when we get"); add("back to the ship!"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,1)"); add("Let's go exploring!"); add("position(red,above)"); add("speak_active"); add("squeak(player)"); add("changemood(player,0)"); add("text(player,0,0,1)"); add("Ok then!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("telesave()"); add("endcutscene()"); add("untilbars()"); add("gamestate(14)"); } else if(t == "int1red_2") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(player)"); add("text(player,0,0,1)"); add("Follow me!"); add("position(player,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,1)"); add("Aye aye, Captain!"); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("gamestate(11)"); } else if(t == "int1red_3") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,2)"); add("Hey Viridian... how did"); add("the crash happen, exactly?"); add("position(red,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("Oh, I don't really know -"); add("some sort of interference..."); add("position(player,below)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("...or something sciencey like"); add("that. It's not really my area."); add("position(player,below)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,3)"); add("Ah! Well, do you think"); add("we'll be able to fix"); add("the ship and go home?"); add("position(red,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Of course! Everything will be ok!"); add("position(player,below)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1red_4") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,1)"); add("Hi again! You doing ok?"); add("position(red,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("I think so! But I really want"); add("to get back to the ship..."); add("position(player,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,3)"); add("We'll be ok! If we can find"); add("a teleporter somewhere we"); add("should be able to get back!"); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1red_5") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,1)"); add("Are we there yet?"); add("position(red,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("We're getting closer, I think..."); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("I hope..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1red_6") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(player)"); add("text(player,0,0,1)"); add("I wonder where we are, anyway?"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,3)"); add("This seems different from"); add("that dimension we crashed"); add("in, somehow..."); add("position(player,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("I dunno... But we must be"); add("close to a teleporter by now..."); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1red_7") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(player)"); add("text(player,0,0,1)"); add("We're there!"); add("position(player,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("See? I told you! Let's"); add("get back to the ship!"); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1yellow_1") { add("cutscene()"); add("untilbars()"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("Oooh! This is interesting..."); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("Captain! Have you"); add("been here before?"); add("position(yellow,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("What? Where are we?"); add("position(player,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,3)"); add("I suspect something deflected"); add("our teleporter transmission!"); add("This is somewhere new..."); add("position(yellow,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("Oh no!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("changemood(player,0)"); add("text(player,0,0,3)"); add("We should try to find a"); add("teleporter and get back"); add("to the ship..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("telesave()"); add("endcutscene()"); add("untilbars()"); add("gamestate(14)"); } else if(t == "int1yellow_2") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(player)"); add("text(player,0,0,1)"); add("Follow me!"); add("position(player,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("Right behind you, Captain!"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("gamestate(11)"); } else if(t == "int1yellow_3") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(player)"); add("text(player,0,0,2)"); add("What do you make of"); add("all this, Professor?"); add("position(player,below)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,4)"); add("I'm guessing this dimension"); add("has something to do with the"); add("interference that caused"); add("us to crash!"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("Maybe we'll find the"); add("cause of it here?"); add("position(yellow,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Oh wow! Really?"); add("position(player,below)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,4)"); add("Well, it's just a guess."); add("I'll need to get back to"); add("the ship before I can do"); add("any real tests..."); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1yellow_4") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("Ohh! What was that?"); add("position(yellow,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("What was what?"); add("position(player,above)"); add("speak_active"); add("squeak(yellow)"); add("changedir(yellow,0)"); add("text(yellow,0,0,2)"); add("That big... C thing!"); add("I wonder what it does?"); add("position(yellow,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,2)"); add("Em... I don't really know"); add("how to answer that question..."); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("changemood(player,0)"); add("text(player,0,0,3)"); add("It's probably best not"); add("to acknowledge that"); add("it's there at all."); add("position(player,above)"); add("speak_active"); add("squeak(yellow)"); add("changedir(yellow,1)"); add("text(yellow,0,0,2)"); add("Maybe we should take it back"); add("to the ship to study it?"); add("position(yellow,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,3)"); add("We really shouldn't think"); add("about it too much... Let's"); add("keep moving!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1yellow_5") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,3)"); add("You know, there's"); add("something really odd"); add("about this dimension..."); add("position(yellow,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Yeah?"); add("position(player,above)"); add("speak_active"); add("squeak(yellow)"); add("changedir(yellow,0)"); add("text(yellow,0,0,3)"); add("We shouldn't really be able"); add("to move between dimensions"); add("with a regular teleporter..."); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("changedir(yellow,0)"); add("text(yellow,0,0,2)"); add("Maybe this isn't a proper"); add("dimension at all?"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("changedir(yellow,0)"); add("text(yellow,0,0,4)"); add("Maybe it's some kind of"); add("polar dimension? Something"); add("artificially created for"); add("some reason?"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("changedir(yellow,1)"); add("text(yellow,0,0,2)"); add("I can't wait to get back to the"); add("ship. I have a lot of tests to run!"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1yellow_6") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,3)"); add("I wonder if there's anything"); add("else in this dimension"); add("worth exploring?"); add("position(yellow,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,3)"); add("Maybe... but we should probably"); add("just focus on finding the rest"); add("of the crew for now..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "int1yellow_7") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("At last!"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("Let's go back to the ship!"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); } else if(t == "skipint2") { add("finalmode(53,49)"); add("gotoposition(228,129,0)"); add("changedir(player,1)"); add("setcheckpoint()"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("showplayer()"); add("play(8)"); add("hascontrol()"); add("befadein()"); } else if(t == "intermission_2") { add("ifskip(skipint2)"); add("finalmode(53,49)"); add("gotoposition(228,129,0)"); add("changedir(player,1)"); add("setcheckpoint()"); add("cutscene()"); add("delay(15)"); add("flash(5)"); add("shake(20)"); add("playef(9,10)"); add("delay(35)"); add("flash(5)"); add("shake(20)"); add("playef(9,10)"); add("delay(25)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("showplayer()"); add("play(8)"); add("befadein()"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("Uh oh..."); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("Not again!"); add("position(player,above)"); add("speak_active"); add("iflast(2,int2intro_yellow)"); add("iflast(3,int2intro_red)"); add("iflast(4,int2intro_green)"); add("iflast(5,int2intro_blue)"); } else if(t == "int2intro_yellow") { add("squeak(cry)"); add("text(player,0,0,1)"); add("Vitellary? Where are you?"); add("position(player,above)"); add("speak_active"); add("endtext"); add("delay(15)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("delay(15)"); add("changedir(player,0)"); add("createcrewman(150,-20,yellow,1,17,1)"); add("squeak(cry)"); add("text(yellow,170,50,1)"); add("Captain!"); add("speak_active"); add("endtext"); add("delay(15)"); add("squeak(player)"); add("changemood(player,0)"); add("text(player,0,0,1)"); add("Hang on! I'll save you!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("telesave()"); add("endcutscene()"); add("untilbars()"); } else if(t == "int2intro_red") { add("squeak(cry)"); add("text(player,0,0,1)"); add("Vermilion? Where are you?"); add("position(player,above)"); add("speak_active"); add("endtext"); add("delay(15)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("delay(15)"); add("changedir(player,0)"); add("createcrewman(150,-20,red,0,17,1)"); add("squeak(red)"); add("text(red,170,50,1)"); add("Wheeeee!"); add("speak_active"); add("endtext"); add("delay(15)"); add("squeak(player)"); add("changemood(player,0)"); add("text(player,0,0,1)"); add("Hang on! I'll save you!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("telesave()"); add("endcutscene()"); add("untilbars()"); } else if(t == "int2intro_green") { add("squeak(cry)"); add("text(player,0,0,1)"); add("Verdigris? Where are you?"); add("position(player,above)"); add("speak_active"); add("endtext"); add("delay(15)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("delay(15)"); add("changedir(player,0)"); add("createcrewman(150,-20,green,1,17,1)"); add("squeak(cry)"); add("text(green,170,50,1)"); add("Aaagghh!"); add("speak_active"); add("endtext"); add("delay(15)"); add("squeak(player)"); add("changemood(player,0)"); add("text(player,0,0,1)"); add("Hang on! I'll save you!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("telesave()"); add("endcutscene()"); add("untilbars()"); } else if(t == "int2intro_blue") { add("squeak(cry)"); add("text(player,0,0,1)"); add("Victoria? Where are you?"); add("position(player,above)"); add("speak_active"); add("endtext"); add("delay(15)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("delay(15)"); add("changedir(player,0)"); add("createcrewman(150,-20,blue,1,17,1)"); add("squeak(cry)"); add("text(blue,170,50,1)"); add("Help!"); add("speak_active"); add("endtext"); add("delay(15)"); add("squeak(player)"); add("changemood(player,0)"); add("text(player,0,0,1)"); add("Hang on! I'll save you!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("telesave()"); add("endcutscene()"); add("untilbars()"); } else if(t == "int2_yellow") { add("ifskip(skipint2yellow)"); add("cutscene()"); add("tofloor()"); add("changeai(yellow,followplayer)"); add("untilbars()"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("That was interesting, wasn't it?"); add("position(yellow,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("I feel dizzy..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("changemood(player,0)"); add("endcutscene()"); add("untilbars()"); add("companion(10)"); } else if(t == "skipint2yellow") { add("squeak(yellow)"); add("companion(10)"); } else if(t == "int2_red") { add("ifskip(skipint2red)"); add("cutscene()"); add("tofloor()"); add("changeai(red,followplayer)"); add("untilbars()"); add("squeak(red)"); add("text(red,0,0,1)"); add("Again! Let's go again!"); add("position(red,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("I feel dizzy..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("changemood(player,0)"); add("endcutscene()"); add("untilbars()"); add("companion(10)"); } else if(t == "skipint2red") { add("squeak(red)"); add("companion(10)"); } else if(t == "int2_green") { add("ifskip(skipint2green)"); add("cutscene()"); add("tofloor()"); add("changeai(green,followplayer)"); add("untilbars()"); add("squeak(green)"); add("text(green,0,0,1)"); add("Phew! You're ok!"); add("position(green,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("I feel dizzy..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("changemood(player,0)"); add("endcutscene()"); add("untilbars()"); add("companion(10)"); } else if(t == "skipint2green") { add("squeak(green)"); add("companion(10)"); } else if(t == "int2_blue") { add("ifskip(skipint2blue)"); add("cutscene()"); add("tofloor()"); add("changeai(blue,followplayer)"); add("untilbars()"); add("squeak(cry)"); add("text(blue,0,0,1)"); add("I think I'm going to be sick..."); add("position(blue,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("I feel dizzy..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("changemood(player,0)"); add("changemood(blue,0)"); add("endcutscene()"); add("untilbars()"); add("companion(10)"); } else if(t == "skipint2blue") { add("squeak(blue)"); add("companion(10)"); } else if(t == "startexpolevel_station2") { //For the Eurogamer EXPO! Scrap later. add("fadeout()"); add("musicfadeout()"); add("untilfade()"); add("delay(30)"); add("resetgame"); add("gotoroom(12,14)"); add("gotoposition(126,38,1)"); add("setcheckpoint()"); add("changedir(player,0)"); add("fadein()"); add("stopmusic()"); add("play(1)"); } else if(t == "finallevel_teleporter") { add("delay(10)"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("Welcome back!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("delay(30)"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("..."); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("Um, where's Captain Viridian?"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("delay(30)"); add("walk(left,3)"); add("delay(60)"); add("everybodysad()"); add("squeak(cry)"); add("delay(30)"); add("fadeout()"); add("untilfade()"); add("changemood(player,0)"); add("musicfadeout()"); add("finalmode(46,54)"); add("gotoposition(101,113,0)"); add("setcheckpoint()"); add("changedir(player,1)"); add("restoreplayercolour"); add("fadein()"); add("untilfade()"); add("delay(15)"); add("squeak(player)"); add("text(player,0,0,1)"); add("... Hello?"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Is anyone there?"); add("position(player,above)"); add("speak_active"); add("endtext"); add("missing(player)"); //add("squeak(cry)"); //add("changemood(player,1)"); add("endcutscene()"); add("untilbars()"); add("play(15)"); add("telesave()"); } else if(t == "skipfinal") { add("finalmode(46,54)"); add("gotoposition(101,113,0)"); add("setcheckpoint()"); add("changedir(player,1)"); add("restoreplayercolour"); add("showplayer()"); add("hascontrol()"); add("missing(player)"); add("play(15)"); add("fadein()"); add("untilfade()"); } else if(t == "startlevel_final") { add("ifskip(skipfinal)"); add("cutscene()"); add("untilbars()"); add("activeteleporter()"); add("stopmusic()"); add("play(5)"); add("gotoroom(2,11)"); add("gotoposition(160,120,0)"); add("createcrewman(190,153,purple,0,faceleft)"); add("createrescuedcrew()"); add("fadein()"); add("untilfade()"); add("gamestate(4070)"); } else if(t == "regularreturn") { add("cutscene()"); add("untilbars()"); add("activeteleporter()"); add("stopmusic()"); add("play(4)"); add("gotoroom(2,11)"); add("gotoposition(160,120,0)"); add("createlastrescued()"); add("fadein()"); add("untilfade()"); add("endcutscene()"); add("setcheckpoint()"); add("gamestate(4010)"); } else if(t == "returntohub") { //For the Eurogamer EXPO! Scrap later. add("fadeout()"); add("musicfadeout()"); add("untilfade()"); add("delay(30)"); add("resetgame"); add("gotoroom(7,8)"); add("gotoposition(145,145,0)"); add("setcheckpoint()"); add("changedir(player,0)"); add("fadein()"); add("stopmusic()"); add("play(4)"); } else if(t == "resetgame") { //For the Eurogamer EXPO! Scrap later. add("resetgame"); add("gotoroom(4,6)"); add("fadein()"); } else if(t == "talkred") { add("redcontrol"); } else if(t == "talkyellow") { add("yellowcontrol"); } else if(t == "talkgreen") { add("greencontrol"); } else if(t == "talkblue") { add("bluecontrol"); } else if(t == "talkpurple") { add("purplecontrol"); } else if(t == "talkred_1") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,1)"); add("Don't worry, Sir!"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("We'll find a way"); add("out of here!"); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_2") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,1)"); add("I hope Victoria is ok..."); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("She doesn't handle"); add("surprises very well..."); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_3") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,3)"); add("I don't know how we're"); add("going to get this ship"); add("working again!"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("Chief Verdigris would"); add("know what to do..."); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_4") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,2)"); add("I wonder what caused"); add("the ship to crash here?"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,3)"); add("It's the shame the Professor"); add("isn't here, huh? I'm sure he"); add("could work it out!"); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_5") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,1)"); add("It's great to be back!"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("I can't wait to help you"); add("find the rest of the crew!"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("It'll be like old"); add("times, huh, Captain?"); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_6") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,2)"); add("It's good to have"); add("Victoria back with us."); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("She really seems happy to"); add("get back to work in her lab!"); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_7") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,3)"); add("I think I saw Verdigris"); add("working on the outside"); add("of the ship!"); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_8") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,2)"); add("You found Professor"); add("Vitellary! All right!"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("We'll have this interference"); add("thing worked out in no time now!"); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_9") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,2)"); add("That other dimension was"); add("really strange, wasn't it?"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("I wonder what caused the"); add("teleporter to send us there?"); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_10") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,1)"); add("Heya Captain!"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("This way looks a little"); add("dangerous..."); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_11") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,1)"); add("I'm helping!"); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_12") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,1)"); add("Hey Captain!"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,3)"); add("I found something interesting"); add("around here - the same warp"); add("signature I saw when I landed!"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("Someone from the ship"); add("must be nearby..."); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_13") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,2)"); add("This dimension is pretty"); add("exciting, isn't it?"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,1)"); add("I wonder what we'll find?"); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkred_14") { add("cutscene()"); add("untilbars()"); add("face(player,red)"); add("face(red,player)"); add("squeak(red)"); add("text(red,0,0,1)"); add("Look what I found!"); add("position(red,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("It's pretty hard, I can only"); add("last for about 10 seconds..."); add("position(red,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(red)"); } else if(t == "talkyellow_1") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("I'm making some fascinating"); add("discoveries, captain!"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkyellow_2") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,3)"); add("This isn't like any"); add("other dimension we've"); add("been to, Captain."); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("There's something strange"); add("about this place..."); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkyellow_3") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,3)"); add("Captain, have you noticed"); add("that this dimension seems"); add("to wrap around?"); add("position(yellow,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Yeah, it's strange..."); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(yellow,1)"); add("text(yellow,0,0,3)"); add("It looks like this dimension"); add("is having the same stability"); add("problems as our own!"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("I hope we're not the"); add("ones causing it..."); add("position(yellow,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("What? Do you think we might be?"); add("position(player,above)"); add("speak_active"); add("squeak(yellow)"); add("changemood(yellow,0)"); add("changemood(player,0)"); add("text(yellow,0,0,2)"); add("No no... that's very"); add("unlikely, really..."); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkyellow_4") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,4)"); add("My guess is that whoever used"); add("to live here was experimenting"); add("with ways to stop the dimension"); add("from collapsing."); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("It would explain why they've"); add("wrapped the edges..."); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("Hey, maybe that's what's"); add("causing the interference?"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkyellow_5") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("I wonder where the people who"); add("used to live here have gone?"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkyellow_6") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,3)"); add("I think it's no coincidence"); add("that the teleporter was drawn"); add("to that dimension..."); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,4)"); add("There's something there. I"); add("think it might be causing the"); add("interference that's stopping"); add("us from leaving..."); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkyellow_7") { //Vertigris is back add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("I'm glad Verdigris is alright."); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,3)"); add("It'll be a lot easier to find"); add("some way out of here now that"); add("we can get the ship working again!"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkyellow_8") { //Victoria is back add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("Ah, you've found Doctor"); add("Victoria? Excellent!"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("I have lots of questions for her!"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkyellow_9") { //Vermilion is back add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,3)"); add("Vermilion says that he"); add("was trapped in some"); add("sort of tunnel?"); add("position(yellow,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("Yeah, it just seemed to"); add("keep going and going..."); add("position(player,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("Interesting... I wonder"); add("why it was built?"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkyellow_10") { //Back on the ship! add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("It's good to be back!"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("I've got so much work"); add("to catch up on..."); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkyellow_11") { //Game Complete add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,3)"); add("I know it's probably a little"); add("dangerous to stay here now that"); add("this dimension is collapsing..."); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("...but it's so rare to find"); add("somewhere this interesting!"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("Maybe we'll find the answers"); add("to our own problems here?"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkyellow_12") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("Captain! Have you seen this?"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,3)"); add("With their research and ours,"); add("we should be able to stabilise"); add("our own dimension!"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("We're saved!"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkgreen_1") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,1)"); add("I'm an engineer!"); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(green)"); } else if(t == "talkgreen_2") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,3)"); add("I think I can get this ship"); add("moving again, but it's going"); add("to take a while..."); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(green)"); } else if(t == "talkgreen_2") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,3)"); add("I think I can get this ship"); add("moving again, but it's going"); add("to take a while..."); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(green)"); } else if(t == "talkgreen_3") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,3)"); add("Victoria mentioned something"); add("about a lab? I wonder if she"); add("found anything down there?"); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(green)"); } else if(t == "talkgreen_4") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,1)"); add("Vermilion's back! Yey!"); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(green)"); } else if(t == "talkgreen_5") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,3)"); add("The Professor had lots of"); add("questions about this"); add("dimension for me..."); add("position(green,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,2)"); add("We still don't really know"); add("that much, though."); add("position(green,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,3)"); add("Until we work out what's"); add("causing that interference,"); add("we can't go anywhere."); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(green)"); } else if(t == "talkgreen_6") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,2)"); add("I'm so glad that"); add("Violet's alright!"); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(green)"); } else if(t == "talkgreen_7") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,3)"); add("That other dimension we ended"); add("up in must be related to this"); add("one, somehow..."); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(green)"); } else if(t == "talkgreen_8") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(cry)"); add("text(green,0,0,3)"); add("The antenna's broken!"); add("This is going to be"); add("very hard to fix..."); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(green)"); } else if(t == "talkgreen_9") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,2)"); add("It looks like we were warped"); add("into solid rock when we crashed!"); add("position(green,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,2)"); add("Hmm. It's going to be hard"); add("to separate from this..."); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(green)"); } else if(t == "talkgreen_10") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,2)"); add("The ship's all fixed up. We"); add("can leave at a moment's notice!"); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(green)"); } else if(t == "talkgreen_11") { add("cutscene()"); add("untilbars()"); add("face(player,green)"); add("face(green,player)"); add("squeak(green)"); add("text(green,0,0,3)"); add("I wonder why they abandoned this"); add("dimension? They were so close to"); add("working out how to fix it..."); add("position(green,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,2)"); add("Maybe we can fix it for them?"); add("Maybe they'll come back?"); add("position(green,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(green)"); } if(t == "talkpurple_1") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(cry)"); add("changemood(purple,1)"); add("text(purple,0,0,1)"); add("... I hope Verdigris is alright."); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("changemood(purple,0)"); add("text(purple,0,0,2)"); add("If you can find him, he'd be a"); add("a big help fixing the ship!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkpurple_2") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("Chief Verdigris is so brave"); add("and ever so smart!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkpurple_3") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("Are you doing ok, Captain?"); add("position(purple,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,0)"); add("specialline(1)"); add("position(player,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("Oh - well, don't worry,"); add("they'll show up!"); add("position(purple,above)"); add("speak_active"); add("changemood(player,0)"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("Here! Have a lollipop!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkpurple_4") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("Welcome back, Captain!"); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("I think Victoria is quite happy"); add("to be back on the ship."); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("She really doesn't like adventuring."); add("She gets very homesick!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkpurple_5") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("Vermilion called in"); add("to say hello!"); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("He's really looking forward"); add("specialline(2)"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkpurple_6") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("Captain! You found Verdigris!"); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("Thank you so much!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkpurple_7") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("I'm glad Professor"); add("Vitellary is ok!"); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("He had lots of questions"); add("for me about this dimension."); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("He's already gotten to"); add("work with his research!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkpurple_8") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(purple)"); add("text(purple,0,0,4)"); add("Hey Captain! Now that you've turned"); add("off the source of the interference,"); add("we can warp everyone back to the"); add("ship instantly, if we need to!"); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,3)"); add("Any time you want to come back"); add("to the ship, just select the"); add("new SHIP option in your menu!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkpurple_9") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(purple)"); add("text(purple,0,0,3)"); add("Look at all this research!"); add("This is going to be a big"); add("help back home!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkpurple_intermission1") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(player)"); add("text(player,0,0,3)"); add("Doctor, something strange"); add("happened when we teleported"); add("back to the ship..."); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("We got lost in another dimension!"); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(purple,1)"); add("text(purple,0,0,1)"); add("Oh no!"); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("changemood(purple,0)"); add("changemood(player,0)"); add("text(purple,0,0,3)"); add("Maybe that dimension has something"); add("to do with the interference that"); add("caused us to crash here?"); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("I'll look into it..."); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkpurple_intermission2") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("Doctor! Doctor! It happened again!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("The teleporter brought us"); add("to that weird dimension..."); add("position(player,above)"); add("speak_active"); add("squeak(purple)"); add("changemood(player,0)"); add("changemood(purple,0)"); add("text(purple,0,0,2)"); add("Hmm, there's definitely"); add("something strange happening..."); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("If only we could find the"); add("source of that interference!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkpurple_intermission3") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(player)"); add("text(player,0,0,3)"); add("Doctor, something strange has"); add("been happening when we teleport"); add("back to the ship..."); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,2)"); add("We keep getting brought to"); add("another weird dimension!"); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(purple,1)"); add("text(purple,0,0,1)"); add("Oh no!"); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("changemood(purple,0)"); add("changemood(player,0)"); add("text(purple,0,0,3)"); add("Maybe that dimension has something"); add("to do with the interference that"); add("caused us to crash here?"); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("changemood(player,0)"); add("changemood(purple,0)"); add("text(purple,0,0,2)"); add("Hmm, there's definitely"); add("something strange happening..."); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("If only we could find the"); add("source of that interference!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkpurple_intro") { add("cutscene()"); add("untilbars()"); add("face(player,purple)"); add("face(purple,player)"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,2)"); add("I'm feeling a bit"); add("overwhelmed, Doctor."); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Where do I begin?"); add("position(player,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("Remember that you can press ENTER"); add("to check where you are on the map!"); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("Look for areas where the rest"); add("of the crew might be..."); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("If you get lost, you can get back"); add("to the ship from any teleporter."); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("And don't worry!"); add("We'll find everyone!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("delay(30)"); add("changemood(player,0)"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("Everything will be ok!"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(purple)"); } else if(t == "talkblue_1") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,1)"); add("Any signs of Professor Vitellary?"); add("position(blue,below)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Sorry, not yet..."); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("changetile(blue,150)"); //upside down frown :( add("text(blue,0,0,1)"); add("I hope he's ok..."); add("position(blue,below)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(blue)"); } else if(t == "talkblue_2") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,2)"); add("Thanks so much for"); add("saving me, Captain!"); add("position(blue,below)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(blue)"); } else if(t == "talkblue_3") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,1)"); add("I'm so glad to be back!"); add("position(blue,below)"); add("speak_active"); add("squeak(cry)"); add("changetile(blue,150)"); //upside down frown :( add("text(blue,0,0,3)"); add("That lab was so dark"); add("and scary! I didn't"); add("like it at all..."); add("position(blue,below)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(blue)"); } else if(t == "talkblue_4") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,2)"); add("Vitellary's back? I"); add("knew you'd find him!"); add("position(blue,below)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,2)"); add("I mean, I admit I was very"); add("worried that you wouldn't..."); add("position(blue,below)"); add("speak_active"); add("squeak(cry)"); add("changetile(blue,150)"); //upside down frown :( add("text(blue,0,0,2)"); add("or that something might"); add("have happened to him..."); add("position(blue,below)"); add("speak_active"); add("squeak(blue)"); add("text(blue,0,0,1)"); add("sniff..."); add("position(blue,below)"); add("speak_active"); add("endtext"); add("delay(30)"); add("squeak(player)"); add("text(player,0,0,1)"); add("Doctor Victoria? He's ok!"); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("changetile(blue,150)"); //upside down frown :( add("text(blue,0,0,3)"); add("Oh! Sorry! I was just"); add("thinking about what"); add("if he wasn't?"); add("position(blue,below)"); add("speak_active"); add("endtext"); add("delay(30)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,1)"); add("Thank you, Captain!"); add("position(blue,below)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(blue)"); } else if(t == "talkblue_5") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,1)"); add("You found Vermilion! Great!"); add("position(blue,below)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,2)"); add("I wish he wasn't"); add("so reckless!"); add("position(blue,below)"); add("speak_active"); add("squeak(cry)"); add("changetile(blue,150)"); //upside down frown :( add("text(blue,0,0,2)"); add("He'll get himself"); add("into trouble..."); add("position(blue,below)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(blue)"); } else if(t == "talkblue_6") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,2)"); add("Verdigris is ok! Violet"); add("will be so happy!"); add("position(blue,below)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,1)"); add("I'm happy!"); add("position(blue,below)"); add("speak_active"); add("endtext"); add("delay(30)"); add("squeak(cry)"); add("changetile(blue,150)"); //upside down frown :( add("text(blue,0,0,1)"); add("Though I was very worried..."); add("position(blue,below)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(blue)"); } else if(t == "talkblue_7") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(cry)"); add("changetile(blue,150)"); //upside down frown :( add("text(blue,0,0,2)"); add("Why did the teleporter send"); add("us to that scary dimension?"); add("position(blue,below)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,150)"); //upside down frown :( add("text(blue,0,0,1)"); add("What happened?"); add("position(blue,below)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("I don't know, Doctor..."); add("position(player,above)"); add("speak_active"); add("squeak(cry)"); add("changetile(blue,150)"); //upside down frown :( add("text(blue,0,0,1)"); add("Why?"); add("position(blue,below)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(blue)"); } else if(t == "talkblue_8") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,1)"); add("Heya Captain!"); add("position(blue,below)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,3)"); add("Are you going to try"); add("and find the rest of"); add("these shiny things?"); add("position(blue,below)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(blue)"); } else if(t == "talkblue_9") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("text(blue,0,0,3)"); add("This lab is amazing! The scentists"); add("who worked here know a lot more"); add("about warp technology than we do!"); add("position(blue,below)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(blue)"); } else if(t == "talkblue_trinket1") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,2)"); add("Hey Captain, I found"); add("this in that lab..."); add("position(blue,below)"); add("speak_active"); add("endtext"); add("delay(30)"); //found a trinket! add("foundtrinket(18)"); add("endtext"); //add("musicfadein"); add("trinketscriptmusic"); add("delay(30)"); add("createentity(136,80,22,18,0)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,1)"); add("Any idea what it does?"); add("position(blue,below)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Sorry, I don't know!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("They seem important, though..."); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("Maybe something will happen"); add("if we find them all?"); add("position(player,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(blue)"); } else if(t == "talkblue_trinket2") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,3)"); add("Captain! Come have a"); add("look at what I've"); add("been working on!"); add("position(blue,below)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,3)"); add("It looks like these shiny"); add("things are giving off a"); add("strange energy reading!"); add("position(blue,below)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,1)"); add("So I analysed it..."); add("position(blue,below)"); add("speak_active"); add("trinketbluecontrol()"); } else if(t == "talkblue_trinket3") { //If you missed the first conversation add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,3)"); add("Captain! Come have a"); add("look at what I've"); add("been working on!"); add("position(blue,below)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,1)"); add("I found this in that lab..."); add("position(blue,below)"); add("speak_active"); add("endtext"); add("delay(30)"); //found a trinket! add("foundtrinket(18)"); add("endtext"); //add("musicfadein"); add("trinketscriptmusic"); add("delay(30)"); add("createentity(136,80,22,18,0)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,3)"); add("It seemed to be"); add("giving off a weird"); add("energy reading..."); add("position(blue,below)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,1)"); add("So I analysed it..."); add("position(blue,below)"); add("speak_active"); add("trinketbluecontrol()"); } else if(t == "talkblue_trinket4") { add("hidetrinkets()"); add("endtextfast"); add("delay(10)"); //add map mode here and wrap up... add("gamemode(teleporter)"); add("delay(20)"); add("squeak(blue)"); add("text(blue,50,15,2)"); add("...and I was able to find more"); add("of them with the ship's scanner!"); add("speak_active"); add("endtext"); add("squeak(terminal)"); add("showtrinkets()"); add("delay(10)"); add("hidetrinkets()"); add("delay(10)"); add("showtrinkets()"); add("delay(10)"); add("hidetrinkets()"); add("delay(10)"); add("showtrinkets()"); add("delay(75)"); add("gamemode(game)"); add("delay(20)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,3)"); add("If you get a chance, it"); add("might be worth finding"); add("the rest of them!"); add("position(blue,below)"); add("speak_active"); add("squeak(cry)"); add("changetile(blue,150)"); //upside down frown :( add("text(blue,0,0,2)"); add("Don't put yourself in"); add("any danger, though!"); add("position(blue,below)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(blue)"); } else if(t == "talkblue_trinket5") { add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,3)"); add("...but it looks like you've"); add("already found all of them"); add("in this dimension!"); add("position(blue,below)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Oh? Really?"); add("position(player,above)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,2)"); add("Yeah, well done! That"); add("can't have been easy!"); add("position(blue,below)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(blue)"); } else if(t == "talkblue_trinket6") { add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,3)"); add("...and they're related."); add("They're all a part of"); add("something bigger!"); add("position(blue,below)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Oh? Really?"); add("position(player,above)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,4)"); add("Yeah! There seem to be"); add("twenty variations of"); add("the fundamental energy"); add("signature..."); add("position(blue,below)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,1)"); add("Wait..."); add("position(blue,below)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,2)"); add("Does that mean you've"); add("found all of them?"); add("position(blue,below)"); add("speak_active"); add("endtext"); add("loadscript(startepilogue)"); } else if(t == "talkyellow_trinket1") { add("cutscene()"); add("untilbars()"); add("face(player,yellow)"); add("face(yellow,player)"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("Captain! I've been meaning"); add("to give this to you..."); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("delay(30)"); //found a trinket! add("foundtrinket(18)"); add("endtext"); //add("musicfadein"); add("trinketscriptmusic"); add("delay(30)"); add("squeak(player)"); add("text(player,0,0,1)"); add("Professor! Where did you find this?"); add("position(player,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("Oh, it was just lying"); add("around that space station."); add("position(yellow,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(yellow,1)"); add("text(yellow,0,0,3)"); add("It's a pity Doctor Victoria"); add("isn't here, she loves studying"); add("that sort of thing..."); add("position(yellow,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Any idea what it does?"); add("position(player,above)"); add("speak_active"); add("squeak(yellow)"); add("changemood(yellow,0)"); add("text(yellow,0,0,2)"); add("Nope! But it is giving off"); add("a strange energy reading..."); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("trinketyellowcontrol()"); } else if(t == "talkyellow_trinket2") { add("hidetrinkets()"); add("endtextfast"); add("delay(10)"); //add map mode here and wrap up... add("gamemode(teleporter)"); add("delay(20)"); add("squeak(yellow)"); add("text(yellow,50,15,2)"); add("...so I used the ship's scanner"); add("to find more of them!"); add("speak_active"); add("endtext"); add("squeak(terminal)"); add("showtrinkets()"); add("delay(10)"); add("hidetrinkets()"); add("delay(10)"); add("showtrinkets()"); add("delay(10)"); add("hidetrinkets()"); add("delay(10)"); add("showtrinkets()"); add("delay(75)"); add("gamemode(game)"); add("delay(20)"); add("squeak(yellow)"); add("changemood(yellow,0)"); add("text(yellow,0,0,3)"); add("...Please don't let them"); add("distract you from finding"); add("Victoria, though!"); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("I hope she's ok..."); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "talkyellow_trinket3") { add("squeak(yellow)"); add("changemood(yellow,0)"); add("text(yellow,0,0,2)"); add("Can't seem to detect any"); add("more of them nearby, though."); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("changemood(yellow,0)"); add("text(yellow,0,0,1)"); add("Maybe you've found them all?"); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("endcutscene()"); add("untilbars()"); add("createactivityzone(yellow)"); } else if(t == "gamecomplete") { add("gotoroom(2,11)"); add("gotoposition(160,120,0)"); add("nocontrol()"); add("createcrewman(185,153,purple,0,faceleft)"); add("createcrewman(205,153,yellow,0,faceleft)"); add("createcrewman(225,153,red,0,faceleft)"); add("createcrewman(245,153,green,0,faceleft)"); add("createcrewman(265,153,blue,1,faceleft)"); add("cutscene()"); add("untilbars()"); add("delay(30)"); add("rescued(player)"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("Any moment now..."); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("nocontrol()"); add("delay(60)"); add("gamestate(4080)"); } else if(t == "gamecomplete_ending") { add("delay(15)"); add("changemood(blue,0)"); add("play(10)"); add("delay(45)"); add("squeak(player)"); add("text(player,0,0,1)"); add("Hello!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("squeak(purple)"); add("delay(1)"); add("squeak(yellow)"); add("delay(1)"); add("squeak(red)"); add("delay(1)"); add("squeak(green)"); add("text(purple,0,0,1)"); add("Captain! "); add("position(purple,above)"); add("backgroundtext"); add("speak"); add("text(yellow,0,0,1)"); add("Captain! "); add("position(yellow,above)"); add("backgroundtext"); add("speak"); add("text(red,0,0,1)"); add("Captain! "); add("position(red,above)"); add("backgroundtext"); add("speak"); add("text(green,0,0,1)"); add("Captain! "); add("position(green,above)"); add("backgroundtext"); add("speak"); add("text(blue,0,0,1)"); add("Captain!"); add("position(blue,above)"); add("speak"); add("endtextfast"); add("squeak(blue)"); add("text(blue,0,0,1)"); add("You're alright!"); add("position(blue,above)"); add("speak_active"); add("squeak(blue)"); add("text(blue,0,0,1)"); add("I knew you'd be ok!"); add("position(blue,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("We were very worried when"); add("you didn't come back..."); add("position(purple,above)"); add("speak_active"); add("squeak(green)"); add("text(green,0,0,3)"); add("...but when you turned"); add("off the source of"); add("the interference..."); add("position(green,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,3)"); add("...we were able to"); add("find you with the"); add("ship's scanners..."); add("position(yellow,above)"); add("speak_active"); add("squeak(red)"); add("text(red,0,0,2)"); add("...and teleport you"); add("back on board!"); add("position(red,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("That was lucky!"); add("Thanks guys!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Thanks guys!"); add("position(player,above)"); add("speak_active"); add("endtext"); //Move to Vitellary's lab add("fadeout()"); add("untilfade()"); add("missing(purple)"); add("missing(red)"); add("missing(green)"); add("missing(blue)"); add("missing(yellow)"); add("gotoroom(3,11)"); add("gotoposition(117,105,0)"); add("changedir(player,0)"); add("createcrewman(75,105,yellow,0,faceright)"); add("createcrewman(190,105,red,0,faceleft)"); add("fadein()"); add("untilfade()"); add("squeak(yellow)"); add("text(yellow,0,0,4)"); add("...it looks like this"); add("dimension is starting"); add("to destabilise, just"); add("like our own..."); add("position(yellow,above)"); add("speak_active"); add("walk(right,3)"); add("squeak(red)"); add("text(red,0,0,3)"); add("...we can stay and"); add("explore for a little"); add("longer, but..."); add("position(red,above)"); add("speak_active"); add("walk(left,3)"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("...eventually, it'll"); add("collapse completely."); add("position(yellow,above)"); add("speak_active"); add("endtext"); //Move to Vertigris' lab add("fadeout()"); add("untilfade()"); add("gotoroom(3,10)"); add("gotoposition(210,177,0)"); add("changedir(player,1)"); add("createcrewman(245,177,green,0,faceleft)"); add("createcrewman(56,177,blue,0,faceright)"); add("fadein()"); add("untilfade()"); add("squeak(green)"); add("text(green,0,0,3)"); add("There's no telling exactly"); add("how long we have here. But"); add("the ship's fixed, so..."); add("position(green,above)"); add("speak_active"); add("walk(left,3)"); add("squeak(blue)"); add("text(blue,0,0,2)"); add("...as soon as we're"); add("ready, we can go home!"); add("position(blue,above)"); add("speak_active"); add("endtext"); //Move to the bridge! add("fadeout()"); add("untilfade()"); add("gotoroom(4,10)"); add("gotoposition(227,113,0)"); add("changedir(player,0)"); add("createcrewman(140,177,purple,0,faceright)"); add("createcrewman(115,177,yellow,0,faceright)"); add("createcrewman(90,177,red,0,faceright)"); add("createcrewman(65,177,green,0,faceright)"); add("createcrewman(40,177,blue,0,faceright)"); add("rescued(purple)"); add("rescued(red)"); add("rescued(green)"); add("rescued(blue)"); add("rescued(yellow)"); add("fadein()"); add("untilfade()"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("What now, Captain?"); add("position(purple,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("Let's find a way to save"); add("this dimension!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("And a way to save our"); add("home dimension too!"); add("position(player,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("The answer is out there, somewhere!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("delay(30)"); add("squeak(player)"); add("text(player,0,0,1)"); add("Let's go!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("fadeout()"); add("untilfade()"); add("rollcredits()"); } else if(t == "startepilogue") { add("cutscene()"); add("untilbars()"); add("face(player,blue)"); add("face(blue,player)"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,1)"); add("Wow! You found all of them!"); add("position(blue,below)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,1)"); add("Really? Great!"); add("position(player,above)"); add("speak_active"); add("squeak(blue)"); add("changetile(blue,6)"); //smiling again! blue always needs to specify her mood add("text(blue,0,0,3)"); add("I'll run some tests and"); add("see if I can work out"); add("what they're for..."); add("position(blue,below)"); add("speak_active"); add("endtext"); add("flash(5)"); add("shake(20)"); add("playef(9,10)"); add("musicfadeout()"); add("delay(30)"); add("squeak(cry)"); add("changemood(player,1)"); add("changetile(blue,150)"); //upside down frown :( add("text(player,0,0,2)"); add("That... that didn't"); add("sound good..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("delay(30)"); add("flash(5)"); add("shake(20)"); add("playef(9,10)"); add("alarmon"); add("delay(30)"); add("squeak(cry)"); add("text(blue,0,0,1)"); add("Run!"); add("position(blue,below)"); add("speak_active"); add("endtext"); add("delay(5)"); add("missing(green)"); add("missing(yellow)"); add("flash(5)"); add("shake(50)"); add("playef(9,10)"); add("gotoroom(3,10)"); add("gotoposition(40,177,0)"); add("createcrewman(208,177,green,1,followposition,120)"); add("createcrewman(240,177,purple,1,followposition,120)"); add("createcrewman(10,177,blue,1,followposition,180)"); add("squeak(player)"); add("text(player,80,150,1)"); add("Oh no!"); add("backgroundtext"); add("speak_active"); add("walk(right,20)"); add("endtextfast"); //and the next! add("flash(5)"); add("shake(50)"); add("playef(9,10)"); add("gotoroom(3,11)"); add("gotoposition(140,0,0)"); add("createcrewman(90,105,green,1,followblue)"); add("createcrewman(125,105,purple,1,followgreen)"); add("createcrewman(55,105,blue,1,followposition,-200)"); add("createcrewman(120,177,yellow,1,followposition,-200)"); add("createcrewman(240,177,red,1,faceleft)"); add("delay(5)"); add("changeai(red,followposition,-200)"); add("squeak(red)"); add("text(red,100,150,1)"); add("Not again!"); add("backgroundtext"); add("speak_active"); add("walk(left,25)"); add("endtextfast"); //final room: add("flash(5)"); add("alarmoff"); add("playef(9,10)"); add("gotoroom(2,11)"); add("gotoposition(265,153,0)"); add("createcrewman(130,153,blue,1,faceleft)"); add("createcrewman(155,153,green,1,faceleft)"); add("createcrewman(180,153,purple,1,faceleft)"); add("createcrewman(205,153,yellow,1,faceleft)"); add("createcrewman(230,153,red,1,faceleft)"); add("delay(75)"); add("squeak(player)"); add("changemood(player,0)"); add("text(player,0,0,1)"); add("Wait! It's stopped!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("delay(30)"); add("changemood(purple,0)"); add("changedir(purple,1)"); add("changemood(red,0)"); add("changedir(red,1)"); add("changemood(green,0)"); add("changedir(green,1)"); add("changemood(blue,0)"); add("changedir(blue,1)"); add("changemood(yellow,0)"); add("changedir(yellow,1)"); add("delay(30)"); add("rescued(green)"); add("rescued(yellow)"); add("missing(blue)"); add("altstates(1)"); add("fadeout()"); add("untilfade()"); add("gotoroom(2,10)"); add("gotoposition(227,113,0)"); add("changedir(player,0)"); add("rescued(blue)"); add("createcrewman(150,177,purple,0,faceleft)"); add("createcrewman(90,177,yellow,0,faceright)"); add("createcrewman(184,185,red,0,faceleft)"); add("createcrewman(65,177,green,0,faceright)"); add("createcrewman(35,177,blue,0,faceright)"); add("rescued(purple)"); add("rescued(red)"); add("rescued(green)"); add("rescued(yellow)"); add("fadein()"); add("untilfade()"); add("delay(30)"); add("squeak(purple)"); add("text(purple,0,0,3)"); add("This is where we were"); add("storing those shiny"); add("things? What happened?"); add("position(purple,above)"); add("speak_active"); add("squeak(player)"); add("text(player,0,0,2)"); add("We were just playing"); add("with them, and..."); add("position(player,above)"); add("speak_active"); add("endtext"); add("squeak(cry)"); add("changemood(player,1)"); add("text(player,0,0,1)"); add("...they suddenly exploded!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("squeak(blue)"); add("text(blue,0,0,2)"); add("But look what they made!"); add("Is that a teleporter?"); add("position(blue,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("I think so, but..."); add("position(yellow,above)"); add("speak_active"); add("squeak(yellow)"); add("text(yellow,0,0,2)"); add("I've never seen a teleporter"); add("like that before..."); add("position(yellow,above)"); add("speak_active"); add("endtext"); add("changemood(player,0)"); add("delay(30)"); add("squeak(red)"); add("text(red,0,0,1)"); add("We should investigate!"); add("position(red,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,1)"); add("What do you think, Captain?"); add("position(purple,above)"); add("speak_active"); add("squeak(purple)"); add("text(purple,0,0,2)"); add("Should we find out"); add("where it leads?"); add("position(purple,above)"); add("speak_active"); add("endtext"); add("delay(15)"); add("squeak(player)"); add("text(player,0,0,1)"); add("Let's go!"); add("position(player,above)"); add("speak_active"); add("endtext"); add("walk(left,10)"); add("flip"); add("walk(left,5)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("blackout()"); add("delay(45)"); add("gotoroom(17,6)"); add("gotoposition(80,109,1)"); add("changedir(player,1)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("blackon()"); add("delay(15)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("createcrewman(28,65,purple,0,faceright)"); add("delay(15)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("createcrewman(145,169,yellow,0,faceleft)"); add("delay(15)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("createcrewman(32,169,red,0,faceright)"); add("delay(15)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("createcrewman(96,149,green,0,faceleft)"); add("delay(15)"); add("flash(5)"); add("shake(20)"); add("playef(10,10)"); add("createcrewman(155,57,blue,0,faceleft)"); add("delay(45)"); add("squeak(cry)"); add("changemood(blue,1)"); add("text(blue,0,0,1)"); add("Oh no! We're trapped!"); add("position(blue,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(yellow,1)"); add("text(yellow,0,0,1)"); add("Oh dear..."); add("position(yellow,above)"); add("speak_active"); add("squeak(cry)"); add("changemood(red,1)"); add("changemood(green,1)"); add("changemood(purple,1)"); add("changemood(player,1)"); add("text(player,0,0,2)"); add("Hmm... how should we"); add("get out of this?"); add("position(player,below)"); add("speak_active"); add("endtext"); add("delay(70)"); add("squeak(purple)"); add("delay(1)"); add("squeak(yellow)"); add("delay(1)"); add("squeak(red)"); add("delay(1)"); add("squeak(blue)"); add("delay(1)"); add("squeak(player)"); add("delay(1)"); add("squeak(green)"); add("changemood(yellow,0)"); add("changemood(blue,0)"); add("changemood(red,0)"); add("changemood(player,0)"); add("changemood(green,0)"); add("changemood(purple,0)"); add("text(player,0,0,1)"); add("COMBINE!"); add("position(player,above)"); add("backgroundtext"); add("speak"); add("text(purple,0,0,1)"); add("COMBINE!"); add("position(purple,above)"); add("backgroundtext"); add("speak"); add("text(yellow,0,0,1)"); add("COMBINE!"); add("position(yellow,above)"); add("backgroundtext"); add("speak"); add("text(red,0,0,1)"); add("COMBINE!"); add("position(red,above)"); add("backgroundtext"); add("speak"); add("text(green,0,0,1)"); add("COMBINE!"); add("position(green,above)"); add("backgroundtext"); add("speak"); add("text(blue,0,0,1)"); add("COMBINE!"); add("position(blue,above)"); add("speak"); add("endtextfast"); add("delay(15)"); add("flip"); add("changeai(purple,followplayer)"); add("changeai(blue,followplayer)"); add("changeai(red,followplayer)"); add("changeai(yellow,followplayer)"); add("changeai(green,followplayer)"); add("walk(right,3)"); add("delay(5)"); add("flash(10)"); add("shake(20)"); add("playef(24,10)"); add("gotoroom(17,6)"); add("vvvvvvman()"); add("delay(90)"); add("walk(right,6)"); add("flash(10)"); add("shake(20)"); add("playef(23,10)"); add("altstates(2)"); add("gotoroom(17,6)"); add("delay(20)"); add("walk(right,12)"); add("flash(10)"); add("shake(20)"); add("playef(23,10)"); add("altstates(0)"); add("gotoroom(17,6)"); add("delay(20)"); add("walk(right,15)"); add("gotoroom(18,6)"); add("gotoposition(0,46,0)"); add("walk(right,5)"); add("delay(20)"); add("flash(10)"); add("shake(20)"); add("playef(24,10)"); add("undovvvvvvman()"); add("createcrewman(30,99,purple,0,faceright)"); add("createcrewman(65,119,yellow,0,faceright)"); add("createcrewman(135,149,red,0,faceleft)"); add("createcrewman(170,159,green,0,faceleft)"); add("createcrewman(205,159,blue,0,faceleft)"); add("delay(60)"); add("changedir(yellow,0)"); add("changedir(player,0)"); add("delay(20)"); add("squeak(purple)"); add("text(purple,0,0,3)"); add("Or, you know... we could"); add("have just warped back"); add("to the ship..."); add("position(purple,above)"); add("speak_active"); add("endtext"); add("delay(30)"); add("changedir(purple,1)"); add("changedir(yellow,1)"); add("changedir(player,1)"); add("changedir(red,1)"); add("changedir(green,1)"); add("squeak(green)"); add("text(green,0,0,1)"); add("Wow! What is this?"); add("position(green,above)"); add("speak_active"); add("changedir(purple,1)"); add("changedir(yellow,1)"); add("changedir(player,0)"); add("changedir(red,0)"); add("changedir(green,0)"); add("squeak(yellow)"); add("text(yellow,0,0,1)"); add("It looks like another laboratory!"); add("position(yellow,above)"); add("speak_active"); add("changedir(purple,1)"); add("changedir(yellow,1)"); add("changedir(player,1)"); add("squeak(red)"); add("text(red,0,0,1)"); add("Let's have a look around!"); add("position(red,above)"); add("speak_active"); add("endtext"); add("delay(20)"); add("changeai(yellow,followposition,500)"); add("changeai(purple,followposition,500)"); add("changeai(blue,followposition,500)"); add("changeai(red,followposition,500)"); add("changeai(green,followposition,500)"); add("delay(21)"); add("changeai(yellow,faceright)"); add("flipgravity(yellow)"); add("playef(0,10)"); add("delay(2)"); add("changeai(purple,faceright)"); add("flipgravity(purple)"); add("playef(0,10)"); add("delay(48)"); add("foundlab"); add("endtext"); add("foundlab2"); add("endtext"); add("entersecretlab"); add("play(11)"); add("endcutscene()"); add("untilbars()"); } else if(t == "returntolab") { //To get back to the lab from the gravitron add("gotoroom(19,7)"); add("gotoposition(132,137,0)"); add("fadein()"); add("setcheckpoint()"); add("play(11)"); add("endcutscene()"); add("untilbars()"); } else { loadother(t); } } #endif /* SCRIPTS_H */
22.367703
99
0.588506
TijmenUU
6a30e92ecc4497e24d6fd76e0318126d8704bdcc
11,729
cpp
C++
TensorShaderAvxBackend/Complex/Convolution/Convolution2D/complex_kernelproduct_2d.cpp
tk-yoshimura/TensorShaderAVX
de47428efbeaa4df694e4a3584b0397162e711d9
[ "MIT" ]
null
null
null
TensorShaderAvxBackend/Complex/Convolution/Convolution2D/complex_kernelproduct_2d.cpp
tk-yoshimura/TensorShaderAVX
de47428efbeaa4df694e4a3584b0397162e711d9
[ "MIT" ]
null
null
null
TensorShaderAvxBackend/Complex/Convolution/Convolution2D/complex_kernelproduct_2d.cpp
tk-yoshimura/TensorShaderAVX
de47428efbeaa4df694e4a3584b0397162e711d9
[ "MIT" ]
null
null
null
#include "../../../TensorShaderAvxBackend.h" using namespace System; __forceinline __m256d _mm256_complexmulkernelgrad_pd(__m256d u, __m256d v) { __m256d vri = v; __m256d urr = _mm256_permute4x64_pd(u, _MM_PERM_CCAA); __m256d vir = _mm256_permute4x64_pd(v, _MM_PERM_CDAB); __m256d uii = _mm256_permute4x64_pd(u, _MM_PERM_DDBB); return _mm256_fmsubadd_pd(vri, urr, _mm256_mul_pd(vir, uii)); } void complex_kernelproduct_2d(unsigned int inchannels, unsigned int outchannels, unsigned int inwidth, unsigned int outwidth, unsigned int kwidth, unsigned int inheight, unsigned int outheight, unsigned int kheight, unsigned int stride, unsigned int batch, unsigned int outch, float* inmap_ptr, float* outmap_ptr, float* kernel_ptr) { const unsigned int inch_sep = inchannels & ~7u, inch_rem = inchannels - inch_sep, koutch = outch / 2; const unsigned int kerneloutchannels = outchannels / 2; const __m256i mask = TensorShaderAvxBackend::masktable_m256(inch_rem); for (unsigned int inch = 0; inch < inch_sep; inch += 8) { for (unsigned int ky = 0; ky < kheight; ky++) { for (unsigned int kx = 0; kx < kwidth; kx++) { __m256d uv_hi = _mm256_setzero_pd(), uv_lo = _mm256_setzero_pd(); for (unsigned int th = 0; th < batch; th++) { for (unsigned int oy = 0, iy = ky; oy < outheight; oy++, iy += stride) { for (unsigned int ox = 0, ix = kx; ox < outwidth; ox++, ix += stride) { __m256 u = _mm256_loadu_ps(inmap_ptr + inch + inchannels * (ix + inwidth * (iy + inheight * th))); float vr = outmap_ptr[outch + outchannels * (ox + outwidth * (oy + outheight * th))]; float vi = outmap_ptr[outch + 1 + outchannels * (ox + outwidth * (oy + outheight * th))]; __m256d v = _mm256_setr_pd(vr, vi, vr, vi); __m256d u_hi = _mm256_cvtps_pd(_mm256_extractf128_ps(u, 1)); __m256d u_lo = _mm256_cvtps_pd(_mm256_castps256_ps128(u)); uv_hi = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(u_hi, v), uv_hi); uv_lo = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(u_lo, v), uv_lo); } } } _mm_storeu_ps(kernel_ptr + inch + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), _mm256_cvtpd_ps(uv_lo)); _mm_storeu_ps(kernel_ptr + inch + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)) + 4, _mm256_cvtpd_ps(uv_hi)); } } } if (inch_rem > 0) { for (unsigned int ky = 0; ky < kheight; ky++) { for (unsigned int kx = 0; kx < kwidth; kx++) { __m256d uv_hi = _mm256_setzero_pd(), uv_lo = _mm256_setzero_pd(); for (unsigned int th = 0; th < batch; th++) { for (unsigned int oy = 0, iy = ky; oy < outheight; oy++, iy += stride) { for (unsigned int ox = 0, ix = kx; ox < outwidth; ox++, ix += stride) { __m256 u = _mm256_maskload_ps(inmap_ptr + inch_sep + inchannels * (ix + inwidth * (iy + inheight * th)), mask); float vr = outmap_ptr[outch + outchannels * (ox + outwidth * (oy + outheight * th))]; float vi = outmap_ptr[outch + 1 + outchannels * (ox + outwidth * (oy + outheight * th))]; __m256d v = _mm256_setr_pd(vr, vi, vr, vi); __m256d u_hi = _mm256_cvtps_pd(_mm256_extractf128_ps(u, 1)); __m256d u_lo = _mm256_cvtps_pd(_mm256_castps256_ps128(u)); uv_hi = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(u_hi, v), uv_hi); uv_lo = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(u_lo, v), uv_lo); } } } if (inch_rem > 4) { _mm_storeu_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), _mm256_cvtpd_ps(uv_lo)); _mm_maskstore_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)) + 4, TensorShaderAvxBackend::masktable_m128(inch_rem - 4), _mm256_cvtpd_ps(uv_hi)); } else if (inch_rem >= 4) { _mm_storeu_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), _mm256_cvtpd_ps(uv_lo)); } else { _mm_maskstore_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), TensorShaderAvxBackend::masktable_m128(inch_rem), _mm256_cvtpd_ps(uv_lo)); } } } } } void complex_kernelproduct_2d_transpose(unsigned int inchannels, unsigned int outchannels, unsigned int inwidth, unsigned int outwidth, unsigned int kwidth, unsigned int inheight, unsigned int outheight, unsigned int kheight, unsigned int stride, unsigned int batch, unsigned int outch, float* inmap_ptr, float* outmap_ptr, float* kernel_ptr) { const unsigned int inch_sep = inchannels & ~7u, inch_rem = inchannels - inch_sep, koutch = outch / 2; const unsigned int kerneloutchannels = outchannels / 2; const __m256i mask = TensorShaderAvxBackend::masktable_m256(inch_rem); for (unsigned int inch = 0; inch < inch_sep; inch += 8) { for (unsigned int ky = 0; ky < kheight; ky++) { for (unsigned int kx = 0; kx < kwidth; kx++) { __m256d vu_hi = _mm256_setzero_pd(), vu_lo = _mm256_setzero_pd(); for (unsigned int th = 0; th < batch; th++) { for (unsigned int oy = 0, iy = ky; oy < outheight; oy++, iy += stride) { for (unsigned int ox = 0, ix = kx; ox < outwidth; ox++, ix += stride) { __m256 u = _mm256_loadu_ps(inmap_ptr + inch + inchannels * (ix + inwidth * (iy + inheight * th))); float vr = outmap_ptr[outch + outchannels * (ox + outwidth * (oy + outheight * th))]; float vi = outmap_ptr[outch + 1 + outchannels * (ox + outwidth * (oy + outheight * th))]; __m256d v = _mm256_setr_pd(vr, vi, vr, vi); __m256d u_hi = _mm256_cvtps_pd(_mm256_extractf128_ps(u, 1)); __m256d u_lo = _mm256_cvtps_pd(_mm256_castps256_ps128(u)); vu_hi = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(v, u_hi), vu_hi); vu_lo = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(v, u_lo), vu_lo); } } } _mm_storeu_ps(kernel_ptr + inch + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), _mm256_cvtpd_ps(vu_lo)); _mm_storeu_ps(kernel_ptr + inch + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)) + 4, _mm256_cvtpd_ps(vu_hi)); } } } if (inch_rem > 0) { for (unsigned int ky = 0; ky < kheight; ky++) { for (unsigned int kx = 0; kx < kwidth; kx++) { __m256d vu_hi = _mm256_setzero_pd(), vu_lo = _mm256_setzero_pd(); for (unsigned int th = 0; th < batch; th++) { for (unsigned int oy = 0, iy = ky; oy < outheight; oy++, iy += stride) { for (unsigned int ox = 0, ix = kx; ox < outwidth; ox++, ix += stride) { __m256 u = _mm256_maskload_ps(inmap_ptr + inch_sep + inchannels * (ix + inwidth * (iy + inheight * th)), mask); float vr = outmap_ptr[outch + outchannels * (ox + outwidth * (oy + outheight * th))]; float vi = outmap_ptr[outch + 1 + outchannels * (ox + outwidth * (oy + outheight * th))]; __m256d v = _mm256_setr_pd(vr, vi, vr, vi); __m256d u_hi = _mm256_cvtps_pd(_mm256_extractf128_ps(u, 1)); __m256d u_lo = _mm256_cvtps_pd(_mm256_castps256_ps128(u)); vu_hi = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(v, u_hi), vu_hi); vu_lo = _mm256_add_pd(_mm256_complexmulkernelgrad_pd(v, u_lo), vu_lo); } } } if (inch_rem > 4) { _mm_storeu_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), _mm256_cvtpd_ps(vu_lo)); _mm_maskstore_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)) + 4, TensorShaderAvxBackend::masktable_m128(inch_rem - 4), _mm256_cvtpd_ps(vu_hi)); } else if (inch_rem >= 4) { _mm_storeu_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), _mm256_cvtpd_ps(vu_lo)); } else { _mm_maskstore_ps(kernel_ptr + inch_sep + inchannels * (koutch + kerneloutchannels * (kx + kwidth * ky)), TensorShaderAvxBackend::masktable_m128(inch_rem), _mm256_cvtpd_ps(vu_lo)); } } } } } void TensorShaderAvxBackend::Complex::KernelProduct2D(unsigned int inchannels, unsigned int outchannels, unsigned int inwidth, unsigned int inheight, unsigned int batch, unsigned int outch, unsigned int kwidth, unsigned int kheight, unsigned int stride, bool transpose, AvxArray<float>^ inmap, AvxArray<float>^ outmap, AvxArray<float>^ kernel) { Util::CheckDuplicateArray(inmap, kernel, outmap); if (inchannels % 2 != 0 || outchannels % 2 != 0 || outch % 2 != 0) { throw gcnew System::ArgumentException(); } if (outch >= outchannels) { throw gcnew System::ArgumentException(); } unsigned int outwidth = (inwidth - kwidth) / stride + 1; unsigned int outheight = (inheight - kheight) / stride + 1; Util::CheckLength(inchannels * inwidth * inheight * batch, inmap); Util::CheckLength(outchannels * outwidth * outheight * batch, outmap); Util::CheckLength(inchannels * outchannels * kwidth * kheight / 2, kernel); float* inmap_ptr = (float*)(inmap->Ptr.ToPointer()); float* outmap_ptr = (float*)(outmap->Ptr.ToPointer()); float* kernel_ptr = (float*)(kernel->Ptr.ToPointer()); if (transpose) { complex_kernelproduct_2d_transpose(inchannels, outchannels, inwidth, outwidth, kwidth, inheight, outheight, kheight, stride, batch, outch, inmap_ptr, outmap_ptr, kernel_ptr); } else { complex_kernelproduct_2d(inchannels, outchannels, inwidth, outwidth, kwidth, inheight, outheight, kheight, stride, batch, outch, inmap_ptr, outmap_ptr, kernel_ptr); } }
56.389423
207
0.541393
tk-yoshimura
6a33579b6c7590590fd3157e14cdc72bcc2bc27b
5,006
hpp
C++
3rdparty/stout/include/stout/check.hpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
4
2019-03-06T03:04:40.000Z
2019-07-20T15:35:00.000Z
3rdparty/stout/include/stout/check.hpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
6
2018-11-30T08:04:45.000Z
2019-05-15T03:04:28.000Z
3rdparty/stout/include/stout/check.hpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
4
2019-03-11T11:51:22.000Z
2020-05-11T07:27:31.000Z
// 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. #ifndef __STOUT_CHECK_HPP__ #define __STOUT_CHECK_HPP__ #include <ostream> #include <sstream> #include <string> #include <glog/logging.h> #include <stout/abort.hpp> #include <stout/error.hpp> #include <stout/none.hpp> #include <stout/option.hpp> #include <stout/result.hpp> #include <stout/some.hpp> #include <stout/try.hpp> // A generic macro to facilitate definitions of CHECK_*, akin to CHECK. // This appends the error if possible to the end of the log message, // so there's no need to append the error message explicitly. // To define a new CHECK_*, provide the name, the function that performs the // check, and the expression. See below for examples (e.g. CHECK_SOME). #define CHECK_STATE(name, check, expression) \ for (const Option<Error> _error = check(expression); _error.isSome();) \ _CheckFatal(__FILE__, \ __LINE__, \ #name, \ #expression, \ _error.get()).stream() #define CHECK_SOME(expression) \ CHECK_STATE(CHECK_SOME, _check_some, expression) #define CHECK_NONE(expression) \ CHECK_STATE(CHECK_NONE, _check_none, expression) #define CHECK_ERROR(expression) \ CHECK_STATE(CHECK_ERROR, _check_error, expression) // A private helper for CHECK_NOTNONE which is similar to the // CHECK_NOTNULL provided by glog. template <typename T> T&& _check_not_none( const char* file, int line, const char* message, Option<T>&& t) { if (t.isNone()) { google::LogMessageFatal(file, line, new std::string(message)); } return std::move(t).get(); } template <typename T> T& _check_not_none( const char* file, int line, const char* message, Option<T>& t) { if (t.isNone()) { google::LogMessageFatal(file, line, new std::string(message)); } return t.get(); } template <typename T> const T& _check_not_none( const char* file, int line, const char* message, const Option<T>& t) { if (t.isNone()) { google::LogMessageFatal(file, line, new std::string(message)); } return t.get(); } #define CHECK_NOTNONE(expression) \ _check_not_none( \ __FILE__, \ __LINE__, \ "'" #expression "' Must be SOME", \ (expression)) // Private structs/functions used for CHECK_*. template <typename T> Option<Error> _check_some(const Option<T>& o) { if (o.isNone()) { return Error("is NONE"); } else { CHECK(o.isSome()); return None(); } } template <typename T> Option<Error> _check_some(const Try<T>& t) { if (t.isError()) { return Error(t.error()); } else { CHECK(t.isSome()); return None(); } } template <typename T> Option<Error> _check_some(const Result<T>& r) { if (r.isError()) { return Error(r.error()); } else if (r.isNone()) { return Error("is NONE"); } else { CHECK(r.isSome()); return None(); } } template <typename T> Option<Error> _check_none(const Option<T>& o) { if (o.isSome()) { return Error("is SOME"); } else { CHECK(o.isNone()); return None(); } } template <typename T> Option<Error> _check_none(const Result<T>& r) { if (r.isError()) { return Error("is ERROR"); } else if (r.isSome()) { return Error("is SOME"); } else { CHECK(r.isNone()); return None(); } } template <typename T> Option<Error> _check_error(const Try<T>& t) { if (t.isSome()) { return Error("is SOME"); } else { CHECK(t.isError()); return None(); } } template <typename T> Option<Error> _check_error(const Result<T>& r) { if (r.isNone()) { return Error("is NONE"); } else if (r.isSome()) { return Error("is SOME"); } else { CHECK(r.isError()); return None(); } } struct _CheckFatal { _CheckFatal(const char* _file, int _line, const char* type, const char* expression, const Error& error) : file(_file), line(_line) { out << type << "(" << expression << "): " << error.message << " "; } ~_CheckFatal() { google::LogMessageFatal(file.c_str(), line).stream() << out.str(); } std::ostream& stream() { return out; } const std::string file; const int line; std::ostringstream out; }; #endif // __STOUT_CHECK_HPP__
22.150442
76
0.609069
sagar8192
6a38780d1b710f066df14776ac3123ca67498177
8,807
cpp
C++
ugv_sdk/src/tracer_base.cpp
Wataru-Oshima-Tokyo/ugv_sdk
689a872af6733eff93dccbc4b1c56405f69acb4f
[ "BSD-3-Clause" ]
null
null
null
ugv_sdk/src/tracer_base.cpp
Wataru-Oshima-Tokyo/ugv_sdk
689a872af6733eff93dccbc4b1c56405f69acb4f
[ "BSD-3-Clause" ]
null
null
null
ugv_sdk/src/tracer_base.cpp
Wataru-Oshima-Tokyo/ugv_sdk
689a872af6733eff93dccbc4b1c56405f69acb4f
[ "BSD-3-Clause" ]
null
null
null
#include "ugv_sdk/tracer/tracer_base.hpp" #include <string> #include <cstring> #include <iostream> #include <algorithm> #include <array> #include <chrono> #include <cstdint> #include <ratio> #include <thread> #include "stopwatch.hpp" namespace westonrobot { void TracerBase::SendRobotCmd() { static uint8_t cmd_count = 0; if (can_connected_) { EnableCommandedMode(); SendMotionCmd(cmd_count++); } } void TracerBase::EnableCommandedMode() { AgxMessage c_msg; c_msg.type = AgxMsgCtrlModeSelect; memset(c_msg.body.ctrl_mode_select_msg.raw, 0, 8); c_msg.body.ctrl_mode_select_msg.cmd.control_mode = CTRL_MODE_CMD_CAN; // send to can bus can_frame c_frame; EncodeCanFrame(&c_msg, &c_frame); can_if_->SendFrame(c_frame); } void TracerBase::SendMotionCmd(uint8_t count) { // motion control message AgxMessage m_msg; m_msg.type = AgxMsgMotionCommand; memset(m_msg.body.motion_command_msg.raw, 0, 8); motion_cmd_mutex_.lock(); int16_t linear_cmd = static_cast<int16_t>(current_motion_cmd_.linear_velocity * 1000); int16_t angular_cmd = static_cast<int16_t>(current_motion_cmd_.angular_velocity * 1000); motion_cmd_mutex_.unlock(); // SendControlCmd(); m_msg.body.motion_command_msg.cmd.linear_velocity.high_byte = (static_cast<uint16_t>(linear_cmd) >> 8) & 0x00ff; m_msg.body.motion_command_msg.cmd.linear_velocity.low_byte = (static_cast<uint16_t>(linear_cmd) >> 0) & 0x00ff; m_msg.body.motion_command_msg.cmd.angular_velocity.high_byte = (static_cast<uint16_t>(angular_cmd) >> 8) & 0x00ff; m_msg.body.motion_command_msg.cmd.angular_velocity.low_byte = (static_cast<uint16_t>(angular_cmd) >> 0) & 0x00ff; // send to can bus can_frame m_frame; EncodeCanFrame(&m_msg, &m_frame); can_if_->SendFrame(m_frame); } void TracerBase::SendLightCmd(const TracerLightCmd &lcmd, uint8_t count) { AgxMessage l_msg; l_msg.type = AgxMsgLightCommand; memset(l_msg.body.light_command_msg.raw, 0, 8); if (lcmd.enable_ctrl) { l_msg.body.light_command_msg.cmd.light_ctrl_enabled = LIGHT_CTRL_ENABLE; l_msg.body.light_command_msg.cmd.front_light_mode = static_cast<uint8_t>(lcmd.front_mode); l_msg.body.light_command_msg.cmd.front_light_custom = lcmd.front_custom_value; l_msg.body.light_command_msg.cmd.rear_light_mode = static_cast<uint8_t>(lcmd.rear_mode); l_msg.body.light_command_msg.cmd.rear_light_custom = lcmd.rear_custom_value; } else { l_msg.body.light_command_msg.cmd.light_ctrl_enabled = LIGHT_CTRL_DISABLE; } l_msg.body.light_command_msg.cmd.count = count; // send to can bus can_frame l_frame; EncodeCanFrame(&l_msg, &l_frame); can_if_->SendFrame(l_frame); } TracerState TracerBase::GetTracerState() { std::lock_guard<std::mutex> guard(tracer_state_mutex_); return tracer_state_; } void TracerBase::SetMotionCommand(double linear_vel, double angular_vel) { // make sure cmd thread is started before attempting to send commands if (!cmd_thread_started_) StartCmdThread(); if (linear_vel < TracerMotionCmd::min_linear_velocity) linear_vel = TracerMotionCmd::min_linear_velocity; if (linear_vel > TracerMotionCmd::max_linear_velocity) linear_vel = TracerMotionCmd::max_linear_velocity; if (angular_vel < TracerMotionCmd::min_angular_velocity) angular_vel = TracerMotionCmd::min_angular_velocity; if (angular_vel > TracerMotionCmd::max_angular_velocity) angular_vel = TracerMotionCmd::max_angular_velocity; std::lock_guard<std::mutex> guard(motion_cmd_mutex_); current_motion_cmd_.linear_velocity = linear_vel; current_motion_cmd_.angular_velocity = angular_vel; FeedCmdTimeoutWatchdog(); } void TracerBase::SetLightCommand(const TracerLightCmd &cmd) { static uint8_t light_cmd_count = 0; SendLightCmd(cmd, light_cmd_count++); } void TracerBase::ParseCANFrame(can_frame *rx_frame) { AgxMessage status_msg; DecodeCanFrame(rx_frame, &status_msg); NewStatusMsgReceivedCallback(status_msg); } void TracerBase::NewStatusMsgReceivedCallback(const AgxMessage &msg) { // std::cout << "new status msg received" << std::endl; std::lock_guard<std::mutex> guard(tracer_state_mutex_); UpdateTracerState(msg, tracer_state_); } void TracerBase::UpdateTracerState(const AgxMessage &status_msg, TracerState &state) { switch (status_msg.type) { case AgxMsgSystemState: { // std::cout << "system status feedback received" << std::endl; const SystemStateMessage &msg = status_msg.body.system_state_msg; state.control_mode = msg.state.control_mode; state.base_state = msg.state.vehicle_state; state.battery_voltage = (static_cast<uint16_t>(msg.state.battery_voltage.low_byte) | static_cast<uint16_t>(msg.state.battery_voltage.high_byte) << 8) / 10.0; state.fault_code = msg.state.fault_code; break; } case AgxMsgMotionState: { // std::cout << "motion control feedback received" << std::endl; const MotionStateMessage &msg = status_msg.body.motion_state_msg; state.linear_velocity = static_cast<int16_t>( static_cast<uint16_t>(msg.state.linear_velocity.low_byte) | static_cast<uint16_t>(msg.state.linear_velocity.high_byte) << 8) / 1000.0; state.angular_velocity = static_cast<int16_t>( static_cast<uint16_t>(msg.state.angular_velocity.low_byte) | static_cast<uint16_t>(msg.state.angular_velocity.high_byte) << 8) / 1000.0; break; } case AgxMsgLightState: { // std::cout << "light control feedback received" << std::endl; const LightStateMessage &msg = status_msg.body.light_state_msg; if (msg.state.light_ctrl_enabled == LIGHT_CTRL_DISABLE) state.light_control_enabled = false; else state.light_control_enabled = true; state.front_light_state.mode = msg.state.front_light_mode; state.front_light_state.custom_value = msg.state.front_light_custom; break; } case AgxMsgActuatorHSState: { // std::cout << "actuator hs feedback received" << std::endl; const ActuatorHSStateMessage &msg = status_msg.body.actuator_hs_state_msg; state.actuator_states[msg.motor_id].motor_current = (static_cast<uint16_t>(msg.data.state.current.low_byte) | static_cast<uint16_t>(msg.data.state.current.high_byte) << 8) / 10.0; state.actuator_states[msg.motor_id].motor_rpm = static_cast<int16_t>( static_cast<uint16_t>(msg.data.state.rpm.low_byte) | static_cast<uint16_t>(msg.data.state.rpm.high_byte) << 8); state.actuator_states[msg.motor_id].motor_pulses = static_cast<int16_t>( static_cast<uint16_t>(msg.data.state.pulse_count.low_byte) | static_cast<uint16_t>(msg.data.state.pulse_count.high_byte) << 8); break; } case AgxMsgActuatorLSState: { // std::cout << "actuator ls feedback received" << std::endl; const ActuatorLSStateMessage &msg = status_msg.body.actuator_ls_state_msg; for (int i = 0; i < 2; ++i) { state.actuator_states[msg.motor_id].driver_voltage = (static_cast<uint16_t>(msg.data.state.driver_voltage.low_byte) | static_cast<uint16_t>(msg.data.state.driver_voltage.high_byte) << 8) / 10.0; state.actuator_states[msg.motor_id] .driver_temperature = static_cast<int16_t>( static_cast<uint16_t>(msg.data.state.driver_temperature.low_byte) | static_cast<uint16_t>(msg.data.state.driver_temperature.high_byte) << 8); state.actuator_states[msg.motor_id].motor_temperature = msg.data.state.motor_temperature; state.actuator_states[msg.motor_id].driver_state = msg.data.state.driver_state; } break; } case AgxMsgOdometry: { // std::cout << "Odometer msg feedback received" << std::endl; const OdometryMessage &msg = status_msg.body.odometry_msg; state.right_odometry = static_cast<int32_t>( (static_cast<uint32_t>(msg.state.right_wheel.lsb)) | (static_cast<uint32_t>(msg.state.right_wheel.low_byte) << 8) | (static_cast<uint32_t>(msg.state.right_wheel.high_byte) << 16) | (static_cast<uint32_t>(msg.state.right_wheel.msb) << 24)); state.left_odometry = static_cast<int32_t>( (static_cast<uint32_t>(msg.state.left_wheel.lsb)) | (static_cast<uint32_t>(msg.state.left_wheel.low_byte) << 8) | (static_cast<uint32_t>(msg.state.left_wheel.high_byte) << 16) | (static_cast<uint32_t>(msg.state.left_wheel.msb) << 24)); } } } } // namespace westonrobot
38.458515
80
0.704326
Wataru-Oshima-Tokyo
6a38ab70f815e485508e36391dad7176a16c3975
12,197
hpp
C++
include/codegen/include/RootMotion/FinalIK/IKSolverVR.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/RootMotion/FinalIK/IKSolverVR.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/RootMotion/FinalIK/IKSolverVR.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:17 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: RootMotion.FinalIK.IKSolver #include "RootMotion/FinalIK/IKSolver.hpp" // Including type: RootMotion.FinalIK.VRIK #include "RootMotion/FinalIK/VRIK.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: RootMotion::FinalIK namespace RootMotion::FinalIK { } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Transform class Transform; // Forward declaring type: Keyframe struct Keyframe; // Skipping declaration: Quaternion because it is already included! } // Completed forward declares // Type namespace: RootMotion.FinalIK namespace RootMotion::FinalIK { // Autogenerated type: RootMotion.FinalIK.IKSolverVR class IKSolverVR : public RootMotion::FinalIK::IKSolver { public: // Nested type: RootMotion::FinalIK::IKSolverVR::Arm class Arm; // Nested type: RootMotion::FinalIK::IKSolverVR::BodyPart class BodyPart; // Nested type: RootMotion::FinalIK::IKSolverVR::Footstep class Footstep; // Nested type: RootMotion::FinalIK::IKSolverVR::Leg class Leg; // Nested type: RootMotion::FinalIK::IKSolverVR::Locomotion class Locomotion; // Nested type: RootMotion::FinalIK::IKSolverVR::Spine class Spine; // Nested type: RootMotion::FinalIK::IKSolverVR::PositionOffset struct PositionOffset; // Nested type: RootMotion::FinalIK::IKSolverVR::RotationOffset struct RotationOffset; // Nested type: RootMotion::FinalIK::IKSolverVR::VirtualBone class VirtualBone; // private UnityEngine.Transform[] solverTransforms // Offset: 0x58 ::Array<UnityEngine::Transform*>* solverTransforms; // private System.Boolean hasChest // Offset: 0x60 bool hasChest; // private System.Boolean hasNeck // Offset: 0x61 bool hasNeck; // private System.Boolean hasShoulders // Offset: 0x62 bool hasShoulders; // private System.Boolean hasToes // Offset: 0x63 bool hasToes; // private System.Boolean hasLegs // Offset: 0x64 bool hasLegs; // private UnityEngine.Vector3[] readPositions // Offset: 0x68 ::Array<UnityEngine::Vector3>* readPositions; // private UnityEngine.Quaternion[] readRotations // Offset: 0x70 ::Array<UnityEngine::Quaternion>* readRotations; // private UnityEngine.Vector3[] solvedPositions // Offset: 0x78 ::Array<UnityEngine::Vector3>* solvedPositions; // private UnityEngine.Quaternion[] solvedRotations // Offset: 0x80 ::Array<UnityEngine::Quaternion>* solvedRotations; // private UnityEngine.Quaternion[] defaultLocalRotations // Offset: 0x88 ::Array<UnityEngine::Quaternion>* defaultLocalRotations; // private UnityEngine.Vector3[] defaultLocalPositions // Offset: 0x90 ::Array<UnityEngine::Vector3>* defaultLocalPositions; // private UnityEngine.Vector3 rootV // Offset: 0x98 UnityEngine::Vector3 rootV; // private UnityEngine.Vector3 rootVelocity // Offset: 0xA4 UnityEngine::Vector3 rootVelocity; // private UnityEngine.Vector3 bodyOffset // Offset: 0xB0 UnityEngine::Vector3 bodyOffset; // private System.Int32 supportLegIndex // Offset: 0xBC int supportLegIndex; // private System.Int32 lastLOD // Offset: 0xC0 int lastLOD; // public System.Int32 LOD // Offset: 0xC4 int LOD; // public System.Boolean plantFeet // Offset: 0xC8 bool plantFeet; // private RootMotion.FinalIK.IKSolverVR/VirtualBone <rootBone>k__BackingField // Offset: 0xD0 RootMotion::FinalIK::IKSolverVR::VirtualBone* rootBone; // public RootMotion.FinalIK.IKSolverVR/Spine spine // Offset: 0xD8 RootMotion::FinalIK::IKSolverVR::Spine* spine; // public RootMotion.FinalIK.IKSolverVR/Arm leftArm // Offset: 0xE0 RootMotion::FinalIK::IKSolverVR::Arm* leftArm; // public RootMotion.FinalIK.IKSolverVR/Arm rightArm // Offset: 0xE8 RootMotion::FinalIK::IKSolverVR::Arm* rightArm; // public RootMotion.FinalIK.IKSolverVR/Leg leftLeg // Offset: 0xF0 RootMotion::FinalIK::IKSolverVR::Leg* leftLeg; // public RootMotion.FinalIK.IKSolverVR/Leg rightLeg // Offset: 0xF8 RootMotion::FinalIK::IKSolverVR::Leg* rightLeg; // public RootMotion.FinalIK.IKSolverVR/Locomotion locomotion // Offset: 0x100 RootMotion::FinalIK::IKSolverVR::Locomotion* locomotion; // private RootMotion.FinalIK.IKSolverVR/Leg[] legs // Offset: 0x108 ::Array<RootMotion::FinalIK::IKSolverVR::Leg*>* legs; // private RootMotion.FinalIK.IKSolverVR/Arm[] arms // Offset: 0x110 ::Array<RootMotion::FinalIK::IKSolverVR::Arm*>* arms; // private UnityEngine.Vector3 headPosition // Offset: 0x118 UnityEngine::Vector3 headPosition; // private UnityEngine.Vector3 headDeltaPosition // Offset: 0x124 UnityEngine::Vector3 headDeltaPosition; // private UnityEngine.Vector3 raycastOriginPelvis // Offset: 0x130 UnityEngine::Vector3 raycastOriginPelvis; // private UnityEngine.Vector3 lastOffset // Offset: 0x13C UnityEngine::Vector3 lastOffset; // private UnityEngine.Vector3 debugPos1 // Offset: 0x148 UnityEngine::Vector3 debugPos1; // private UnityEngine.Vector3 debugPos2 // Offset: 0x154 UnityEngine::Vector3 debugPos2; // private UnityEngine.Vector3 debugPos3 // Offset: 0x160 UnityEngine::Vector3 debugPos3; // private UnityEngine.Vector3 debugPos4 // Offset: 0x16C UnityEngine::Vector3 debugPos4; // public System.Void SetToReferences(RootMotion.FinalIK.VRIK/References references) // Offset: 0x133BDB4 void SetToReferences(RootMotion::FinalIK::VRIK::References* references); // public System.Void GuessHandOrientations(RootMotion.FinalIK.VRIK/References references, System.Boolean onlyIfZero) // Offset: 0x133C248 void GuessHandOrientations(RootMotion::FinalIK::VRIK::References* references, bool onlyIfZero); // public System.Void DefaultAnimationCurves() // Offset: 0x133C0D0 void DefaultAnimationCurves(); // public System.Void AddPositionOffset(RootMotion.FinalIK.IKSolverVR/PositionOffset positionOffset, UnityEngine.Vector3 value) // Offset: 0x133CC34 void AddPositionOffset(RootMotion::FinalIK::IKSolverVR::PositionOffset positionOffset, UnityEngine::Vector3 value); // public System.Void AddRotationOffset(RootMotion.FinalIK.IKSolverVR/RotationOffset rotationOffset, UnityEngine.Vector3 value) // Offset: 0x133CF10 void AddRotationOffset(RootMotion::FinalIK::IKSolverVR::RotationOffset rotationOffset, UnityEngine::Vector3 value); // public System.Void AddRotationOffset(RootMotion.FinalIK.IKSolverVR/RotationOffset rotationOffset, UnityEngine.Quaternion value) // Offset: 0x133CFB4 void AddRotationOffset(RootMotion::FinalIK::IKSolverVR::RotationOffset rotationOffset, UnityEngine::Quaternion value); // public System.Void AddPlatformMotion(UnityEngine.Vector3 deltaPosition, UnityEngine.Quaternion deltaRotation, UnityEngine.Vector3 platformPivot) // Offset: 0x133D148 void AddPlatformMotion(UnityEngine::Vector3 deltaPosition, UnityEngine::Quaternion deltaRotation, UnityEngine::Vector3 platformPivot); // public System.Void Reset() // Offset: 0x133D2D4 void Reset(); // private UnityEngine.Vector3 GetNormal(UnityEngine.Transform[] transforms) // Offset: 0x133E1D0 UnityEngine::Vector3 GetNormal(::Array<UnityEngine::Transform*>* transforms); // private UnityEngine.Vector3 GuessWristToPalmAxis(UnityEngine.Transform hand, UnityEngine.Transform forearm) // Offset: 0x133C4E8 UnityEngine::Vector3 GuessWristToPalmAxis(UnityEngine::Transform* hand, UnityEngine::Transform* forearm); // private UnityEngine.Vector3 GuessPalmToThumbAxis(UnityEngine.Transform hand, UnityEngine.Transform forearm) // Offset: 0x133C6C0 UnityEngine::Vector3 GuessPalmToThumbAxis(UnityEngine::Transform* hand, UnityEngine::Transform* forearm); // static private UnityEngine.Keyframe[] GetSineKeyframes(System.Single mag) // Offset: 0x133CB10 static ::Array<UnityEngine::Keyframe>* GetSineKeyframes(float mag); // private System.Void UpdateSolverTransforms() // Offset: 0x133D44C void UpdateSolverTransforms(); // private System.Void WriteTransforms() // Offset: 0x133FBFC void WriteTransforms(); // private System.Void Read(UnityEngine.Vector3[] positions, UnityEngine.Quaternion[] rotations, System.Boolean hasChest, System.Boolean hasNeck, System.Boolean hasShoulders, System.Boolean hasToes, System.Boolean hasLegs) // Offset: 0x133D5B4 void Read(::Array<UnityEngine::Vector3>* positions, ::Array<UnityEngine::Quaternion>* rotations, bool hasChest, bool hasNeck, bool hasShoulders, bool hasToes, bool hasLegs); // private System.Void Solve() // Offset: 0x133E9C0 void Solve(); // private UnityEngine.Vector3 GetPosition(System.Int32 index) // Offset: 0x133FFE8 UnityEngine::Vector3 GetPosition(int index); // private UnityEngine.Quaternion GetRotation(System.Int32 index) // Offset: 0x1340030 UnityEngine::Quaternion GetRotation(int index); // public RootMotion.FinalIK.IKSolverVR/VirtualBone get_rootBone() // Offset: 0x1340674 RootMotion::FinalIK::IKSolverVR::VirtualBone* get_rootBone(); // private System.Void set_rootBone(RootMotion.FinalIK.IKSolverVR/VirtualBone value) // Offset: 0x134067C void set_rootBone(RootMotion::FinalIK::IKSolverVR::VirtualBone* value); // private System.Void Write() // Offset: 0x133FAAC void Write(); // private UnityEngine.Vector3 GetPelvisOffset() // Offset: 0x1340074 UnityEngine::Vector3 GetPelvisOffset(); // public override System.Void StoreDefaultLocalState() // Offset: 0x133DB4C // Implemented from: RootMotion.FinalIK.IKSolver // Base method: System.Void IKSolver::StoreDefaultLocalState() void StoreDefaultLocalState(); // public override System.Void FixTransforms() // Offset: 0x133DCC0 // Implemented from: RootMotion.FinalIK.IKSolver // Base method: System.Void IKSolver::FixTransforms() void FixTransforms(); // public override RootMotion.FinalIK.IKSolver/Point[] GetPoints() // Offset: 0x133DEC8 // Implemented from: RootMotion.FinalIK.IKSolver // Base method: RootMotion.FinalIK.IKSolver/Point[] IKSolver::GetPoints() ::Array<RootMotion::FinalIK::IKSolver::Point*>* GetPoints(); // public override RootMotion.FinalIK.IKSolver/Point GetPoint(UnityEngine.Transform transform) // Offset: 0x133DF3C // Implemented from: RootMotion.FinalIK.IKSolver // Base method: RootMotion.FinalIK.IKSolver/Point IKSolver::GetPoint(UnityEngine.Transform transform) RootMotion::FinalIK::IKSolver::Point* GetPoint(UnityEngine::Transform* transform); // public override System.Boolean IsValid(System.String message) // Offset: 0x133DFB0 // Implemented from: RootMotion.FinalIK.IKSolver // Base method: System.Boolean IKSolver::IsValid(System.String message) bool IsValid(::Il2CppString*& message); // protected override System.Void OnInitiate() // Offset: 0x133E4B0 // Implemented from: RootMotion.FinalIK.IKSolver // Base method: System.Void IKSolver::OnInitiate() void OnInitiate(); // protected override System.Void OnUpdate() // Offset: 0x133E4F8 // Implemented from: RootMotion.FinalIK.IKSolver // Base method: System.Void IKSolver::OnUpdate() void OnUpdate(); // public System.Void .ctor() // Offset: 0x1340684 // Implemented from: RootMotion.FinalIK.IKSolver // Base method: System.Void IKSolver::.ctor() // Base method: System.Void Object::.ctor() static IKSolverVR* New_ctor(); }; // RootMotion.FinalIK.IKSolverVR } DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::IKSolverVR*, "RootMotion.FinalIK", "IKSolverVR"); #pragma pack(pop)
45.342007
226
0.729852
Futuremappermydud
6a39cf622bf398dc2d2cc623f01369fb5a6fd9f8
405
cpp
C++
cpp/beginner_contest_154/c.cpp
kitoko552/atcoder
a1e18b6d855baefb90ae6df010bcf1ffa8ff5562
[ "MIT" ]
1
2020-03-31T05:53:38.000Z
2020-03-31T05:53:38.000Z
cpp/beginner_contest_154/c.cpp
kitoko552/atcoder
a1e18b6d855baefb90ae6df010bcf1ffa8ff5562
[ "MIT" ]
null
null
null
cpp/beginner_contest_154/c.cpp
kitoko552/atcoder
a1e18b6d855baefb90ae6df010bcf1ffa8ff5562
[ "MIT" ]
null
null
null
// https://atcoder.jp/contests/abc154/tasks/abc154_c #include<iostream> using namespace std; int main() { int N; cin >> N; int A[N]; for (int i = 0; i < N; i++) { cin >> A[i]; } sort(A, A + N); string ans = "YES"; for (int i = 0; i < N - 1; i++) { if (A[i] == A[i+1]) { ans = "NO"; } } cout << ans << endl; return 0; }
15
52
0.419753
kitoko552
6a3c03312997bc4325a4dc78961ed30277123281
8,319
cpp
C++
src/behaviortree/nodes/composites/referencebehavior.cpp
pjkui/behaviac_2.0.7
db4bec559c184c4af125005bf07bc0b25e2c6e66
[ "BSD-3-Clause" ]
null
null
null
src/behaviortree/nodes/composites/referencebehavior.cpp
pjkui/behaviac_2.0.7
db4bec559c184c4af125005bf07bc0b25e2c6e66
[ "BSD-3-Clause" ]
null
null
null
src/behaviortree/nodes/composites/referencebehavior.cpp
pjkui/behaviac_2.0.7
db4bec559c184c4af125005bf07bc0b25e2c6e66
[ "BSD-3-Clause" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed under the License is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "behaviac/base/base.h" #include "behaviac/behaviortree/nodes/composites/referencebehavior.h" #include "behaviac/agent/agent.h" #include "behaviac/agent/taskmethod.h" #include "behaviac/behaviortree/nodes/actions/action.h" #include "behaviac/htn/planner.h" #include "behaviac/htn/plannertask.h" #include "behaviac/htn/task.h" #include "behaviac/fsm/state.h" #include "behaviac/fsm/transitioncondition.h" namespace behaviac { ReferencedBehavior::ReferencedBehavior() : m_taskNode(0), m_taskMethod(0), m_transitions(0) {} ReferencedBehavior::~ReferencedBehavior() { BEHAVIAC_DELETE this->m_transitions; } void ReferencedBehavior::load(int version, const char* agentType, const properties_t& properties) { super::load(version, agentType, properties); for (propertie_const_iterator_t it = properties.begin(); it != properties.end(); ++it) { const property_t& p = (*it); if (strcmp(p.name, "ReferenceFilename") == 0) { this->m_referencedBehaviorPath = p.value; bool bOk = Workspace::GetInstance()->Load(this->m_referencedBehaviorPath.c_str()); BEHAVIAC_UNUSED_VAR(bOk); BEHAVIAC_ASSERT(bOk); } else if (strcmp(p.name, "Task") == 0) { BEHAVIAC_ASSERT(!StringUtils::IsNullOrEmpty(p.value)); CMethodBase* m = Action::LoadMethod(p.value); //BEHAVIAC_ASSERT(m is CTaskMethod); this->m_taskMethod = (CTaskMethod*)m; } else { //BEHAVIAC_ASSERT(0, "unrecognised property %s", p.name); } } } bool ReferencedBehavior::decompose(BehaviorNode* node, PlannerTaskComplex* seqTask, int depth, Planner* planner) { bool bOk = false; ReferencedBehavior* taskSubTree = (ReferencedBehavior*)node;// as ReferencedBehavior; BEHAVIAC_ASSERT(taskSubTree != 0); int depth2 = planner->GetAgent()->m_variables.Depth(); BEHAVIAC_UNUSED_VAR(depth2); { AgentState::AgentStateScope scopedState(planner->GetAgent()->m_variables.Push(false)); //planner.agent.Variables.Log(planner.agent, true); taskSubTree->SetTaskParams(planner->GetAgent()); Task* task = taskSubTree->RootTaskNode(); if (task != 0) { planner->LogPlanReferenceTreeEnter(planner->GetAgent(), taskSubTree); const BehaviorNode* tree = task->GetParent(); tree->InstantiatePars(planner->GetAgent()); PlannerTask* childTask = planner->decomposeNode(task, depth); if (childTask != 0) { seqTask->AddChild(childTask); bOk = true; } tree->UnInstantiatePars(planner->GetAgent()); planner->LogPlanReferenceTreeExit(planner->GetAgent(), taskSubTree); BEHAVIAC_ASSERT(true); } } BEHAVIAC_ASSERT(planner->GetAgent()->m_variables.Depth() == depth2); return bOk; } void ReferencedBehavior::Attach(BehaviorNode* pAttachment, bool bIsPrecondition, bool bIsEffector, bool bIsTransition) { if (bIsTransition) { BEHAVIAC_ASSERT(!bIsEffector && !bIsPrecondition); if (this->m_transitions == 0) { this->m_transitions = BEHAVIAC_NEW behaviac::vector<Transition*>(); } BEHAVIAC_ASSERT(Transition::DynamicCast(pAttachment) != 0); Transition* pTransition = (Transition*)pAttachment; this->m_transitions->push_back(pTransition); return; } BEHAVIAC_ASSERT(bIsTransition == false); super::Attach(pAttachment, bIsPrecondition, bIsEffector, bIsTransition); } bool ReferencedBehavior::IsValid(Agent* pAgent, BehaviorTask* pTask) const { if (!ReferencedBehavior::DynamicCast(pTask->GetNode())) { return false; } return super::IsValid(pAgent, pTask); } BehaviorTask* ReferencedBehavior::createTask() const { ReferencedBehaviorTask* pTask = BEHAVIAC_NEW ReferencedBehaviorTask(); return pTask; } void ReferencedBehavior::SetTaskParams(Agent* pAgent) { if (this->m_taskMethod != 0) { this->m_taskMethod->SetTaskParams(pAgent); } } Task* ReferencedBehavior::RootTaskNode() { if (this->m_taskNode == 0) { BehaviorTree* bt = Workspace::GetInstance()->LoadBehaviorTree(this->m_referencedBehaviorPath.c_str()); if (bt != 0 && bt->GetChildrenCount() == 1) { BehaviorNode* root = (BehaviorNode*)bt->GetChild(0); this->m_taskNode = (Task*)root; } } return this->m_taskNode; } const char* ReferencedBehavior::GetReferencedTree() const { return this->m_referencedBehaviorPath.c_str(); } ReferencedBehaviorTask::ReferencedBehaviorTask() : SingeChildTask(), m_nextStateId(-1), m_subTree(0) { } ReferencedBehaviorTask::~ReferencedBehaviorTask() { } void ReferencedBehaviorTask::copyto(BehaviorTask* target) const { super::copyto(target); // BEHAVIAC_ASSERT(ReferencedBehaviorTask::DynamicCast(target)); // ReferencedBehaviorTask* ttask = (ReferencedBehaviorTask*)target; } void ReferencedBehaviorTask::save(ISerializableNode* node) const { super::save(node); } void ReferencedBehaviorTask::load(ISerializableNode* node) { super::load(node); } void ReferencedBehaviorTask::Init(const BehaviorNode* node) { super::Init(node); } bool ReferencedBehaviorTask::onenter(Agent* pAgent) { BEHAVIAC_UNUSED_VAR(pAgent); BEHAVIAC_ASSERT(ReferencedBehavior::DynamicCast(this->m_node) != 0); ReferencedBehavior* pNode = (ReferencedBehavior*)this->m_node; BEHAVIAC_ASSERT(pNode != 0); this->m_nextStateId = -1; pNode->SetTaskParams(pAgent); this->m_subTree = Workspace::GetInstance()->CreateBehaviorTreeTask(pNode->m_referencedBehaviorPath.c_str()); { const char* pThisTree = pAgent->btgetcurrent()->GetName().c_str(); const char* pReferencedTree = pNode->m_referencedBehaviorPath.c_str(); behaviac::string msg = FormatString("%s[%d] %s", pThisTree, pNode->GetId(), pReferencedTree); LogManager::GetInstance()->Log(pAgent, msg.c_str(), EAR_none, ELM_jump); } return true; } void ReferencedBehaviorTask::onexit(Agent* pAgent, EBTStatus s) { BEHAVIAC_UNUSED_VAR(pAgent); BEHAVIAC_UNUSED_VAR(s); } int ReferencedBehaviorTask::GetNextStateId() const { return this->m_nextStateId; } EBTStatus ReferencedBehaviorTask::update(Agent* pAgent, EBTStatus childStatus) { BEHAVIAC_UNUSED_VAR(childStatus); BEHAVIAC_ASSERT(ReferencedBehavior::DynamicCast(this->GetNode())); const ReferencedBehavior* pNode = (const ReferencedBehavior*)this->m_node; BEHAVIAC_ASSERT(pNode); EBTStatus result = this->m_subTree->exec(pAgent); bool bTransitioned = State::UpdateTransitions(pAgent, pNode, pNode->m_transitions, this->m_nextStateId); if (bTransitioned) { result = BT_SUCCESS; } return result; } }//namespace behaviac
31.392453
119
0.630484
pjkui
6a3d065597852b9a7f2a53df9617722c242192a7
1,169
cc
C++
src/linear/qr_unpack_pt.cc
Seeenman/Draco
8540aeb8bbbf467c3aa1caa9521d0910e0ca7917
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
src/linear/qr_unpack_pt.cc
Seeenman/Draco
8540aeb8bbbf467c3aa1caa9521d0910e0ca7917
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
src/linear/qr_unpack_pt.cc
Seeenman/Draco
8540aeb8bbbf467c3aa1caa9521d0910e0ca7917
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
//--------------------------------------------*-C++-*---------------------------------------------// /*! * \file linear/qr_unpack_pt.cc * \author Kent Budge * \date Wed Aug 11 15:21:38 2004 * \brief Specializations of qr_unpack * \note Copyright (C) 2016-2020 Triad National Security, LLC., All rights reserved. */ //------------------------------------------------------------------------------------------------// #include "qr_unpack.i.hh" #include <vector> namespace rtt_linear { using std::vector; //------------------------------------------------------------------------------------------------// // RandomContainer = vector<double> //------------------------------------------------------------------------------------------------// template void qr_unpack(vector<double> &r, const unsigned n, const vector<double> &c, const vector<double> &d, vector<double> &qt); } // end namespace rtt_linear //------------------------------------------------------------------------------------------------// // end of qr_unpack.cc //------------------------------------------------------------------------------------------------//
41.75
100
0.328486
Seeenman
6a455ed406a69917886c71789c57f47d9c9c50e2
1,246
hh
C++
enc_modules/crypto_mk/main/sha.hh
Tofuseng/Mylar
852bbeb27e077e36cdc561803d33bafa5dc795a9
[ "Apache-2.0" ]
240
2015-01-04T10:47:28.000Z
2022-03-17T10:50:34.000Z
enc_modules/crypto_mk/main/sha.hh
eternaltyro/mylar
18e9d0e6ef8fd836073c8bc47d79bb76c5405da5
[ "Apache-2.0" ]
8
2015-03-18T14:35:41.000Z
2017-04-11T06:01:41.000Z
enc_modules/crypto_mk/main/sha.hh
eternaltyro/mylar
18e9d0e6ef8fd836073c8bc47d79bb76c5405da5
[ "Apache-2.0" ]
42
2015-01-18T12:22:49.000Z
2022-01-20T04:21:47.000Z
#pragma once #include <openssl/sha.h> #include <string> template<class State, int OutBytes, int BlockBytes, int (*Init)(State*), int (*Update)(State*, const void*, size_t), int (*Final)(uint8_t*, State*)> class sha { public: sha() { Init(&s); } void update(const void *data, size_t len) { Update(&s, data, len); } void final(uint8_t *buf) { Final(buf, &s); } std::string final() { std::string v; v.resize(hashsize); final((uint8_t*) v.data()); return v; } static std::string hash(const std::string &s) { sha x; x.update(s.data(), s.length()); return x.final(); } static const size_t hashsize = OutBytes; static const size_t blocksize = BlockBytes; private: State s; }; typedef sha<SHA_CTX, 20, 64, SHA1_Init, SHA1_Update, SHA1_Final> sha1; typedef sha<SHA256_CTX, 28, 64, SHA224_Init, SHA224_Update, SHA224_Final> sha224; typedef sha<SHA256_CTX, 32, 64, SHA256_Init, SHA256_Update, SHA256_Final> sha256; typedef sha<SHA512_CTX, 48, 128, SHA384_Init, SHA384_Update, SHA384_Final> sha384; typedef sha<SHA512_CTX, 64, 128, SHA512_Init, SHA512_Update, SHA512_Final> sha512;
27.086957
82
0.62199
Tofuseng
6a46229abe2ea1c1b2f81fa77e92a668d6ba487e
4,336
cc
C++
lib/ts/ConsistentHash.cc
garfieldonly/ats_git
940ff5c56bebabb96130a55c2a17212c5c518138
[ "Apache-2.0" ]
1
2022-01-19T14:34:34.000Z
2022-01-19T14:34:34.000Z
lib/ts/ConsistentHash.cc
mingzym/trafficserver
a01c3a357b4ff9193f2e2a8aee48e3751ef2177a
[ "Apache-2.0" ]
2
2017-12-05T23:48:37.000Z
2017-12-20T01:22:07.000Z
lib/ts/ConsistentHash.cc
maskit/trafficserver
3ffa19873f7cd7ced2fbdfed5a0ac8ddbbe70a68
[ "Apache-2.0" ]
null
null
null
/** @file @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ #include "ConsistentHash.h" #include <cstring> #include <string> #include <sstream> #include <cmath> #include <climits> #include <cstdio> std::ostream &operator<<(std::ostream &os, ATSConsistentHashNode &thing) { return os << thing.name; } ATSConsistentHash::ATSConsistentHash(int r, ATSHash64 *h) : replicas(r), hash(h) { } void ATSConsistentHash::insert(ATSConsistentHashNode *node, float weight, ATSHash64 *h) { int i; char numstr[256]; ATSHash64 *thash; std::ostringstream string_stream; std::string std_string; if (h) { thash = h; } else if (hash) { thash = hash; } else { return; } string_stream << *node; std_string = string_stream.str(); for (i = 0; i < (int)roundf(replicas * weight); i++) { snprintf(numstr, 256, "%d-", i); thash->update(numstr, strlen(numstr)); thash->update(std_string.c_str(), strlen(std_string.c_str())); thash->final(); NodeMap.insert(std::pair<uint64_t, ATSConsistentHashNode *>(thash->get(), node)); thash->clear(); } } ATSConsistentHashNode * ATSConsistentHash::lookup(const char *url, ATSConsistentHashIter *i, bool *w, ATSHash64 *h) { uint64_t url_hash; ATSConsistentHashIter NodeMapIterUp, *iter; ATSHash64 *thash; bool *wptr, wrapped = false; if (h) { thash = h; } else if (hash) { thash = hash; } else { return NULL; } if (w) { wptr = w; } else { wptr = &wrapped; } if (i) { iter = i; } else { iter = &NodeMapIterUp; } if (url) { thash->update(url, strlen(url)); thash->final(); url_hash = thash->get(); thash->clear(); *iter = NodeMap.lower_bound(url_hash); if (*iter == NodeMap.end()) { *wptr = true; *iter = NodeMap.begin(); } } else { (*iter)++; } if (!(*wptr) && *iter == NodeMap.end()) { *wptr = true; *iter = NodeMap.begin(); } if (*wptr && *iter == NodeMap.end()) { return NULL; } return (*iter)->second; } ATSConsistentHashNode * ATSConsistentHash::lookup_available(const char *url, ATSConsistentHashIter *i, bool *w, ATSHash64 *h) { uint64_t url_hash; ATSConsistentHashIter NodeMapIterUp, *iter; ATSHash64 *thash; bool *wptr, wrapped = false; if (h) { thash = h; } else if (hash) { thash = hash; } else { return NULL; } if (w) { wptr = w; } else { wptr = &wrapped; } if (i) { iter = i; } else { iter = &NodeMapIterUp; } if (url) { thash->update(url, strlen(url)); thash->final(); url_hash = thash->get(); thash->clear(); *iter = NodeMap.lower_bound(url_hash); } if (*iter == NodeMap.end()) { *wptr = true; *iter = NodeMap.begin(); } while (!(*iter)->second->available) { (*iter)++; if (!(*wptr) && *iter == NodeMap.end()) { *wptr = true; *iter = NodeMap.begin(); } else if (*wptr && *iter == NodeMap.end()) { return NULL; } } return (*iter)->second; } ATSConsistentHashNode * ATSConsistentHash::lookup_by_hashval(uint64_t hashval, ATSConsistentHashIter *i, bool *w) { ATSConsistentHashIter NodeMapIterUp, *iter; bool *wptr, wrapped = false; if (w) { wptr = w; } else { wptr = &wrapped; } if (i) { iter = i; } else { iter = &NodeMapIterUp; } *iter = NodeMap.lower_bound(hashval); if (*iter == NodeMap.end()) { *wptr = true; *iter = NodeMap.begin(); } return (*iter)->second; } ATSConsistentHash::~ATSConsistentHash() { if (hash) { delete hash; } }
20.167442
101
0.622232
garfieldonly
6a466d6900d1e788292c0df3476c873f631e4f2d
974
hxx
C++
libstudxml/libstudxml/details/config.hxx
pdpdds/yuza_thirdparty
461b7481322df4f1c3f0d258c1b4ea4bad16f10c
[ "MIT" ]
null
null
null
libstudxml/libstudxml/details/config.hxx
pdpdds/yuza_thirdparty
461b7481322df4f1c3f0d258c1b4ea4bad16f10c
[ "MIT" ]
null
null
null
libstudxml/libstudxml/details/config.hxx
pdpdds/yuza_thirdparty
461b7481322df4f1c3f0d258c1b4ea4bad16f10c
[ "MIT" ]
null
null
null
// file : libstudxml/details/config.hxx // license : MIT; see accompanying LICENSE file #ifndef LIBSTUDXML_DETAILS_CONFIG_HXX #define LIBSTUDXML_DETAILS_CONFIG_HXX // C++11 support. // #ifdef _MSC_VER # if _MSC_VER >= 1900 # define STUDXML_CXX11_NOEXCEPT # endif #else # if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L # ifdef __clang__ // Pretends to be a really old __GNUC__ on some platforms. # define STUDXML_CXX11_NOEXCEPT # elif defined(__GNUC__) # if (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) || __GNUC__ > 4 # define STUDXML_CXX11_NOEXCEPT # endif # else # define STUDXML_CXX11_NOEXCEPT # endif # endif #endif #ifdef STUDXML_CXX11_NOEXCEPT # define STUDXML_NOTHROW_NOEXCEPT noexcept #else # define STUDXML_NOTHROW_NOEXCEPT throw() #endif #ifdef _MSC_VER # include <libstudxml/details/config-vc.h> #else # include <libstudxml/details/config.h> #endif #endif // LIBSTUDXML_DETAILS_CONFIG_HXX
24.35
79
0.732033
pdpdds
6a4683a580bb07722e090ae5df87a17cfeb87fff
378
cpp
C++
archive/codevs.6061.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
archive/codevs.6061.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
archive/codevs.6061.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
#include <cstdio> using namespace std; int n,r,a[30]; bool x; void dfs(int deep,int temp){ if(deep==r){ for(int i=0;i<r;i++) printf("%3d",a[i]); printf("\n"); } else for(int i=1;i<=n;i++){ x=false; for(int j=0;j<deep;j++){ if(a[j]==i) x=true; } if(x) continue; a[deep]=i; dfs(deep+1,i); a[deep]=0; } } int main(){ scanf("%d%d",&n,&r); dfs(0,0); }
13.034483
42
0.521164
woshiluo
6a46a21f962427727c4faf617fcf83a19d2e221a
3,405
cpp
C++
test/test_connection_adapter.cpp
iTuMaN4iK/asio_utils
2182f14f46bdd3ab96cccf038ad925bf9b83e55f
[ "MIT" ]
null
null
null
test/test_connection_adapter.cpp
iTuMaN4iK/asio_utils
2182f14f46bdd3ab96cccf038ad925bf9b83e55f
[ "MIT" ]
null
null
null
test/test_connection_adapter.cpp
iTuMaN4iK/asio_utils
2182f14f46bdd3ab96cccf038ad925bf9b83e55f
[ "MIT" ]
null
null
null
 #include "asio_utils/connection_adapter.hpp" #include "asio_utils/testing/stub_connection.h" #include <asio.hpp> #include <gtest/gtest.h> #include <cstdint> #include <numeric> #include <vector> namespace e_testing = eld::testing; template<typename ConnectionT> class connection_wrapper { public: using connection_type = ConnectionT; using config_type = typename eld::traits::connection<connection_type>::config_type; explicit connection_wrapper(connection_type &connection) // : connection_(connection) { } template<typename ConstBuffer, typename CompletionT> auto async_send(ConstBuffer &&constBuffer, CompletionT &&a_completion) { return connection_.async_send(std::forward<ConstBuffer>(constBuffer), std::forward<CompletionT>(a_completion)); } template<typename ConstBuffer, typename CompletionT> auto async_receive(ConstBuffer &&constBuffer, CompletionT &&a_completion) { return connection_.async_receive(std::forward<ConstBuffer>(constBuffer), std::forward<CompletionT>(a_completion)); } void configure(const config_type &config) { connection_.configure(config); } config_type get_config() const { return connection_.get_config(); } void cancel() { connection_.cancel(); } private: connection_type &connection_; }; template<typename ConnectionT> connection_wrapper<ConnectionT> wrap_connection(ConnectionT &connection) { return connection_wrapper<ConnectionT>(connection); } /* * destination (to emulate receiving) -> source -> adapter -> destination -> source (to emulate * sending) * 1. make connections * 2. make wrappers to send and receive * 3. make adapter from wrappers * 4. send data with future * 5. wait for data with future * 6. compare data */ TEST(connection_adapter, stub_connection) { using namespace e_testing; std::vector<uint32_t> send(size_t(512)), // receive(size_t(512)); std::iota(send.begin(), send.end(), 0); asio::thread_pool context{ 2 }; stub_connection connectionSourceRemote{ context, stub_config{ 0, 1 } }, connectionSource{ context, stub_config{ 1, 2 } }, connectionDest{ context, stub_config{ 2, 3 } }, connectionDestRemote{ context, stub_config{ 3, 4 } }; connectionSourceRemote.set_remote_host(connectionSource); connectionDest.set_remote_host(connectionDestRemote); { auto adapter = eld::make_connection_adapter(wrap_connection(connectionSource), wrap_connection(connectionDest)); adapter.async_run(eld::direction::a_to_b, [](const asio::error_code &errorCode) { // EXPECT_EQ(errorCode, asio::error_code()); }); auto futureSent = connectionSourceRemote.async_send(asio::buffer(send), asio::use_future); auto futureReceive = connectionDestRemote.async_receive(asio::buffer(receive), asio::use_future); // why does future not block on destruction? futureSent.get(); futureReceive.get(); } std::cout << "end of receiving data" << std::endl; ASSERT_EQ(send, receive); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
30.675676
98
0.666079
iTuMaN4iK
6a489ef252197c20397dd7704bc0fe8677956fbe
2,395
cpp
C++
Cappuccino/src/Cappuccino/AnimationSystem.cpp
Promethaes/CappuccinoEngine
e0e2dacaf14c8176d4fbc0d85645783e364a06a4
[ "MIT" ]
5
2019-10-25T11:51:08.000Z
2020-01-09T00:56:24.000Z
Cappuccino/src/Cappuccino/AnimationSystem.cpp
Promethaes/CappuccinoEngine
e0e2dacaf14c8176d4fbc0d85645783e364a06a4
[ "MIT" ]
145
2019-09-10T18:33:49.000Z
2020-02-02T09:59:23.000Z
Cappuccino/src/Cappuccino/AnimationSystem.cpp
Promethaes/CappuccinoEngine
e0e2dacaf14c8176d4fbc0d85645783e364a06a4
[ "MIT" ]
null
null
null
#include "Cappuccino/AnimationSystem.h" #include "Cappuccino/CappMath.h" #include "glm/common.hpp" #include "glm/gtx/compatibility.hpp" namespace Cappuccino { std::vector<Animation*> Animation::_allAnimations = {}; Animation::Animation(const std::vector<Mesh*>& keyFrames, AnimationType type) : _type(type) { _keyFrames = keyFrames; _allAnimations.push_back(this); } float Animation::play(float dt) { if (_animationShader == nullptr) { printf("Animation shader not set! animations cannot be played!\n"); return -1.0f; } _animationShader->use(); if (!_shouldPlay) return -1.0f; if (t == 0.0f) _keyFrames[0]->animationFunction(*_keyFrames[index], _shouldPlay); t += dt * _speed; //_animationShader->setUniform("dt",t); if (t >= 1.0f) { t = 0.0f; _keyFrames[0]->_VBO = _keyFrames[index]->_VBO; index++; if (index > _keyFrames.size() - 1) { if (!_loop) _shouldPlay = false; index = 1; _keyFrames[0]->resetVertAttribPointers(); } } return t; } float Animator::_dt = 0.0f; Animator::Animator() { for (unsigned i = 0; i < (int)AnimationType::NumTypes; i++) _animations.push_back(nullptr); } void Animator::update(float dt) { _dt = dt; for (auto x : _animations) { if (x != nullptr && x->_shouldPlay) { _currentT = x->play(dt); break; } } } void Animator::addAnimation(Animation* animation) { _animations[(int)animation->getAnimationType()] = animation; } void Animator::playAnimation(AnimationType type) { _animations[(int)type]->_shouldPlay = true; _playingAnimation = true; } bool Animator::isPlaying(AnimationType type) { return _animations[(int)type]->_shouldPlay; } void Animator::setAnimationShader(AnimationType type, Shader* shader) { _animations[(int)type]->_animationShader = shader; } void Animator::clearAnimation(AnimationType type) { delete _animations[(int)type]; _animations[(int)type] = nullptr; } void Animator::setLoop(AnimationType type, bool yn) { _animations[(int)type]->setLoop(yn); } void Animator::setSpeed(AnimationType type, float speed) { _animations[(int)type]->setSpeed(speed); } bool Animator::animationExists(AnimationType type) { if (_animations[(int)type] != nullptr) return true; return false; } }
23.480392
79
0.650104
Promethaes
6a4956bcd6605b90e344f1b9889139e3abca2933
359
cpp
C++
AirFloat/NotificationObserver.cpp
davhelm/AirFloat
460a97d57f9adf3372093e1e62a38b726ab08737
[ "Unlicense" ]
2
2015-07-20T17:09:11.000Z
2017-02-05T11:08:34.000Z
AirFloat/NotificationObserver.cpp
davhelm/AirFloat
460a97d57f9adf3372093e1e62a38b726ab08737
[ "Unlicense" ]
null
null
null
AirFloat/NotificationObserver.cpp
davhelm/AirFloat
460a97d57f9adf3372093e1e62a38b726ab08737
[ "Unlicense" ]
null
null
null
// // NotificationReceiver.cpp // AirFloat // // Created by Kristian Trenskow on 2/8/12. // Copyright (c) 2012 The Famous Software Company. All rights reserved. // #include "NotificationCenter.h" #include "NotificationObserver.h" NotificationObserver::~NotificationObserver() { NotificationCenter::defaultCenter()->removeObserver(this); }
21.117647
72
0.724234
davhelm
c69957b1b1efa65a9407875a3c1ac25975b74583
5,132
cpp
C++
Roguelike/Code/Game/Stats.cpp
cugone/Roguelike
0f53a1ae2a37e683773c1707ce4aeb056973af13
[ "MIT" ]
null
null
null
Roguelike/Code/Game/Stats.cpp
cugone/Roguelike
0f53a1ae2a37e683773c1707ce4aeb056973af13
[ "MIT" ]
4
2021-05-04T03:21:49.000Z
2021-10-06T05:21:24.000Z
Roguelike/Code/Game/Stats.cpp
cugone/Roguelike
0f53a1ae2a37e683773c1707ce4aeb056973af13
[ "MIT" ]
2
2020-01-19T00:50:34.000Z
2021-04-01T07:51:02.000Z
#include "Game/Stats.hpp" #include <type_traits> StatsID& operator++(StatsID& a) { using underlying = std::underlying_type_t<StatsID>; a = static_cast<StatsID>(static_cast<underlying>(a) + 1); return a; } StatsID operator++(StatsID& a, int) { auto result = a; ++a; return result; } StatsID& operator--(StatsID& a) { using underlying = std::underlying_type_t<StatsID>; a = static_cast<StatsID>(static_cast<underlying>(a) - 1); return a; } StatsID operator--(StatsID& a, int) { auto result = a; --a; return result; } Stats Stats::operator+(const Stats& rhs) const { auto result = *this; result += rhs; return result; } Stats& Stats::operator+=(const Stats& rhs) { for(auto id = StatsID::First_; id != StatsID::Last_; ++id) { AdjustStat(id, rhs.GetStat(id)); } return *this; } Stats Stats::operator-(const Stats& rhs) const { auto result = *this; result -= rhs; return result; } Stats& Stats::operator-=(const Stats& rhs) { for(auto id = StatsID::First_; id != StatsID::Last_; ++id) { AdjustStat(id, -rhs.GetStat(id)); } return *this; } Stats Stats::operator-() { auto result = *this; for(auto id = StatsID::First_; id != StatsID::Last_; ++id) { result.SetStat(id, -result.GetStat(id)); } return result; } Stats::Stats(const XMLElement& elem) { DataUtils::ValidateXmlElement(elem, "stats", "", "", "level,health,attack,defense,speed,accuracy,evasion,luck,experience"); if(auto* xml_level = elem.FirstChildElement("level")) { auto id = StatsID::Level; auto default_value = GetStat(id); auto value = DataUtils::ParseXmlElementText(*xml_level, default_value); SetStat(id, value); } else { auto value = 1L; SetStat(StatsID::Level, value); } if(auto* xml_health = elem.FirstChildElement("health")) { auto id = StatsID::Health; auto default_value = GetStat(id); auto value = DataUtils::ParseXmlElementText(*xml_health, default_value); SetStat(id, value); SetStat(StatsID::Health_Max, value); } else { auto value = 1L; SetStat(StatsID::Health, value); SetStat(StatsID::Health_Max, value); } if(auto* xml_attack = elem.FirstChildElement("attack")) { auto id = StatsID::Attack; auto default_value = GetStat(id); auto value = DataUtils::ParseXmlElementText(*xml_attack, default_value); SetStat(id, value); } if(auto* xml_defense = elem.FirstChildElement("defense")) { auto id = StatsID::Defense; auto default_value = GetStat(id); auto value = DataUtils::ParseXmlElementText(*xml_defense, default_value); SetStat(id, value); } if(auto* xml_speed = elem.FirstChildElement("speed")) { auto id = StatsID::Speed; auto default_value = GetStat(id); auto value = DataUtils::ParseXmlElementText(*xml_speed, default_value); SetStat(id, value); } if(auto* xml_evasion = elem.FirstChildElement("evasion")) { auto id = StatsID::Evasion; auto default_value = GetStat(id); auto value = DataUtils::ParseXmlElementText(*xml_evasion, default_value); SetStat(id, value); } if(auto* xml_luck = elem.FirstChildElement("luck")) { auto id = StatsID::Luck; auto default_value = GetStat(id); auto value = DataUtils::ParseXmlElementText(*xml_luck, default_value); SetStat(id, value); } else { auto value = 5L; SetStat(StatsID::Luck, value); } if(auto* xml_experience = elem.FirstChildElement("experience")) { auto id = StatsID::Experience; auto default_value = GetStat(id); auto value = DataUtils::ParseXmlElementText(*xml_experience, default_value); SetStat(id, value); } } Stats::Stats(std::initializer_list<decltype(_stats)::value_type> l) { auto id = StatsID::First_; for(const auto value : l) { if(id < StatsID::Last_) { SetStat(id++, value); } } for(; id != StatsID::Last_; ++id) { SetStat(id, decltype(_stats)::value_type{0}); } } auto Stats::GetStat(const StatsID& id) const noexcept -> decltype(_stats)::value_type{ return _stats[static_cast<std::size_t>(id)]; } void Stats::SetStat(const StatsID& id, decltype(_stats)::value_type value) noexcept { _stats[static_cast<std::size_t>(id)] = value; } decltype(Stats::_stats)::value_type Stats::AdjustStat(const StatsID& id, long value) noexcept { const auto i = static_cast<std::size_t>(id); _stats[i] += static_cast<decltype(_stats)::value_type>(value); return _stats[i]; } decltype(Stats::_stats)::value_type Stats::MultiplyStat(const StatsID& id, long double value) noexcept { const auto i = static_cast<std::size_t>(id); _stats[i] *= static_cast<decltype(_stats)::value_type>(std::floor(value)); return _stats[i]; }
32.687898
128
0.614186
cugone
c69a15080bf83cc00e321cffcbdd269a2804af65
527
cpp
C++
CodeChef/MOU2H/Mountain Holidays 2.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
2
2018-02-24T06:45:56.000Z
2018-05-29T04:47:39.000Z
CodeChef/MOU2H/Mountain Holidays 2.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
null
null
null
CodeChef/MOU2H/Mountain Holidays 2.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
2
2018-06-28T09:53:27.000Z
2022-03-23T13:29:57.000Z
#include <bits/stdc++.h> using namespace std; typedef long long LL; const LL maxn=2123456,mod=1e9+9; LL t,n,i,m,a[maxn],v[maxn*4],dp[maxn]; int main(){ scanf("%lld",&t); while(t--){ scanf("%lld",&n); for(i=1;i<=n;i++) scanf("%lld",&a[i]); for(i=1,m=0;i<n;i++) a[i]=a[i+1]-a[i],m=min(m,a[i]); for(i=1;i<n;i++) a[i]-=m,v[a[i]]=-1; for(i=1;i<n;i++){ if(~v[a[i]]) dp[i]=(dp[i-1]*2-dp[v[a[i]]-1]+mod)%mod; else dp[i]=(dp[i-1]*2+1)%mod; v[a[i]]=i; } printf("%lld\n",dp[n-1]); } return 0; }
20.269231
44
0.493359
QAQrz
c69c8c79208ac5ee51f1c4b3c8baf7183842b2f8
12,448
cc
C++
src/mem/dtu/mem_unit.cc
utcs-scea/gem5-dtu
0922df0e8f47fe3bd2fbad9f57b1b855181c64dd
[ "BSD-3-Clause" ]
3
2016-03-23T09:21:51.000Z
2019-07-22T22:07:26.000Z
src/mem/dtu/mem_unit.cc
TUD-OS/gem5-dtu
0922df0e8f47fe3bd2fbad9f57b1b855181c64dd
[ "BSD-3-Clause" ]
null
null
null
src/mem/dtu/mem_unit.cc
TUD-OS/gem5-dtu
0922df0e8f47fe3bd2fbad9f57b1b855181c64dd
[ "BSD-3-Clause" ]
6
2018-01-01T02:15:26.000Z
2021-11-03T10:54:04.000Z
/* * Copyright (c) 2015, Christian Menard * Copyright (c) 2015, Nils Asmussen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ #include "debug/Dtu.hh" #include "debug/DtuBuf.hh" #include "debug/DtuPackets.hh" #include "debug/DtuSysCalls.hh" #include "mem/dtu/mem_unit.hh" #include "mem/dtu/xfer_unit.hh" #include "mem/dtu/noc_addr.hh" static uint cmdToXferFlags(uint flags) { return flags & 1; } static uint cmdToNocFlags(uint flags) { return flags & 1; } static uint nocToXferFlags(uint flags) { return flags & 3; } static uint xferToNocFlags(uint flags) { return flags & 3; } static void finishReadWrite(Dtu &dtu, Addr size) { // change data register accordingly DataReg data = dtu.regs().getDataReg(); data.size -= size; data.addr += size; dtu.regs().setDataReg(data); // change command register Dtu::Command::Bits cmd = dtu.regs().get(CmdReg::COMMAND); cmd.arg = cmd.arg + size; dtu.regs().set(CmdReg::COMMAND, cmd); } void MemoryUnit::regStats() { readBytes .init(8) .name(dtu.name() + ".mem.readBytes") .desc("Sent read requests (in bytes)") .flags(Stats::nozero); writtenBytes .init(8) .name(dtu.name() + ".mem.writtenBytes") .desc("Sent write requests (in bytes)") .flags(Stats::nozero); receivedBytes .init(8) .name(dtu.name() + ".mem.receivedBytes") .desc("Received read/write requests (in bytes)") .flags(Stats::nozero); wrongVPE .name(dtu.name() + ".mem.wrongVPE") .desc("Number of received requests that targeted the wrong VPE") .flags(Stats::nozero); } void MemoryUnit::startRead(const Dtu::Command::Bits& cmd) { MemEp ep = dtu.regs().getMemEp(cmd.epid); if(!(ep.flags & Dtu::MemoryFlags::READ)) { dtu.scheduleFinishOp(Cycles(1), Dtu::Error::INV_EP); return; } DataReg data = dtu.regs().getDataReg(); Addr offset = cmd.arg; Addr size = std::min(static_cast<Addr>(data.size), dtu.maxNocPacketSize); readBytes.sample(size); DPRINTFS(Dtu, (&dtu), "\e[1m[rd -> %u]\e[0m at %#018lx+%#lx with EP%u into %#018lx:%lu\n", ep.targetCore, ep.remoteAddr, offset, cmd.epid, data.addr, size); if(size == 0) { dtu.scheduleFinishOp(Cycles(1), Dtu::Error::NONE); return; } // TODO error handling assert(size + offset >= size); assert(size + offset <= ep.remoteSize); NocAddr nocAddr(ep.targetCore, ep.remoteAddr + offset); uint flags = cmdToNocFlags(cmd.flags); if (dtu.coherent && !dtu.mmioRegion.contains(nocAddr.offset) && dtu.isMemPE(nocAddr.coreId)) { flags |= XferUnit::NOXLATE; auto xfer = new LocalReadTransferEvent(nocAddr.getAddr(), data.addr, size, flags); dtu.startTransfer(xfer, Cycles(1)); } else { auto pkt = dtu.generateRequest(nocAddr.getAddr(), size, MemCmd::ReadReq); dtu.sendNocRequest(Dtu::NocPacketType::READ_REQ, pkt, ep.vpeId, flags, dtu.commandToNocRequestLatency); } } void MemoryUnit::LocalReadTransferEvent::transferDone(Dtu::Error result) { Cycles delay(1); if (result != Dtu::Error::NONE) { dtu().scheduleFinishOp(delay, result); return; } uint wflags = flags() & ~XferUnit::NOXLATE; uint8_t *tmp = new uint8_t[size()]; memcpy(tmp, data(), size()); auto xfer = new LocalWriteTransferEvent(dest, tmp, size(), wflags); dtu().startTransfer(xfer, delay); } void MemoryUnit::LocalWriteTransferEvent::transferStart() { memcpy(data(), tmp, tmpSize); delete[] tmp; } void MemoryUnit::LocalWriteTransferEvent::transferDone(Dtu::Error result) { if (result == Dtu::Error::NONE) finishReadWrite(dtu(), tmpSize); dtu().scheduleFinishOp(Cycles(1), result); } void MemoryUnit::readComplete(const Dtu::Command::Bits& cmd, PacketPtr pkt, Dtu::Error error) { dtu.printPacket(pkt); const DataReg data = dtu.regs().getDataReg(); // since the transfer is done in steps, we can start after the header // delay here Cycles delay = dtu.ticksToCycles(pkt->headerDelay); if (error != Dtu::Error::NONE) { dtu.scheduleFinishOp(delay, error); return; } uint flags = cmdToXferFlags(cmd.flags); auto xfer = new ReadTransferEvent(data.addr, flags, pkt); dtu.startTransfer(xfer, delay); } void MemoryUnit::ReadTransferEvent::transferStart() { // here is also no additional delay, because we are doing that in // parallel and are already paying for it at other places memcpy(data(), pkt->getPtr<uint8_t>(), pkt->getSize()); } void MemoryUnit::ReadTransferEvent::transferDone(Dtu::Error result) { if (result == Dtu::Error::NONE) finishReadWrite(dtu(), pkt->getSize()); dtu().scheduleFinishOp(Cycles(1), result); dtu().freeRequest(pkt); } void MemoryUnit::startWrite(const Dtu::Command::Bits& cmd) { MemEp ep = dtu.regs().getMemEp(cmd.epid); if(!(ep.flags & Dtu::MemoryFlags::WRITE)) { dtu.scheduleFinishOp(Cycles(1), Dtu::Error::INV_EP); return; } DataReg data = dtu.regs().getDataReg(); Addr offset = cmd.arg; Addr size = std::min(static_cast<Addr>(data.size), dtu.maxNocPacketSize); writtenBytes.sample(size); DPRINTFS(Dtu, (&dtu), "\e[1m[wr -> %u]\e[0m at %#018lx+%#lx with EP%u from %#018lx:%lu\n", ep.targetCore, ep.remoteAddr, offset, cmd.epid, data.addr, size); if(size == 0) { dtu.scheduleFinishOp(Cycles(1), Dtu::Error::NONE); return; } // TODO error handling assert(ep.flags & Dtu::MemoryFlags::WRITE); assert(size + offset >= size); assert(size + offset <= ep.remoteSize); NocAddr dest(ep.targetCore, ep.remoteAddr + offset); uint flags = cmdToXferFlags(cmd.flags); auto xfer = new WriteTransferEvent( data.addr, size, flags, dest, ep.vpeId); dtu.startTransfer(xfer, Cycles(0)); } void MemoryUnit::WriteTransferEvent::transferDone(Dtu::Error result) { if (result != Dtu::Error::NONE) { dtu().scheduleFinishOp(Cycles(1), result); } else { auto pkt = dtu().generateRequest(dest.getAddr(), size(), MemCmd::WriteReq); memcpy(pkt->getPtr<uint8_t>(), data(), size()); Cycles delay = dtu().transferToNocLatency; dtu().printPacket(pkt); if (dtu().coherent && !dtu().mmioRegion.contains(dest.offset) && dtu().isMemPE(dest.coreId)) { uint rflags = (flags() & XferUnit::NOPF) | XferUnit::NOXLATE; auto xfer = new ReadTransferEvent(dest.getAddr(), rflags, pkt); dtu().startTransfer(xfer, delay); } else { Dtu::NocPacketType pktType; if (flags() & XferUnit::MESSAGE) pktType = Dtu::NocPacketType::MESSAGE; else pktType = Dtu::NocPacketType::WRITE_REQ; uint rflags = xferToNocFlags(flags()); dtu().setCommandSent(); dtu().sendNocRequest(pktType, pkt, vpeId, rflags, delay); } } } void MemoryUnit::writeComplete(const Dtu::Command::Bits& cmd, PacketPtr pkt, Dtu::Error error) { if (cmd.opcode == Dtu::Command::WRITE && error == Dtu::Error::NONE) finishReadWrite(dtu, pkt->getSize()); // we don't need to pay the payload delay here because the message // basically has no payload since we only receive an ACK back for // writing Cycles delay = dtu.ticksToCycles(pkt->headerDelay); dtu.scheduleFinishOp(delay, error); dtu.freeRequest(pkt); } void MemoryUnit::recvFunctionalFromNoc(PacketPtr pkt) { // set the local address pkt->setAddr(NocAddr(pkt->getAddr()).offset); dtu.sendFunctionalMemRequest(pkt); } Dtu::Error MemoryUnit::recvFromNoc(PacketPtr pkt, uint vpeId, uint flags) { NocAddr addr(pkt->getAddr()); DPRINTFS(Dtu, (&dtu), "\e[1m[%s <- ?]\e[0m %#018lx:%lu\n", pkt->isWrite() ? "wr" : "rd", addr.offset, pkt->getSize()); if (pkt->isWrite()) dtu.printPacket(pkt); receivedBytes.sample(pkt->getSize()); uint16_t ourVpeId = dtu.regs().get(DtuReg::VPE_ID); if (vpeId != ourVpeId || (!(flags & Dtu::NocFlags::PRIV) && dtu.regs().hasFeature(Features::COM_DISABLED))) { DPRINTFS(Dtu, (&dtu), "Received memory request for VPE %u, but VPE %u is running with" " communication %sabled\n", vpeId, ourVpeId, dtu.regs().hasFeature(Features::COM_DISABLED) ? "dis" : "en"); wrongVPE++; dtu.sendNocResponse(pkt); return Dtu::Error::VPE_GONE; } if (dtu.mmioRegion.contains(addr.offset)) { pkt->setAddr(addr.offset); dtu.forwardRequestToRegFile(pkt, false); // as this is synchronous, we can restore the address right away pkt->setAddr(addr.getAddr()); } else { // the same as above: the transfer happens piece by piece and we can // start after the header Cycles delay = dtu.ticksToCycles(pkt->headerDelay); pkt->headerDelay = 0; auto type = pkt->isWrite() ? Dtu::TransferType::REMOTE_WRITE : Dtu::TransferType::REMOTE_READ; uint xflags = nocToXferFlags(flags); auto *ev = new ReceiveTransferEvent(type, addr.offset, xflags, pkt); dtu.startTransfer(ev, delay); } return Dtu::Error::NONE; } void MemoryUnit::ReceiveTransferEvent::transferStart() { if (pkt->isWrite()) { // here is also no additional delay, because we are doing that in // parallel and are already paying for it at other places memcpy(data(), pkt->getPtr<uint8_t>(), pkt->getSize()); } } void MemoryUnit::ReceiveTransferEvent::transferDone(Dtu::Error result) { // some requests from the cache (e.g. cleanEvict) do not need a // response if (pkt->needsResponse()) { pkt->makeResponse(); if (pkt->isRead()) memcpy(pkt->getPtr<uint8_t>(), data(), size()); // set result auto state = dynamic_cast<Dtu::NocSenderState*>(pkt->senderState); if (result != Dtu::Error::NONE && dtu().regs().hasFeature(Features::COM_DISABLED)) state->result = Dtu::Error::VPE_GONE; else state->result = result; Cycles delay = dtu().transferToNocLatency; dtu().schedNocResponse(pkt, dtu().clockEdge(delay)); } }
28.881671
89
0.612147
utcs-scea
c69ce88cf26e990cf6771127199b3a484be47fea
4,777
cpp
C++
Code/BellmanFord.cpp
RossieeyirouQian10/EE450-Lab1-Bellman-Ford-Algorithm
383afe5c57672350643e2c774c751e80e46da7a7
[ "MIT" ]
null
null
null
Code/BellmanFord.cpp
RossieeyirouQian10/EE450-Lab1-Bellman-Ford-Algorithm
383afe5c57672350643e2c774c751e80e46da7a7
[ "MIT" ]
null
null
null
Code/BellmanFord.cpp
RossieeyirouQian10/EE450-Lab1-Bellman-Ford-Algorithm
383afe5c57672350643e2c774c751e80e46da7a7
[ "MIT" ]
null
null
null
// // BellmanFord.cpp // LAB1 // // Created by 钱依柔 on 5/30/19. // Copyright © 2019 钱依柔. All rights reserved. // #include "BellmanFord.hpp" #include <iostream> #include <string> #include <cstring> #include <fstream> #include <sstream> #include <vector> #include <climits> #include <regex> #include <algorithm> #include <stdio.h> using namespace std; const int INF = INT_MAX; string srcFileName; // read in file vector<vector<int>> readFile(const string fileName){ vector<vector<int>> graph; ifstream inFile(fileName,ios::in); if(!inFile.is_open()){ cout << "File not found: " << fileName << endl; exit(0); } //get line in file to string string line; while (getline(inFile, line)){ if (line.length() < 2){ continue; } stringstream ss(line); string strIn; ss >> strIn; vector<int> vertex; while (strIn.length() > 0){ transform(strIn.begin(), strIn.end(), strIn.begin(), ::toupper); // store distance value if (strIn.compare("INF") == 0) { vertex.push_back(INF); }else{ // multi-cost case if (strIn[0] == '['){ int n1, n2, n3; sscanf(strIn.c_str(), "[%d,%d,%d]", &n1, &n2, &n3); vertex.push_back(n1 + n2 + n3); }else{ vertex.push_back(stoi(strIn.c_str())); } } strIn.clear(); ss >> strIn; } // store values into graph graph.push_back(vertex); } return graph; } // do Bellman-Ford algorithm void bellmanFord(vector<vector<int>> graph){ int numNode = (int)graph.size(); int count = 0; vector<int> distance; distance.push_back(0); //initialize the distance for (int i = 1; i < numNode; i++){ distance.push_back(INT_MAX); } //last node having done relax calcution vector<int> preNode(numNode, -1); bool distUpdate; //do relax and save the shortest distance value for (int i = 0; i < numNode - 1; i++){ distUpdate = false; count++; for (int j = 0; j < numNode; j++){ for (int k = 0; k < graph[j].size(); k ++){ if (graph[j][k] != INT_MAX && distance[j] != INT_MAX && distance[j] + graph[j][k] < distance[k]){ distance[k] = distance[j] + graph[j][k]; preNode[k] = j; distUpdate = true; } } } if (!distUpdate){ break; } } //detect negative loop count++; bool bFlag = false; for (int j = 0; j < numNode; j++){ if(bFlag){ break; } for (int k = 0; k < graph[j].size(); k++){ if (graph[j][k] != INT_MAX && distance[j] != INT_MAX && distance[j] + graph[j][k] < distance[k]){ bFlag = true; break; } } } // output file with result ofstream outFile; outFile.open("output-" + srcFileName, ios::out); if (bFlag){ outFile << "Negative Loop Detected" << endl; //show negative iteration path int nPre; string strOut; stringstream ssOut; nPre = preNode[0]; ssOut << nPre << "->" << 0; strOut = ssOut.str(); while (nPre){ nPre = preNode[nPre]; stringstream ssOut2; ssOut2 << nPre << "->" << strOut; strOut = ssOut2.str(); } outFile << strOut << endl; }else{ //show distance to each node outFile << distance[0]; for (int i = 1; i < numNode; i++){ outFile << "," << distance[i]; } outFile << endl << 0 << endl; //show non-negative iteration path int nPre; string strOut; for (int i = 1; i < numNode; i++){ stringstream ssOut; nPre = preNode[i]; ssOut << nPre << "->" << i; strOut = ssOut.str(); while (nPre){ nPre = preNode[nPre]; stringstream ssOut2; ssOut2 << nPre << "->" << strOut; strOut = ssOut2.str(); } outFile << strOut << endl; } // times of iteration outFile << "Iteration: " << count << endl; } outFile.close(); } int main(int argc, char **argv){ if (argc != 2){ return 0; } srcFileName = argv[1]; vector<vector<int>> newGraph = readFile(argv[1]); bellmanFord(newGraph); return 0; }
25.821622
113
0.472054
RossieeyirouQian10
c69f75aae8890928f2433c8430db872e7a77a6c0
17,472
cpp
C++
fsck/source/toolkit/FsckTkEx.cpp
congweitao/congfs
54cedf484f8a2cacab567fe182cc1f6413c25cf2
[ "BSD-3-Clause" ]
null
null
null
fsck/source/toolkit/FsckTkEx.cpp
congweitao/congfs
54cedf484f8a2cacab567fe182cc1f6413c25cf2
[ "BSD-3-Clause" ]
null
null
null
fsck/source/toolkit/FsckTkEx.cpp
congweitao/congfs
54cedf484f8a2cacab567fe182cc1f6413c25cf2
[ "BSD-3-Clause" ]
null
null
null
#include "FsckTkEx.h" #include <common/net/message/fsck/FsckSetEventLoggingMsg.h> #include <common/net/message/fsck/FsckSetEventLoggingRespMsg.h> #include <common/net/message/storage/StatStoragePathMsg.h> #include <common/net/message/storage/StatStoragePathRespMsg.h> #include <common/toolkit/ListTk.h> #include <common/toolkit/FsckTk.h> #include <common/toolkit/UnitTk.h> #include <program/Program.h> #include <mutex> char FsckTkEx::progressChar = '-'; Mutex FsckTkEx::outputMutex; /* * check the reachability of all nodes in the system */ bool FsckTkEx::checkReachability() { NodeStore* metaNodes = Program::getApp()->getMetaNodes(); NodeStore* storageNodes = Program::getApp()->getStorageNodes(); StringList errors; bool commSuccess = true; FsckTkEx::fsckOutput("Step 1: Check reachability of nodes: ", OutputOptions_FLUSH); if ( metaNodes->getSize() == 0 ) { errors.push_back("No metadata nodes found"); commSuccess = false; } if ( storageNodes->getSize() == 0 ) { errors.push_back("No storage nodes found"); commSuccess = false; } for (const auto& node : metaNodes->referenceAllNodes()) { if ( !FsckTkEx::checkReachability(*node, NODETYPE_Meta) ) { errors.push_back("Communication with metadata node failed: " + node->getID()); commSuccess = false; } } for (const auto& node : storageNodes->referenceAllNodes()) { if ( !FsckTkEx::checkReachability(*node, NODETYPE_Storage) ) { errors.push_back("Communication with storage node failed: " + node->getID()); commSuccess = false; } } if ( commSuccess ) FsckTkEx::fsckOutput("Finished", OutputOptions_LINEBREAK); else { for ( StringListIter iter = errors.begin(); iter != errors.end(); iter++ ) { FsckTkEx::fsckOutput(*iter, OutputOptions_NONE | OutputOptions_LINEBREAK | OutputOptions_STDERR); } } return commSuccess; } /* * check reachability of a single node */ bool FsckTkEx::checkReachability(Node& node, NodeType nodetype) { bool retVal = false; HeartbeatRequestMsg heartbeatRequestMsg; std::string realNodeID = node.getID(); const auto respMsg = MessagingTk::requestResponse(node, heartbeatRequestMsg, NETMSGTYPE_Heartbeat); if (respMsg) { HeartbeatMsg *heartbeatMsg = (HeartbeatMsg *) respMsg.get(); std::string receivedNodeID = heartbeatMsg->getNodeID(); retVal = receivedNodeID.compare(realNodeID) == 0; } return retVal; } void FsckTkEx::fsckOutput(std::string text, int optionFlags) { const std::lock_guard<Mutex> lock(outputMutex); static bool fileErrLogged = false; // to make sure we print logfile open err only once Config* cfg = Program::getApp()->getConfig(); // might be NULL on app init failure bool toLog = cfg && (!(OutputOptions_NOLOG & optionFlags)); // true if write to log file FILE *logFile = NULL; if (likely(toLog)) { std::string logFilePath = cfg->getLogOutFile(); logFile = fopen(logFilePath.c_str(),"a+"); if (logFile == NULL) { toLog = false; if(!fileErrLogged) { std::cerr << "Cannot open output file for writing: '" << logFilePath << "'" << std::endl; fileErrLogged = true; } } } const char* colorNormal = OutputColor_NORMAL; const char* color = OutputColor_NORMAL; FILE *outFile = stdout; if (OutputOptions_STDERR & optionFlags) { outFile = stderr; } else if (OutputOptions_NOSTDOUT & optionFlags) { outFile = NULL; } bool outFileIsTty; if (outFile) outFileIsTty = isatty(fileno(outFile)); else outFileIsTty = false; if (OutputOptions_COLORGREEN & optionFlags) { color = OutputColor_GREEN; } else if (OutputOptions_COLORRED & optionFlags) { color = OutputColor_RED; } else { color = OutputColor_NORMAL; } if (OutputOptions_LINEDELETE & optionFlags) { optionFlags = optionFlags | OutputOptions_FLUSH; SAFE_FPRINTF(outFile, "\r"); SAFE_FPRINTF(outFile, " "); SAFE_FPRINTF(outFile, "\r"); } if (OutputOptions_ADDLINEBREAKBEFORE & optionFlags) { SAFE_FPRINTF(outFile, "\n"); if (likely(toLog)) SAFE_FPRINTF(logFile,"\n"); } if (OutputOptions_HEADLINE & optionFlags) { SAFE_FPRINTF(outFile, "\n--------------------------------------------------------------------\n"); if (likely(toLog)) SAFE_FPRINTF(logFile,"\n--------------------------------------------------------------------\n"); if (likely(outFileIsTty)) SAFE_FPRINTF(outFile, "%s%s%s",color,text.c_str(),colorNormal); else SAFE_FPRINTF(outFile, "%s",text.c_str()); if (likely(toLog)) SAFE_FPRINTF(logFile,"%s",text.c_str()); SAFE_FPRINTF(outFile, "\n--------------------------------------------------------------------\n") ; if (likely(toLog)) SAFE_FPRINTF(logFile,"\n--------------------------------------------------------------------\n"); } else { if (likely(outFileIsTty)) SAFE_FPRINTF(outFile, "%s%s%s",color,text.c_str(),colorNormal); else SAFE_FPRINTF(outFile, "%s",text.c_str()); if (likely(toLog)) SAFE_FPRINTF(logFile,"%s",text.c_str()); } if (OutputOptions_LINEBREAK & optionFlags) { SAFE_FPRINTF(outFile, "\n"); if (likely(toLog)) SAFE_FPRINTF(logFile,"\n"); } if (OutputOptions_DOUBLELINEBREAK & optionFlags) { SAFE_FPRINTF(outFile, "\n\n"); if (likely(toLog)) SAFE_FPRINTF(logFile,"\n\n"); } if (OutputOptions_FLUSH & optionFlags) { fflush(outFile); if (likely(toLog)) fflush(logFile); } if (logFile != NULL) { fclose(logFile); } } void FsckTkEx::printVersionHeader(bool toStdErr, bool noLogFile) { int optionFlags = OutputOptions_LINEBREAK; if (toStdErr) { optionFlags = OutputOptions_LINEBREAK | OutputOptions_STDERR; } if (noLogFile) { optionFlags = optionFlags | OutputOptions_NOLOG; } FsckTkEx::fsckOutput("\n", optionFlags); FsckTkEx::fsckOutput("ConGFS File System Check Version : " + std::string(CONGFS_VERSION), optionFlags); FsckTkEx::fsckOutput("----", optionFlags); } void FsckTkEx::progressMeter() { const std::lock_guard<Mutex> lock(outputMutex); printf("\b%c",progressChar); fflush(stdout); switch(progressChar) { case '-' : { progressChar = '\\'; break; } case '\\' : { progressChar = '|'; break; } case '|' : { progressChar = '/'; break; } case '/' : { progressChar = '-'; break; } default: { progressChar = '-'; break; } } } /* * this is only a rough approximation */ int64_t FsckTkEx::calcNeededSpace() { const char* logContext = "FsckTkEx (calcNeededSpace)"; int64_t neededSpace = 0; // get used inodes from all meta data servers and sum them up NodeStore* metaNodes = Program::getApp()->getMetaNodes(); for (const auto& metaNode : metaNodes->referenceAllNodes()) { NumNodeID nodeID = metaNode->getNumID(); StatStoragePathMsg statStoragePathMsg(0); const auto respMsg = MessagingTk::requestResponse(*metaNode, statStoragePathMsg, NETMSGTYPE_StatStoragePathResp); if (respMsg) { StatStoragePathRespMsg* statStoragePathRespMsg = (StatStoragePathRespMsg *) respMsg.get(); int64_t usedInodes = statStoragePathRespMsg->getInodesTotal() - statStoragePathRespMsg->getInodesFree(); neededSpace += usedInodes * NEEDED_DISKSPACE_META_INODE; } else { LogContext(logContext).logErr( "Unable to calculate needed disk space; Communication error with node: " + nodeID.str()); return 0; } } // get used inodes from all storage servers and sum them up NodeStore* storageNodes = Program::getApp()->getStorageNodes(); TargetMapper* targetMapper = Program::getApp()->getTargetMapper(); for (const auto& storageNode : storageNodes->referenceAllNodes()) { NumNodeID nodeID = storageNode->getNumID(); UInt16List targetIDs; targetMapper->getTargetsByNode(nodeID, targetIDs); for ( UInt16ListIter targetIDIter = targetIDs.begin(); targetIDIter != targetIDs.end(); targetIDIter++ ) { uint16_t targetID = *targetIDIter; StatStoragePathMsg statStoragePathMsg(targetID); const auto respMsg = MessagingTk::requestResponse(*storageNode, statStoragePathMsg, NETMSGTYPE_StatStoragePathResp); if (respMsg) { auto* statStoragePathRespMsg = (StatStoragePathRespMsg *) respMsg.get(); int64_t usedInodes = statStoragePathRespMsg->getInodesTotal() - statStoragePathRespMsg->getInodesFree(); neededSpace += usedInodes * NEEDED_DISKSPACE_STORAGE_INODE; } else { LogContext(logContext).logErr( "Unable to calculate needed disk space; Communication error with node: " + nodeID.str()); return -1; } } } // now we take the calculated approximation and double it to have a lot of space for errors return neededSpace*2; } bool FsckTkEx::checkDiskSpace(Path& dbPath) { int64_t neededDiskSpace = FsckTkEx::calcNeededSpace(); if ( unlikely(neededDiskSpace < 0) ) { FsckTkEx::fsckOutput("Could not determine needed disk space. Aborting now.", OutputOptions_LINEBREAK | OutputOptions_ADDLINEBREAKBEFORE); return false; } int64_t sizeTotal; int64_t sizeFree; int64_t inodesTotal; int64_t inodesFree; bool statRes = StorageTk::statStoragePath(dbPath, true, &sizeTotal, &sizeFree, &inodesTotal, &inodesFree); if (!statRes) { FsckTkEx::fsckOutput( "Could not stat database file path to determine free space; database file: " + dbPath.str()); return false; } if ( neededDiskSpace >= sizeFree ) { std::string neededDiskSpaceUnit; double neededDiskSpaceValue = UnitTk::byteToXbyte(neededDiskSpace, &neededDiskSpaceUnit); std::string sizeFreeUnit; double sizeFreeValue = UnitTk::byteToXbyte(sizeFree, &sizeFreeUnit); FsckTkEx::fsckOutput( "Not enough disk space to create database file: " + dbPath.str() + "; Recommended free space: " + StringTk::doubleToStr(neededDiskSpaceValue) + neededDiskSpaceUnit + "; Free space: " + StringTk::doubleToStr(sizeFreeValue) + sizeFreeUnit, OutputOptions_LINEBREAK | OutputOptions_ADDLINEBREAKBEFORE); bool ignoreDBDiskSpace = Program::getApp()->getConfig()->getIgnoreDBDiskSpace(); if(!ignoreDBDiskSpace) return false; } return true; } std::string FsckTkEx::getRepairActionDesc(FsckRepairAction repairAction, bool shortDesc) { for (size_t i = 0; __FsckRepairActions[i].actionDesc != nullptr; i++) { if( repairAction == __FsckRepairActions[i].action ) { // we have a match if (shortDesc) return __FsckRepairActions[i].actionShortDesc; else return __FsckRepairActions[i].actionDesc; } } return ""; } FhgfsOpsErr FsckTkEx::startModificationLogging(NodeStore* metaNodes, Node& localNode, bool forceRestart) { const char* logContext = "FsckTkEx (startModificationLogging)"; FhgfsOpsErr retVal = FhgfsOpsErr_SUCCESS; NicAddressList localNicList = localNode.getNicList(); unsigned localPortUDP = localNode.getPortUDP(); FsckTkEx::fsckOutput("-----", OutputOptions_ADDLINEBREAKBEFORE | OutputOptions_FLUSH | OutputOptions_LINEBREAK); FsckTkEx::fsckOutput( "Waiting for metadata servers to start modification logging. This might take some time.", OutputOptions_FLUSH | OutputOptions_LINEBREAK); FsckTkEx::fsckOutput("-----", OutputOptions_FLUSH | OutputOptions_DOUBLELINEBREAK); NumNodeIDList nodeIDs; auto metaNodeList = metaNodes->referenceAllNodes(); for (auto iter = metaNodeList.begin(); iter != metaNodeList.end(); iter++) { auto node = metaNodes->referenceNode((*iter)->getNumID()); NicAddressList nicList; FsckSetEventLoggingMsg fsckSetEventLoggingMsg(true, localPortUDP, &localNicList, forceRestart); const auto respMsg = MessagingTk::requestResponse(*node, fsckSetEventLoggingMsg, NETMSGTYPE_FsckSetEventLoggingResp); if (respMsg) { auto* fsckSetEventLoggingRespMsg = (FsckSetEventLoggingRespMsg*) respMsg.get(); bool started = fsckSetEventLoggingRespMsg->getLoggingEnabled(); if (!started) // EventFlusher was already running on this node! { LogContext(logContext).logErr("Modification logging already running on node: " + node->getID()); retVal = FhgfsOpsErr_INUSE; break; } } else { LogContext(logContext).logErr("Communication error occured with node: " + node->getID()); retVal = FhgfsOpsErr_COMMUNICATION; } } return retVal; } bool FsckTkEx::stopModificationLogging(NodeStore* metaNodes) { const char* logContext = "FsckTkEx (stopModificationLogging)"; bool retVal = true; FsckTkEx::fsckOutput("-----", OutputOptions_ADDLINEBREAKBEFORE | OutputOptions_FLUSH | OutputOptions_LINEBREAK); FsckTkEx::fsckOutput( "Waiting for metadata servers to stop modification logging. This might take some time.", OutputOptions_FLUSH | OutputOptions_LINEBREAK); FsckTkEx::fsckOutput("-----", OutputOptions_FLUSH | OutputOptions_DOUBLELINEBREAK); NumNodeIDList nodeIDs; auto metaNodeList = metaNodes->referenceAllNodes(); for (auto iter = metaNodeList.begin(); iter != metaNodeList.end(); iter++) nodeIDs.push_back((*iter)->getNumID()); NumNodeIDListIter nodeIdIter = nodeIDs.begin(); while (! nodeIDs.empty()) { NumNodeID nodeID = *nodeIdIter; auto node = metaNodes->referenceNode(nodeID); NicAddressList nicList; FsckSetEventLoggingMsg fsckSetEventLoggingMsg(false, 0, &nicList, false); const auto respMsg = MessagingTk::requestResponse(*node, fsckSetEventLoggingMsg, NETMSGTYPE_FsckSetEventLoggingResp); if (respMsg) { auto* fsckSetEventLoggingRespMsg = (FsckSetEventLoggingRespMsg*) respMsg.get(); bool result = fsckSetEventLoggingRespMsg->getResult(); bool missedEvents = fsckSetEventLoggingRespMsg->getMissedEvents(); if ( result ) { nodeIdIter = nodeIDs.erase(nodeIdIter); if ( missedEvents ) { retVal = false; } } else nodeIdIter++; // keep in list and try again later } else { LogContext(logContext).logErr("Communication error occured with node: " + node->getID()); retVal = false; } if (nodeIdIter == nodeIDs.end()) { nodeIdIter = nodeIDs.begin(); sleep(5); } } return retVal; } bool FsckTkEx::checkConsistencyStates() { auto mgmtdNode = Program::getApp()->getMgmtNodes()->referenceFirstNode(); if (!mgmtdNode) throw std::runtime_error("Management node not found"); std::list<uint8_t> storageReachabilityStates; std::list<uint8_t> storageConsistencyStates; std::list<uint16_t> storageTargetIDs; std::list<uint8_t> metaReachabilityStates; std::list<uint8_t> metaConsistencyStates; std::list<uint16_t> metaTargetIDs; if (!NodesTk::downloadTargetStates(*mgmtdNode, NODETYPE_Storage, &storageTargetIDs, &storageReachabilityStates, &storageConsistencyStates, false) || !NodesTk::downloadTargetStates(*mgmtdNode, NODETYPE_Meta, &metaTargetIDs, &metaReachabilityStates, &metaConsistencyStates, false)) { throw std::runtime_error("Could not download target states from management."); } bool result = true; { auto idIt = storageTargetIDs.begin(); auto stateIt = storageConsistencyStates.begin(); for (; idIt != storageTargetIDs.end() && stateIt != storageConsistencyStates.end(); idIt++, stateIt++) { if (*stateIt == TargetConsistencyState_NEEDS_RESYNC) { FsckTkEx::fsckOutput("Storage target " + StringTk::uintToStr(*idIt) + " is set to " "NEEDS_RESYNC.", OutputOptions_LINEBREAK); result = false; } } } { auto idIt = metaTargetIDs.begin(); auto stateIt = metaConsistencyStates.begin(); for (; idIt != metaTargetIDs.end() && stateIt != metaConsistencyStates.end(); idIt++, stateIt++) { if (*stateIt == TargetConsistencyState_NEEDS_RESYNC) { FsckTkEx::fsckOutput("Meta node " + StringTk::uintToStr(*idIt) + " is set to " "NEEDS_RESYNC.", OutputOptions_LINEBREAK); result = false; } } } return result; }
28.879339
106
0.627862
congweitao
c69fb2596c3c21a93b42faa98573b71d49655a99
4,302
cpp
C++
Game_exe/release_mode/windows/obj/src/flixel/input/actions/FlxInputDeviceID.cpp
hisatsuga/Salty-Psyche-Engine-Port-Main
0c6afc6ef57f6f6a8b83ff23bb6a26bb05117ab7
[ "Apache-2.0" ]
1
2021-07-19T05:10:43.000Z
2021-07-19T05:10:43.000Z
export/release/windows/obj/src/flixel/input/actions/FlxInputDeviceID.cpp
Tyrcnex/tai-mod
b83152693bb3139ee2ae73002623934f07d35baf
[ "Apache-2.0" ]
null
null
null
export/release/windows/obj/src/flixel/input/actions/FlxInputDeviceID.cpp
Tyrcnex/tai-mod
b83152693bb3139ee2ae73002623934f07d35baf
[ "Apache-2.0" ]
null
null
null
#include <hxcpp.h> #ifndef INCLUDED_flixel_input_actions_FlxInputDeviceID #include <flixel/input/actions/FlxInputDeviceID.h> #endif HX_LOCAL_STACK_FRAME(_hx_pos_8815d627a254acc2_117_boot,"flixel.input.actions.FlxInputDeviceID","boot",0x9ec96ab0,"flixel.input.actions.FlxInputDeviceID.boot","flixel/input/actions/FlxActionInput.hx",117,0x5d496a72) HX_LOCAL_STACK_FRAME(_hx_pos_8815d627a254acc2_122_boot,"flixel.input.actions.FlxInputDeviceID","boot",0x9ec96ab0,"flixel.input.actions.FlxInputDeviceID.boot","flixel/input/actions/FlxActionInput.hx",122,0x5d496a72) HX_LOCAL_STACK_FRAME(_hx_pos_8815d627a254acc2_127_boot,"flixel.input.actions.FlxInputDeviceID","boot",0x9ec96ab0,"flixel.input.actions.FlxInputDeviceID.boot","flixel/input/actions/FlxActionInput.hx",127,0x5d496a72) namespace flixel{ namespace input{ namespace actions{ void FlxInputDeviceID_obj::__construct() { } Dynamic FlxInputDeviceID_obj::__CreateEmpty() { return new FlxInputDeviceID_obj; } void *FlxInputDeviceID_obj::_hx_vtable = 0; Dynamic FlxInputDeviceID_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< FlxInputDeviceID_obj > _hx_result = new FlxInputDeviceID_obj(); _hx_result->__construct(); return _hx_result; } bool FlxInputDeviceID_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x10dfec1c; } int FlxInputDeviceID_obj::ALL; int FlxInputDeviceID_obj::FIRST_ACTIVE; int FlxInputDeviceID_obj::NONE; FlxInputDeviceID_obj::FlxInputDeviceID_obj() { } #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo *FlxInputDeviceID_obj_sMemberStorageInfo = 0; static ::hx::StaticInfo FlxInputDeviceID_obj_sStaticStorageInfo[] = { {::hx::fsInt,(void *) &FlxInputDeviceID_obj::ALL,HX_("ALL",01,95,31,00)}, {::hx::fsInt,(void *) &FlxInputDeviceID_obj::FIRST_ACTIVE,HX_("FIRST_ACTIVE",55,71,b1,b1)}, {::hx::fsInt,(void *) &FlxInputDeviceID_obj::NONE,HX_("NONE",b8,da,ca,33)}, { ::hx::fsUnknown, 0, null()} }; #endif static void FlxInputDeviceID_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(FlxInputDeviceID_obj::ALL,"ALL"); HX_MARK_MEMBER_NAME(FlxInputDeviceID_obj::FIRST_ACTIVE,"FIRST_ACTIVE"); HX_MARK_MEMBER_NAME(FlxInputDeviceID_obj::NONE,"NONE"); }; #ifdef HXCPP_VISIT_ALLOCS static void FlxInputDeviceID_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(FlxInputDeviceID_obj::ALL,"ALL"); HX_VISIT_MEMBER_NAME(FlxInputDeviceID_obj::FIRST_ACTIVE,"FIRST_ACTIVE"); HX_VISIT_MEMBER_NAME(FlxInputDeviceID_obj::NONE,"NONE"); }; #endif ::hx::Class FlxInputDeviceID_obj::__mClass; static ::String FlxInputDeviceID_obj_sStaticFields[] = { HX_("ALL",01,95,31,00), HX_("FIRST_ACTIVE",55,71,b1,b1), HX_("NONE",b8,da,ca,33), ::String(null()) }; void FlxInputDeviceID_obj::__register() { FlxInputDeviceID_obj _hx_dummy; FlxInputDeviceID_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("flixel.input.actions.FlxInputDeviceID",b0,0a,ac,bf); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = FlxInputDeviceID_obj_sMarkStatics; __mClass->mStatics = ::hx::Class_obj::dupFunctions(FlxInputDeviceID_obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = ::hx::TCanCast< FlxInputDeviceID_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = FlxInputDeviceID_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = FlxInputDeviceID_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = FlxInputDeviceID_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } void FlxInputDeviceID_obj::__boot() { { HX_STACKFRAME(&_hx_pos_8815d627a254acc2_117_boot) HXDLIN( 117) ALL = -1; } { HX_STACKFRAME(&_hx_pos_8815d627a254acc2_122_boot) HXDLIN( 122) FIRST_ACTIVE = -2; } { HX_STACKFRAME(&_hx_pos_8815d627a254acc2_127_boot) HXDLIN( 127) NONE = -3; } } } // end namespace flixel } // end namespace input } // end namespace actions
35.262295
214
0.77801
hisatsuga
c6a0bd9e00e6362f6eae1c600a020a063cf55fc6
6,880
cpp
C++
src/difont/opengl/OpenGLInterface.windows.cpp
cdave1/difont
2c38726cc3b7a6e06b920accef4ce752967fa61d
[ "MIT" ]
3
2015-03-09T05:51:02.000Z
2019-07-29T10:33:32.000Z
src/difont/opengl/OpenGLInterface.windows.cpp
cdave1/difont
2c38726cc3b7a6e06b920accef4ce752967fa61d
[ "MIT" ]
null
null
null
src/difont/opengl/OpenGLInterface.windows.cpp
cdave1/difont
2c38726cc3b7a6e06b920accef4ce752967fa61d
[ "MIT" ]
null
null
null
/* Copyright (c) 2010 David Petrie Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "OpenGLInterface.h" #include <string.h> #define DIFONT_GLUE_MAX_VERTICES 32768 #define DIFONT_GLUE_MAX_MESHES 64 typedef struct { GLfloat position[4]; GLfloat color[4]; GLfloat texCoord[2]; } difontVertex_t; typedef struct { difontVertex_t vertices[DIFONT_GLUE_MAX_VERTICES]; short quadIndices[DIFONT_GLUE_MAX_VERTICES * 3 / 2]; difontVertex_t currVertex; unsigned int currIndex; } difontGlueArrays_t; difontGlueArrays_t difontGlueArrays; GLenum difontCurrentPrimitive = GL_TRIANGLES; bool DIFONTQuadIndicesInitted = false; void difontBindPositionAttribute(GLint attributeHandle) { glVertexAttribPointer(attributeHandle, 4, GL_FLOAT, 0, sizeof(difontVertex_t), difontGlueArrays.vertices[0].position); glEnableVertexAttribArray(attributeHandle); } void difontBindColorAttribute(GLint attributeHandle) { glVertexAttribPointer(attributeHandle, 4, GL_FLOAT, 0, sizeof(difontVertex_t), difontGlueArrays.vertices[0].color); glEnableVertexAttribArray(attributeHandle); } void difontBindTextureAttribute(GLint attributeHandle) { glVertexAttribPointer(attributeHandle, 2, GL_FLOAT, 0, sizeof(difontVertex_t), difontGlueArrays.vertices[0].texCoord); glEnableVertexAttribArray(attributeHandle); } GLvoid difont::gl::Begin(GLenum prim) { if (!DIFONTQuadIndicesInitted) { for (int i = 0; i < DIFONT_GLUE_MAX_VERTICES * 3 / 2; i += 6) { int q = i / 6 * 4; difontGlueArrays.quadIndices[i + 0] = q + 0; difontGlueArrays.quadIndices[i + 1] = q + 1; difontGlueArrays.quadIndices[i + 2] = q + 2; difontGlueArrays.quadIndices[i + 3] = q + 0; difontGlueArrays.quadIndices[i + 4] = q + 2; difontGlueArrays.quadIndices[i + 5] = q + 3; } DIFONTQuadIndicesInitted = true; } difontGlueArrays.currIndex = 0; difontCurrentPrimitive = prim; } GLvoid difont::gl::Vertex3f(float x, float y, float z) { if (difontGlueArrays.currIndex >= DIFONT_GLUE_MAX_VERTICES) { return; } difontGlueArrays.currVertex.position[0] = x; difontGlueArrays.currVertex.position[1] = y; difontGlueArrays.currVertex.position[2] = z; difontGlueArrays.currVertex.position[3] = 1.0f; difontGlueArrays.vertices[difontGlueArrays.currIndex] = difontGlueArrays.currVertex; difontGlueArrays.currIndex++; } GLvoid difont::gl::Vertex2f(float x, float y) { if (difontGlueArrays.currIndex >= DIFONT_GLUE_MAX_VERTICES) { return; } difontGlueArrays.currVertex.position[0] = x; difontGlueArrays.currVertex.position[1] = y; difontGlueArrays.currVertex.position[2] = 0.0f; difontGlueArrays.currVertex.position[3] = 1.0f; difontGlueArrays.vertices[difontGlueArrays.currIndex] = difontGlueArrays.currVertex; difontGlueArrays.currIndex++; } GLvoid difont::gl::Color4f(GLfloat r, GLfloat g, GLfloat b, GLfloat a) { difontGlueArrays.currVertex.color[0] = r; difontGlueArrays.currVertex.color[1] = g; difontGlueArrays.currVertex.color[2] = b; difontGlueArrays.currVertex.color[3] = a; } GLvoid difont::gl::TexCoord2f(GLfloat s, GLfloat t) { difontGlueArrays.currVertex.texCoord[0] = s; difontGlueArrays.currVertex.texCoord[1] = t; } GLvoid bindArrayBuffers() {} GLvoid difont::gl::BindTexture(unsigned int textureId) { GLint activeTextureID; glGetIntegerv(GL_TEXTURE_BINDING_2D, &activeTextureID); if ((unsigned int)activeTextureID != textureId) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } } GLvoid difont::gl::End() { /* if (difontGlueArrays.currIndex == 0) { DIFONTCurrentPrimitive = 0; return; } if (DIFONTCurrentPrimitive == GL_QUADS) { glDrawElements(GL_TRIANGLES, difontGlueArrays.currIndex / 4 * 6, GL_UNSIGNED_SHORT, difontGlueArrays.quadIndices); } else { glDrawArrays(DIFONTCurrentPrimitive, 0, difontGlueArrays.currIndex); }*/ } uint32_t difont::gl::VertexSize() { return sizeof(difontVertex_t); } uint32_t difont::gl::VertexCount() { return difontGlueArrays.currIndex; } /* void difont::gl::CopyMesh(void *dataPointer, uint32_t *dataLen, uint32_t *vertexCount) { if (difontCurrentPrimitive == 0 || difontGlueArrays.currIndex == 0) { dataPointer = NULL; dataLen = 0; vertexCount = 0; return; } memcpy(dataPointer, difontGlueArrays.vertices, sizeof(difontVertex_t) * difontGlueArrays.currIndex); *vertexCount = difontGlueArrays.currIndex; *dataLen = sizeof(difontVertex_t) * difontGlueArrays.currIndex; }*/ GLvoid difont::gl::Error(const char *source) { GLenum error = glGetError(); switch (error) { case GL_NO_ERROR: break; case GL_INVALID_ENUM: printf("GL Error (%x): GL_INVALID_ENUM. %s\n\n", error, source); break; case GL_INVALID_VALUE: printf("GL Error (%x): GL_INVALID_VALUE. %s\n\n", error, source); break; case GL_INVALID_OPERATION: printf("GL Error (%x): GL_INVALID_OPERATION. %s\n\n", error, source); break;/* case GL_STACK_OVERFLOW: printf("GL Error (%x): GL_STACK_OVERFLOW. %s\n\n", error, source); break; case GL_STACK_UNDERFLOW: printf("GL Error (%x): GL_STACK_UNDERFLOW. %s\n\n", error, source); break;*/ case GL_OUT_OF_MEMORY: printf("GL Error (%x): GL_OUT_OF_MEMORY. %s\n\n", error, source); break; default: printf("GL Error (%x): %s\n\n", error, source); break; } }
31.851852
122
0.717733
cdave1
c6a699f8bab50b56270512da3d65508174783456
63,273
cpp
C++
src/basetestsealbfv.cpp
YiJingGuo/HEBenchmark
3154b4b638b32c97d307c598a2dd2fbf0a543de2
[ "MIT" ]
27
2019-07-27T10:32:24.000Z
2021-05-17T12:32:30.000Z
src/basetestsealbfv.cpp
YiJingGuo/HEBenchmark
3154b4b638b32c97d307c598a2dd2fbf0a543de2
[ "MIT" ]
null
null
null
src/basetestsealbfv.cpp
YiJingGuo/HEBenchmark
3154b4b638b32c97d307c598a2dd2fbf0a543de2
[ "MIT" ]
11
2019-07-28T03:57:06.000Z
2021-04-27T09:24:52.000Z
#include "basetestsealbfv.h" #include "ui_basetestsealbfv.h" #include "mainwindow.h" #include <QHBoxLayout> #include <QValueAxis> BaseTestSealBFV::BaseTestSealBFV(QWidget *parent) : QWidget(parent), ui(new Ui::BaseTestSealBFV) { ui->setupUi(this); QPalette bgpal = palette(); bgpal.setColor (QPalette::Background, QColor (0, 0 , 0, 255)); bgpal.setColor (QPalette::Foreground, QColor (255,255,255,255)); setPalette (bgpal); } BaseTestSealBFV::~BaseTestSealBFV() { delete ui; } void BaseTestSealBFV::charts() { QLineSeries *series = new QLineSeries(); *series << QPointF(1, noise_budget_initial) << QPointF(2, noise_budget_end); QChart *chart = new QChart(); chart->legend()->hide(); chart->addSeries(series); //chart->createDefaultAxes(); //自动化建立XY轴 QValueAxis *axisX = new QValueAxis();//轴变量、数据系列变量,都不能声明为局部临时变量 QValueAxis *axisY = new QValueAxis();//创建X/Y轴 axisX->setRange(1, 2); axisY->setRange(noise_budget_end-5, noise_budget_initial+5);//设置X/Y显示的区间 chart->setAxisX(axisX); chart->setAxisY(axisY);//设置chart的坐标轴 series->attachAxis(axisX);//连接数据集与坐标轴。 series->attachAxis(axisY); chart->setTitle("噪音剩余空间"); ui->graphicsView->setChart(chart); ui->graphicsView->setRenderHint(QPainter::Antialiasing); } void BaseTestSealBFV::print_parameters(shared_ptr<SEALContext> context) { QString result = ""; // Verify parameters if (!context) { throw invalid_argument("context is not set"); } auto &context_data = *context->context_data(); /* Which scheme are we using? */ QString scheme_name; switch (context_data.parms().scheme()) { case scheme_type::BFV: scheme_name = "BFV"; break; case scheme_type::CKKS: scheme_name = "CKKS"; break; default: throw invalid_argument("unsupported scheme"); } result += "/ Encryption parameters:\n"; result += "| scheme: "; result += scheme_name; result += "\n| poly_modulus_degree: "; int temp_int; temp_int = context_data.parms().poly_modulus_degree(); QString temp = QString::number(temp_int); result += temp; /* Print the size of the true (product) coefficient modulus. */ result += "\n| coeff_modulus size: "; temp_int = context_data. total_coeff_modulus_bit_count(); temp = QString::number(temp_int); result += temp; result += " bits\n"; /* For the BFV scheme print the plain_modulus parameter. */ if (context_data.parms().scheme() == scheme_type::BFV) { result += "| plain_modulus: "; temp_int = context_data. parms().plain_modulus().value(); temp = QString::number(temp_int); result += temp; } result += "\n\\ noise_standard_deviation: "; temp_int = context_data. parms().noise_standard_deviation(); temp = QString::number(temp_int); result += temp; ui->param->setText(result); } void BaseTestSealBFV::test_add(shared_ptr<SEALContext> context) { ui->graphicsView->show(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_add_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; for (int i = 0; i < test_number; i++) { /* [Add] */ Ciphertext encrypted1(context); encryptor.encrypt(encoder.encode(i), encrypted1); Ciphertext encrypted2(context); encryptor.encrypt(encoder.encode(i+1), encrypted2); noise_budget_initial = decryptor.invariant_noise_budget(encrypted1); time_start = chrono::high_resolution_clock::now(); evaluator.add_inplace(encrypted1, encrypted1); time_end = chrono::high_resolution_clock::now(); time_add_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start) ; noise_budget_end = decryptor.invariant_noise_budget(encrypted1); } result += "Initial noise budget: "; temp = QString::number(noise_budget_initial); result += temp; result += " bits\n"; result += "The residual noise: "; temp = QString::number(noise_budget_end); result += temp; result += " bits\n"; auto avg_add = time_add_sum.count() / test_number; result += "Average add: "; temp = QString::number(avg_add); result += temp; result += " microseconds\n"; ui->result->setText(result); charts(); } void BaseTestSealBFV::test_add_plain(shared_ptr<SEALContext> context) { ui->graphicsView->show(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_add_plain_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; Plaintext plain(curr_parms.poly_modulus_degree(), 0); batch_encoder.encode(pod_vector, plain); for (int i = 0; i < test_number; i++) { /* [Add Plain] */ Ciphertext encrypted1(context); encryptor.encrypt(encoder.encode(i), encrypted1); Ciphertext encrypted2(context); encryptor.encrypt(encoder.encode(i + 1), encrypted2); noise_budget_initial = decryptor.invariant_noise_budget(encrypted1); time_start = chrono::high_resolution_clock::now(); evaluator.add_plain_inplace(encrypted1, plain); time_end = chrono::high_resolution_clock::now(); time_add_plain_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); noise_budget_end = decryptor.invariant_noise_budget(encrypted1); } result += "Initial noise budget: "; temp = QString::number(noise_budget_initial); result += temp; result += " bits\n"; result += "The residual noise: "; temp = QString::number(noise_budget_end); result += temp; result += " bits\n"; auto avg_add_plain = time_add_plain_sum.count() / test_number; result += "Average add plain: "; temp = QString::number(avg_add_plain); result += temp; result += " microseconds\n"; ui->result->setText(result); charts(); } void BaseTestSealBFV::test_mult(shared_ptr<SEALContext> context) { ui->graphicsView->show(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_mult_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; for (int i = 0; i < test_number; i++) { /* [Multiply] */ Ciphertext encrypted1(context); encryptor.encrypt(encoder.encode(i), encrypted1); Ciphertext encrypted2(context); encryptor.encrypt(encoder.encode(i + 1), encrypted2); encrypted1.reserve(3); noise_budget_initial = decryptor.invariant_noise_budget(encrypted1); time_start = chrono::high_resolution_clock::now(); evaluator.multiply_inplace(encrypted1, encrypted2); time_end = chrono::high_resolution_clock::now(); time_mult_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); noise_budget_end = decryptor.invariant_noise_budget(encrypted1); } result += "Initial noise budget: "; temp = QString::number(noise_budget_initial); result += temp; result += " bits\n"; result += "The residual noise: "; temp = QString::number(noise_budget_end); result += temp; result += " bits\n"; auto avg_mult = time_mult_sum.count() / test_number; result += "Average multiply: "; temp = QString::number(avg_mult); result += temp; result += " microseconds\n"; ui->result->setText(result); charts(); } void BaseTestSealBFV::test_mult_plain(shared_ptr<SEALContext> context) { ui->graphicsView->show(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_mult_plain_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; Plaintext plain(curr_parms.poly_modulus_degree(), 0); batch_encoder.encode(pod_vector, plain); for (int i = 0; i < test_number; i++) { /* [Multiply Plain] */ Ciphertext encrypted1(context); encryptor.encrypt(encoder.encode(i), encrypted1); noise_budget_initial = decryptor.invariant_noise_budget(encrypted1); time_start = chrono::high_resolution_clock::now(); evaluator.multiply_plain_inplace(encrypted1, plain); time_end = chrono::high_resolution_clock::now(); time_mult_plain_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); noise_budget_end = decryptor.invariant_noise_budget(encrypted1); } result += "Initial noise budget: "; temp = QString::number(noise_budget_initial); result += temp; result += " bits\n"; result += "The residual noise: "; temp = QString::number(noise_budget_end); result += temp; result += " bits\n"; auto avg_mult_plain = time_mult_plain_sum.count() / test_number; result += "Average multiply plain: "; temp = QString::number(avg_mult_plain); result += temp; result += " microseconds\n"; ui->result->setText(result); charts(); } void BaseTestSealBFV::test_sub(shared_ptr<SEALContext> context) { ui->graphicsView->show(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_sub_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; for (int i = 0; i < test_number; i++) { /* [Sub] */ Ciphertext encrypted1(context); encryptor.encrypt(encoder.encode(i), encrypted1); Ciphertext encrypted2(context); encryptor.encrypt(encoder.encode(i+1), encrypted2); noise_budget_initial = decryptor.invariant_noise_budget(encrypted1); time_start = chrono::high_resolution_clock::now(); evaluator.sub_inplace(encrypted1, encrypted2); time_end = chrono::high_resolution_clock::now(); time_sub_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); noise_budget_end = decryptor.invariant_noise_budget(encrypted1); } result += "Initial noise budget: "; temp = QString::number(noise_budget_initial); result += temp; result += " bits\n"; result += "The residual noise: "; temp = QString::number(noise_budget_end); result += temp; result += " bits\n"; auto avg_sub = time_sub_sum.count() / test_number; result += "Average subtraction: "; temp = QString::number(avg_sub); result += temp; result += " microseconds\n"; ui->result->setText(result); charts(); } void BaseTestSealBFV::test_sub_plain(shared_ptr<SEALContext> context) { ui->graphicsView->show(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); result += "Done ["; result += QString::number(time_diff.count()); result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); result += "Done ["; result += QString::number(time_diff.count()); result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_sub_plain_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; Plaintext plain(curr_parms.poly_modulus_degree(), 0); batch_encoder.encode(pod_vector, plain); for (int i = 0; i < test_number; i++) { /* [Sub Plain] */ Ciphertext encrypted1(context); encryptor.encrypt(encoder.encode(i), encrypted1); Ciphertext encrypted2(context); encryptor.encrypt(encoder.encode(i + 1), encrypted2); noise_budget_initial = decryptor.invariant_noise_budget(encrypted1); time_start = chrono::high_resolution_clock::now(); evaluator.sub_plain_inplace(encrypted1, plain); time_end = chrono::high_resolution_clock::now(); time_sub_plain_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); noise_budget_end = decryptor.invariant_noise_budget(encrypted1); } result += "Initial noise budget: "; result += QString::number(noise_budget_initial); result += " bits\n"; result += "The residual noise: "; result += QString::number(noise_budget_end); result += " bits\n"; auto avg_sub_plain = time_sub_plain_sum.count() / test_number; result += "Average sub plain: "; result += QString::number(avg_sub_plain); result += " microseconds\n"; ui->result->setText(result); charts(); } void BaseTestSealBFV::test_square(shared_ptr<SEALContext> context) { ui->graphicsView->show(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_square_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; for (int i = 0; i < test_number; i++) { /* [Square] */ Ciphertext encrypted1(context); encryptor.encrypt(encoder.encode(i), encrypted1); noise_budget_initial = decryptor.invariant_noise_budget(encrypted1); time_start = chrono::high_resolution_clock::now(); evaluator.square_inplace(encrypted1); time_end = chrono::high_resolution_clock::now(); time_square_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); noise_budget_end = decryptor.invariant_noise_budget(encrypted1); } result += "Initial noise budget: "; temp = QString::number(noise_budget_initial); result += temp; result += " bits\n"; result += "The residual noise: "; temp = QString::number(noise_budget_end); result += temp; result += " bits\n"; auto avg_square = time_square_sum.count() / test_number; result += "Average multiply: "; temp = QString::number(avg_square); result += temp; result += " microseconds\n"; ui->result->setText(result); charts(); } void BaseTestSealBFV::test_negation(shared_ptr<SEALContext> context) { ui->graphicsView->show(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_negation_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; for (int i = 0; i < test_number; i++) { /* [Negation] */ Ciphertext encrypted1(context); encryptor.encrypt(encoder.encode(i), encrypted1); noise_budget_initial = decryptor.invariant_noise_budget(encrypted1); time_start = chrono::high_resolution_clock::now(); evaluator.negate_inplace(encrypted1); time_end = chrono::high_resolution_clock::now(); time_negation_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); noise_budget_end = decryptor.invariant_noise_budget(encrypted1); } result += "Initial noise budget: "; temp = QString::number(noise_budget_initial); result += temp; result += " bits\n"; result += "The residual noise: "; temp = QString::number(noise_budget_end); result += temp; result += " bits\n"; auto avg_negation = time_negation_sum.count() / test_number; result += "Average negation: "; temp = QString::number(avg_negation); result += temp; result += " microseconds\n"; ui->result->setText(result); charts(); } void BaseTestSealBFV::test_rotate_rows_one_step(shared_ptr<SEALContext> context) { ui->graphicsView->show(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_rotate_rows_one_step_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; for (int i = 0; i < test_number; i++) { /* [Rotate Rows One Step] */ Ciphertext encrypted1(context); encryptor.encrypt(encoder.encode(i), encrypted1); noise_budget_initial = decryptor.invariant_noise_budget(encrypted1); time_start = chrono::high_resolution_clock::now(); evaluator.rotate_rows_inplace(encrypted1, 1, gal_keys); time_end = chrono::high_resolution_clock::now(); time_rotate_rows_one_step_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); noise_budget_end = decryptor.invariant_noise_budget(encrypted1); } result += "Initial noise budget: "; temp = QString::number(noise_budget_initial); result += temp; result += " bits\n"; result += "The residual noise: "; temp = QString::number(noise_budget_end); result += temp; result += " bits\n"; auto avg_rotate_rows_one_step = time_rotate_rows_one_step_sum.count() / test_number; result += "Average rotate rows one step: "; temp = QString::number(avg_rotate_rows_one_step); result += temp; result += " microseconds\n"; ui->result->setText(result); charts(); } void BaseTestSealBFV::test_rotate_rows_random(shared_ptr<SEALContext> context) { ui->graphicsView->show(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_rotate_rows_random_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; for (int i = 0; i < test_number; i++) { /* [Rotate Rows Random] */ Ciphertext encrypted1(context); encryptor.encrypt(encoder.encode(i), encrypted1); noise_budget_initial = decryptor.invariant_noise_budget(encrypted1); size_t row_size = batch_encoder.slot_count() / 2; int random_rotation = static_cast<int>(rd() % row_size); time_start = chrono::high_resolution_clock::now(); evaluator.rotate_rows_inplace(encrypted1, random_rotation, gal_keys); time_end = chrono::high_resolution_clock::now(); time_rotate_rows_random_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); noise_budget_end = decryptor.invariant_noise_budget(encrypted1); } result += "Initial noise budget: "; temp = QString::number(noise_budget_initial); result += temp; result += " bits\n"; result += "The residual noise: "; temp = QString::number(noise_budget_end); result += temp; result += " bits\n"; auto avg_rotate_rows_random = time_rotate_rows_random_sum.count() / test_number; result += "Average rotate rows random: "; temp = QString::number(avg_rotate_rows_random); result += temp; result += " microseconds\n"; ui->result->setText(result); charts(); } void BaseTestSealBFV::test_rotate_columns(shared_ptr<SEALContext> context) { ui->graphicsView->show(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_rotate_columns_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; for (int i = 0; i < test_number; i++) { /* [Rotate Columns] */ Ciphertext encrypted1(context); encryptor.encrypt(encoder.encode(i), encrypted1); noise_budget_initial = decryptor.invariant_noise_budget(encrypted1); time_start = chrono::high_resolution_clock::now(); evaluator.rotate_columns_inplace(encrypted1, gal_keys); time_end = chrono::high_resolution_clock::now(); time_rotate_columns_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); noise_budget_end = decryptor.invariant_noise_budget(encrypted1); } result += "Initial noise budget: "; temp = QString::number(noise_budget_initial); result += temp; result += " bits\n"; result += "The residual noise: "; temp = QString::number(noise_budget_end); result += temp; result += " bits\n"; auto avg_rotate_columns = time_rotate_columns_sum.count() / test_number; result += "Average rotate columns: "; temp = QString::number(avg_rotate_columns); result += temp; result += " microseconds\n"; ui->result->setText(result); charts(); } void BaseTestSealBFV::test_encryption(shared_ptr<SEALContext> context) { ui->graphicsView->hide(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_encrypt_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; Plaintext plain(curr_parms.poly_modulus_degree(), 0); batch_encoder.encode(pod_vector, plain); for (int i = 0; i < test_number; i++){ /* [Encryption] */ Ciphertext encrypted(context); time_start = chrono::high_resolution_clock::now(); encryptor.encrypt(plain, encrypted); time_end = chrono::high_resolution_clock::now(); time_encrypt_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); } auto avg_encrypt = time_encrypt_sum.count() / test_number; result += "Average encrypt: "; temp = QString::number(avg_encrypt); result += temp; result += " microseconds\n"; ui->result->setText(result); } void BaseTestSealBFV::test_decryption(shared_ptr<SEALContext> context) { ui->graphicsView->hide(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_decrypt_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; Plaintext plain(curr_parms.poly_modulus_degree(), 0); batch_encoder.encode(pod_vector, plain); for (int i = 0; i < test_number; i++){ /* [Encryption] */ Ciphertext encrypted(context); encryptor.encrypt(plain, encrypted); /* [Decryption] */ Plaintext plain2(poly_modulus_degree, 0); time_start = chrono::high_resolution_clock::now(); decryptor.decrypt(encrypted, plain2); time_end = chrono::high_resolution_clock::now(); time_decrypt_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); if (plain2 != plain) { throw runtime_error("Encrypt/decrypt failed. Something is wrong."); } } auto avg_decrypt = time_decrypt_sum.count() / test_number; result += "Average decrypt: "; temp = QString::number(avg_decrypt); result += temp; result += " microseconds\n"; ui->result->setText(result); } void BaseTestSealBFV::test_batching(shared_ptr<SEALContext> context) { ui->graphicsView->hide(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_batch_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; for (int i = 0; i < test_number; i++){ /* [Batching] */ Plaintext plain(curr_parms.poly_modulus_degree(), 0); time_start = chrono::high_resolution_clock::now(); batch_encoder.encode(pod_vector, plain); time_end = chrono::high_resolution_clock::now(); time_batch_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); } auto avg_batch = time_batch_sum.count() / test_number; result += "Average batch: "; temp = QString::number(avg_batch); result += temp; result += " microseconds\n"; ui->result->setText(result); } void BaseTestSealBFV::test_unbatching(shared_ptr<SEALContext> context) { ui->graphicsView->hide(); chrono::high_resolution_clock::time_point time_start, time_end; QString result = ""; print_parameters(context); auto &curr_parms = context->context_data()->parms(); auto &plain_modulus = curr_parms.plain_modulus(); /* Set up keys. */ result += "Generating secret/public keys: "; KeyGenerator keygen(context); result += "Done\n" ; auto secret_key = keygen.secret_key(); auto public_key = keygen.public_key(); /* 生成relinearization keys时间. */ int dbc = DefaultParams::dbc_max(); result += "Generating relinearization keys (dbc = "; QString temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto relin_keys = keygen.relin_keys(dbc); time_end = chrono::high_resolution_clock::now(); auto time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); int time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; /* 生成Galois keys时间. */ if (!context->context_data()->qualifiers().using_batching) { result += "Given encryption parameters do not support batching."; return; } result += "Generating Galois keys (dbc = "; temp = QString::number(dbc); result += temp; result += "): "; time_start = chrono::high_resolution_clock::now(); auto gal_keys = keygen.galois_keys(dbc); time_end = chrono::high_resolution_clock::now(); time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start); time_temp = time_diff.count(); temp = QString::number(time_temp); result += "Done ["; result += temp; result += " microseconds]\n"; Encryptor encryptor(context, public_key); Decryptor decryptor(context, secret_key); Evaluator evaluator(context); BatchEncoder batch_encoder(context); IntegerEncoder encoder(context); chrono::microseconds time_unbatch_sum(0); /* Populate a vector of values to batch. */ vector<uint64_t> pod_vector; random_device rd; for (size_t i = 0; i < batch_encoder.slot_count(); i++) { pod_vector.push_back(rd() % plain_modulus.value()); } result += "\n"; Plaintext plain(curr_parms.poly_modulus_degree(), 0); batch_encoder.encode(pod_vector, plain); for (int i = 0; i < test_number; i++){ /* [Unbatching] */ vector<uint64_t> pod_vector2(batch_encoder.slot_count()); time_start = chrono::high_resolution_clock::now(); batch_encoder.decode(plain, pod_vector2); time_end = chrono::high_resolution_clock::now(); time_unbatch_sum += chrono::duration_cast< chrono::microseconds>(time_end - time_start); if (pod_vector2 != pod_vector) { throw runtime_error("Batch/unbatch failed. Something is wrong."); } } auto avg_unbatch = time_unbatch_sum.count() / test_number; result += "Average batch: "; temp = QString::number(avg_unbatch); result += temp; result += " microseconds\n"; ui->result->setText(result); } void BaseTestSealBFV::BaseBFV128(int poly_modulus_degree, int coeff_modulus, int plain_modulus) { EncryptionParameters parms(scheme_type::BFV); parms.set_poly_modulus_degree(poly_modulus_degree); parms.set_coeff_modulus(DefaultParams::coeff_modulus_128(coeff_modulus)); parms.set_plain_modulus(plain_modulus); if(test_type == "Add测试") test_add(SEALContext::Create(parms)); if(test_type == "Add Plain测试") test_add_plain(SEALContext::Create(parms)); if(test_type == "Mult测试") test_mult(SEALContext::Create(parms)); if(test_type == "Mult Plain测试") test_mult_plain(SEALContext::Create(parms)); if(test_type == "Sub测试") test_sub(SEALContext::Create(parms)); if(test_type == "Sub Plain测试") test_sub_plain(SEALContext::Create(parms)); if(test_type == "Square测试") test_square(SEALContext::Create(parms)); if(test_type == "Negation测试") test_negation(SEALContext::Create(parms)); if(test_type == "Rotate rows one step测试") test_rotate_rows_one_step(SEALContext::Create(parms)); if(test_type == "Rotate rows random测试") test_rotate_rows_random(SEALContext::Create(parms)); if(test_type == "Rotate columns测试") test_rotate_columns(SEALContext::Create(parms)); if(test_type == "Encryption测试") test_encryption(SEALContext::Create(parms)); if(test_type == "Decryption测试") test_decryption(SEALContext::Create(parms)); if(test_type == "Batching测试") test_batching(SEALContext::Create(parms)); if(test_type == "Unbatching测试") test_unbatching(SEALContext::Create(parms)); } void BaseTestSealBFV::BaseBFV192(int poly_modulus_degree, int coeff_modulus, int plain_modulus) { EncryptionParameters parms(scheme_type::BFV); parms.set_poly_modulus_degree(poly_modulus_degree); parms.set_coeff_modulus(DefaultParams::coeff_modulus_192(coeff_modulus)); parms.set_plain_modulus(plain_modulus); if(test_type == "Add测试") test_add(SEALContext::Create(parms)); if(test_type == "Add Plain测试") test_add_plain(SEALContext::Create(parms)); if(test_type == "Mult测试") test_mult(SEALContext::Create(parms)); if(test_type == "Mult Plain测试") test_mult_plain(SEALContext::Create(parms)); if(test_type == "Sub测试") test_sub(SEALContext::Create(parms)); if(test_type == "Sub Plain测试") test_sub_plain(SEALContext::Create(parms)); if(test_type == "Square测试") test_square(SEALContext::Create(parms)); if(test_type == "Negation测试") test_negation(SEALContext::Create(parms)); if(test_type == "Rotate rows one step测试") test_rotate_rows_one_step(SEALContext::Create(parms)); if(test_type == "Rotate rows random测试") test_rotate_rows_random(SEALContext::Create(parms)); if(test_type == "Rotate columns测试") test_rotate_columns(SEALContext::Create(parms)); if(test_type == "Encryption测试") test_encryption(SEALContext::Create(parms)); if(test_type == "Decryption测试") test_decryption(SEALContext::Create(parms)); if(test_type == "Batching测试") test_batching(SEALContext::Create(parms)); if(test_type == "Unbatching测试") test_unbatching(SEALContext::Create(parms)); } void BaseTestSealBFV::BaseBFV256(int poly_modulus_degree, int coeff_modulus, int plain_modulus) { EncryptionParameters parms(scheme_type::BFV); parms.set_poly_modulus_degree(poly_modulus_degree); parms.set_coeff_modulus(DefaultParams::coeff_modulus_256(coeff_modulus)); parms.set_plain_modulus(plain_modulus); if(test_type == "Add测试") test_add(SEALContext::Create(parms)); if(test_type == "Add Plain测试") test_add_plain(SEALContext::Create(parms)); if(test_type == "Mult测试") test_mult(SEALContext::Create(parms)); if(test_type == "Mult Plain测试") test_mult_plain(SEALContext::Create(parms)); if(test_type == "Sub测试") test_sub(SEALContext::Create(parms)); if(test_type == "Sub Plain测试") test_sub_plain(SEALContext::Create(parms)); if(test_type == "Square测试") test_square(SEALContext::Create(parms)); if(test_type == "Negation测试") test_negation(SEALContext::Create(parms)); if(test_type == "Rotate rows one step测试") test_rotate_rows_one_step(SEALContext::Create(parms)); if(test_type == "Rotate rows random测试") test_rotate_rows_random(SEALContext::Create(parms)); if(test_type == "Rotate columns测试") test_rotate_columns(SEALContext::Create(parms)); if(test_type == "Encryption测试") test_encryption(SEALContext::Create(parms)); if(test_type == "Decryption测试") test_decryption(SEALContext::Create(parms)); if(test_type == "Batching测试") test_batching(SEALContext::Create(parms)); if(test_type == "Unbatching测试") test_unbatching(SEALContext::Create(parms)); } void BaseTestSealBFV::on_TestType_activated(const QString &arg1) { test_type = arg1; } void BaseTestSealBFV::on_ToBeginTesting_clicked() { if (security_parameters == 128) BaseBFV128(poly_modulus_degree, coeff_modulus, plain_modulus); if (security_parameters == 192) BaseBFV192(poly_modulus_degree, coeff_modulus, plain_modulus); if (security_parameters == 256) BaseBFV256(poly_modulus_degree, coeff_modulus, plain_modulus); } void BaseTestSealBFV::on_Return_clicked() { MainWindow *win = new MainWindow; this->hide(); win->show(); } void BaseTestSealBFV::on_lineEdit_textChanged(const QString &arg1) { ui->lineEdit->setValidator(new QRegExpValidator(QRegExp("[0-9]+$"))); test_number = arg1.toInt(); } void BaseTestSealBFV::on_security_parameters_activated(const QString &arg1) { QMap<QString, int> map_security_parameters; map_security_parameters.insert("128(默认)",128); map_security_parameters.insert("192",192); map_security_parameters.insert("256",256); security_parameters = map_security_parameters[arg1]; } void BaseTestSealBFV::on_poly_modulus_degree_activated(const QString &arg1) { QMap<QString, int> map_poly_modulus_degree; map_poly_modulus_degree.insert("1024(默认)",1024); map_poly_modulus_degree.insert("2048",2048); map_poly_modulus_degree.insert("4096",4096); map_poly_modulus_degree.insert("8192",8192); map_poly_modulus_degree.insert("16384",16384); map_poly_modulus_degree.insert("32768",32768); poly_modulus_degree = map_poly_modulus_degree[arg1]; } void BaseTestSealBFV::on_coeff_modulus_activated(const QString &arg1) { QMap<QString, int> map_coeff_modulus; map_coeff_modulus.insert("4096(默认)",4096); map_coeff_modulus.insert("8192",8192); map_coeff_modulus.insert("16384",16384); map_coeff_modulus.insert("32768",32768); coeff_modulus = map_coeff_modulus[arg1]; } void BaseTestSealBFV::on_plain_modulus_activated(const QString &arg1) { QMap<QString, int> map_plain_modulus; map_plain_modulus.insert("786433(默认)",786433); plain_modulus = map_plain_modulus[arg1]; }
30.317681
119
0.650593
YiJingGuo
c6a733a50739af5698ff6b9effb7d5fed8075c8b
397
cpp
C++
src/server/quantum_chess/pseudo_random_coin.cpp
Santoi/quantum-chess
a2f5a0f322c6aa51488c52c8ebacbe0ad75ca9f9
[ "MIT" ]
9
2021-12-22T02:10:34.000Z
2021-12-30T17:14:25.000Z
src/server/quantum_chess/pseudo_random_coin.cpp
Santoi/quantum-chess
a2f5a0f322c6aa51488c52c8ebacbe0ad75ca9f9
[ "MIT" ]
null
null
null
src/server/quantum_chess/pseudo_random_coin.cpp
Santoi/quantum-chess
a2f5a0f322c6aa51488c52c8ebacbe0ad75ca9f9
[ "MIT" ]
null
null
null
#include "pseudo_random_coin.h" #include <ctime> #include <iostream> PseudoRandomCoin::PseudoRandomCoin() : engine(clock() * time(nullptr)), random(true) {} PseudoRandomCoin::PseudoRandomCoin(bool random_) : engine(), random(random_) { } bool PseudoRandomCoin::flip() { if (!random) return true; uint64_t number = engine(); return number % 2; }
23.352941
78
0.639798
Santoi
c6abce6e3958e03498b21c32fb67ae8accaf256f
2,219
hpp
C++
include/re_fft/Hann_window.hpp
reBass/reFFT
96f83a7b62d8329ac8d6304706c4ab981851807e
[ "MIT" ]
null
null
null
include/re_fft/Hann_window.hpp
reBass/reFFT
96f83a7b62d8329ac8d6304706c4ab981851807e
[ "MIT" ]
null
null
null
include/re_fft/Hann_window.hpp
reBass/reFFT
96f83a7b62d8329ac8d6304706c4ab981851807e
[ "MIT" ]
null
null
null
// Copyright (c) 2016 Roman Beránek. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #pragma once #include <cmath> #include <algorithm> #include <array> #include <iterator> #include <functional> #include "common.hpp" namespace reFFT { template<typename T, std::ptrdiff_t N> class Hann_window { static_assert(std::is_floating_point<T>::value); public: Hann_window() noexcept { encache(); } template <class InputIt, class OutputIt> void cut(InputIt in, OutputIt out) const noexcept { std::transform( std::cbegin(cache), std::cend(cache), in, out, std::multiplies<>() ); } static constexpr T norm_correction() { return 0.5f; } private: void encache() noexcept { for (auto i = 0; i < N; ++i) { cache[i] = window_function(i); } } static constexpr T window_function(std::ptrdiff_t position) noexcept { auto relative_position = static_cast<T>(position) / N; return (1 - std::cos(relative_position * 2 * pi<T>)) / 2; } std::array<T, N> cache; }; }
27.395062
80
0.666066
reBass
c6ad9b376203cda37a8b26abcf028d1281c25a73
682
hpp
C++
libs/input/include/sge/input/create_multi_system.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/input/include/sge/input/create_multi_system.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/input/include/sge/input/create_multi_system.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_INPUT_CREATE_MULTI_SYSTEM_HPP_INCLUDED #define SGE_INPUT_CREATE_MULTI_SYSTEM_HPP_INCLUDED #include <sge/input/system_unique_ptr.hpp> #include <sge/input/detail/symbol.hpp> #include <sge/input/plugin/collection_fwd.hpp> #include <fcppt/log/context_reference_fwd.hpp> namespace sge::input { SGE_INPUT_DETAIL_SYMBOL sge::input::system_unique_ptr create_multi_system(fcppt::log::context_reference, sge::input::plugin::collection const &); } #endif
28.416667
91
0.777126
cpreh
c6b1f0820d1be7cff2557652df4b47a71ca9ada0
889
cpp
C++
examples/xtd.core.examples/date_time/date_time_day_of_year/src/date_time_day_of_year.cpp
BaderEddineOuaich/xtd
6f28634c7949a541d183879d2de18d824ec3c8b1
[ "MIT" ]
1
2022-02-25T16:53:06.000Z
2022-02-25T16:53:06.000Z
examples/xtd.core.examples/date_time/date_time_day_of_year/src/date_time_day_of_year.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
null
null
null
examples/xtd.core.examples/date_time/date_time_day_of_year/src/date_time_day_of_year.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
null
null
null
#include <xtd/xtd> using namespace xtd; class program { public: static void main() { date_time dec31(2010, 12, 31); for (uint32_t ctr = 0U; ctr <= 10U; ctr++) { date_time date_to_display = dec31.add_years(ctr); console::write_line("{0:d}: day {1} of {2} {3}", date_to_display, date_to_display.day_of_year(), date_to_display.year(), date_time::is_leap_year(date_to_display.year()) ? "(Leap Year)" : ""); } } }; startup_(program); // This code can produces the following output: // // 12/31/2010: day 365 of 2010 // 12/31/2011: day 365 of 2011 // 12/31/2012: day 366 of 2012 (Leap Year) // 12/31/2013: day 365 of 2013 // 12/31/2014: day 365 of 2014 // 12/31/2015: day 365 of 2015 // 12/31/2016: day 366 of 2016 (Leap Year) // 12/31/2017: day 365 of 2017 // 12/31/2018: day 365 of 2018 // 12/31/2019: day 365 of 2019 // 12/31/2020: day 366 of 2020 (Leap Year)
28.677419
197
0.653543
BaderEddineOuaich
c6b5381f26390ab20db9de13b6e6dbbe7d4ea86b
4,553
hpp
C++
irohad/network/impl/channel_factory.hpp
Insafin/iroha
5e3c3252b2a62fa887274bdf25547dc264c10c26
[ "Apache-2.0" ]
1,467
2016-10-25T12:27:19.000Z
2022-03-28T04:32:05.000Z
irohad/network/impl/channel_factory.hpp
Insafin/iroha
5e3c3252b2a62fa887274bdf25547dc264c10c26
[ "Apache-2.0" ]
2,366
2016-10-25T10:07:57.000Z
2022-03-31T22:03:24.000Z
irohad/network/impl/channel_factory.hpp
Insafin/iroha
5e3c3252b2a62fa887274bdf25547dc264c10c26
[ "Apache-2.0" ]
662
2016-10-26T04:41:22.000Z
2022-03-31T04:15:02.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_CHANNEL_FACTORY_HPP #define IROHA_CHANNEL_FACTORY_HPP #include "network/impl/channel_provider.hpp" #include <memory> #include <set> #include <string> #include <grpc++/grpc++.h> #include "common/result.hpp" #include "interfaces/common_objects/types.hpp" #include "network/impl/grpc_channel_params.hpp" namespace iroha { namespace network { namespace detail { grpc::ChannelArguments makeChannelArguments( const std::set<std::string> &services, const GrpcChannelParams &params); grpc::ChannelArguments makeInterPeerChannelArguments( const std::set<std::string> &services, const GrpcChannelParams &params); } // namespace detail /** * Creates channel arguments for inter-peer communication. * @tparam Service type for gRPC stub, e.g. proto::Yac * @param params grpc channel params * @return gRPC channel arguments */ template <typename Service> grpc::ChannelArguments makeInterPeerChannelArguments( const GrpcChannelParams &params) { return detail::makeInterPeerChannelArguments( {Service::service_full_name()}, params); } /** * Creates a channel * @tparam Service type for gRPC stub, e.g. proto::Yac * @param address ip address and port for connection, ipv4:port * @param maybe_params grpc channel params * @return grpc channel with provided params */ template <typename Service> std::shared_ptr<grpc::Channel> createInsecureChannel( const shared_model::interface::types::AddressType &address, std::optional<std::reference_wrapper<GrpcChannelParams const>> maybe_params) { return createInsecureChannel( address, Service::service_full_name(), maybe_params); } /** * Creates a channel * @param address ip address and port to connect to, ipv4:port * @param service_full_name gRPC service full name, * e.g. iroha.consensus.yac.proto.Yac * @param maybe_params grpc channel params * @return grpc channel with provided params */ std::shared_ptr<grpc::Channel> createInsecureChannel( const shared_model::interface::types::AddressType &address, const std::string &service_full_name, std::optional<std::reference_wrapper<GrpcChannelParams const>> maybe_params); /** * Creates client * @tparam Service type for gRPC stub, e.g. proto::Yac * @param address ip address and port for connection, ipv4:port * @param maybe_params grpc channel params * @return gRPC stub of parametrized type */ template <typename Service> std::unique_ptr<typename Service::StubInterface> createInsecureClient( const std::string &address, std::optional<std::reference_wrapper<GrpcChannelParams const>> params) { return Service::NewStub(createInsecureChannel<Service>(address, params)); } /** * Creates client * @tparam Service type for gRPC stub, e.g. proto::Yac * @param address ip address to connect to * @param port port to connect to * @param params grpc channel params * @return gRPC stub of parametrized type */ template <typename Service> std::unique_ptr<typename Service::StubInterface> createInsecureClient( const std::string &ip, size_t port, std::optional<std::reference_wrapper<GrpcChannelParams const>> maybe_params) { return createInsecureClient<Service>(ip + ":" + std::to_string(port), maybe_params); } class ChannelFactory : public ChannelProvider { public: /// @param params grpc channel params ChannelFactory( std::optional<std::shared_ptr<const GrpcChannelParams>> maybe_params); ~ChannelFactory() override; iroha::expected::Result<std::shared_ptr<grpc::Channel>, std::string> getChannel(const std::string &service_full_name, const shared_model::interface::Peer &peer) override; protected: virtual iroha::expected::Result<std::shared_ptr<grpc::ChannelCredentials>, std::string> getChannelCredentials(const shared_model::interface::Peer &) const; private: class ChannelArgumentsProvider; std::unique_ptr<ChannelArgumentsProvider> args_; }; } // namespace network } // namespace iroha #endif
33.977612
80
0.670327
Insafin
c6b70c4430ac01a93cb0d5f4ff6d031c0de4bcc7
616
cpp
C++
sorting-the-sentence/sorting-the-sentence.cpp
sharmishtha2401/leetcode
0c7389877afb64b3ff277f075ed9c87b24cb587b
[ "MIT" ]
1
2022-02-14T07:57:07.000Z
2022-02-14T07:57:07.000Z
sorting-the-sentence/sorting-the-sentence.cpp
sharmishtha2401/leetcode
0c7389877afb64b3ff277f075ed9c87b24cb587b
[ "MIT" ]
null
null
null
sorting-the-sentence/sorting-the-sentence.cpp
sharmishtha2401/leetcode
0c7389877afb64b3ff277f075ed9c87b24cb587b
[ "MIT" ]
null
null
null
class Solution { public: string sortSentence(string s) { vector<string> pos(10,""); for(int i=0; i<s.size(); i++) { int j=i; string temp=""; while(!isdigit(s[j])) { temp+=s[j]; j++; } pos[s[j]-'0']=temp; i=j+1; } string res=""; for(int i=1; i<10; i++) { if(pos[i].size()>0) { res+=pos[i]; res+=" "; } } res.pop_back(); return res; } };
20.533333
37
0.303571
sharmishtha2401
c6b8ae276ea89ab55e574431b759ea716580fd79
2,781
cpp
C++
3rdParty/fuerte/src/loop.cpp
snykiotcubedev/arangodb-3.7.6
fce8f85f1c2f070c8e6a8e76d17210a2117d3833
[ "Apache-2.0" ]
1
2020-10-27T12:19:33.000Z
2020-10-27T12:19:33.000Z
3rdParty/fuerte/src/loop.cpp
charity1475/arangodb
32bef3ed9abef6f41a11466fe6361ae3e6d99b5e
[ "Apache-2.0" ]
109
2022-01-06T07:05:24.000Z
2022-03-21T01:39:35.000Z
3rdParty/fuerte/src/loop.cpp
charity1475/arangodb
32bef3ed9abef6f41a11466fe6361ae3e6d99b5e
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Christoph Uhde //////////////////////////////////////////////////////////////////////////////// #include <memory> #include <fuerte/FuerteLogger.h> #include <fuerte/loop.h> #include <fuerte/types.h> #ifdef __linux__ #include <sys/prctl.h> #endif namespace arangodb { namespace fuerte { inline namespace v1 { EventLoopService::EventLoopService(unsigned int threadCount, char const* name) : _lastUsed(0), _sslContext(nullptr) { for (unsigned i = 0; i < threadCount; i++) { _ioContexts.emplace_back(std::make_shared<asio_ns::io_context>(1)); _guards.emplace_back(asio_ns::make_work_guard(*_ioContexts.back())); asio_ns::io_context* ctx = _ioContexts.back().get(); _threads.emplace_back([=]() { #ifdef __linux__ // set name of threadpool thread, so threads can be distinguished from each other if (name != nullptr && *name != '\0') { prctl(PR_SET_NAME, name, 0, 0, 0); } #endif ctx->run(); }); } } EventLoopService::~EventLoopService() { stop(); } asio_ns::ssl::context& EventLoopService::sslContext() { std::lock_guard<std::mutex> guard(_sslContextMutex); if (!_sslContext) { #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) _sslContext.reset(new asio_ns::ssl::context(asio_ns::ssl::context::tls)); #else _sslContext.reset(new asio_ns::ssl::context(asio_ns::ssl::context::sslv23)); #endif _sslContext->set_default_verify_paths(); } return *_sslContext; } void EventLoopService::stop() { // allow run() to exit, wait for threads to finish only then stop the context std::for_each(_guards.begin(), _guards.end(), [](auto& g) { g.reset(); }); std::this_thread::sleep_for(std::chrono::milliseconds(50)); std::for_each(_ioContexts.begin(), _ioContexts.end(), [](auto& c) { c->stop(); }); std::this_thread::sleep_for(std::chrono::milliseconds(50)); std::for_each(_threads.begin(), _threads.end(), [](auto& t) { if (t.joinable()) { t.join(); } }); } }}} // namespace arangodb::fuerte::v1
34.333333
99
0.649407
snykiotcubedev
c6bbb40d95571820d1ce00e1c360cfe93bc39512
2,759
cpp
C++
src/move.cpp
hang-sun1/spareduck
d56c5174c6e8e21b8845af100e7147e272a88b2a
[ "MIT" ]
1
2022-02-19T03:19:33.000Z
2022-02-19T03:19:33.000Z
src/move.cpp
hang-sun1/spareduck
d56c5174c6e8e21b8845af100e7147e272a88b2a
[ "MIT" ]
null
null
null
src/move.cpp
hang-sun1/spareduck
d56c5174c6e8e21b8845af100e7147e272a88b2a
[ "MIT" ]
null
null
null
#include "move.hpp" #include "piece.hpp" #include <optional> Move::Move(uint16_t from, uint16_t to, MoveType type) { move_repr = (from << 10) | (to << 4) | static_cast<uint16_t>(type); this->t = type; captured = std::nullopt; } // New move from algebraic notation. Move::Move(std::string from, std::string to) { uint16_t from_square = (from[0] - 'a') | 7 | (from[1] - '1') << 3; uint16_t to_square = (to[0] - 'a') | 7 | (from[1] - '1') << 3; MoveType type = MoveType::QUIET; move_repr = (from_square << 10) | (to_square << 4) | static_cast<uint16_t>(type); this->t = type; captured = std::nullopt; } Move::Move() { } std::ostream& operator<<(std::ostream& strm, const Move& move) { return strm << " (" << move.origin_square_algebraic() << ", " << move.destination_square_algebraic() << ") "; } bool operator==(const Move& lhs, const Move& rhs) { return lhs.get_move_repr() == rhs.get_move_repr(); } uint16_t Move::get_move_repr() const { return this->move_repr; } uint16_t Move::origin_square() const { return move_repr >> 10; } uint16_t Move::destination_square() const { return (move_repr >> 4) & 63; } MoveType Move::type() const { return t; } bool Move::is_capture() const { auto as_integer = static_cast<uint16_t>(t); return as_integer == 2 || as_integer > 8 || t == MoveType::EN_PASSANT; } bool Move::is_promotion() const { auto as_integer = static_cast<uint16_t>(t); return as_integer >= 5 && as_integer <= 12; } std::string Move::origin_square_algebraic() const{ uint16_t origin = origin_square(); char algebraic_move[3] = {(char)((origin & 7) + 'a'), (char)((origin >> 3) + '1'), '\0'}; return std::string(algebraic_move); } std::string Move::destination_square_algebraic() const { uint16_t destination = destination_square(); char algebraic_move[3] = {(char)((destination & 7) + 'a'), (char)((destination >> 3) + '1'), '\0'}; return std::string(algebraic_move); } std::array<uint16_t, 2> Move::origin_square_cartesian() const { uint16_t origin = origin_square(); return {static_cast<uint16_t>(origin & 7), static_cast<uint16_t>(origin >> 3)}; } std::array<uint16_t, 2> Move::destination_square_cartesian()const { uint16_t destination = destination_square(); return {static_cast<uint16_t>(destination & 7), static_cast<uint16_t>(destination >> 3)}; } void Move::set_moved(Piece p) { moved = p; } void Move::set_captured(Piece p) { captured = std::make_optional(p); } Piece Move::get_moved() { return moved; } std::optional<Piece> Move::get_captured() { return captured; }
27.316832
113
0.617253
hang-sun1
c6c2ab7497289fe7aa4f864189e0d82de8f62fc0
2,856
cpp
C++
hd2605/Driver.cpp
flowerinthenight/tidrv2605-haptic-driver-umdf
51ee51aae1536079e22b20b84e9a3daad38df016
[ "MIT" ]
null
null
null
hd2605/Driver.cpp
flowerinthenight/tidrv2605-haptic-driver-umdf
51ee51aae1536079e22b20b84e9a3daad38df016
[ "MIT" ]
null
null
null
hd2605/Driver.cpp
flowerinthenight/tidrv2605-haptic-driver-umdf
51ee51aae1536079e22b20b84e9a3daad38df016
[ "MIT" ]
null
null
null
#include "Internal.h" // #include "SpbAccelerometer.h" // IDL Generated File #include "LenHapticDriverDrv2605.h" // IDL Generated File #include "Device.h" #include "__dump.h" #include "Driver.h" #include "Driver.tmh" ///////////////////////////////////////////////////////////////////////// // // CMyDriver::CMyDriver // // Object constructor function // ///////////////////////////////////////////////////////////////////////// CMyDriver::CMyDriver() { } ///////////////////////////////////////////////////////////////////////// // // CMyDriver::OnDeviceAdd // // The framework call this function when device is detected. This driver // creates a device callback object // // Parameters: // pDriver - pointer to an IWDFDriver object // pDeviceInit - pointer to a device initialization object // // Return Values: // S_OK: device initialized successfully // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDriver::OnDeviceAdd(_In_ IWDFDriver *pDriver, _In_ IWDFDeviceInitialize *pDeviceInit) { CComObject<CMyDevice>* pMyDevice = nullptr; HRESULT hr; L2(WFN, L"Called."); hr = CMyDevice::CreateInstance(pDriver, pDeviceInit, &pMyDevice); if (FAILED(hr)) { Trace( TRACE_LEVEL_ERROR, "Failed to create instance of CMyDevice, %!HRESULT!", hr); } if (SUCCEEDED(hr)) { hr = pMyDevice->Configure(); if (FAILED(hr)) { Trace( TRACE_LEVEL_ERROR, "Failed to configure CMyDevice %p, %!HRESULT!", pMyDevice, hr); } // Release the pMyDevice pointer when done. // Note: UMDF holds a reference to it above SAFE_RELEASE(pMyDevice); } return hr; } ///////////////////////////////////////////////////////////////////////// // // CMyDriver::OnInitialize // // The framework calls this function just after loading the driver. The driver // can perform any global, device independent intialization in this routine. // ///////////////////////////////////////////////////////////////////////// HRESULT CMyDriver::OnInitialize(_In_ IWDFDriver *pDriver) { UNREFERENCED_PARAMETER(pDriver); L2(WFN, L"Called."); return S_OK; } ///////////////////////////////////////////////////////////////////////// // // CMyDriver::OnDeinitialize // // The framework calls this function just before de-initializing itself. All // WDF framework resources should be released by driver before returning // from this call. // ///////////////////////////////////////////////////////////////////////// void CMyDriver::OnDeinitialize(_In_ IWDFDriver *pDriver) { UNREFERENCED_PARAMETER(pDriver); return; }
28.56
97
0.496849
flowerinthenight
c6c6f33acb1fc50ae971467181fab017ae005126
593
cc
C++
src/extensions/compact/compact16_unweighted_acceptor-fst.cc
unixnme/openfst
159ee426d79485f6769a122a264e94f73da88642
[ "Apache-2.0" ]
1
2020-05-11T00:44:54.000Z
2020-05-11T00:44:54.000Z
src/extensions/compact/compact16_unweighted_acceptor-fst.cc
unixnme/openfst
159ee426d79485f6769a122a264e94f73da88642
[ "Apache-2.0" ]
null
null
null
src/extensions/compact/compact16_unweighted_acceptor-fst.cc
unixnme/openfst
159ee426d79485f6769a122a264e94f73da88642
[ "Apache-2.0" ]
null
null
null
// See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #include <fst/compact-fst.h> #include <fst/fst.h> namespace fst { static FstRegisterer< CompactUnweightedAcceptorFst<StdArc, uint16>> CompactUnweightedAcceptorFst_StdArc_uint16_registerer; static FstRegisterer< CompactUnweightedAcceptorFst<LogArc, uint16>> CompactUnweightedAcceptorFst_LogArc_uint16_registerer; static FstRegisterer< CompactUnweightedAcceptorFst<Log64Arc, uint16>> CompactUnweightedAcceptorFst_Log64Arc_uint16_registerer; } // namespace fst
26.954545
67
0.812816
unixnme
c6c6f6da4b1fd326fa5d7a0196f2e98745e9aa28
17,225
cpp
C++
Source/DlgSystemEditor/Private/Commandlets/DlgExportTwineCommandlet.cpp
derossm/DlgSystem
69d4539067fa4c5c8cc26cdb7cc019cf0576cd5a
[ "MIT" ]
97
2020-03-09T11:37:10.000Z
2022-03-31T23:45:00.000Z
Source/DlgSystemEditor/Private/Commandlets/DlgExportTwineCommandlet.cpp
derossm/DlgSystem
69d4539067fa4c5c8cc26cdb7cc019cf0576cd5a
[ "MIT" ]
1
2020-03-06T07:35:35.000Z
2020-03-07T15:31:13.000Z
Source/DlgSystemEditor/Private/Commandlets/DlgExportTwineCommandlet.cpp
derossm/DlgSystem
69d4539067fa4c5c8cc26cdb7cc019cf0576cd5a
[ "MIT" ]
16
2021-03-20T17:29:13.000Z
2022-03-30T08:28:42.000Z
// Copyright Csaba Molnar, Daniel Butum. All Rights Reserved. #include "DlgExportTwineCommandlet.h" #include "Misc/Paths.h" #include "Misc/FileHelper.h" #if ENGINE_MAJOR_VERSION >= 5 #include "HAL/PlatformFileManager.h" #else #include "HAL/PlatformFilemanager.h" #endif #include "GenericPlatform/GenericPlatformFile.h" #include "UObject/Package.h" #include "FileHelpers.h" #include "DlgManager.h" #include "Nodes/DlgNode_Speech.h" #include "Nodes/DlgNode_SpeechSequence.h" #include "DialogueEditor/Nodes/DialogueGraphNode.h" #include "DlgCommandletHelper.h" #include "DlgHelper.h" DEFINE_LOG_CATEGORY(LogDlgExportTwineCommandlet); const FString UDlgExportTwineCommandlet::TagNodeStart(TEXT("node-start")); const FString UDlgExportTwineCommandlet::TagNodeEnd(TEXT("node-end")); const FString UDlgExportTwineCommandlet::TagNodeVirtualParent(TEXT("node-virtual-parent")); const FString UDlgExportTwineCommandlet::TagNodeSpeech(TEXT("node-speech")); const FString UDlgExportTwineCommandlet::TagNodeSpeechSequence(TEXT("node-speech-sequence")); const FString UDlgExportTwineCommandlet::TagNodeSelectorFirst(TEXT("node-selector-first")); const FString UDlgExportTwineCommandlet::TagNodeSelectorRandom(TEXT("node-selector-random")); const FIntPoint UDlgExportTwineCommandlet::SizeSmall(100, 100); const FIntPoint UDlgExportTwineCommandlet::SizeWide(200, 100); const FIntPoint UDlgExportTwineCommandlet::SizeTall(100, 200); const FIntPoint UDlgExportTwineCommandlet::SizeLarge(200, 200); TMap<FString, FString> UDlgExportTwineCommandlet::TwineTagNodesColorsMap; UDlgExportTwineCommandlet::UDlgExportTwineCommandlet() { IsClient = false; IsEditor = true; IsServer = false; LogToConsole = true; ShowErrorCount = true; } int32 UDlgExportTwineCommandlet::Main(const FString& Params) { UE_LOG(LogDlgExportTwineCommandlet, Display, TEXT("Starting")); InitTwinetagNodesColors(); // Parse command line - we're interested in the param vals TArray<FString> Tokens; TArray<FString> Switches; TMap<FString, FString> ParamVals; UCommandlet::ParseCommandLine(*Params, Tokens, Switches, ParamVals); if (Switches.Contains(TEXT("Flatten"))) { bFlatten = true; } // Set the output directory const FString* OutputDirectoryVal = ParamVals.Find(FString(TEXT("OutputDirectory"))); if (OutputDirectoryVal == nullptr) { UE_LOG(LogDlgExportTwineCommandlet, Error, TEXT("Did not provide argument -OutputDirectory=<Path>")); return -1; } OutputDirectory = *OutputDirectoryVal; if (OutputDirectory.IsEmpty()) { UE_LOG(LogDlgExportTwineCommandlet, Error, TEXT("OutputDirectory is empty, please provide a non empty one with -OutputDirectory=<Path>")); return -1; } // Make it absolute if (FPaths::IsRelative(OutputDirectory)) { OutputDirectory = FPaths::Combine(FPaths::ProjectDir(), OutputDirectory); } // Create destination directory IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile(); if (!PlatformFile.DirectoryExists(*OutputDirectory) && PlatformFile.CreateDirectoryTree(*OutputDirectory)) { UE_LOG(LogDlgExportTwineCommandlet, Display, TEXT("Creating OutputDirectory = `%s`"), *OutputDirectory); } UDlgManager::LoadAllDialoguesIntoMemory(); UE_LOG(LogDlgExportTwineCommandlet, Display, TEXT("Exporting to = `%s`"), *OutputDirectory); // Some Dialogues may be unclean? //FDlgCommandletHelper::SaveAllDialogues(); // Keep track of all created files so that we don't have duplicates TSet<FString> CreateFiles; // Export to twine const TArray<UDlgDialogue*> AllDialogues = UDlgManager::GetAllDialoguesFromMemory(); for (const UDlgDialogue* Dialogue : AllDialogues) { UPackage* Package = Dialogue->GetOutermost(); check(Package); const FString OriginalDialoguePath = Package->GetPathName(); FString DialoguePath = OriginalDialoguePath; // Only export game dialogues if (!FDlgHelper::IsPathInProjectDirectory(DialoguePath)) { UE_LOG(LogDlgExportTwineCommandlet, Warning, TEXT("Dialogue = `%s` is not in the game directory, ignoring"), *DialoguePath); continue; } verify(DialoguePath.RemoveFromStart(TEXT("/Game"))); const FString FileName = FPaths::GetBaseFilename(DialoguePath); const FString Directory = FPaths::GetPath(DialoguePath); FString FileSystemFilePath; if (bFlatten) { // Create in root of output directory // Make sure file does not exist FString FlattenedFileName = FileName; int32 CurrentTryIndex = 1; while (CreateFiles.Contains(FlattenedFileName) && CurrentTryIndex < 100) { FlattenedFileName = FString::Printf(TEXT("%s-%d"), *FileName, CurrentTryIndex); CurrentTryIndex++; } // Give up :( if (CreateFiles.Contains(FlattenedFileName)) { UE_LOG(LogDlgExportTwineCommandlet, Warning, TEXT("Dialogue = `%s` could not generate unique flattened file, ignoring"), *DialoguePath); continue; } CreateFiles.Add(FlattenedFileName); FileSystemFilePath = OutputDirectory / FlattenedFileName + TEXT(".html"); } else { // Ensure directory tree const FString FileSystemDirectoryPath = OutputDirectory / Directory; if (!PlatformFile.DirectoryExists(*FileSystemDirectoryPath) && PlatformFile.CreateDirectoryTree(*FileSystemDirectoryPath)) { UE_LOG(LogDlgExportTwineCommandlet, Display, TEXT("Creating directory = `%s`"), *FileSystemDirectoryPath); } FileSystemFilePath = FileSystemDirectoryPath / FileName + TEXT(".html"); } // Compute minimum graph node positions const TArray<UDlgNode*>& Nodes = Dialogue->GetNodes(); MinimumGraphX = 0; MinimumGraphY = 0; if (const UDialogueGraphNode* DialogueGraphNode = Cast<UDialogueGraphNode>(Dialogue->GetStartNode().GetGraphNode())) { MinimumGraphX = FMath::Min(MinimumGraphX, DialogueGraphNode->NodePosX); MinimumGraphY = FMath::Min(MinimumGraphY, DialogueGraphNode->NodePosY); } for (const UDlgNode* Node : Nodes) { const UDialogueGraphNode* DialogueGraphNode = Cast<UDialogueGraphNode>(Node->GetGraphNode()); if (DialogueGraphNode == nullptr) { continue; } MinimumGraphX = FMath::Min(MinimumGraphX, DialogueGraphNode->NodePosX); MinimumGraphY = FMath::Min(MinimumGraphY, DialogueGraphNode->NodePosY); } //UE_LOG(LogDlgExportTwineCommandlet, Verbose, TEXT("MinimumGraphX = %d, MinimumGraphY = %d"), MinimumGraphX, MinimumGraphY); // Gather passages data CurrentNodesAreas.Empty(); FString PassagesData; PassagesData += CreateTwinePassageDataFromNode(*Dialogue, Dialogue->GetStartNode(), INDEX_NONE) + TEXT("\n"); // The rest of the nodes for (int32 NodeIndex = 0; NodeIndex < Nodes.Num(); NodeIndex++) { PassagesData += CreateTwinePassageDataFromNode(*Dialogue, *Nodes[NodeIndex], NodeIndex) + TEXT("\n"); } // Export file const FString TwineFileContent = CreateTwineStoryData(Dialogue->GetDialogueName(), Dialogue->GetGUID(), INDEX_NONE, PassagesData); if (FFileHelper::SaveStringToFile(TwineFileContent, *FileSystemFilePath, FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM)) { UE_LOG(LogDlgExportTwineCommandlet, Display, TEXT("Writing file = `%s` for Dialogue = `%s` "), *FileSystemFilePath, *OriginalDialoguePath); } else { UE_LOG(LogDlgExportTwineCommandlet, Error, TEXT("FAILED to write file = `%s` for Dialogue = `%s`"), *FileSystemFilePath, *OriginalDialoguePath); } } return 0; } FString UDlgExportTwineCommandlet::CreateTwineStoryData(const FString& Name, const FGuid& DialogueGUID, int32 StartNodeIndex, const FString& PassagesData) { static const FString Creator = TEXT("UE-NotYetDlgSystem"); static const FString CreatorVersion = TEXT("5.0"); // TODO static constexpr int32 Zoom = 1; static const FString Format = TEXT("Harlowe"); static const FString FormatVersion = TEXT("2.1.0"); //const FGuid UUID = FGuid::NewGuid(); return FString::Printf( TEXT("<tw-storydata name=\"%s\" startnode=\"%d\" creator=\"%s\" creator-version=\"%s\"") TEXT(" ifid=\"%s\" zoom=\"%d\" format=\"%s\" format-version=\"%s\" options=\"\" hidden>\n") TEXT("<style role=\"stylesheet\" id=\"twine-user-stylesheet\" type=\"text/twine-css\">%s</style>\n") TEXT("<script role=\"script\" id=\"twine-user-script\" type=\"text/twine-javascript\"></script>\n") // tags colors data TEXT("\n%s\n") // Special tag to identify the dialogue id //TEXT("<tw-passagedata pid=\"-1\" tags=\"\" name=\"DialogueGUID\" position=\"0,0\" size=\"10,10\">%s</tw-passagedata>\n") TEXT("%s\n") TEXT("</tw-storydata>"), *Name, StartNodeIndex + 2, *Creator, *CreatorVersion, *DialogueGUID.ToString(EGuidFormats::DigitsWithHyphens), Zoom, *Format, *FormatVersion, *CreateTwineCustomCss(), *CreateTwineTagColorsData(), *PassagesData ); } bool UDlgExportTwineCommandlet::GetBoxThatConflicts(const FBox2D& Box, FBox2D& OutConflict) { for (const FBox2D& CurrentBox : CurrentNodesAreas) { if (CurrentBox.Intersect(Box)) { OutConflict = CurrentBox; return true; } } return false; } FIntPoint UDlgExportTwineCommandlet::GetNonConflictingPointFor(const FIntPoint& Point, const FIntPoint& Size, const FIntPoint& Padding) { FVector2D MinVector(Point + Padding); FVector2D MaxVector(MinVector + Size); FBox2D NewBox(MinVector, MaxVector); FBox2D ConflictBox; while (GetBoxThatConflicts(NewBox, ConflictBox)) { //UE_LOG(LogDlgExportTwineCommandlet, Warning, TEXT("Found conflict in rectangle: %s for Point: %s"), *ConflictRect.ToString(), *NewPoint.ToString()); // Assume the curent box is a child, adjust FVector2D Center, Extent; ConflictBox.GetCenterAndExtents(Center, Extent); // Update on vertical MinVector.Y += Extent.Y / 2.f; MaxVector = MinVector + Size; NewBox = FBox2D(MinVector, MaxVector); } CurrentNodesAreas.Add(NewBox); return MinVector.IntPoint(); } FString UDlgExportTwineCommandlet::CreateTwinePassageDataFromNode(const UDlgDialogue& Dialogue, const UDlgNode& Node, int32 NodeIndex) { const UDialogueGraphNode* DialogueGraphNode = Cast<UDialogueGraphNode>(Node.GetGraphNode()); if (DialogueGraphNode == nullptr) { UE_LOG(LogDlgExportTwineCommandlet, Warning, TEXT("Invalid UDialogueGraphNode for Node index = %d in Dialogue = `%s`. Ignoring."), NodeIndex, *Dialogue.GetPathName()); return ""; } const bool bIsRootNode = DialogueGraphNode->IsRootNode(); const FString NodeName = GetNodeNameFromNode(Node, NodeIndex, bIsRootNode); FString Tags; FIntPoint Position = GraphNodeToTwineCanvas(DialogueGraphNode->NodePosX, DialogueGraphNode->NodePosY); // TODO fix this TSharedPtr<SGraphNode> NodeWidget = DialogueGraphNode->GetNodeWidget(); FIntPoint Size = SizeLarge; if (NodeWidget.IsValid()) { Size = FIntPoint(NodeWidget->GetDesiredSize().X, NodeWidget->GetDesiredSize().Y); } FString NodeContent; const FIntPoint Padding(20, 20); if (DialogueGraphNode->IsRootNode()) { verify(NodeIndex == INDEX_NONE); Tags += TagNodeStart; Size = SizeSmall; Position = GetNonConflictingPointFor(Position, Size, Padding); NodeContent += CreateTwinePassageDataLinksFromEdges(Dialogue, Node.GetNodeChildren()); return CreateTwinePassageData(NodeIndex, NodeName, Tags, Position, Size, NodeContent); } verify(NodeIndex >= 0); if (DialogueGraphNode->IsVirtualParentNode()) { // Edges from this node do not matter Tags += TagNodeVirtualParent; Position = GetNonConflictingPointFor(Position, Size, Padding); //CurrentNodesAreas.Add(FIntRect(Position + Padding, Position + Size + Padding)); const UDlgNode_Speech& NodeSpeech = DialogueGraphNode->GetDialogueNode<UDlgNode_Speech>(); NodeContent += EscapeHtml(NodeSpeech.GetNodeUnformattedText().ToString()); NodeContent += TEXT("\n\n\n") + CreateTwinePassageDataLinksFromEdges(Dialogue, Node.GetNodeChildren(), true); return CreateTwinePassageData(NodeIndex, NodeName, Tags, Position, Size, NodeContent); } if (DialogueGraphNode->IsSpeechNode()) { Tags += TagNodeSpeech; Position = GetNonConflictingPointFor(Position, Size, Padding); //CurrentNodesAreas.Add(FIntRect(Position + Padding, Position + Size + Padding)); const UDlgNode_Speech& NodeSpeech = DialogueGraphNode->GetDialogueNode<UDlgNode_Speech>(); NodeContent += EscapeHtml(NodeSpeech.GetNodeUnformattedText().ToString()); NodeContent += TEXT("\n\n\n") + CreateTwinePassageDataLinksFromEdges(Dialogue, Node.GetNodeChildren()); return CreateTwinePassageData(NodeIndex, NodeName, Tags, Position, Size, NodeContent); } if (DialogueGraphNode->IsEndNode()) { // Does not have any children/text Tags += TagNodeEnd; Size = SizeSmall; Position = GetNonConflictingPointFor(Position, Size, Padding); //CurrentNodesAreas.Add(FIntRect(Position + Padding, Position + Size + Padding)); NodeContent += TEXT("END"); return CreateTwinePassageData(NodeIndex, NodeName, Tags, Position, Size, NodeContent); } if (DialogueGraphNode->IsSelectorNode()) { // Does not have any text and text for edges does not matter if (DialogueGraphNode->IsSelectorFirstNode()) { Tags += TagNodeSelectorFirst; } if (DialogueGraphNode->IsSelectorRandomNode()) { Tags += TagNodeSelectorRandom; } Size = SizeSmall; Position = GetNonConflictingPointFor(Position, Size, Padding); NodeContent += TEXT("SELECTOR\n"); NodeContent += CreateTwinePassageDataLinksFromEdges(Dialogue, Node.GetNodeChildren(), true); return CreateTwinePassageData(NodeIndex, NodeName, Tags, Position, Size, NodeContent); } if (DialogueGraphNode->IsSpeechSequenceNode()) { Tags += TagNodeSpeechSequence; Position = GetNonConflictingPointFor(Position, Size, Padding); const UDlgNode_SpeechSequence& NodeSpeechSequence = DialogueGraphNode->GetDialogueNode<UDlgNode_SpeechSequence>(); // Fill sequence const TArray<FDlgSpeechSequenceEntry>& Sequence = NodeSpeechSequence.GetNodeSpeechSequence(); for (int32 EntryIndex = 0; EntryIndex < Sequence.Num(); EntryIndex++) { const FDlgSpeechSequenceEntry& Entry = Sequence[EntryIndex]; NodeContent += FString::Printf( TEXT("``Speaker:`` //%s//\n") TEXT("``Text:`` //%s//\n") TEXT("``EdgeText:`` //%s//\n"), *EscapeHtml(Entry.Speaker.ToString()), *EscapeHtml(Entry.Text.ToString()), *EscapeHtml(Entry.EdgeText.ToString()) ); if (EntryIndex != Sequence.Num() - 1) { NodeContent += TEXT("---\n"); } } NodeContent += TEXT("\n\n\n") + CreateTwinePassageDataLinksFromEdges(Dialogue, Node.GetNodeChildren()); return CreateTwinePassageData(NodeIndex, NodeName, Tags, Position, Size, NodeContent); } UE_LOG(LogDlgExportTwineCommandlet, Warning, TEXT("Node index = %d not handled in Dialogue = `%s`. Ignoring."), NodeIndex, *Dialogue.GetPathName()); return ""; } FString UDlgExportTwineCommandlet::GetNodeNameFromNode(const UDlgNode& Node, int32 NodeIndex, bool bIsRootNode) { return FString::Printf(TEXT("%d. %s"), NodeIndex, bIsRootNode ? TEXT("START") : *Node.GetNodeParticipantName().ToString()); } FString UDlgExportTwineCommandlet::CreateTwinePassageDataLinksFromEdges(const UDlgDialogue& Dialogue, const TArray<FDlgEdge>& Edges, bool bNoTextOnEdges) { FString Links; const TArray<UDlgNode*>& Nodes = Dialogue.GetNodes(); for (const FDlgEdge& Edge : Edges) { if (!Edge.IsValid()) { continue; } if (!Nodes.IsValidIndex(Edge.TargetIndex)) { UE_LOG(LogDlgExportTwineCommandlet, Warning, TEXT("Target index = %d not valid. Ignoring"), Edge.TargetIndex); continue; } FString EdgeText; if (bNoTextOnEdges || Edge.GetUnformattedText().IsEmpty()) { EdgeText = FString::Printf(TEXT("~ignore~ To Node %d"), Edge.TargetIndex); } else { EdgeText = EscapeHtml(Edge.GetUnformattedText().ToString()); } Links += FString::Printf(TEXT("[[%s|%s]]\n"), *EdgeText, *GetNodeNameFromNode(*Nodes[Edge.TargetIndex], Edge.TargetIndex, false)); } Links.RemoveFromEnd(TEXT("\n")); return Links; } FString UDlgExportTwineCommandlet::CreateTwinePassageData(int32 Pid, const FString& Name, const FString& Tags, const FIntPoint& Position, const FIntPoint& Size, const FString& Content) { return FString::Printf( TEXT("<tw-passagedata pid=\"%d\" name=\"%s\" tags=\"%s\" position=\"%d, %d\" size=\"%d, %d\">%s</tw-passagedata>"), Pid + 2, *Name, *Tags, Position.X, Position.Y, Size.X, Size.Y, *Content ); } FString UDlgExportTwineCommandlet::CreateTwineCustomCss() { return TEXT("#storyEditView.passage.tags div.cyan { background: #19e5e6; }"); } FString UDlgExportTwineCommandlet::CreateTwineTagColorsData() { InitTwinetagNodesColors(); FString TagColorsString; for (const auto& Elem : TwineTagNodesColorsMap) { TagColorsString += FString::Printf( TEXT("<tw-tag name=\"%s\" color=\"%s\"></tw-tag>\n"), *Elem.Key, *Elem.Value ); } return TagColorsString; } void UDlgExportTwineCommandlet::InitTwinetagNodesColors() { if (TwineTagNodesColorsMap.Num() > 0) { return; } TwineTagNodesColorsMap.Add(TagNodeStart, TEXT("green")); TwineTagNodesColorsMap.Add(TagNodeEnd, TEXT("red")); TwineTagNodesColorsMap.Add(TagNodeVirtualParent, TEXT("blue")); TwineTagNodesColorsMap.Add(TagNodeSpeech, TEXT("blue")); TwineTagNodesColorsMap.Add(TagNodeSpeechSequence, TEXT("blue")); TwineTagNodesColorsMap.Add(TagNodeSelectorFirst, TEXT("purple")); TwineTagNodesColorsMap.Add(TagNodeSelectorRandom, TEXT("yellow")); }
35.36961
184
0.743745
derossm
c6ca0d727904f77b73da4471badfb5bdca03db13
2,235
cpp
C++
Plataformer_2D/Motor2D/UI_button.cpp
marcpt98/Plataformer-2D
edeb43bc3c886293bcc6bdece9e831d5e5eecdf0
[ "Unlicense" ]
1
2020-02-24T11:14:38.000Z
2020-02-24T11:14:38.000Z
Plataformer_2D/Motor2D/UI_button.cpp
marcpt98/Plataformer-2D
edeb43bc3c886293bcc6bdece9e831d5e5eecdf0
[ "Unlicense" ]
null
null
null
Plataformer_2D/Motor2D/UI_button.cpp
marcpt98/Plataformer-2D
edeb43bc3c886293bcc6bdece9e831d5e5eecdf0
[ "Unlicense" ]
null
null
null
#include "UI_Button.h" #include "j1App.h" #include "j1Render.h" #include "UI_Button.h" #include "j1App.h" #include "j1Scene_UI.h" #include "j1Render.h" #include "j1Input.h" #include "p2Log.h" #include "j1Audio.h" void UI_button::BlitElement() { BROFILER_CATEGORY("Blitbutton", Profiler::Color::OldLace) iPoint globalPos = calculateAbsolutePosition(); App->input->GetMousePosition(x, y); ChangeVolume(); switch (state) { case STANDBY: if (element_action != SLIDER_BUTTON && element_action != SLIDER_FX_BUTTON) { App->render->Blit(texture, globalPos.x, globalPos.y, &section, false); } else { App->render->Blit(texture, localPosition.x, globalPos.y, &section, false); } break; case MOUSEOVER: if (element_action != SLIDER_BUTTON && element_action != SLIDER_FX_BUTTON) { App->render->Blit(texture, globalPos.x - 10, globalPos.y - 3, &OnMouse, false); } else { App->render->Blit(texture, localPosition.x, globalPos.y, &section, false); } break; case CLICKED: if (element_action != SLIDER_BUTTON && element_action != SLIDER_FX_BUTTON) { App->render->Blit(texture, globalPos.x, globalPos.y, &OnClick, false); } else { newposition = x; App->render->Blit(texture, localPosition.x -10, globalPos.y, &section, false); } break; } } void UI_button::ChangeVolume() { if (App->sceneui->slider_volume == true && x > 206 && x < 760 && element_action == SLIDER_BUTTON)//206 760 { localPosition.x = x-10; save_position = x; OnMouse.x = x; Tick.x = x; OnClick.x = x; iPoint globalPos=calculateAbsolutePosition(); LOG("position: %i", localPosition.x);//197 746 musicvolume = (((localPosition.x - 197) * 1.) / 552); App->audio->setMusicVolume(musicvolume); LOG("position: %f", musicvolume); } if (App->sceneui->fx_volume == true && x > 206 && x < 760 && element_action == SLIDER_FX_BUTTON)//206 760 { localPosition.x = x - 10; save_position = x; OnMouse.x = x; Tick.x = x; OnClick.x = x; iPoint globalPos = calculateAbsolutePosition(); LOG("position: %i", localPosition.x);//197 746 fxvolume = (((localPosition.x-197) * 1.) / 552); App->audio->setFxVolume(fxvolume); LOG("position: %f", musicvolume); } }//App->audio->setMusicVolume(0.2);
27.592593
107
0.672036
marcpt98
c6caae90dcdd350a46bab6e49dcd4efccbbd6b18
1,457
cc
C++
code/qttoolkit/contentbrowser/code/widgets/models/physicsnodehandler.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/qttoolkit/contentbrowser/code/widgets/models/physicsnodehandler.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/qttoolkit/contentbrowser/code/widgets/models/physicsnodehandler.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // physicsnodehandler.cc // (C) 2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "physicsnodehandler.h" namespace Widgets { __ImplementClass(Widgets::PhysicsNodeHandler, 'PHNR', Core::RefCounted); //------------------------------------------------------------------------------ /** */ PhysicsNodeHandler::PhysicsNodeHandler() { // empty } //------------------------------------------------------------------------------ /** */ PhysicsNodeHandler::~PhysicsNodeHandler() { // empty } //------------------------------------------------------------------------------ /** */ void PhysicsNodeHandler::AddNode(const Util::String& name) { QLabel* label = new QLabel; label->setAlignment(Qt::AlignRight); label->setText(name.AsCharPtr()); this->ui->nodeFrame->layout()->addWidget(label); this->labels.Append(label); } //------------------------------------------------------------------------------ /** */ void PhysicsNodeHandler::Discard() { IndexT i; for (i = 0; i < this->labels.Size(); i++) { delete this->labels[i]; } this->labels.Clear(); } //------------------------------------------------------------------------------ /** */ void PhysicsNodeHandler::OnMaterialChanged(int index) { //this->modelHandler->GetPhysics()->set } } // namespace Widgets
22.765625
80
0.423473
gscept
c6cda49d327bf72afc71dab3d78fba575e97af35
229
inl
C++
include/beluga/tcp/tcp_server.inl
Stazer/beluga
38232796669524c4f6b08f281e5a367390de24d0
[ "MIT" ]
1
2021-04-16T08:37:37.000Z
2021-04-16T08:37:37.000Z
include/beluga/tcp/tcp_server.inl
Stazer/beluga
38232796669524c4f6b08f281e5a367390de24d0
[ "MIT" ]
null
null
null
include/beluga/tcp/tcp_server.inl
Stazer/beluga
38232796669524c4f6b08f281e5a367390de24d0
[ "MIT" ]
null
null
null
template <typename... args> std::shared_ptr<beluga::tcp_server> beluga::tcp_server::create(args&&... params) { // TODO std::make_shared return std::shared_ptr<tcp_server>(new tcp_server(std::forward<args>(params)...)); }
32.714286
86
0.703057
Stazer
c6d03f1cbec76c59ab232b04369b88501a5eaad8
4,712
cpp
C++
unicorn-bios/UB/FAT/DAP.cpp
macmade/unicorn-bios
97a53ff5c8c418e79f0f5798da3d365b2ceaa7f2
[ "MIT" ]
96
2019-07-23T20:32:38.000Z
2022-02-13T23:55:27.000Z
unicorn-bios/UB/FAT/DAP.cpp
macmade/unicorn-bios
97a53ff5c8c418e79f0f5798da3d365b2ceaa7f2
[ "MIT" ]
null
null
null
unicorn-bios/UB/FAT/DAP.cpp
macmade/unicorn-bios
97a53ff5c8c418e79f0f5798da3d365b2ceaa7f2
[ "MIT" ]
20
2019-07-30T03:46:45.000Z
2022-02-03T12:03:26.000Z
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2019 Jean-David Gadina - www.xs-labs.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "UB/FAT/DAP.hpp" #include "UB/BinaryStream.hpp" namespace UB { namespace FAT { class DAP::IMPL { public: IMPL( void ); IMPL( const IMPL & o ); IMPL( BinaryStream & stream ); ~IMPL( void ); uint8_t _size; uint8_t _zero; uint16_t _numberOfSectors; uint16_t _destinationOffset; uint16_t _destinationSegment; uint64_t _logicalBlockAddress; }; size_t DAP::DataSize( void ) { return 16; } DAP::DAP( void ): impl( std::make_unique< IMPL >() ) {} DAP::DAP( const DAP & o ): impl( std::make_unique< IMPL >( *( o.impl ) ) ) {} DAP::DAP( BinaryStream & stream ): impl( std::make_unique< IMPL >( stream ) ) {} DAP::DAP( DAP && o ) noexcept: impl( std::move( o.impl ) ) {} DAP::~DAP( void ) {} DAP & DAP::operator =( DAP o ) { swap( *( this ), o ); return *( this ); } uint8_t DAP::size( void ) const { return this->impl->_size; } uint8_t DAP::zero( void ) const { return this->impl->_zero; } uint16_t DAP::numberOfSectors( void ) const { return this->impl->_numberOfSectors; } uint16_t DAP::destinationOffset( void ) const { return this->impl->_destinationOffset; } uint16_t DAP::destinationSegment( void ) const { return this->impl->_destinationSegment; } uint64_t DAP::logicalBlockAddress( void ) const { return this->impl->_logicalBlockAddress; } void swap( DAP & o1, DAP & o2 ) { using std::swap; swap( o1.impl, o2.impl ); } DAP::IMPL::IMPL( void ): _size( 0 ), _zero( 0 ), _numberOfSectors( 0 ), _destinationOffset( 0 ), _destinationSegment( 0 ), _logicalBlockAddress( 0 ) {} DAP::IMPL::IMPL( BinaryStream & stream ): _size( stream.readUInt8() ), _zero( stream.readUInt8() ), _numberOfSectors( stream.readLittleEndianUInt16() ), _destinationOffset( stream.readLittleEndianUInt16() ), _destinationSegment( stream.readLittleEndianUInt16() ), _logicalBlockAddress( stream.readLittleEndianUInt16() ) {} DAP::IMPL::IMPL( const IMPL & o ): _size( o._size ), _zero( o._zero ), _numberOfSectors( o._numberOfSectors ), _destinationOffset( o._destinationOffset ), _destinationSegment( o._destinationSegment ), _logicalBlockAddress( o._logicalBlockAddress ) {} DAP::IMPL::~IMPL( void ) {} } }
31.837838
80
0.500212
macmade
c6d16090d4b50170b20214d663036fdd6c2a0041
14,482
hh
C++
dune/hdd/linearelliptic/discreteproblem.hh
tobiasleibner/dune-hdd
35a122c1c6fd019aebbdbb8ee1eb8a36ae2f2b26
[ "BSD-2-Clause" ]
null
null
null
dune/hdd/linearelliptic/discreteproblem.hh
tobiasleibner/dune-hdd
35a122c1c6fd019aebbdbb8ee1eb8a36ae2f2b26
[ "BSD-2-Clause" ]
null
null
null
dune/hdd/linearelliptic/discreteproblem.hh
tobiasleibner/dune-hdd
35a122c1c6fd019aebbdbb8ee1eb8a36ae2f2b26
[ "BSD-2-Clause" ]
null
null
null
// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETEPROBLEM_HH #define DUNE_HDD_LINEARELLIPTIC_DISCRETEPROBLEM_HH #include <memory> #include <limits> #include <boost/numeric/conversion/cast.hpp> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/mpihelper.hh> # include <dune/common/timer.hh> # if HAVE_DUNE_FEM # include <dune/fem/misc/mpimanager.hh> # endif #include <dune/stuff/common/reenable_warnings.hh> #if HAVE_DUNE_GRID_MULTISCALE # include <dune/grid/multiscale/provider.hh> #endif #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/string.hh> #include <dune/stuff/grid/provider.hh> #include <dune/stuff/grid/boundaryinfo.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/grid/layers.hh> #include <dune/stuff/common/memory.hh> #include "problems.hh" namespace Dune { namespace HDD { namespace LinearElliptic { template< class GridImp > class DiscreteProblem { public: typedef GridImp GridType; typedef Stuff::Grid::ProviderInterface< GridType > GridProviderType; private: typedef Stuff::GridProviders< GridType > GridProviders; typedef typename GridType::LeafIntersection IntersectionType; typedef Stuff::Grid::BoundaryInfoProvider< IntersectionType > BoundaryInfoProvider; typedef typename GridType::template Codim< 0 >::Entity EntityType; typedef typename GridType::ctype DomainFieldType; static const unsigned int dimDomain = GridType::dimension; public: typedef double RangeFieldType; static const unsigned int dimRange = 1; typedef LinearElliptic::ProblemInterface< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType; typedef LinearElliptic::ProblemsProvider< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemsProvider; static void write_config(const std::string filename, const std::string id) { std::ofstream file; file.open(filename); file << "[" << id << "]" << std::endl; write_keys_to_file("gridprovider", GridProviders::available(), file); write_keys_to_file("boundaryinfo", BoundaryInfoProvider::available(), file); write_keys_to_file("problem", ProblemsProvider::available(), file); file << "[logging]" << std::endl; file << "info = true" << std::endl; file << "debug = true" << std::endl; file << "file = false" << std::endl; file << "visualize = true" << std::endl; file << "[parameter]" << std::endl; file << "0.diffusion_factor = [0.1 0.1 1.0 1.0]" << std::endl; file << "1.diffusion_factor = [1.0 1.0 0.1 0.1]" << std::endl; write_config_to_file< GridProviders >(file); write_config_to_file< BoundaryInfoProvider >(file); write_config_to_file< ProblemsProvider >(file); file.close(); } // ... write_config(...) DiscreteProblem(const std::string id, const std::vector< std::string >& arguments) { // mpi assert(arguments.size() < std::numeric_limits< int >::max()); int argc = boost::numeric_cast< int >(arguments.size()); char** argv = Stuff::Common::String::vectorToMainArgs(arguments); #if HAVE_DUNE_FEM Fem::MPIManager::initialize(argc, argv); #else MPIHelper::instance(argc, argv); #endif // configuration config_ = Stuff::Common::Configuration(argc, argv, id + ".cfg"); if (!config_.has_sub(id)) DUNE_THROW(Stuff::Exceptions::configuration_error, "Missing sub '" << id << "' in the following Configuration:\n\n" << config_); filename_ = config_.get(id + ".filename", id); // logger const Stuff::Common::Configuration logger_config = config_.sub("logging"); int log_flags = Stuff::Common::LOG_CONSOLE; debug_logging_ = logger_config.get< bool >("debug", false); if (logger_config.get< bool >("info")) log_flags = log_flags | Stuff::Common::LOG_INFO; if (debug_logging_) log_flags = log_flags | Stuff::Common::LOG_DEBUG; if (logger_config.get< bool >("file", false)) log_flags = log_flags | Stuff::Common::LOG_FILE; Stuff::Common::Logger().create(log_flags, id, "", ""); auto& info = Stuff::Common::Logger().info(); Timer timer; const std::string griprovider_type = config_.get< std::string >(id + ".gridprovider"); info << "creating grid with '" << griprovider_type << "'... " << std::flush; grid_provider_ = GridProviders::create(griprovider_type, config_); const auto grid_view = grid_provider_->leaf_view(); info << " done (took " << timer.elapsed() << "s, has " << grid_view.indexSet().size(0) << " element"; if (grid_view.indexSet().size(0) > 1) info << "s"; info << ")" << std::endl; const std::string boundary_info_type = config_.get< std::string >(id + ".boundaryinfo"); if (config_.has_sub(boundary_info_type)) boundary_info_ = config_.sub(boundary_info_type); else boundary_info_ = Stuff::Common::Configuration("type", boundary_info_type); info << "setting up "; timer.reset(); const std::string problem_type = config_.get< std::string >(id + ".problem"); if (!debug_logging_) info << "'" << problem_type << "'... " << std::flush; problem_ = ProblemsProvider::create(problem_type, config_); if (debug_logging_) info << *problem_ << std::endl; else info << "done (took " << timer.elapsed() << "s)" << std::endl; if (logger_config.get("visualize", true)) { info << "visualizing grid and problem... " << std::flush; timer.reset(); grid_provider_->visualize(boundary_info_, filename_ + ".grid"); problem_->visualize(grid_view, filename_ + ".problem"); info << "done (took " << timer.elapsed() << "s)" << std::endl; } // if (visualize) } // DiscreteProblem std::string filename() const { return filename_; } const Stuff::Common::Configuration& config() const { return config_; } bool debug_logging() const { return debug_logging_; } GridProviderType& grid_provider() { return *grid_provider_; } const GridProviderType& grid_provider() const { return *grid_provider_; } const Stuff::Common::Configuration& boundary_info() const { return boundary_info_; } const ProblemType& problem() const { return *problem_; } private: static void write_keys_to_file(const std::string name, const std::vector< std::string > keys, std::ofstream& file) { std::string whitespace = Stuff::Common::whitespaceify(name + " = "); file << name << " = " << keys[0] << std::endl; for (size_t ii = 1; ii < keys.size(); ++ii) file << whitespace << keys[ii] << std::endl; } // ... write_keys_to_file(...) template< class ConfigProvider > static void write_config_to_file(std::ofstream& file) { for (const auto& type : ConfigProvider::available()) { auto config = ConfigProvider::default_config(type, type); if (!config.empty()) file << config; } } // ... write_config_to_file(...) std::string filename_; Stuff::Common::Configuration config_; bool debug_logging_; std::unique_ptr< GridProviderType > grid_provider_; Stuff::Common::Configuration boundary_info_; std::unique_ptr< const ProblemType > problem_; }; // class DiscreteProblem #if HAVE_DUNE_GRID_MULTISCALE template< class GridImp > class DiscreteBlockProblem { public: typedef GridImp GridType; typedef grid::Multiscale::ProviderInterface< GridType > GridProviderType; typedef grid::Multiscale::MsGridProviders< GridType > GridProviders; typedef typename GridType::LeafIntersection IntersectionType; typedef Stuff::Grid::BoundaryInfoProvider< IntersectionType > BoundaryInfoProvider; typedef typename GridType::template Codim< 0 >::Entity EntityType; typedef typename GridType::ctype DomainFieldType; static const unsigned int dimDomain = GridType::dimension; typedef double RangeFieldType; static const unsigned int dimRange = 1; typedef LinearElliptic::ProblemInterface < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType; typedef LinearElliptic::ProblemsProvider < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemsProvider; static void write_config(const std::string filename, const std::string id, const Stuff::Common::Configuration& problem_cfg = Stuff::Common::Configuration(), const Stuff::Common::Configuration& grid_cfg = Stuff::Common::Configuration(), const Stuff::Common::Configuration& additional_cfg = Stuff::Common::Configuration()) { std::ofstream file; file.open(filename); file << "[" << id << "]" << std::endl; if (grid_cfg.has_key("type")) file << "gridprovider = " << grid_cfg.get< std::string >("type") << std::endl; else write_keys_to_file("gridprovider", GridProviders::available(), file); if (problem_cfg.has_key("type")) file << "problem = " << problem_cfg.get< std::string >("type") << std::endl; else write_keys_to_file("problem", ProblemsProvider::available(), file); file << "[logging]" << std::endl; file << "info = true" << std::endl; file << "debug = false" << std::endl; file << "file = false" << std::endl; file << "visualize = true" << std::endl; if (grid_cfg.has_key("type")) file << Stuff::Common::Configuration(grid_cfg, grid_cfg.get< std::string >("type")); else write_config_to_file< GridProviders >(file); if (problem_cfg.has_key("type")) file << Stuff::Common::Configuration(problem_cfg, problem_cfg.get< std::string >("type")); else write_config_to_file< ProblemsProvider >(file); file << additional_cfg; file.close(); } // ... write_config(...) DiscreteBlockProblem(const std::string id, const std::vector< std::string >& arguments) { // mpi int argc = boost::numeric_cast< int >(arguments.size()); char** argv = Stuff::Common::String::vectorToMainArgs(arguments); #if HAVE_DUNE_FEM Fem::MPIManager::initialize(argc, argv); #else MPIHelper::instance(argc, argv); #endif // configuration config_ = Stuff::Common::Configuration(argc, argv, id + ".cfg"); if (!config_.has_sub(id)) DUNE_THROW(Stuff::Exceptions::configuration_error, "Missing sub '" << id << "' in the following Configuration:\n\n" << config_); filename_ = config_.get(id + ".filename", id); // logger const Stuff::Common::Configuration logger_config = config_.sub("logging"); int log_flags = Stuff::Common::LOG_CONSOLE; debug_logging_ = logger_config.get< bool >("debug", false); if (logger_config.get< bool >("info")) log_flags = log_flags | Stuff::Common::LOG_INFO; if (debug_logging_) log_flags = log_flags | Stuff::Common::LOG_DEBUG; if (logger_config.get< bool >("file", false)) log_flags = log_flags | Stuff::Common::LOG_FILE; Stuff::Common::Logger().create(log_flags, id, "", ""); auto& info = Stuff::Common::Logger().info(); Timer timer; const std::string griprovider_type = config_.get< std::string >(id + ".gridprovider"); info << "creating grid with '" << griprovider_type << "'..." << std::flush; grid_provider_ = GridProviders::create(griprovider_type, config_); const auto grid_view = grid_provider_->leaf_view(); info << " done (took " << timer.elapsed() << "s, has " << grid_view.indexSet().size(0) << " element"; if (grid_view.indexSet().size(0) > 1) info << "s"; info << ")" << std::endl; boundary_info_ = Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config(); // info << "setting up "; // timer.reset(); const std::string problem_type = config_.get< std::string >(id + ".problem"); // if (!debug_logging_) // info << "'" << problem_type << "'... " << std::flush; problem_ = ProblemsProvider::create(problem_type, config_); // if (debug_logging_) // info << *problem_ << std::endl; // else // info << "done (took " << timer.elapsed() << "s)" << std::endl; if (logger_config.get("visualize", true)) { info << "visualizing grid and problem... " << std::flush; timer.reset(); grid_provider_->visualize(filename_ + ".ms_grid", false); grid_provider_->visualize(boundary_info_, filename_ + ".grid"); problem_->visualize(grid_view, filename_ + ".problem"); info << "done (took " << timer.elapsed() << "s)" << std::endl; } // if (visualize) } // DiscreteBlockProblem std::string filename() const { return filename_; } const Stuff::Common::Configuration& config() const { return config_; } bool debug_logging() const { return debug_logging_; } GridProviderType& grid_provider() { return *grid_provider_; } const GridProviderType& grid_provider() const { return *grid_provider_; } const Stuff::Common::Configuration& boundary_info() const { return boundary_info_; } const ProblemType& problem() const { return *problem_; } private: static void write_keys_to_file(const std::string name, const std::vector< std::string > keys, std::ofstream& file) { std::string whitespace = Stuff::Common::whitespaceify(name + " = "); file << name << " = " << keys[0] << std::endl; for (size_t ii = 1; ii < keys.size(); ++ii) file << whitespace << keys[ii] << std::endl; } // ... write_keys_to_file(...) template< class ConfigProvider > static void write_config_to_file(std::ofstream& file) { for (const auto& type : ConfigProvider::available()) { auto config = ConfigProvider::default_config(type, type); if (!config.empty()) file << config; } } // ... write_config_to_file(...) std::string filename_; Stuff::Common::Configuration config_; bool debug_logging_; std::unique_ptr< GridProviderType > grid_provider_; Stuff::Common::Configuration boundary_info_; std::unique_ptr< const ProblemType > problem_; }; // class DiscreteBlockProblem #endif // HAVE_DUNE_GRID_MULTISCALE } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_LINEARELLIPTIC_DISCRETEPROBLEM_HH
35.408313
128
0.66593
tobiasleibner
c6d4482769886d70fab3078b6cab93305126ed75
2,721
hpp
C++
Axis.Capsicum/services/memory/gpu/BcBlockLayout.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.Capsicum/services/memory/gpu/BcBlockLayout.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.Capsicum/services/memory/gpu/BcBlockLayout.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#pragma once #include "services/memory/MemoryLayout.hpp" namespace axis { namespace services { namespace memory { namespace gpu { /** * Describes memory layout of a boundary condition descriptor block. */ class BcBlockLayout : public axis::services::memory::MemoryLayout { public: /** * Constructor. * * @param specificDataSize Total length of data that is specific to boundary * condition implementation. */ BcBlockLayout(int specificDataSize); virtual ~BcBlockLayout(void); virtual MemoryLayout& Clone( void ) const; /** * Initialises the memory block. * * @param [in,out] targetBlock Base memory address of the target block. * @param dofId Unique identifier of the associated degree of * freedom. */ void InitMemoryBlock(void *targetBlock, uint64 dofId); /** * Returns the base address of boundary condition implementation-related data. * * @param [in,out] bcBaseAddress Base memory address of the boundary condition * descriptor block. * * @return The custom data base address. */ void *GetCustomDataAddress(void *bcBaseAddress) const; /** * Returns the base address of boundary condition implementation-related data. * * @param [in,out] bcBaseAddress Base memory address of the boundary condition * descriptor block. * * @return The custom data base address. */ const void *GetCustomDataAddress(const void *bcBaseAddress) const; /** * Returns the address of the output slot where the boundary condition shall * write its updated value. * * @param [in,out] bcBaseAddress Base memory address of the boundary condition * descriptor block. * * @return The output slot address. */ real *GetOutputBucketAddress(void *bcBaseAddress) const; /** * Returns the address of the output slot where the boundary condition shall * write its updated value. * * @param [in,out] bcBaseAddress Base memory address of the boundary condition * descriptor block. * * @return The output slot address. */ const real *GetOutputBucketAddress(const void *bcBaseAddress) const; /** * Returns the unique identifier of the degree of freedom associated to this * boundary condition. * * @param [in,out] bcBaseAddress Base memory address of the boundary condition * descriptor block. * * @return The degree of freedom identifier. */ uint64 GetDofId(void *bcBaseAddress) const; private: virtual size_type DoGetSegmentSize( void ) const; real blockSize_; }; } } } } // namespace axis::services::memory::gpu
29.901099
80
0.670342
renato-yuzup
c6d6869a2c901168d82504b9f3d7aa7a31c4f8dc
453
cpp
C++
18_minimum_path_sum.cpp
Mohit-Nathrani/30-day-leetcoding-challenge
7eff9bb3faee8b7a720b6a712226319b9a56d588
[ "MIT" ]
null
null
null
18_minimum_path_sum.cpp
Mohit-Nathrani/30-day-leetcoding-challenge
7eff9bb3faee8b7a720b6a712226319b9a56d588
[ "MIT" ]
null
null
null
18_minimum_path_sum.cpp
Mohit-Nathrani/30-day-leetcoding-challenge
7eff9bb3faee8b7a720b6a712226319b9a56d588
[ "MIT" ]
null
null
null
class Solution { public: int minPathSum(vector<vector<int>>& grid) { int n=grid.size(); int m=grid[0].size(); for(int i=n-1;i>=0;i--){ for(int j=m-1;j>=0;j--){ if(j<m-1 && i<n-1) grid[i][j]+=min(grid[i][j+1], grid[i+1][j]); else if(j<m-1) grid[i][j]+=grid[i][j+1]; else if(i<n-1) grid[i][j]+=grid[i+1][j]; } } return grid[0][0]; } };
30.2
79
0.412804
Mohit-Nathrani
c6d7410ecf178a28f536f0694339d7380d7e4c84
1,561
cpp
C++
C++/prison-cells-after-n-days.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/prison-cells-after-n-days.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/prison-cells-after-n-days.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(1) // Space: O(1) class Solution { public: vector<int> prisonAfterNDays(vector<int>& cells, int N) { for (N = (N - 1) % 14 + 1; N > 0; --N) { vector<int> cells2(8); for (int i = 1; i < 7; ++i) { cells2[i] = static_cast<int>(cells[i - 1] == cells[i + 1]); } cells = move(cells2); } return cells; } }; // Time: O(1) // Space: O(1) class Solution2 { public: vector<int> prisonAfterNDays(vector<int>& cells, int N) { unordered_map<vector<int>, int, VectorHash<int>> lookup; while (N) { lookup[cells] = N--; vector<int> cells2(8); for (int i = 1; i < 7; ++i) { cells2[i] = static_cast<int>(cells[i - 1] == cells[i + 1]); } cells = move(cells2); if (lookup.count(cells)) { N %= lookup[cells] - N; break; } } while (N--) { vector<int> cells2(8); for (int i = 1; i < 7; ++i) { cells2[i] = static_cast<int>(cells[i - 1] == cells[i + 1]); } cells = move(cells2); } return cells; } private: template<typename T> struct VectorHash { size_t operator()(const std::vector<T>& v) const { size_t seed = 0; for (const auto& i : v) { seed ^= std::hash<T>{}(i) + 0x9e3779b9 + (seed<<6) + (seed>>2); } return seed; } }; };
26.457627
80
0.424728
jaiskid
c6d82bcc9c0861f6854916b85589305a014d48e5
199
cpp
C++
NetServer/MessageParser.cpp
CRAFTSTARCN/PlayBall-Server
c50974a2e688ad0834e5381a6a202d7e2b896799
[ "Apache-2.0" ]
1
2021-06-14T16:14:43.000Z
2021-06-14T16:14:43.000Z
NetServer/MessageParser.cpp
CRAFTSTARCN/PlayBall-Server
c50974a2e688ad0834e5381a6a202d7e2b896799
[ "Apache-2.0" ]
null
null
null
NetServer/MessageParser.cpp
CRAFTSTARCN/PlayBall-Server
c50974a2e688ad0834e5381a6a202d7e2b896799
[ "Apache-2.0" ]
null
null
null
/* MessageParser.cpp Created 2021/6/14 By: Ag2S */ #include "MessageParser.h" DataObject* MessageParser::generalStrParser(const std::string str, int& st) { //TODO return nullptr; }
16.583333
77
0.678392
CRAFTSTARCN
c6d947fe9fe3a2c82918b29766a7d62042f8bf2e
259
cpp
C++
tests/test.cpp
CrestoniX/Lab3.0
7c01142ca420628cd97d5e053d17b79870214de0
[ "MIT" ]
null
null
null
tests/test.cpp
CrestoniX/Lab3.0
7c01142ca420628cd97d5e053d17b79870214de0
[ "MIT" ]
null
null
null
tests/test.cpp
CrestoniX/Lab3.0
7c01142ca420628cd97d5e053d17b79870214de0
[ "MIT" ]
1
2019-12-27T11:28:32.000Z
2019-12-27T11:28:32.000Z
// Copyright 2019 CrestoniX <[email protected]> #include <gtest/gtest.h> #include <SharedPtr.hpp> TEST(Control_Block, Test) { EXPECT_EQ(counter, 0); } TEST(SharedPtr, Tests) { EXPECT_EQ(ptr, nullptr); EXPECT_EQ(control_block, nullptr); }
21.583333
55
0.714286
CrestoniX
c6dfbbc588926fc16cfdd360435abba247d4b596
813
cpp
C++
WrecklessEngine/PixelShader.cpp
ThreadedStream/WrecklessEngine
735ac601914c2445b8eef72a14ec0fcd4d0d12d2
[ "MIT" ]
9
2021-02-07T21:33:41.000Z
2022-03-20T18:48:06.000Z
WrecklessEngine/PixelShader.cpp
ThreadedStream/WrecklessEngine
735ac601914c2445b8eef72a14ec0fcd4d0d12d2
[ "MIT" ]
null
null
null
WrecklessEngine/PixelShader.cpp
ThreadedStream/WrecklessEngine
735ac601914c2445b8eef72a14ec0fcd4d0d12d2
[ "MIT" ]
4
2021-02-11T15:05:35.000Z
2022-02-20T15:26:35.000Z
#include "PixelShader.h" #include "BindableCodex.h" #include "Renderer.h" using namespace Graphics; namespace Bindable { PixelShader::PixelShader(const std::string& path) { m_pShader = Renderer::GetDevice()->CreatePixelShader(path); } void* PixelShader::GetByteCode() const noexcept { return m_pShader->GetByteCode(); } Ref<PixelShader> PixelShader::Resolve(const std::string& path) { return Codex::Resolve<PixelShader>("Shaders/Bin/" + path); } std::string PixelShader::GenerateUID(const std::string& path) { using namespace std::string_literals; return typeid(PixelShader).name() + "#"s + path; } std::string PixelShader::GetUID() const noexcept { return GenerateUID(m_Path); } void PixelShader::Bind() noxnd { Renderer::GetRenderContext()->BindPixelShader(m_pShader); } }
20.846154
63
0.722017
ThreadedStream
c6e00c8d0d85c4247d5a39e261881883adf09d11
769
cpp
C++
examples/example.cpp
PDB-REDO/libcifpp
f97e742daa7c1cfd0670ad00d3aef004708a3461
[ "BSD-2-Clause" ]
7
2021-01-12T07:00:04.000Z
2022-03-11T08:44:14.000Z
examples/example.cpp
PDB-REDO/libcifpp
f97e742daa7c1cfd0670ad00d3aef004708a3461
[ "BSD-2-Clause" ]
12
2021-03-11T17:53:45.000Z
2022-02-09T15:06:04.000Z
examples/example.cpp
PDB-REDO/libcifpp
f97e742daa7c1cfd0670ad00d3aef004708a3461
[ "BSD-2-Clause" ]
7
2021-02-08T00:45:31.000Z
2021-12-06T22:37:22.000Z
#include <iostream> #include <filesystem> #include <cif++/Cif++.hpp> namespace fs = std::filesystem; int main() { fs::path in("1cbs.cif.gz"); cif::File file; file.loadDictionary("mmcif_pdbx_v50"); file.load("1cbs.cif.gz"); auto& db = file.firstDatablock()["atom_site"]; auto n = db.find(cif::Key("label_atom_id") == "OXT").size(); std::cout << "File contains " << db.size() << " atoms of which " << n << (n == 1 ? " is" : " are") << " OXT" << std::endl << "residues with an OXT are:" << std::endl; for (const auto& [asym, comp, seqnr]: db.find<std::string,std::string,int>( cif::Key("label_atom_id") == "OXT", "label_asym_id", "label_comp_id", "label_seq_id")) { std::cout << asym << ' ' << comp << ' ' << seqnr << std::endl; } return 0; }
24.03125
122
0.590377
PDB-REDO
c6e482539f28ec4dcc06e8671a02a7f88205cdf1
3,510
cpp
C++
webkit/WebCore/bindings/js/JSEventSourceConstructor.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
webkit/WebCore/bindings/js/JSEventSourceConstructor.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
webkit/WebCore/bindings/js/JSEventSourceConstructor.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * Copyright (C) 2009 Ericsson AB * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Ericsson 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 COPYRIGHT HOLDERS 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 COPYRIGHT * OWNER 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. */ #include "config.h" #if ENABLE(EVENTSOURCE) #include "JSEventSourceConstructor.h" #include "EventSource.h" #include "ExceptionCode.h" #include "JSEventSource.h" #include "ScriptExecutionContext.h" #include <runtime/Error.h> using namespace JSC; namespace WebCore { ASSERT_CLASS_FITS_IN_CELL(JSEventSourceConstructor); const ClassInfo JSEventSourceConstructor::s_info = { "EventSourceContructor", 0, 0, 0 }; JSEventSourceConstructor::JSEventSourceConstructor(ExecState* exec, JSDOMGlobalObject* globalObject) : DOMConstructorObject(JSEventSourceConstructor::createStructure(globalObject->objectPrototype()), globalObject) { putDirect(exec->propertyNames().prototype, JSEventSourcePrototype::self(exec, globalObject), None); putDirect(exec->propertyNames().length, jsNumber(exec, 1), ReadOnly|DontDelete|DontEnum); } static JSObject* constructEventSource(ExecState* exec, JSObject* constructor, const ArgList& args) { if (args.size() < 1) return throwError(exec, SyntaxError, "Not enough arguments"); UString url = args.at(0).toString(exec); if (exec->hadException()) return 0; JSEventSourceConstructor* jsConstructor = static_cast<JSEventSourceConstructor*>(constructor); ScriptExecutionContext* context = jsConstructor->scriptExecutionContext(); if (!context) return throwError(exec, ReferenceError, "EventSource constructor associated document is unavailable"); ExceptionCode ec = 0; RefPtr<EventSource> eventSource = EventSource::create(url, context, ec); if (ec) { setDOMException(exec, ec); return 0; } return asObject(toJS(exec, jsConstructor->globalObject(), eventSource.release())); } ConstructType JSEventSourceConstructor::getConstructData(ConstructData& constructData) { constructData.native.function = constructEventSource; return ConstructTypeHost; } } // namespace WebCore #endif // ENABLE(EVENTSOURCE)
38.152174
116
0.758405
s1rcheese
c6e930df04492ebf996d43d96cdbb444afe9fe03
4,763
cpp
C++
src/polycubed/src/server/Resources/Body/AbstractFactory.cpp
francescomessina/polycube
38f2fb4ffa13cf51313b3cab9994be738ba367be
[ "ECL-2.0", "Apache-2.0" ]
337
2018-12-12T11:50:15.000Z
2022-03-15T00:24:35.000Z
src/polycubed/src/server/Resources/Body/AbstractFactory.cpp
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
253
2018-12-17T21:36:15.000Z
2022-01-17T09:30:42.000Z
src/polycubed/src/server/Resources/Body/AbstractFactory.cpp
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
90
2018-12-19T15:49:38.000Z
2022-03-27T03:56:07.000Z
/* * Copyright 2018 The Polycube Authors * * 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. */ #include "AbstractFactory.h" #include <memory> #include <string> #include <utility> #include <vector> #include "CaseResource.h" #include "ChoiceResource.h" #include "JsonNodeField.h" #include "JsonValueField.h" #include "LeafListResource.h" #include "LeafResource.h" #include "ListKey.h" #include "ListResource.h" #include "ParentResource.h" namespace polycube::polycubed::Rest::Resources::Body { std::unique_ptr<Body::JsonValueField> AbstractFactory::JsonValueField() const { return std::make_unique<Body::JsonValueField>(); } std::unique_ptr<Body::JsonValueField> AbstractFactory::JsonValueField( LY_DATA_TYPE type, std::vector<std::shared_ptr<Validators::ValueValidator>> &&validators) const { return std::make_unique<Body::JsonValueField>(type, std::move(validators)); } std::unique_ptr<CaseResource> AbstractFactory::BodyCase( const std::string &name, const std::string &description, const std::string &cli_example, const Body::ParentResource *parent) const { return std::make_unique<CaseResource>(name, description, cli_example, parent, core_); } std::unique_ptr<ChoiceResource> AbstractFactory::BodyChoice( const std::string &name, const std::string &description, const std::string &cli_example, const Body::ParentResource *parent, bool mandatory, std::unique_ptr<const std::string> &&default_case) const { return std::make_unique<ChoiceResource>(name, description, cli_example, parent, core_, mandatory, std::move(default_case)); } std::unique_ptr<LeafResource> AbstractFactory::BodyLeaf( const std::string &name, const std::string &description, const std::string &cli_example, const Body::ParentResource *parent, std::unique_ptr<Body::JsonValueField> &&value_field, const std::vector<Body::JsonNodeField> &node_fields, bool configuration, bool init_only_config, bool mandatory, Types::Scalar type, std::unique_ptr<const std::string> &&default_value) const { return std::make_unique<LeafResource>( name, description, cli_example, parent, core_, std::move(value_field), node_fields, configuration, init_only_config, mandatory, type, std::move(default_value)); } std::unique_ptr<LeafListResource> AbstractFactory::BodyLeafList( const std::string &name, const std::string &description, const std::string &cli_example, const Body::ParentResource *parent, std::unique_ptr<Body::JsonValueField> &&value_field, const std::vector<JsonNodeField> &node_fields, bool configuration, bool init_only_config, bool mandatory, Types::Scalar type, std::vector<std::string> &&default_value) const { return std::make_unique<LeafListResource>( name, description, cli_example, parent, core_, std::move(value_field), node_fields, configuration, init_only_config, mandatory, type, std::move(default_value)); } std::unique_ptr<ListResource> AbstractFactory::BodyList( const std::string &name, const std::string &description, const std::string &cli_example, const Body::ParentResource *parent, std::vector<Resources::Body::ListKey> &&keys, const std::vector<JsonNodeField> &node_fields, bool configuration, bool init_only_config) const { return std::make_unique<ListResource>(name, description, cli_example, parent, core_, std::move(keys), node_fields, configuration, init_only_config); } std::unique_ptr<ParentResource> AbstractFactory::BodyGeneric( const std::string &name, const std::string &description, const std::string &cli_example, const Body::ParentResource *parent, const std::vector<JsonNodeField> &node_fields, bool configuration, bool init_only_config, bool container_presence) const { return std::make_unique<ParentResource>( name, description, cli_example, parent, core_, node_fields, configuration, init_only_config, container_presence); } AbstractFactory::AbstractFactory(PolycubedCore *core) : core_(core) {} } // namespace polycube::polycubed::Rest::Resources::Body
43.3
80
0.720134
francescomessina
c6ecb3f9d09e07d4ef170f22a9beabdfa1093d60
2,009
cpp
C++
ass3/problem2.cpp
starcraft66/COEN243-Fall-2019-Assignments
66caa4d6bf0f960218c86288e1c17bdae16b22b1
[ "BSD-3-Clause" ]
2
2021-07-24T15:01:50.000Z
2022-01-17T21:49:09.000Z
ass3/problem2.cpp
starcraft66/COEN243-Fall-2019-Assignments
66caa4d6bf0f960218c86288e1c17bdae16b22b1
[ "BSD-3-Clause" ]
null
null
null
ass3/problem2.cpp
starcraft66/COEN243-Fall-2019-Assignments
66caa4d6bf0f960218c86288e1c17bdae16b22b1
[ "BSD-3-Clause" ]
null
null
null
#include <string> #include <iostream> int main(int argc, char *argv[]) { std::string phrase; std::cout << "Enter a phrase: "; std::getline(std::cin, phrase); std::cout << phrase.size() << std::endl; int word_start = 0, temp_end = 0, word_end = 0, words = 0, proper = 0, repeat = 0; while (word_end != std::string::npos) { word_end = phrase.find(" ", word_start); if(word_end == std::string::npos) { temp_end = phrase.size(); } else { temp_end = word_end; } std::cout << phrase.substr(word_start, temp_end - word_start) << std::endl; words++; bool is_proper = true; bool is_repeat = false; char previous_letter = phrase[word_start]; for(int i = 0; i < (temp_end - word_start); i++) { if (!is_repeat) { if (i > 0) { if (phrase[word_start + i] == previous_letter) { is_repeat = true; } } } if (is_proper) { if (i == 0) { if (!(phrase[word_start + i] >= 'A' && phrase[word_start + i] <= 'Z')) { is_proper = false; } } else // i > 1 { if (!(phrase[word_start + i] >= 'a' && phrase[word_start + i] <= 'z')) { is_proper = false; } } } previous_letter = phrase[word_start + i]; } if(is_proper) { proper++; } if(is_repeat) { repeat++; } word_start = word_end + 1; } std::cout << words << std::endl; std::cout << proper << std::endl; std::cout << repeat << std::endl; }
28.7
90
0.390742
starcraft66
c6ee06713592b71f52636ffc964fb7833f6f73d7
1,614
cc
C++
obcache/libs/sql/storage.cc
sandtreader/obtools
2382e2d90bb62c9665433d6d01bbd31b8ad66641
[ "MIT" ]
null
null
null
obcache/libs/sql/storage.cc
sandtreader/obtools
2382e2d90bb62c9665433d6d01bbd31b8ad66641
[ "MIT" ]
null
null
null
obcache/libs/sql/storage.cc
sandtreader/obtools
2382e2d90bb62c9665433d6d01bbd31b8ad66641
[ "MIT" ]
null
null
null
//========================================================================== // ObTools::ObCache::SQL: storage.cc // // Implementation of SQL storage manager // // Copyright (c) 2008 Paul Clark. All rights reserved // This code comes with NO WARRANTY and is subject to licence agreement //========================================================================== #include "ot-obcache-sql.h" #include "ot-log.h" #include "ot-text.h" namespace ObTools { namespace ObCache { namespace SQL { //-------------------------------------------------------------------------- // Load an object Object *Storage::load(object_id_t id) { // Get DB connection DB::AutoConnection db(db_pool); // Look up ID in main object table, to get type ref string types = db.select_value_by_id64("root", "_type", id, "_id"); if (types.empty()) throw Exception("Attempt to load non-existent object "+Text::i64tos(id)); type_id_t type = Text::stoi64(types); // Look up storer interface by type ref map<type_id_t, Storer *>::iterator p = storers.find(type); if (p == storers.end()) throw Exception("Attempt to load unknown type "+Text::i64tos(type)); Storer *storer = p->second; // Get storer to load it, using the same DB connection return storer->load(id, db); } //-------------------------------------------------------------------------- // Save an object void Storage::save(Object * /*ob*/) { // !!! Get type name from object get_name // !!! Look up storer interface // !!! Get DB connection // !!! Get storer to save it throw Exception("Not yet implemented!"); } }}} // namespaces
27.827586
77
0.547708
sandtreader
c6f715c843a2145735014d0816d667ad033be0b1
571
cpp
C++
coding-for-fun/cpp/08_valueSwitchWithoutTemp.cpp
AnotherGithubDude/AnotherGithubDude
9ba334dfc1964e6e78920a7495865a2fc3e04d81
[ "CC0-1.0" ]
null
null
null
coding-for-fun/cpp/08_valueSwitchWithoutTemp.cpp
AnotherGithubDude/AnotherGithubDude
9ba334dfc1964e6e78920a7495865a2fc3e04d81
[ "CC0-1.0" ]
null
null
null
coding-for-fun/cpp/08_valueSwitchWithoutTemp.cpp
AnotherGithubDude/AnotherGithubDude
9ba334dfc1964e6e78920a7495865a2fc3e04d81
[ "CC0-1.0" ]
null
null
null
#include <iostream> using std::cout; using std::endl; // author: https://github.com/AnotherGithubDude, 2022 int main(){ int valueOne = 15, valueTwo = 8; cout << "valueOne original:" << valueOne << endl; cout << "valueTwo original:" << valueTwo << endl; valueOne += valueTwo; // 15 + 8 = 23 valueTwo = valueOne - valueTwo; // 23 - 8 = 15 valueOne -= valueTwo; // 23 - 15 = 8 cout << "valueOne after manipulation:" << valueOne << endl; cout << "valueTwo after manipulation:" << valueTwo << endl; return 0; }
33.588235
63
0.583187
AnotherGithubDude
c6f87265d7e832b2bf064d5cf9376071bf2540f6
1,150
hpp
C++
Level_3/II.3/CPP_2.3/CPP_2.3/LineSegment.hpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
Level_3/II.3/CPP_2.3/CPP_2.3/LineSegment.hpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
Level_3/II.3/CPP_2.3/CPP_2.3/LineSegment.hpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
// // LineSegment.hpp // CPP_2.3 // // Created by Zhehao Li on 2020/2/26. // Copyright © 2020 Zhehao Li. All rights reserved. // #ifndef LineSegment_hpp #define LineSegment_hpp #include "Point.hpp" #include <iostream> using namespace std; class LineSegment { private: Point startPoint; // e1 Point endPoint; // e2 public: // Constructor LineSegment(); // Default constructor LineSegment(const Point &p1, const Point &p2); // Initialize with two points LineSegment(const LineSegment &l); // Copy constructor // Destructor virtual ~LineSegment(); // Accessing functions Point Start() const; // May not change the data member Point End() const; // May not change the data member // Modifers void Start(const Point &pt); // Call by reference, may not change the original object void End(const Point &pt); // Overloading function name }; #endif /* LineSegment_hpp */
26.744186
112
0.551304
ZhehaoLi9705
c6ff79679ac9a8179c1b079104ba97f4879935bc
7,756
cpp
C++
android-28/android/content/pm/LauncherApps.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/content/pm/LauncherApps.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-28/android/content/pm/LauncherApps.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../ComponentName.hpp" #include "../Context.hpp" #include "../Intent.hpp" #include "../IntentSender.hpp" #include "./ApplicationInfo.hpp" #include "./LauncherActivityInfo.hpp" #include "./LauncherApps_Callback.hpp" #include "./LauncherApps_PinItemRequest.hpp" #include "./LauncherApps_ShortcutQuery.hpp" #include "./ShortcutInfo.hpp" #include "../../graphics/Rect.hpp" #include "../../graphics/drawable/Drawable.hpp" #include "../../os/Bundle.hpp" #include "../../os/Handler.hpp" #include "../../os/UserHandle.hpp" #include "../../../JString.hpp" #include "./LauncherApps.hpp" namespace android::content::pm { // Fields JString LauncherApps::ACTION_CONFIRM_PIN_APPWIDGET() { return getStaticObjectField( "android.content.pm.LauncherApps", "ACTION_CONFIRM_PIN_APPWIDGET", "Ljava/lang/String;" ); } JString LauncherApps::ACTION_CONFIRM_PIN_SHORTCUT() { return getStaticObjectField( "android.content.pm.LauncherApps", "ACTION_CONFIRM_PIN_SHORTCUT", "Ljava/lang/String;" ); } JString LauncherApps::EXTRA_PIN_ITEM_REQUEST() { return getStaticObjectField( "android.content.pm.LauncherApps", "EXTRA_PIN_ITEM_REQUEST", "Ljava/lang/String;" ); } // QJniObject forward LauncherApps::LauncherApps(QJniObject obj) : JObject(obj) {} // Constructors // Methods JObject LauncherApps::getActivityList(JString arg0, android::os::UserHandle arg1) const { return callObjectMethod( "getActivityList", "(Ljava/lang/String;Landroid/os/UserHandle;)Ljava/util/List;", arg0.object<jstring>(), arg1.object() ); } android::content::pm::ApplicationInfo LauncherApps::getApplicationInfo(JString arg0, jint arg1, android::os::UserHandle arg2) const { return callObjectMethod( "getApplicationInfo", "(Ljava/lang/String;ILandroid/os/UserHandle;)Landroid/content/pm/ApplicationInfo;", arg0.object<jstring>(), arg1, arg2.object() ); } android::content::pm::LauncherApps_PinItemRequest LauncherApps::getPinItemRequest(android::content::Intent arg0) const { return callObjectMethod( "getPinItemRequest", "(Landroid/content/Intent;)Landroid/content/pm/LauncherApps$PinItemRequest;", arg0.object() ); } JObject LauncherApps::getProfiles() const { return callObjectMethod( "getProfiles", "()Ljava/util/List;" ); } android::graphics::drawable::Drawable LauncherApps::getShortcutBadgedIconDrawable(android::content::pm::ShortcutInfo arg0, jint arg1) const { return callObjectMethod( "getShortcutBadgedIconDrawable", "(Landroid/content/pm/ShortcutInfo;I)Landroid/graphics/drawable/Drawable;", arg0.object(), arg1 ); } android::content::IntentSender LauncherApps::getShortcutConfigActivityIntent(android::content::pm::LauncherActivityInfo arg0) const { return callObjectMethod( "getShortcutConfigActivityIntent", "(Landroid/content/pm/LauncherActivityInfo;)Landroid/content/IntentSender;", arg0.object() ); } JObject LauncherApps::getShortcutConfigActivityList(JString arg0, android::os::UserHandle arg1) const { return callObjectMethod( "getShortcutConfigActivityList", "(Ljava/lang/String;Landroid/os/UserHandle;)Ljava/util/List;", arg0.object<jstring>(), arg1.object() ); } android::graphics::drawable::Drawable LauncherApps::getShortcutIconDrawable(android::content::pm::ShortcutInfo arg0, jint arg1) const { return callObjectMethod( "getShortcutIconDrawable", "(Landroid/content/pm/ShortcutInfo;I)Landroid/graphics/drawable/Drawable;", arg0.object(), arg1 ); } JObject LauncherApps::getShortcuts(android::content::pm::LauncherApps_ShortcutQuery arg0, android::os::UserHandle arg1) const { return callObjectMethod( "getShortcuts", "(Landroid/content/pm/LauncherApps$ShortcutQuery;Landroid/os/UserHandle;)Ljava/util/List;", arg0.object(), arg1.object() ); } android::os::Bundle LauncherApps::getSuspendedPackageLauncherExtras(JString arg0, android::os::UserHandle arg1) const { return callObjectMethod( "getSuspendedPackageLauncherExtras", "(Ljava/lang/String;Landroid/os/UserHandle;)Landroid/os/Bundle;", arg0.object<jstring>(), arg1.object() ); } jboolean LauncherApps::hasShortcutHostPermission() const { return callMethod<jboolean>( "hasShortcutHostPermission", "()Z" ); } jboolean LauncherApps::isActivityEnabled(android::content::ComponentName arg0, android::os::UserHandle arg1) const { return callMethod<jboolean>( "isActivityEnabled", "(Landroid/content/ComponentName;Landroid/os/UserHandle;)Z", arg0.object(), arg1.object() ); } jboolean LauncherApps::isPackageEnabled(JString arg0, android::os::UserHandle arg1) const { return callMethod<jboolean>( "isPackageEnabled", "(Ljava/lang/String;Landroid/os/UserHandle;)Z", arg0.object<jstring>(), arg1.object() ); } void LauncherApps::pinShortcuts(JString arg0, JObject arg1, android::os::UserHandle arg2) const { callMethod<void>( "pinShortcuts", "(Ljava/lang/String;Ljava/util/List;Landroid/os/UserHandle;)V", arg0.object<jstring>(), arg1.object(), arg2.object() ); } void LauncherApps::registerCallback(android::content::pm::LauncherApps_Callback arg0) const { callMethod<void>( "registerCallback", "(Landroid/content/pm/LauncherApps$Callback;)V", arg0.object() ); } void LauncherApps::registerCallback(android::content::pm::LauncherApps_Callback arg0, android::os::Handler arg1) const { callMethod<void>( "registerCallback", "(Landroid/content/pm/LauncherApps$Callback;Landroid/os/Handler;)V", arg0.object(), arg1.object() ); } android::content::pm::LauncherActivityInfo LauncherApps::resolveActivity(android::content::Intent arg0, android::os::UserHandle arg1) const { return callObjectMethod( "resolveActivity", "(Landroid/content/Intent;Landroid/os/UserHandle;)Landroid/content/pm/LauncherActivityInfo;", arg0.object(), arg1.object() ); } void LauncherApps::startAppDetailsActivity(android::content::ComponentName arg0, android::os::UserHandle arg1, android::graphics::Rect arg2, android::os::Bundle arg3) const { callMethod<void>( "startAppDetailsActivity", "(Landroid/content/ComponentName;Landroid/os/UserHandle;Landroid/graphics/Rect;Landroid/os/Bundle;)V", arg0.object(), arg1.object(), arg2.object(), arg3.object() ); } void LauncherApps::startMainActivity(android::content::ComponentName arg0, android::os::UserHandle arg1, android::graphics::Rect arg2, android::os::Bundle arg3) const { callMethod<void>( "startMainActivity", "(Landroid/content/ComponentName;Landroid/os/UserHandle;Landroid/graphics/Rect;Landroid/os/Bundle;)V", arg0.object(), arg1.object(), arg2.object(), arg3.object() ); } void LauncherApps::startShortcut(android::content::pm::ShortcutInfo arg0, android::graphics::Rect arg1, android::os::Bundle arg2) const { callMethod<void>( "startShortcut", "(Landroid/content/pm/ShortcutInfo;Landroid/graphics/Rect;Landroid/os/Bundle;)V", arg0.object(), arg1.object(), arg2.object() ); } void LauncherApps::startShortcut(JString arg0, JString arg1, android::graphics::Rect arg2, android::os::Bundle arg3, android::os::UserHandle arg4) const { callMethod<void>( "startShortcut", "(Ljava/lang/String;Ljava/lang/String;Landroid/graphics/Rect;Landroid/os/Bundle;Landroid/os/UserHandle;)V", arg0.object<jstring>(), arg1.object<jstring>(), arg2.object(), arg3.object(), arg4.object() ); } void LauncherApps::unregisterCallback(android::content::pm::LauncherApps_Callback arg0) const { callMethod<void>( "unregisterCallback", "(Landroid/content/pm/LauncherApps$Callback;)V", arg0.object() ); } } // namespace android::content::pm
30.415686
173
0.7295
YJBeetle
c6ffe920b92306e6248db3462edb7623ef403156
2,486
hpp
C++
ct_optcon/include/ct/optcon/nloc/algorithms/ilqr/iLQR.hpp
vklemm/control-toolbox
f5f8cf9331c0aecd721ff6296154e2a55c72f679
[ "BSD-2-Clause" ]
1
2019-12-01T14:45:18.000Z
2019-12-01T14:45:18.000Z
ct_optcon/include/ct/optcon/nloc/algorithms/ilqr/iLQR.hpp
deidaraho/control-toolbox
f0ccdf4b6c25e02948215fd3bff212d891f0fd69
[ "BSD-2-Clause" ]
null
null
null
ct_optcon/include/ct/optcon/nloc/algorithms/ilqr/iLQR.hpp
deidaraho/control-toolbox
f0ccdf4b6c25e02948215fd3bff212d891f0fd69
[ "BSD-2-Clause" ]
1
2021-04-01T20:05:31.000Z
2021-04-01T20:05:31.000Z
/********************************************************************************************************************** This file is part of the Control Toolbox (https://github.com/ethz-adrl/control-toolbox), copyright by ETH Zurich. Licensed under the BSD-2 license (see LICENSE file in main directory) **********************************************************************************************************************/ #pragma once #include <ct/optcon/solver/NLOptConSettings.hpp> #include <ct/optcon/nloc/NLOCAlgorithm.hpp> namespace ct { namespace optcon { template <size_t STATE_DIM, size_t CONTROL_DIM, size_t P_DIM, size_t V_DIM, typename SCALAR = double, bool CONTINUOUS = true> class iLQR : public NLOCAlgorithm<STATE_DIM, CONTROL_DIM, P_DIM, V_DIM, SCALAR, CONTINUOUS> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW static const size_t STATE_D = STATE_DIM; static const size_t CONTROL_D = CONTROL_DIM; typedef NLOCAlgorithm<STATE_DIM, CONTROL_DIM, P_DIM, V_DIM, SCALAR, CONTINUOUS> Base; typedef typename Base::Policy_t Policy_t; typedef typename Base::Settings_t Settings_t; typedef typename Base::Backend_t Backend_t; typedef SCALAR Scalar_t; //! constructor iLQR(std::shared_ptr<Backend_t>& backend_, const Settings_t& settings); //! destructor virtual ~iLQR(); //! configure the solver virtual void configure(const Settings_t& settings) override; //! set an initial guess virtual void setInitialGuess(const Policy_t& initialGuess) override; //! runIteration combines prepareIteration and finishIteration /*! * For iLQR the separation between prepareIteration and finishIteration would actually not be necessary * @return */ virtual bool runIteration() override; /*! * for iLQR, as it is a purely sequential approach, we cannot prepare anything prior to solving, */ virtual void prepareIteration() override; /*! * for iLQR, finishIteration contains the whole main iLQR iteration. * @return */ virtual bool finishIteration() override; /*! * for iLQR, as it is a purely sequential approach, we cannot prepare anything prior to solving, */ virtual void prepareMPCIteration() override; /*! * for iLQR, finishIteration contains the whole main iLQR iteration. * @return */ virtual bool finishMPCIteration() override; }; } // namespace optcon } // namespace ct
28.574713
120
0.641191
vklemm
050040d4700ee9be39dd097dea40a8b51696163d
604
cpp
C++
_Online/Codechef/UWCOI2020/d.cpp
AYUSHMOHANJHA/Code4CP
7d50d45c5446ad917b4664fc7016d3c82655d947
[ "MIT" ]
null
null
null
_Online/Codechef/UWCOI2020/d.cpp
AYUSHMOHANJHA/Code4CP
7d50d45c5446ad917b4664fc7016d3c82655d947
[ "MIT" ]
null
null
null
_Online/Codechef/UWCOI2020/d.cpp
AYUSHMOHANJHA/Code4CP
7d50d45c5446ad917b4664fc7016d3c82655d947
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { long long int V,H,O,ans=0; cin>>V>>H>>O; for(long long int i=0;i<O;i++) { long long int x1,y1,x2,y2; cin>>x1>>y1>>x2>>y2; ans= ans+ abs(x1-x2); //cout<<"out"<<ans<<endl; if(((y1==1 && y2==1))|| ((y1==y2)&&((x1==y1)||(x2==y2)))) continue; else{ if((abs(y2-y1)*2)==0) ans= ans+ 4; else { ans= ans+(abs(y2-y1)*2); } } //cout<<"ans ="<<ans<<endl; } cout<<ans<<endl; return 0; }
22.37037
75
0.397351
AYUSHMOHANJHA
05007e5873f820766c43860a3e73bad97492ad66
843
cpp
C++
C++/medium/6. ZigZag Conversion.cpp
18810817370/LeetCodePracticeJava
e800e828cc64fedbc26e37f223d16ad9fdb711c2
[ "MIT" ]
1
2019-03-19T12:04:20.000Z
2019-03-19T12:04:20.000Z
C++/medium/6. ZigZag Conversion.cpp
18810817370/LeetCodePracticeJava
e800e828cc64fedbc26e37f223d16ad9fdb711c2
[ "MIT" ]
null
null
null
C++/medium/6. ZigZag Conversion.cpp
18810817370/LeetCodePracticeJava
e800e828cc64fedbc26e37f223d16ad9fdb711c2
[ "MIT" ]
null
null
null
/** * @author zly * * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) * * P A H N * A P L S I I G * Y I R * And then read line by line: "PAHNAPLSIIGYIR" * * Write the code that will take a string and make this conversion given a number of rows: * * string convert(string s, int numRows); * * Example 1: * Input: s = "PAYPALISHIRING", numRows = 3 * Output: "PAHNAPLSIIGYIR" * * Example 2: * Input: s = "PAYPALISHIRING", numRows = 4 * Output: "PINALSIGYAHRPI" * * Explanation: * * P I N * A L S I G * Y A H R * P I */ #include <string> class Solution { public: std::string convert(std::string s, int numRows) { } };
21.075
175
0.59312
18810817370
0504259f718b7b581be2c21ed357ac6b4dd2f21d
26,447
cpp
C++
src/dialogs/StartDialog.cpp
mmahmoudian/Gittyup
96702f3b96160fff540886722f7f195163c4e41b
[ "MIT" ]
127
2021-10-29T19:01:32.000Z
2022-03-31T18:23:56.000Z
src/dialogs/StartDialog.cpp
mmahmoudian/Gittyup
96702f3b96160fff540886722f7f195163c4e41b
[ "MIT" ]
90
2021-11-05T13:03:58.000Z
2022-03-30T16:42:49.000Z
src/dialogs/StartDialog.cpp
mmahmoudian/Gittyup
96702f3b96160fff540886722f7f195163c4e41b
[ "MIT" ]
20
2021-10-30T12:25:33.000Z
2022-02-18T03:08:21.000Z
// // Copyright (c) 2016, Scientific Toolworks, Inc. // // This software is licensed under the MIT License. The LICENSE.md file // describes the conditions under which this software may be distributed. // // Author: Jason Haslam // #include "StartDialog.h" #include "AccountDialog.h" #include "CloneDialog.h" #include "IconLabel.h" #include "app/Application.h" #include "conf/RecentRepositories.h" #include "conf/RecentRepository.h" #include "host/Accounts.h" #include "host/Repository.h" #include "ui/Footer.h" #include "ui/MainWindow.h" #include "ui/ProgressIndicator.h" #include "ui/RepoView.h" #include "ui/TabWidget.h" #include <QAbstractItemModel> #include <QAbstractListModel> #include <QApplication> #include <QComboBox> #include <QDesktopServices> #include <QDialogButtonBox> #include <QFileDialog> #include <QHBoxLayout> #include <QIcon> #include <QLabel> #include <QLineEdit> #include <QListView> #include <QMessageBox> #include <QMenu> #include <QMultiMap> #include <QPushButton> #include <QPointer> #include <QSettings> #include <QStyledItemDelegate> #include <QTimer> #include <QTreeView> #include <QVBoxLayout> namespace { const QString kSubtitleFmt = "<h4 style='margin-top: 0px; color: gray'>%2</h4>"; const QString kGeometryKey = "geometry"; const QString kStartGroup = "start"; const QString kCloudIcon = ":/cloud.png"; enum Role { KindRole = Qt::UserRole, AccountRole, RepositoryRole }; class RepoModel : public QAbstractListModel { Q_OBJECT public: enum Row { Clone, Open, Init }; RepoModel(QObject *parent = nullptr) : QAbstractListModel(parent) { RecentRepositories *repos = RecentRepositories::instance(); connect(repos, &RecentRepositories::repositoryAboutToBeAdded, this, &RepoModel::beginResetModel); connect(repos, &RecentRepositories::repositoryAdded, this, &RepoModel::endResetModel); connect(repos, &RecentRepositories::repositoryAboutToBeRemoved, this, &RepoModel::beginResetModel); connect(repos, &RecentRepositories::repositoryRemoved, this, &RepoModel::endResetModel); } void setShowFullPath(bool enabled) { beginResetModel(); mShowFullPath = enabled; endResetModel(); } int rowCount(const QModelIndex &parent = QModelIndex()) const override { RecentRepositories *repos = RecentRepositories::instance(); return (repos->count() > 0) ? repos->count() : 3; } QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override { RecentRepositories *repos = RecentRepositories::instance(); if (repos->count() <= 0) { switch (role) { case Qt::DisplayRole: switch (index.row()) { case Clone: return tr("Clone Repository"); case Open: return tr("Open Existing Repository"); case Init: return tr("Initialize New Repository"); } case Qt::DecorationRole: { switch (index.row()) { case Clone: return QIcon(":/clone.png"); case Open: return QIcon(":/open.png"); case Init: return QIcon(":/new.png"); } } } return QVariant(); } RecentRepository *repo = repos->repository(index.row()); switch (role) { case Qt::DisplayRole: return mShowFullPath ? repo->path() : repo->name(); case Qt::UserRole: return repo->path(); } return QVariant(); } Qt::ItemFlags flags(const QModelIndex &index) const override { Qt::ItemFlags flags = QAbstractItemModel::flags(index); if (RecentRepositories::instance()->count() <= 0) flags &= ~Qt::ItemIsSelectable; return flags; } private: bool mShowFullPath = false; }; class HostModel : public QAbstractItemModel { Q_OBJECT public: HostModel(QStyle *style, QObject *parent = nullptr) : QAbstractItemModel(parent), mErrorIcon(style->standardIcon(QStyle::SP_MessageBoxCritical)) { Accounts *accounts = Accounts::instance(); connect(accounts, &Accounts::accountAboutToBeAdded, this, &HostModel::beginResetModel); connect(accounts, &Accounts::accountAdded, this, &HostModel::endResetModel); connect(accounts, &Accounts::accountAboutToBeRemoved, this, &HostModel::beginResetModel); connect(accounts, &Accounts::accountRemoved, this, &HostModel::endResetModel); connect(accounts, &Accounts::progress, this, [this](int accountIndex) { QModelIndex idx = index(0, 0, index(accountIndex, 0)); emit dataChanged(idx, idx, {Qt::DisplayRole}); }); connect(accounts, &Accounts::started, this, [this](int accountIndex) { beginResetModel(); endResetModel(); }); connect(accounts, &Accounts::finished, this, [this](int accountIndex) { beginResetModel(); endResetModel(); }); connect(accounts, &Accounts::repositoryAboutToBeAdded, this, &HostModel::beginResetModel); connect(accounts, &Accounts::repositoryAdded, this, &HostModel::endResetModel); connect(accounts, &Accounts::repositoryPathChanged, this, [this](int accountIndex, int repoIndex) { QModelIndex idx = index(repoIndex, 0, index(accountIndex, 0)); emit dataChanged(idx, idx, {Qt::DisplayRole}); }); } void setShowFullName(bool enabled) { beginResetModel(); mShowFullName = enabled; endResetModel(); } QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override { bool id = (!parent.isValid() || parent.internalId()); return createIndex(row, column, !id ? parent.row() + 1 : 0); } QModelIndex parent(const QModelIndex &index) const override { quintptr id = index.internalId(); return !id ? QModelIndex() : createIndex(id - 1, 0); } int rowCount(const QModelIndex &parent = QModelIndex()) const override { // no accounts Accounts *accounts = Accounts::instance(); if (accounts->count() <= 0) return !parent.isValid() ? 4 : 0; // account if (!parent.isValid()) return accounts->count(); if (parent.internalId()) return 0; // repos Account *account = accounts->account(parent.row()); int count = account->repositoryCount(); if (count > 0) return count; AccountError *error = account->error(); AccountProgress *progress = account->progress(); return (error->isValid() || progress->isValid()) ? 1 : 0; } int columnCount(const QModelIndex &parent = QModelIndex()) const override { return 1; } QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override { // no accounts Accounts *accounts = Accounts::instance(); if (accounts->count() <= 0) { Account::Kind kind = static_cast<Account::Kind>(index.row()); switch (role) { case Qt::DisplayRole: return Account::name(kind); case Qt::DecorationRole: return Account::icon(kind); case KindRole: return kind; } return QVariant(); } // account quintptr id = index.internalId(); if (!id) { Account *account = accounts->account(index.row()); switch (role) { case Qt::DisplayRole: return account->username(); case Qt::DecorationRole: return Account::icon(account->kind()); case KindRole: return account->kind(); case AccountRole: return QVariant::fromValue(account); } return QVariant(); } // error Account *account = accounts->account(id - 1); AccountError *error = account->error(); if (error->isValid()) { switch (role) { case Qt::DisplayRole: return error->text(); case Qt::DecorationRole: return mErrorIcon; case Qt::ToolTipRole: return error->detailedText(); } return QVariant(); } // progress if (account->repositoryCount() <= 0) { switch (role) { case Qt::DisplayRole: return tr("Connecting"); case Qt::DecorationRole: return account->progress()->value(); case Qt::FontRole: { QFont font = static_cast<QWidget *>(QObject::parent())->font(); font.setItalic(true); return font; } default: return QVariant(); } } // repo int row = index.row(); Repository *repo = account->repository(row); switch (role) { case Qt::DisplayRole: return mShowFullName ? repo->fullName() : repo->name(); case Qt::DecorationRole: { QString path = account->repositoryPath(row); return path.isEmpty() ? QIcon(kCloudIcon) : QIcon(); } case KindRole: return account->kind(); case RepositoryRole: return QVariant::fromValue(repo); } return QVariant(); } Qt::ItemFlags flags(const QModelIndex &index) const override { Qt::ItemFlags flags = QAbstractItemModel::flags(index); if (Accounts::instance()->count() <= 0) flags &= ~Qt::ItemIsSelectable; return flags; } private: bool mShowFullName = false; QIcon mErrorIcon; }; class ProgressDelegate : public QStyledItemDelegate { public: ProgressDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {} void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override { QStyleOptionViewItem opt = option; initStyleOption(&opt, index); // Draw background. QStyledItemDelegate::paint(painter, opt, index); // Draw busy indicator. QVariant progress = index.data(Qt::DecorationRole); if (!progress.canConvert<int>()) return; QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); QStyle::SubElement se = QStyle::SE_ItemViewItemDecoration; QRect rect = style->subElementRect(se, &opt, opt.widget); ProgressIndicator::paint(painter, rect, "#808080", progress.toInt()); } protected: void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const override { QStyledItemDelegate::initStyleOption(option, index); if (index.data(Qt::DecorationRole).canConvert<int>()) { option->decorationSize = ProgressIndicator::size(); } else if (index.data(RepositoryRole).isValid()) { option->features |= QStyleOptionViewItem::HasDecoration; option->decorationSize = QSize(20, 20); } } }; } // namespace StartDialog::StartDialog(QWidget *parent) : QDialog(parent) { setAttribute(Qt::WA_DeleteOnClose); setWindowTitle(tr("Choose Repository")); QIcon icon(":/Gittyup.iconset/icon_128x128.png"); IconLabel *iconLabel = new IconLabel(icon, 128, 128, this); QIcon title(":/[email protected]"); IconLabel *titleLabel = new IconLabel(title, 163, 38, this); QString subtitleText = kSubtitleFmt.arg(tr("Understand your history!")); QLabel *subtitle = new QLabel(subtitleText, this); subtitle->setAlignment(Qt::AlignHCenter); QVBoxLayout *left = new QVBoxLayout; left->addWidget(iconLabel); left->addWidget(titleLabel); left->addWidget(subtitle); left->addStretch(); mRepoList = new QListView(this); mRepoList->setIconSize(QSize(32, 32)); mRepoList->setSelectionMode(QAbstractItemView::ExtendedSelection); connect(mRepoList, &QListView::clicked, this, [this](const QModelIndex &index) { if (!index.data(Qt::UserRole).isValid()) { switch (index.row()) { case RepoModel::Clone: mClone->trigger(); break; case RepoModel::Open: mOpen->trigger(); break; case RepoModel::Init: mInit->trigger(); break; } } }); connect(mRepoList, &QListView::doubleClicked, this, &QDialog::accept); RepoModel *repoModel = new RepoModel(mRepoList); mRepoList->setModel(repoModel); connect(repoModel, &RepoModel::modelReset, this, [this] { mRepoList->setCurrentIndex(mRepoList->model()->index(0, 0)); }); mRepoFooter = new Footer(mRepoList); connect(mRepoFooter, &Footer::minusClicked, this, [this] { // Sort selection in reverse order. QModelIndexList indexes = mRepoList->selectionModel()->selectedIndexes(); std::sort(indexes.begin(), indexes.end(), [](const QModelIndex &lhs, const QModelIndex &rhs) { return rhs.row() < lhs.row(); }); // Remove selected indexes from settings. foreach (const QModelIndex &index, indexes) RecentRepositories::instance()->remove(index.row()); }); QMenu *repoPlusMenu = new QMenu(this); mRepoFooter->setPlusMenu(repoPlusMenu); mClone = repoPlusMenu->addAction(tr("Clone Repository")); connect(mClone, &QAction::triggered, this, [this] { CloneDialog *dialog = new CloneDialog(CloneDialog::Clone, this); connect(dialog, &CloneDialog::accepted, this, [this, dialog] { if (MainWindow *window = openWindow(dialog->path())) window->currentView()->addLogEntry(dialog->message(), dialog->messageTitle()); }); dialog->open(); }); mOpen = repoPlusMenu->addAction(tr("Open Existing Repository")); connect(mOpen, &QAction::triggered, this, [this] { // FIXME: Filter out non-git dirs. QFileDialog *dialog = new QFileDialog(this, tr("Open Repository"), QDir::homePath()); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setFileMode(QFileDialog::Directory); dialog->setOption(QFileDialog::ShowDirsOnly); connect(dialog, &QFileDialog::fileSelected, this, &StartDialog::openWindow); dialog->open(); }); mInit = repoPlusMenu->addAction(tr("Initialize New Repository")); connect(mInit, &QAction::triggered, this, [this] { CloneDialog *dialog = new CloneDialog(CloneDialog::Init, this); connect(dialog, &CloneDialog::accepted, this, [this, dialog] { if (MainWindow *window = openWindow(dialog->path())) window->currentView()->addLogEntry(dialog->message(), dialog->messageTitle()); }); dialog->open(); }); QMenu *repoContextMenu = new QMenu(this); mRepoFooter->setContextMenu(repoContextMenu); QAction *clear = repoContextMenu->addAction(tr("Clear All")); connect(clear, &QAction::triggered, [] { RecentRepositories::instance()->clear(); }); QSettings settings; QAction *showFullPath = repoContextMenu->addAction(tr("Show Full Path")); bool recentChecked = settings.value("start/recent/fullpath").toBool(); showFullPath->setCheckable(true); showFullPath->setChecked(recentChecked); repoModel->setShowFullPath(recentChecked); connect(showFullPath, &QAction::triggered, this, [repoModel](bool checked) { QSettings().setValue("start/recent/fullpath", checked); repoModel->setShowFullPath(checked); }); QAction *filter = repoContextMenu->addAction(tr("Filter Non-existent Paths")); filter->setCheckable(true); filter->setChecked(settings.value("recent/filter", true).toBool()); connect(filter, &QAction::triggered, [](bool checked) { QSettings().setValue("recent/filter", checked); }); QVBoxLayout *middle = new QVBoxLayout; middle->setSpacing(0); middle->addWidget(new QLabel(tr("Repositories:"), this)); middle->addSpacing(8); // FIXME: Query style? middle->addWidget(mRepoList); middle->addWidget(mRepoFooter); mHostTree = new QTreeView(this); mHostTree->setHeaderHidden(true); mHostTree->setExpandsOnDoubleClick(false); mHostTree->setIconSize(QSize(32, 32)); mHostTree->setSelectionMode(QAbstractItemView::ExtendedSelection); connect(mHostTree, &QTreeView::clicked, this, [this](const QModelIndex &index) { int rows = mHostTree->model()->rowCount(index); if (!rows && !index.data(RepositoryRole).isValid()) edit(index); }); connect(mHostTree, &QTreeView::doubleClicked, this, [this](const QModelIndex &index) { QModelIndex parent = index.parent(); if (parent.isValid()) { Account *account = parent.data(AccountRole).value<Account *>(); if (!account->repositoryPath(index.row()).isEmpty()) { accept(); return; } } edit(index); }); HostModel *hostModel = new HostModel(style(), mHostTree); mHostTree->setModel(hostModel); connect(hostModel, &QAbstractItemModel::modelReset, this, [this] { QModelIndex index = mHostTree->model()->index(0, 0); mHostTree->setRootIsDecorated(index.data(AccountRole).isValid()); mHostTree->expandAll(); }); mHostTree->setItemDelegate(new ProgressDelegate(this)); mHostFooter = new Footer(mHostTree); connect(mHostFooter, &Footer::plusClicked, this, [this] { edit(); }); connect(mHostFooter, &Footer::minusClicked, this, &StartDialog::remove); QMenu *hostContextMenu = new QMenu(this); mHostFooter->setContextMenu(hostContextMenu); QAction *refresh = hostContextMenu->addAction(tr("Refresh")); connect(refresh, &QAction::triggered, this, [] { Accounts *accounts = Accounts::instance(); for (int i = 0; i < accounts->count(); ++i) accounts->account(i)->connect(); }); QAction *showFullName = hostContextMenu->addAction(tr("Show Full Name")); bool remoteChecked = QSettings().value("start/remote/fullname").toBool(); showFullName->setCheckable(true); showFullName->setChecked(remoteChecked); hostModel->setShowFullName(remoteChecked); connect(showFullName, &QAction::triggered, this, [hostModel](bool checked) { QSettings().setValue("start/remote/fullname", checked); hostModel->setShowFullName(checked); }); // Clear the other list when this selection changes. QItemSelectionModel *repoSelModel = mRepoList->selectionModel(); connect(repoSelModel, &QItemSelectionModel::selectionChanged, this, [this] { if (!mRepoList->selectionModel()->selectedIndexes().isEmpty()) mHostTree->clearSelection(); updateButtons(); }); // Clear the other list when this selection changes. QItemSelectionModel *hostSelModel = mHostTree->selectionModel(); connect(hostSelModel, &QItemSelectionModel::selectionChanged, this, [this] { if (!mHostTree->selectionModel()->selectedIndexes().isEmpty()) mRepoList->clearSelection(); updateButtons(); }); QVBoxLayout *right = new QVBoxLayout; right->setSpacing(0); right->addWidget(new QLabel(tr("Remote:"), this)); right->addSpacing(8); // FIXME: Query style? right->addWidget(mHostTree); right->addWidget(mHostFooter); QHBoxLayout *top = new QHBoxLayout; top->addLayout(left); top->addSpacing(12); top->addLayout(middle); top->addSpacing(12); top->addLayout(right); QDialogButtonBox::StandardButtons buttons = QDialogButtonBox::Open | QDialogButtonBox::Cancel; mButtonBox = new QDialogButtonBox(buttons, this); connect(mButtonBox, &QDialogButtonBox::accepted, this, &StartDialog::accept); connect(mButtonBox, &QDialogButtonBox::rejected, this, &StartDialog::reject); QString text = tr("View Getting Started Video"); QPushButton *help = mButtonBox->addButton(text, QDialogButtonBox::ResetRole); connect(help, &QPushButton::clicked, [] { QDesktopServices::openUrl(QUrl("https://gitahead.com/#tutorials")); }); QVBoxLayout *layout = new QVBoxLayout(this); layout->addLayout(top); layout->addWidget(mButtonBox); } void StartDialog::accept() { QModelIndexList repoIndexes = mRepoList->selectionModel()->selectedIndexes(); QModelIndexList hostIndexes = mHostTree->selectionModel()->selectedIndexes(); QStringList paths; foreach (const QModelIndex &index, repoIndexes) paths.append(index.data(Qt::UserRole).toString()); QModelIndexList uncloned; foreach (const QModelIndex &index, hostIndexes) { QModelIndex parent = index.parent(); if (parent.isValid()) { Account *account = parent.data(AccountRole).value<Account *>(); QString path = account->repositoryPath(index.row()); if (path.isEmpty()) { uncloned.append(index); } else { paths.append(path); } } } // Clone the first repo. if (!uncloned.isEmpty()) { edit(uncloned.first()); return; } // FIXME: Fail if none of the windows were able to be opened? QDialog::accept(); if (paths.isEmpty()) return; // Open a new window for the first valid repo. MainWindow *window = MainWindow::open(paths.takeFirst()); while (!window && !paths.isEmpty()) window = MainWindow::open(paths.takeFirst()); if (!window) return; // Add the remainder as tabs. foreach (const QString &path, paths) window->addTab(path); } StartDialog *StartDialog::openSharedInstance() { static QPointer<StartDialog> dialog; if (dialog) { dialog->show(); dialog->raise(); dialog->activateWindow(); return dialog; } dialog = new StartDialog; dialog->show(); return dialog; } void StartDialog::showEvent(QShowEvent *event) { // Restore geometry. QSettings settings; settings.beginGroup(kStartGroup); if (settings.contains(kGeometryKey)) restoreGeometry(settings.value(kGeometryKey).toByteArray()); settings.endGroup(); QDialog::showEvent(event); } void StartDialog::hideEvent(QHideEvent *event) { QSettings settings; settings.beginGroup(kStartGroup); settings.setValue(kGeometryKey, saveGeometry()); settings.endGroup(); QDialog::hideEvent(event); } void StartDialog::updateButtons() { QModelIndexList repoIndexes = mRepoList->selectionModel()->selectedIndexes(); QModelIndexList hostIndexes = mHostTree->selectionModel()->selectedIndexes(); // Update dialog Open button. bool clone = false; QPushButton *open = mButtonBox->button(QDialogButtonBox::Open); open->setEnabled(!repoIndexes.isEmpty() || !hostIndexes.isEmpty()); foreach (const QModelIndex &index, hostIndexes) { QModelIndex parent = index.parent(); if (!parent.isValid()) { open->setEnabled(false); } else { Account *account = parent.data(AccountRole).value<Account *>(); if (Repository *repo = index.data(RepositoryRole).value<Repository *>()) { if (account->repositoryPath(index.row()).isEmpty()) clone = true; } else { open->setEnabled(false); } } } open->setText((clone && open->isEnabled()) ? tr("Clone") : tr("Open")); // Update repo list footer buttons. mRepoFooter->setMinusEnabled(!repoIndexes.isEmpty()); // Update host list footer buttons. mHostFooter->setMinusEnabled(false); if (!hostIndexes.isEmpty()) { QModelIndex index = hostIndexes.first(); Account *account = index.data(AccountRole).value<Account *>(); QString repoPath; QModelIndex parent = index.parent(); if (parent.isValid()) { Account *account = parent.data(AccountRole).value<Account *>(); repoPath = account->repositoryPath(index.row()); } mHostFooter->setMinusEnabled(account || !repoPath.isEmpty()); } } void StartDialog::edit(const QModelIndex &index) { // account if (!index.isValid() || !index.parent().isValid()) { Account *account = nullptr; if (index.isValid()) account = index.data(AccountRole).value<Account *>(); AccountDialog *dialog = new AccountDialog(account, this); if (!account && index.isValid()) dialog->setKind(index.data(KindRole).value<Account::Kind>()); dialog->open(); return; } // repo Repository *repo = index.data(RepositoryRole).value<Repository *>(); if (!repo) return; CloneDialog *dialog = new CloneDialog(CloneDialog::Clone, this, repo); connect(dialog, &CloneDialog::accepted, this, [this, index, dialog] { // Set local path. Account *account = Accounts::instance()->account(index.parent().row()); account->setRepositoryPath(index.row(), dialog->path()); // Open the repo. QCoreApplication::processEvents(); accept(); }); dialog->open(); } void StartDialog::remove() { QModelIndexList indexes = mHostTree->selectionModel()->selectedIndexes(); Q_ASSERT(!indexes.isEmpty()); // account QModelIndex index = indexes.first(); if (!index.parent().isValid()) { Account::Kind kind = index.data(KindRole).value<Account::Kind>(); QString name = index.data(Qt::DisplayRole).toString(); QString fmt = tr("<p>Are you sure you want to remove the %1 account for '%2'?</p>" "<p>Only the account association will be removed. Remote " "configurations and local clones will not be affected.</p>"); QMessageBox mb(QMessageBox::Warning, tr("Remove Account?"), fmt.arg(Account::name(kind), name), QMessageBox::Cancel, this); QPushButton *remove = mb.addButton(tr("Remove"), QMessageBox::AcceptRole); remove->setFocus(); mb.exec(); if (mb.clickedButton() == remove) { mHostTree->clearSelection(); Accounts::instance()->removeAccount(index.row()); } return; } // repo Repository *repo = index.data(RepositoryRole).value<Repository *>(); QString fmt = tr("<p>Are you sure you want to remove the remote repository association " "for %1?</p><p>The local clone itself will not be affected.</p>"); QMessageBox mb(QMessageBox::Warning, tr("Remove Repository Association?"), fmt.arg(repo->fullName()), QMessageBox::Cancel, this); QPushButton *remove = mb.addButton(tr("Remove"), QMessageBox::AcceptRole); remove->setFocus(); mb.exec(); if (mb.clickedButton() == remove) repo->account()->setRepositoryPath(index.row(), QString()); // Update minus and OK buttons. updateButtons(); } MainWindow *StartDialog::openWindow(const QString &repo) { // This dialog has to be hidden before opening another window so that it // doesn't automatically move to a position that still shows the dialog. hide(); if (MainWindow *window = MainWindow::open(repo)) { // Dismiss this dialog without trying to open the selection. reject(); return window; } else { show(); } return nullptr; } #include "StartDialog.moc"
31.863855
80
0.653609
mmahmoudian
0504fab6ccb4f2f2895ac3ac5c9ac2bebc8e4d0b
1,414
cpp
C++
n48.cpp
paolaguarasci/domJudge
830f5ca3f271732668930a2a8d3be98d96661691
[ "MIT" ]
null
null
null
n48.cpp
paolaguarasci/domJudge
830f5ca3f271732668930a2a8d3be98d96661691
[ "MIT" ]
null
null
null
n48.cpp
paolaguarasci/domJudge
830f5ca3f271732668930a2a8d3be98d96661691
[ "MIT" ]
null
null
null
/* 1 3 2 6 1 4 5 5 9 2 3 79 3 -5 */ #include <iostream> using namespace std; void leggo(int n[], int& dim); void seqCrescente(int [], int, int&, int&); int main() { int n[100]; int dim = 0; int lunghezzaSeq; int lmax, imax; leggo(n, dim); if (dim > 0) { seqCrescente(n, dim, imax, lmax); // cout << "lmax: " << lmax << " imax: " << imax; for (int i = imax; i < lmax + imax; i++) { cout << n[i]; } cout << endl << lmax; } else { cout << "Empty"; } return 0; } void leggo(int n[], int& dim) { int num; cin >> num; for (int i = 0; num >= 0; i++) { n[i] = num; cin >> num; dim++; } } void seqCrescente(int seq[], int dim, int& indiceMax, int& lmax) { int tab[100][2] = {1}; // array x * 2 con gli indici e le lunghezze delle sequenze crescenti int index = 0, lung = 0, j = 0; // trovo tutte le sequenza crescenti for (int i = 1; i < dim; i++) { if (seq[i] >= seq[i-1]) { tab[j][0]++; } else { tab[++j][1] = i; tab[j][0] = 1; } } // tra le sequenze crescenti trovo la sequenza più lunga lmax = tab[0][0]; indiceMax = 0; for(int i = 1; i <= j; i++) { // cout << "indice: " << tab[i][1] << " lunghezze: " << tab[i][0] << endl; if (tab[i][0] > lmax) { indiceMax = tab[i][1]; lmax = tab[i][0]; } } }
21.104478
95
0.466761
paolaguarasci
0507f73370ad0aee2ca09d0410ab0f0e2bb54435
15,227
cpp
C++
src/mongo/db/storage/kv/dictionary/kv_dictionary_test_harness.cpp
Tokutek/tokumxse
9d0d92b45dfd75ecacb08feeb477dd4f4a6d430d
[ "Apache-2.0" ]
29
2015-01-13T02:34:23.000Z
2022-01-30T16:57:10.000Z
src/mongo/db/storage/kv/dictionary/kv_dictionary_test_harness.cpp
Tokutek/tokumxse
9d0d92b45dfd75ecacb08feeb477dd4f4a6d430d
[ "Apache-2.0" ]
null
null
null
src/mongo/db/storage/kv/dictionary/kv_dictionary_test_harness.cpp
Tokutek/tokumxse
9d0d92b45dfd75ecacb08feeb477dd4f4a6d430d
[ "Apache-2.0" ]
12
2015-01-24T08:40:28.000Z
2017-10-04T17:23:39.000Z
// kv_dictionary_test_harness.cpp /*====== This file is part of Percona Server for MongoDB. Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved. Percona Server for MongoDB is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. Percona Server for MongoDB is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Percona Server for MongoDB. If not, see <http://www.gnu.org/licenses/>. ======= */ #include <algorithm> #include <vector> #include <boost/scoped_ptr.hpp> #include "mongo/db/storage/kv/dictionary/kv_dictionary.h" #include "mongo/db/storage/kv/dictionary/kv_dictionary_test_harness.h" #include "mongo/db/storage/kv/slice.h" #include "mongo/unittest/unittest.h" namespace mongo { using boost::scoped_ptr; TEST( KVDictionary, Simple1 ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); { const Slice hi = Slice::of("hi"); const Slice there = Slice::of("there"); scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; WriteUnitOfWork uow( opCtx.get() ); Status status = db->insert( opCtx.get(), hi, there, false ); ASSERT( status.isOK() ); status = db->get( opCtx.get(), hi, value ); ASSERT( status.isOK() ); status = db->remove( opCtx.get(), hi ); ASSERT( status.isOK() ); status = db->get( opCtx.get(), hi, value ); ASSERT( status.code() == ErrorCodes::NoSuchKey ); uow.commit(); } } } TEST( KVDictionary, Simple2 ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); const Slice hi = Slice::of("hi"); const Slice there = Slice::of("there"); const Slice apple = Slice::of("apple"); const Slice bears = Slice::of("bears"); { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { WriteUnitOfWork uow( opCtx.get() ); Status status = db->insert( opCtx.get(), hi, there, false ); ASSERT( status.isOK() ); uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { WriteUnitOfWork uow( opCtx.get() ); Status status = db->insert( opCtx.get(), apple, bears, false ); ASSERT( status.isOK() ); uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; Status status = db->get( opCtx.get(), hi, value ); ASSERT( status.isOK() ); ASSERT( value.size() == 6 ); ASSERT( std::string( "there" ) == std::string( value.data() ) ); } { Slice value; Status status = db->get( opCtx.get(), apple, value ); ASSERT( status.isOK() ); ASSERT( value.size() == 6 ); ASSERT( std::string( "bears" ) == std::string( value.data() ) ); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { WriteUnitOfWork uow( opCtx.get() ); Status status = db->remove( opCtx.get(), hi ); ASSERT( status.isOK() ); uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; Status status = db->get( opCtx.get(), hi, value ); ASSERT( status.code() == ErrorCodes::NoSuchKey ); } { Slice value; Status status = db->get( opCtx.get(), apple, value ); ASSERT( status.isOK() ); ASSERT( value.size() == 6 ); ASSERT( std::string( "bears" ) == std::string( value.data() ) ); } { WriteUnitOfWork uow( opCtx.get() ); Status status = db->remove( opCtx.get(), apple ); ASSERT( status.isOK() ); uow.commit(); } { Slice value; Status status = db->get( opCtx.get(), apple, value ); ASSERT( status.code() == ErrorCodes::NoSuchKey ); } } } TEST( KVDictionary, InsertSerialGetSerial ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); const unsigned char nKeys = 100; { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; WriteUnitOfWork uow( opCtx.get() ); for (unsigned char i = 0; i < nKeys; i++) { const Slice slice = Slice::of(i); Status status = db->insert( opCtx.get(), slice, slice, false ); ASSERT( status.isOK() ); } uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { for (unsigned char i = 0; i < nKeys; i++) { Slice value; Status status = db->get( opCtx.get(), Slice::of(i), value ); ASSERT( status.isOK() ); ASSERT( value.as<unsigned char>() == i ); } } } } static int _rng(int i) { return std::rand() % i; } TEST( KVDictionary, InsertRandomGetSerial ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); const unsigned char nKeys = 100; { std::vector<unsigned char> keys; for (unsigned char i = 0; i < nKeys; i++) { keys.push_back(i); } std::srand(unsigned(time(0))); std::random_shuffle(keys.begin(), keys.end(), _rng); scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; WriteUnitOfWork uow( opCtx.get() ); for (unsigned char i = 0; i < nKeys; i++) { const Slice slice = Slice::of(keys[i]); Status status = db->insert( opCtx.get(), slice, slice, false ); ASSERT( status.isOK() ); } uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; for (unsigned char i = 0; i < nKeys; i++) { Status status = db->get( opCtx.get(), Slice::of(i), value ); ASSERT( status.isOK() ); ASSERT( value.as<unsigned char>() == i ); } } } } TEST( KVDictionary, InsertRandomCursor ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); const unsigned char nKeys = 100; { std::vector<unsigned char> keys; for (unsigned char i = 0; i < nKeys; i++) { keys.push_back(i); } std::srand(unsigned(time(0))); std::random_shuffle(keys.begin(), keys.end(), _rng); scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; WriteUnitOfWork uow( opCtx.get() ); for (unsigned char i = 0; i < nKeys; i++) { const Slice slice = Slice::of(keys[i]); Status status = db->insert( opCtx.get(), slice, slice, false ); ASSERT( status.isOK() ); } uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; const int direction = 1; unsigned char i = 0; for (scoped_ptr<KVDictionary::Cursor> c(db->getCursor(opCtx.get(), direction)); c->ok(); c->advance(opCtx.get()), i++) { ASSERT( c->currKey().as<unsigned char>() == i ); ASSERT( c->currVal().as<unsigned char>() == i ); } } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; const int direction = -1; unsigned char i = nKeys - 1; for (scoped_ptr<KVDictionary::Cursor> c(db->getCursor(opCtx.get(), direction)); c->ok(); c->advance(opCtx.get()), i--) { ASSERT( c->currKey().as<unsigned char>() == i ); ASSERT( c->currVal().as<unsigned char>() == i ); } } } } TEST( KVDictionary, InsertDeleteCursor ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); const unsigned char nKeys = 100; std::vector<unsigned char> keys; for (unsigned char i = 0; i < nKeys; i++) { keys.push_back(i); } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; WriteUnitOfWork uow( opCtx.get() ); for (unsigned char i = 0; i < nKeys; i++) { const Slice slice = Slice::of(keys[i]); Status status = db->insert( opCtx.get(), slice, slice, false ); ASSERT( status.isOK() ); } uow.commit(); } } std::srand(unsigned(time(0))); std::random_shuffle(keys.begin(), keys.end(), _rng); std::set<unsigned char> remainingKeys; std::set<unsigned char> deletedKeys; { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { WriteUnitOfWork uow( opCtx.get() ); for (unsigned char i = 0; i < nKeys; i++) { unsigned char k = keys[i]; if (i < (nKeys / 2)) { Status status = db->remove( opCtx.get(), Slice::of(k) ); ASSERT( status.isOK() ); deletedKeys.insert(k); } else { remainingKeys.insert(k); } } uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { const int direction = 1; unsigned char i = 0; for (scoped_ptr<KVDictionary::Cursor> c(db->getCursor(opCtx.get(), direction)); c->ok(); c->advance(opCtx.get()), i++) { unsigned char k = c->currKey().as<unsigned char>(); ASSERT( remainingKeys.count(k) == 1 ); ASSERT( deletedKeys.count(k) == 0 ); ASSERT( k == c->currVal().as<unsigned char>() ); remainingKeys.erase(k); } ASSERT( remainingKeys.empty() ); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { for (std::set<unsigned char>::const_iterator it = deletedKeys.begin(); it != deletedKeys.end(); it++) { unsigned char k = *it; Slice value; Status status = db->get( opCtx.get(), Slice::of(k), value ); ASSERT( status.code() == ErrorCodes::NoSuchKey ); ASSERT( value.size() == 0 ); } } } } TEST( KVDictionary, CursorSeekForward ) { scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() ); scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() ); const unsigned char nKeys = 101; // even number makes the test magic more complicated std::vector<unsigned char> keys; for (unsigned char i = 0; i < nKeys; i++) { keys.push_back(i); } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { Slice value; WriteUnitOfWork uow( opCtx.get() ); for (unsigned char i = 0; i < nKeys; i += 2) { const Slice slice = Slice::of(keys[i]); Status status = db->insert( opCtx.get(), slice, slice, false ); ASSERT( status.isOK() ); } uow.commit(); } } { scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() ); { scoped_ptr<KVDictionary::Cursor> cursor( db->getCursor( opCtx.get(), 1 ) ); for (unsigned char i = 0; i < nKeys; i++) { cursor->seek( opCtx.get(), Slice::of(keys[i]) ); if ( i % 2 == 0 ) { ASSERT( cursor->currKey().as<unsigned char>() == i ); } else if ( i + 1 < nKeys ) { ASSERT( cursor->currKey().as<unsigned char>() == i + 1); } } } { scoped_ptr<KVDictionary::Cursor> cursor( db->getCursor( opCtx.get(), -1 ) ); for (unsigned char i = 1; i < nKeys; i++) { cursor->seek(opCtx.get(), Slice::of(keys[i])); if ( i % 2 == 0 ) { ASSERT( cursor->currKey().as<unsigned char>() == i ); } else { ASSERT( cursor->currKey().as<unsigned char>() == i - 1 ); } } } } } }
36.691566
95
0.481185
Tokutek
05136b7873a9835615730523a238a27a82c65822
179
cpp
C++
Zelig/Zelig/Test/LlilumWin32/LlilumWin32.cpp
NETMF/llilum
7ac7669fe205572e8b572b4f3697e5f802e574be
[ "MIT" ]
188
2015-07-08T21:13:28.000Z
2022-01-01T09:29:33.000Z
Zelig/Zelig/Test/LlilumWin32/LlilumWin32.cpp
lt72/llilum
7ac7669fe205572e8b572b4f3697e5f802e574be
[ "MIT" ]
239
2015-07-10T00:48:20.000Z
2017-09-21T14:04:58.000Z
Zelig/Zelig/Test/LlilumWin32/LlilumWin32.cpp
lt72/llilum
7ac7669fe205572e8b572b4f3697e5f802e574be
[ "MIT" ]
73
2015-07-09T21:02:42.000Z
2022-01-01T09:31:26.000Z
// LlilumWin32.cpp : Defines the entry point for the console application. // #include "stdafx.h" extern int LlosWin32_Main(void); int main() { return LlosWin32_Main(); }
13.769231
73
0.703911
NETMF
05136de571cc809415de1f2c8797dae229842f3c
6,219
hh
C++
src/outlinerindexedmesh.hh
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
4
2021-09-02T16:52:23.000Z
2022-02-07T16:39:50.000Z
src/outlinerindexedmesh.hh
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
87
2021-09-12T06:09:57.000Z
2022-02-15T00:05:43.000Z
src/outlinerindexedmesh.hh
jariarkko/cave-outliner
2077a24627881f45a27aec3eb4e5b4855f6b7fec
[ "BSD-3-Clause" ]
1
2021-09-28T21:38:30.000Z
2021-09-28T21:38:30.000Z
/////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// // // CCC AAA V V EEEEE OOO UU UU TTTTTT LL II NN NN EEEEE RRRRR // CC CC AA AA V V EE OO OO UU UU TT LL II NNN NN EE RR RR // CC AA AA V V EEE OO OO UU UU TT LL II NN N NN EEE RRRRR // CC CC AAAAAA V V EE OO OO UU UU TT LL II NN NNN EE RR R // CCc AA AA V EEEEE OOO UUUUU TT LLLLL II NN NN EEEEE RR R // // CAVE OUTLINER -- Cave 3D model processing software // // Copyright (C) 2021 by Jari Arkko -- See LICENSE.txt for license information. // /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// #ifndef INDEXEDMESH_HH #define INDEXEDMESH_HH /////////////////////////////////////////////////////////////////////////////////////////////// // Includes /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "outlinertypes.hh" #include "outlinerconstants.hh" #include "outlinerdirection.hh" /////////////////////////////////////////////////////////////////////////////////////////////// // Internal data types //////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// struct IndexedMeshOneMeshOneTileFaces { unsigned int nFaces; unsigned int maxNFaces; const aiFace** faces; }; struct IndexedMeshOneMesh { const aiMesh* mesh; unsigned int nOutsideModelBoundingBox; struct IndexedMeshOneMeshOneTileFaces** tileMatrix; }; /////////////////////////////////////////////////////////////////////////////////////////////// // Class interface //////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// /// /// This object represents an optimized index to the mesh faces /// contained in an imported 3D model. The imported model has a large /// datastructure of 'faces' -- typically millions or even tens of /// millions of faces. There is no efficient way to search for faces /// at a given location in the 3D or 2D space, however. The indexed /// mesh object sorts the faces into a 2D matrix of 'tiles'. For /// instance, a large model could be split into 20x20 or 400 tiles, so /// that when we are looking for a face within given (x,y) /// coordinates, we only need to look at the tile where (x,y) falls /// into. The indexing is performed only once, and all searches after /// the indexing operation can use the more efficient search. /// class IndexedMesh { public: /// Create an IndexedMesh object. IndexedMesh(unsigned int maxMeshesIn, unsigned int subdivisionsIn, const OutlinerBox3D& modelBoundingBox, const OutlinerBox2D& viewBoundingBox, enum outlinerdirection directionIn); /// Add a 3D scene to the optimized index. void addScene(const aiScene* scene); /// Add a 3D node to the optimized index. void addNode(const aiScene* scene, const aiNode* node); /// Add a 3D mesh to the optimized index. void addMesh(const aiScene* scene, const aiMesh* mesh); /// Quickly get faces associated with a given (x,y) point in the plan view. void getFaces(const aiMesh* mesh, outlinerreal x, outlinerreal y, unsigned int* p_nFaces, const aiFace*** p_faces); /// Print information about the contents of the mesh void describe(std::ostream& stream); /// Release all resources associated with the index. ~IndexedMesh(); private: unsigned int nMeshes; unsigned int maxMeshes; unsigned int subdivisions; OutlinerBox3D modelBoundingBox; OutlinerBox2D viewBoundingBox; enum outlinerdirection direction; outlinerreal tileSizeX; outlinerreal tileSizeY; struct IndexedMeshOneMesh* meshes; void addFaces(struct IndexedMeshOneMesh& shadow, const aiScene* scene, const aiMesh* mesh); void addFace(struct IndexedMeshOneMesh& shadow, const aiScene* scene, const aiMesh* mesh, const aiFace* face); void addToTile(struct IndexedMeshOneMesh& shadow, const aiScene* scene, const aiMesh* mesh, const aiFace* face, unsigned int tileX, unsigned int tileY); void getFacesTile(struct IndexedMeshOneMesh& shadow, const aiMesh* mesh, unsigned int tileX, unsigned int tileY, unsigned int* p_nFaces, const aiFace*** p_faces); void coordsToTile(outlinerreal x, outlinerreal y, unsigned int& tileX, unsigned int& tileY); void getShadow(const aiMesh* mesh, struct IndexedMeshOneMesh** shadow); unsigned int minFacesPerTile(struct IndexedMeshOneMesh& shadow, unsigned int& n); unsigned int maxFacesPerTile(struct IndexedMeshOneMesh& shadow, unsigned int& n); float avgFacesPerTile(struct IndexedMeshOneMesh& shadow); unsigned int countTilesWithFaces(struct IndexedMeshOneMesh& shadow); void countFaces(struct IndexedMeshOneMesh& shadow, unsigned int& nUniqueFaces, unsigned int& nFacesInTiles); }; #endif // INDEXEDMESH_HH
40.914474
95
0.49397
jariarkko
0518a93e88fa4fffa5d9b5458c47a279399e0780
12,963
cpp
C++
src/frontend/prettyprint/PrettyPrinter.cpp
WilliamHaslet/tip-compiler-extensions-project
4ad8a91b8eca50b58cc194b36fcd336898c6b9b3
[ "MIT" ]
null
null
null
src/frontend/prettyprint/PrettyPrinter.cpp
WilliamHaslet/tip-compiler-extensions-project
4ad8a91b8eca50b58cc194b36fcd336898c6b9b3
[ "MIT" ]
null
null
null
src/frontend/prettyprint/PrettyPrinter.cpp
WilliamHaslet/tip-compiler-extensions-project
4ad8a91b8eca50b58cc194b36fcd336898c6b9b3
[ "MIT" ]
null
null
null
#include "PrettyPrinter.h" #include <iostream> #include <sstream> void PrettyPrinter::print(ASTProgram *p, std::ostream &os, char c, int n) { PrettyPrinter visitor(os, c, n); p->accept(&visitor); } void PrettyPrinter::endVisit(ASTProgram * element) { std::string programString = ""; bool skip = true; for (auto &fn : element->getFunctions()) { if (skip) { programString = visitResults.back() + programString; visitResults.pop_back(); skip = false; continue; } programString = visitResults.back() + "\n" + programString; visitResults.pop_back(); } os << programString; os.flush(); } /* * General approach taken by visit methods. * - visit() is used to increase indentation (decrease should happen in endVisit). * - endVisit() should expect a string for all of its AST nodes in reverse order in visitResults. * Communicate the single string for the visited node by pushing to the back of visitedResults. */ /* * Before visiting function, record string for signature and setup indentation for body. * This visit method pushes a string result, that the endVisit method should extend. */ bool PrettyPrinter::visit(ASTFunction * element) { indentLevel++; return true; } /* * After visiting function, collect the string representations for the: * statements, declarations, formals, and then function name * they are on the visit stack in that order. */ void PrettyPrinter::endVisit(ASTFunction * element) { std::string bodyString = ""; for (auto &stmt : element->getStmts()) { bodyString = visitResults.back() + "\n" + bodyString; visitResults.pop_back(); } for (auto &decl : element->getDeclarations()) { bodyString = visitResults.back() + "\n" + bodyString; visitResults.pop_back(); } std::string formalsString = ""; bool skip = true; for(auto &formal : element->getFormals()) { if (skip) { formalsString = visitResults.back() + formalsString; visitResults.pop_back(); skip = false; continue; } formalsString = visitResults.back() + ", " + formalsString; visitResults.pop_back(); } // function name is last element on stack std::string functionString = visitResults.back(); visitResults.pop_back(); functionString += "(" + formalsString + ") \n{\n" + bodyString + "}\n"; indentLevel--; visitResults.push_back(functionString); } void PrettyPrinter::endVisit(ASTNumberExpr * element) { visitResults.push_back(std::to_string(element->getValue())); } void PrettyPrinter::endVisit(ASTVariableExpr * element) { visitResults.push_back(element->getName()); } void PrettyPrinter::endVisit(ASTBinaryExpr * element) { std::string rightString = visitResults.back(); visitResults.pop_back(); std::string leftString = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(" + leftString + " " + element->getOp() + " " + rightString + ")"); } void PrettyPrinter::endVisit(ASTInputExpr * element) { visitResults.push_back("input"); } void PrettyPrinter::endVisit(ASTFunAppExpr * element) { std::string funAppString; /* * Skip printing of comma separator for last arg. */ std::string actualsString = ""; bool skip = true; for (auto &arg : element->getActuals()) { if (skip) { actualsString = visitResults.back() + actualsString; visitResults.pop_back(); skip = false; continue; } actualsString = visitResults.back() + ", " + actualsString; visitResults.pop_back(); } funAppString = visitResults.back() + "(" + actualsString + ")"; visitResults.pop_back(); visitResults.push_back(funAppString); } void PrettyPrinter::endVisit(ASTAllocExpr * element) { std::string init = visitResults.back(); visitResults.pop_back(); visitResults.push_back("alloc " + init); } void PrettyPrinter::endVisit(ASTRefExpr * element) { std::string var = visitResults.back(); visitResults.pop_back(); visitResults.push_back("&" + var); } void PrettyPrinter::endVisit(ASTDeRefExpr * element) { std::string base = visitResults.back(); visitResults.pop_back(); visitResults.push_back("*" + base); } void PrettyPrinter::endVisit(ASTNullExpr * element) { visitResults.push_back("null"); } void PrettyPrinter::endVisit(ASTFieldExpr * element) { std::string init = visitResults.back(); visitResults.pop_back(); visitResults.push_back(element->getField() + ":" + init); } void PrettyPrinter::endVisit(ASTRecordExpr * element) { /* * Skip printing of comma separator for last record element. */ std::string fieldsString = ""; bool skip = true; for (auto &f : element->getFields()) { if (skip) { fieldsString = visitResults.back() + fieldsString; visitResults.pop_back(); skip = false; continue; } fieldsString = visitResults.back() + ", " + fieldsString; visitResults.pop_back(); } std::string recordString = "{" + fieldsString + "}"; visitResults.push_back(recordString); } void PrettyPrinter::endVisit(ASTAccessExpr * element) { std::string accessString = visitResults.back(); visitResults.pop_back(); visitResults.push_back(accessString + '.' + element->getField()); } void PrettyPrinter::endVisit(ASTDeclNode * element) { visitResults.push_back(element->getName()); } void PrettyPrinter::endVisit(ASTDeclStmt * element) { std::string declString = ""; bool skip = true; for (auto &id : element->getVars()) { if (skip) { declString = visitResults.back() + declString; visitResults.pop_back(); skip = false; continue; } declString = visitResults.back() + ", " + declString; visitResults.pop_back(); } declString = indent() + "var " + declString + ";"; visitResults.push_back(declString); } void PrettyPrinter::endVisit(ASTAssignStmt * element) { std::string rhsString = visitResults.back(); visitResults.pop_back(); std::string lhsString = visitResults.back(); visitResults.pop_back(); visitResults.push_back(indent() + lhsString + " = " + rhsString + ";"); } bool PrettyPrinter::visit(ASTBlockStmt * element) { indentLevel++; return true; } void PrettyPrinter::endVisit(ASTBlockStmt * element) { std::string stmtsString = ""; for (auto &s : element->getStmts()) { stmtsString = visitResults.back() + "\n" + stmtsString; visitResults.pop_back(); } indentLevel--; std::string blockString = indent() + "{\n" + stmtsString + indent() + "}"; visitResults.push_back(blockString); } /* * For a while the body should be indented, but not the condition. * Since conditions are expressions and their visit methods never indent * incrementing here works. */ bool PrettyPrinter::visit(ASTWhileStmt * element) { indentLevel++; return true; } void PrettyPrinter::endVisit(ASTWhileStmt * element) { std::string bodyString = visitResults.back(); visitResults.pop_back(); std::string condString = visitResults.back(); visitResults.pop_back(); indentLevel--; std::string whileString = indent() + "while (" + condString + ") \n" + bodyString; visitResults.push_back(whileString); } bool PrettyPrinter::visit(ASTIfStmt * element) { indentLevel++; return true; } void PrettyPrinter::endVisit(ASTIfStmt * element) { std::string elseString; if (element->getElse() != nullptr) { elseString = visitResults.back(); visitResults.pop_back(); } std::string thenString = visitResults.back(); visitResults.pop_back(); std::string condString = visitResults.back(); visitResults.pop_back(); indentLevel--; std::string ifString = indent() + "if (" + condString + ") \n" + thenString; if (element->getElse() != nullptr) { ifString += "\n" + indent() + "else\n" + elseString; } visitResults.push_back(ifString); } void PrettyPrinter::endVisit(ASTOutputStmt * element) { std::string argString = visitResults.back(); visitResults.pop_back(); visitResults.push_back(indent() + "output " + argString + ";"); } void PrettyPrinter::endVisit(ASTErrorStmt * element) { std::string argString = visitResults.back(); visitResults.pop_back(); visitResults.push_back(indent() + "error " + argString + ";"); } void PrettyPrinter::endVisit(ASTReturnStmt * element) { std::string argString = visitResults.back(); visitResults.pop_back(); visitResults.push_back(indent() + "return " + argString + ";"); } void PrettyPrinter::endVisit(ASTArrayExpr * element) { /* * Skip printing of comma separator for last array element. */ std::string entriesString = ""; bool skip = true; for (auto &f : element->getEntries()) { if (skip) { entriesString = visitResults.back() + entriesString; visitResults.pop_back(); skip = false; continue; } entriesString = visitResults.back() + ", " + entriesString; visitResults.pop_back(); } std::string arrayString = "[" + entriesString + "]"; visitResults.push_back(arrayString); } void PrettyPrinter::endVisit(ASTTernaryExpr * element) { std::string elseString = visitResults.back(); visitResults.pop_back(); std::string thenString = visitResults.back(); visitResults.pop_back(); std::string condString = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(" + condString + " ? " + thenString + " : " + elseString + ")"); } void PrettyPrinter::endVisit(ASTElementRefrenceOperatorExpr * element) { std::string index = visitResults.back(); visitResults.pop_back(); std::string array = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(" + array + "[" + index + "])"); } void PrettyPrinter::endVisit(ASTArrayLengthExpr * element) { std::string array = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(#" + array + ")"); } void PrettyPrinter::endVisit(ASTTrueExpr * element) { visitResults.push_back("true"); } void PrettyPrinter::endVisit(ASTFalseExpr * element) { visitResults.push_back("false"); } std::string PrettyPrinter::indent() const { return std::string(indentLevel*indentSize, indentChar); } void PrettyPrinter::endVisit(ASTAndExpr * element) { std::string rightString = visitResults.back(); visitResults.pop_back(); std::string leftString = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(" + leftString + " and " + rightString + ")"); } void PrettyPrinter::endVisit(ASTDecrementStmt * element) { std::string e = visitResults.back(); visitResults.pop_back(); visitResults.push_back(indent() + e + "--;"); } bool PrettyPrinter::visit(ASTForIterStmt * element) { indentLevel++; return true; } void PrettyPrinter::endVisit(ASTForIterStmt * element) { std::string bodyString = visitResults.back(); visitResults.pop_back(); std::string right = visitResults.back(); visitResults.pop_back(); std::string left = visitResults.back(); visitResults.pop_back(); indentLevel--; std::string forString = indent() + "for (" + left + " : " + right + ") \n" + bodyString; visitResults.push_back(forString); } bool PrettyPrinter::visit(ASTForRangeStmt * element) { indentLevel++; return true; } void PrettyPrinter::endVisit(ASTForRangeStmt * element) { std::string bodyString = visitResults.back(); visitResults.pop_back(); std::string fourString = ""; if (element->getFour() != nullptr) { fourString = visitResults.back(); visitResults.pop_back(); } std::string three = visitResults.back(); visitResults.pop_back(); std::string two = visitResults.back(); visitResults.pop_back(); std::string one = visitResults.back(); visitResults.pop_back(); indentLevel--; std::string forString = indent() + "for (" + one + " : " + two + " .. " + three; if (element->getFour() != nullptr) { forString += " by " + fourString; } forString += ") \n" + bodyString; visitResults.push_back(forString); } void PrettyPrinter::endVisit(ASTIncrementStmt * element) { std::string e = visitResults.back(); visitResults.pop_back(); visitResults.push_back(indent() + e + "++;"); } void PrettyPrinter::endVisit(ASTNegationExpr * element) { std::string e = visitResults.back(); visitResults.pop_back(); visitResults.push_back("-(" + e + ")"); } void PrettyPrinter::endVisit(ASTNotExpr * element) { std::string e = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(not " + e + ")"); } void PrettyPrinter::endVisit(ASTOfArrayExpr * element) { std::string rightString = visitResults.back(); visitResults.pop_back(); std::string leftString = visitResults.back(); visitResults.pop_back(); visitResults.push_back("[" + leftString + " of " + rightString + "]"); } void PrettyPrinter::endVisit(ASTOrExpr * element) { std::string rightString = visitResults.back(); visitResults.pop_back(); std::string leftString = visitResults.back(); visitResults.pop_back(); visitResults.push_back("(" + leftString + " or " + rightString + ")"); }
27.40592
97
0.681709
WilliamHaslet
051be815dae73aabf927a2b29fbc7ab1de5fb6d6
1,129
hpp
C++
android-29/android/app/TimePickerDialog.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/app/TimePickerDialog.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/app/TimePickerDialog.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "./AlertDialog.hpp" namespace android::content { class Context; } namespace android::os { class Bundle; } namespace android::widget { class TimePicker; } namespace android::app { class TimePickerDialog : public android::app::AlertDialog { public: // Fields // QJniObject forward template<typename ...Ts> explicit TimePickerDialog(const char *className, const char *sig, Ts...agv) : android::app::AlertDialog(className, sig, std::forward<Ts>(agv)...) {} TimePickerDialog(QJniObject obj); // Constructors TimePickerDialog(android::content::Context arg0, JObject arg1, jint arg2, jint arg3, jboolean arg4); TimePickerDialog(android::content::Context arg0, jint arg1, JObject arg2, jint arg3, jint arg4, jboolean arg5); // Methods void onClick(JObject arg0, jint arg1) const; void onRestoreInstanceState(android::os::Bundle arg0) const; android::os::Bundle onSaveInstanceState() const; void onTimeChanged(android::widget::TimePicker arg0, jint arg1, jint arg2) const; void show() const; void updateTime(jint arg0, jint arg1) const; }; } // namespace android::app
26.255814
175
0.730735
YJBeetle
051ccf158ecc198ab08157812e03478dcebfdba8
3,131
cpp
C++
Training-Code/2015 Multi-University Training Contest 8/K.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
Training-Code/2015 Multi-University Training Contest 8/K.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
Training-Code/2015 Multi-University Training Contest 8/K.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
#include <cstdio> #include <vector> #include <cassert> #include <algorithm> const int MAXN = 100001; const int MAXM = 200001; const int MAXQ = 100001; const int MAXT = 600001; const int MAXI = 3000001; const int Maxlog = 30; struct Edge{ int node, next; }e[MAXM]; struct Query{ int op, x, y, answer; }q[MAXQ]; struct Trie{ int size, c[MAXI][2], s[MAXI]; int alloc() { size++; c[size][0] = c[size][1] = 0; s[size] = 0; return size; } void clear() { size = 0; alloc(); } void modify(int x, int d) { for (int i = Maxlog, p = 1; i >= 0; i--) { int bit = x >> i & 1; if (!c[p][bit]) c[p][bit] = alloc(); p = c[p][bit]; s[p] += d; assert(s[p] >= 0); } } int query(int x) { int ret = 0; for (int i = Maxlog, p = 1; i >= 0; i--) { int bit = x >> i & 1 ^ 1; if (c[p][bit] && s[c[p][bit]]) { ret |= 1 << i; p = c[p][bit]; } else p = c[p][bit ^ 1]; } return ret; } }trie; struct Tuple{ int first, second, third; Tuple() {} Tuple(int first, int second, int third) : first(first), second(second), third(third) {} }; int T, n, m, t, tot, h[MAXN], oL[MAXN], oR[MAXN], a[MAXN], b[MAXN]; std::vector<Tuple> tree[MAXT]; void update(int &x, int y) { if (x < y) x = y; } void addedge(int x, int y) { t++; e[t] = (Edge){y, h[x]}; h[x] = t; } void dfs(int x) { oL[x] = ++tot; for (int i = h[x]; i; i = e[i].next) { dfs(e[i].node); } oR[x] = tot; } void cover(int n, int l, int r, int x, int y, const Tuple &p) { if (r < x || l > y) return; if (x <= l && r <= y) { tree[n].push_back(p); return; } cover(n << 1, l, l + r >> 1, x, y, p); cover(n << 1 ^ 1, (l + r >> 1) + 1, r, x, y, p); } void cover(int n, int l, int r, int x, const Tuple &p) { tree[n].push_back(p); if (l == r) return; if (x <= (l + r >> 1)) cover(n << 1, l, l + r >> 1, x, p); else cover(n << 1 ^ 1, (l + r >> 1) + 1, r, x, p); } void travel(int n, int l, int r) { trie.clear(); for (std::vector<Tuple>::iterator it = tree[n].begin(); it != tree[n].end(); it++) { if (it -> third) trie.modify(it -> second, it -> third); else update(q[it -> first].answer, trie.query(it -> second)); } tree[n].clear(); if (l == r) return; travel(n << 1, l, l + r >> 1); travel(n << 1 ^ 1, (l + r >> 1) + 1, r); } int main() { freopen("K.in", "r", stdin); scanf("%d", &T); while (T--) { scanf("%d%d", &n, &m); t = tot = 0; std::fill(h + 1, h + n + 1, 0); for (int i = 2; i <= n; i++) { int fa; scanf("%d", &fa); addedge(fa, i); } dfs(1); for (int i = 1; i <= n; i++) { scanf("%d", a + i); b[i] = a[i]; cover(1, 1, n, oL[i], oR[i], Tuple(i, a[i], 1)); } for (int i = 1; i <= m; i++) { scanf("%d%d", &q[i].op, &q[i].x); if (q[i].op == 0) { scanf("%d", &q[i].y); cover(1, 1, n, oL[q[i].x], oR[q[i].x], Tuple(i, a[q[i].x], -1)); cover(1, 1, n, oL[q[i].x], oR[q[i].x], Tuple(i, a[q[i].x] = q[i].y, 1)); } else{ cover(1, 1, n, oL[q[i].x], Tuple(i, a[q[i].x], 0)); q[i].answer = 0; } } travel(1, 1, n); for (int i = 1; i <= m; i++) { if (q[i].op == 1) { printf("%d\n", q[i].answer); } } } return 0; }
21.155405
88
0.474928
PrayStarJirachi
051ed0cc007cfcbdef35914e5dad4facb166375e
5,648
cpp
C++
Lamp/src/Lamp/World/Terrain.cpp
SGS-Ivar/Lamp
e81195bbfb73b6b4bd2c6d4604e2e3aa532aecb2
[ "MIT" ]
null
null
null
Lamp/src/Lamp/World/Terrain.cpp
SGS-Ivar/Lamp
e81195bbfb73b6b4bd2c6d4604e2e3aa532aecb2
[ "MIT" ]
null
null
null
Lamp/src/Lamp/World/Terrain.cpp
SGS-Ivar/Lamp
e81195bbfb73b6b4bd2c6d4604e2e3aa532aecb2
[ "MIT" ]
null
null
null
#include "lppch.h" #include "Terrain.h" #include "Lamp/Core/Application.h" #include "Lamp/Rendering/Buffers/VertexBuffer.h" #include "Lamp/Rendering/Shader/ShaderLibrary.h" #include "Lamp/Rendering/RenderPipeline.h" #include "Lamp/Rendering/Textures/Texture2D.h" #include "Lamp/Rendering/Swapchain.h" #include "Lamp/Rendering/RenderCommand.h" #include "Lamp/Rendering/Renderer.h" #include "Lamp/Mesh/Materials/MaterialLibrary.h" #include "Lamp/Mesh/Mesh.h" #include "Platform/Vulkan/VulkanDevice.h" namespace Lamp { Terrain::Terrain(const std::filesystem::path& aHeightMap) { if (!std::filesystem::exists(aHeightMap)) { LP_CORE_ERROR("[Terrain]: Unable to load file {0}!", aHeightMap.string()); m_isValid = false; return; } m_heightMap = Texture2D::Create(aHeightMap); GenerateMeshFromHeightMap(); } Terrain::Terrain(Ref<Texture2D> heightMap) { m_heightMap = heightMap; GenerateMeshFromHeightMap(); } Terrain::~Terrain() { } void Terrain::Draw(Ref<RenderPipeline> pipeline) { SetupDescriptors(pipeline); RenderCommand::SubmitMesh(m_mesh, nullptr, m_descriptorSet.descriptorSets, (void*)glm::value_ptr(m_transform)); } Ref<Terrain> Terrain::Create(const std::filesystem::path& heightMap) { return CreateRef<Terrain>(heightMap); } Ref<Terrain> Terrain::Create(Ref<Texture2D> heightMap) { return CreateRef<Terrain>(heightMap); } void Terrain::SetupDescriptors(Ref<RenderPipeline> pipeline) { auto vulkanShader = pipeline->GetSpecification().shader; auto device = VulkanContext::GetCurrentDevice(); const uint32_t currentFrame = Application::Get().GetWindow().GetSwapchain()->GetCurrentFrame(); auto descriptorSet = vulkanShader->CreateDescriptorSets(); std::vector<VkWriteDescriptorSet> writeDescriptors; auto vulkanUniformBuffer = pipeline->GetSpecification().uniformBufferSets->Get(0, 0, currentFrame); auto vulkanTerrainBuffer = Renderer::Get().GetStorage().terrainDataBuffer; writeDescriptors.emplace_back(*vulkanShader->GetDescriptorSet("CameraDataBuffer")); writeDescriptors[0].dstSet = descriptorSet.descriptorSets[0]; writeDescriptors[0].pBufferInfo = &vulkanUniformBuffer->GetDescriptorInfo(); writeDescriptors.emplace_back(*vulkanShader->GetDescriptorSet("DirectionalLightBuffer")); writeDescriptors[1].dstSet = descriptorSet.descriptorSets[0]; writeDescriptors[1].pBufferInfo = &vulkanTerrainBuffer->GetDescriptorInfo(); if (m_heightMap) { writeDescriptors.emplace_back(*vulkanShader->GetDescriptorSet("u_HeightMap")); writeDescriptors[2].dstSet = descriptorSet.descriptorSets[0]; writeDescriptors[2].pImageInfo = &m_heightMap->GetDescriptorInfo(); } auto vulkanScreenUB = pipeline->GetSpecification().uniformBufferSets->Get(3, 0, currentFrame); writeDescriptors.emplace_back(*vulkanShader->GetDescriptorSet("ScreenDataBuffer")); writeDescriptors[3].dstSet = descriptorSet.descriptorSets[0]; writeDescriptors[3].pBufferInfo = &vulkanScreenUB->GetDescriptorInfo(); vkUpdateDescriptorSets(device->GetHandle(), (uint32_t)writeDescriptors.size(), writeDescriptors.data(), 0, nullptr); m_descriptorSet = descriptorSet; } void Terrain::GenerateMeshFromHeightMap() { std::vector<Vertex> vertices; std::vector<uint32_t> indices; const uint32_t patchSize = 64; const float uvScale = 1.f; m_scale = m_heightMap->GetHeight() / patchSize; const uint32_t vertexCount = patchSize * patchSize; vertices.resize(vertexCount); const float wx = 2.f; const float wy = 2.f; for (uint32_t x = 0; x < patchSize; x++) { for (uint32_t y = 0; y < patchSize; y++) { uint32_t index = (x + y * patchSize); vertices[index].position = { x * wx + wx / 2.f - (float)patchSize * wx / 2.f, 0.f, y * wy + wy / 2.f - patchSize * wy / 2.f }; vertices[index].textureCoords = glm::vec2{ (float)x / patchSize, (float)y / patchSize } *uvScale; } } const uint32_t w = patchSize - 1; const uint32_t indexCount = w * w * 4; indices.resize(indexCount); for (uint32_t x = 0; x < w; x++) { for (uint32_t y = 0; y < w; y++) { uint32_t index = (x + y * w) * 4; indices[index] = (x + y * patchSize); indices[index + 1] = (indices[index] + patchSize); indices[index + 2] = (indices[index + 1] + 1); indices[index + 3] = (indices[index] + 1); } } for (uint32_t x = 0; x < patchSize; x++) { for (uint32_t y = 0; y < patchSize; y++) { float heights[3][3]; for (int32_t hx = -1; hx <= 1; hx++) { for (int32_t hy = -1; hy <= 1; hy++) { heights[hx + 1][hy + 1] = GetHeight(x + hx, y + hy); } } glm::vec3 normal; normal.x = heights[0][0] - heights[2][0] + 2.f * heights[0][1] - 2.f * heights[2][1] + heights[0][2] - heights[2][2]; normal.y = heights[0][0] + 2.f * heights[1][0] + heights[2][0] - heights[0][2] - 2.f * heights[1][2] - heights[2][2]; normal.y = 0.25f * sqrtf(1.f - normal.x * normal.x - normal.y * normal.y); vertices[x + y * patchSize].normal = glm::normalize(normal * glm::vec3(2.f, 1.f, 2.f)); } } m_mesh = CreateRef<SubMesh>(vertices, indices, 0, ""); m_transform = glm::scale(glm::mat4(1.f), glm::vec3{ 2.f, 1.f, 2.f }); } float Terrain::GetHeight(uint32_t x, uint32_t y) { glm::ivec2 pos = glm::ivec2{ x, y } * glm::ivec2{ m_scale, m_scale }; pos.x = std::max(0, std::min(pos.x, (int)m_heightMap->GetWidth() - 1)); pos.y = std::max(0, std::min(pos.y, (int)m_heightMap->GetWidth() - 1)); pos /= glm::ivec2(m_scale); auto buffer = m_heightMap->GetData(); return buffer.Read<uint16_t>((pos.x + pos.y * m_heightMap->GetHeight()) * m_scale) / 65535.f; } }
31.730337
130
0.682011
SGS-Ivar
0522d21ea9cdb3083806b59c1b4d52bd17a5e3d8
513
hpp
C++
src/utility/create_geometric_progression.hpp
Atsushi-Machida/OpenJij
e4bddebb13536eb26ff0b7b9fc6b1c75659fe934
[ "Apache-2.0" ]
61
2019-01-05T13:37:10.000Z
2022-03-11T02:11:08.000Z
src/utility/create_geometric_progression.hpp
Atsushi-Machida/OpenJij
e4bddebb13536eb26ff0b7b9fc6b1c75659fe934
[ "Apache-2.0" ]
79
2019-01-29T09:55:20.000Z
2022-02-19T04:06:20.000Z
src/utility/create_geometric_progression.hpp
29rou/OpenJij
c2579fba8710cf82b9e6761304f0042b365b595c
[ "Apache-2.0" ]
21
2019-01-07T07:55:10.000Z
2022-03-08T14:27:23.000Z
#ifndef OPENJIJ_UTILITY_CREATE_GEOMETRIC_PROGRESSION_HPP__ #define OPENJIJ_UTILITY_CREATE_GEOMETRIC_PROGRESSION_HPP__ namespace openjij { namespace utility { template<typename ForwardIterator, typename T> void make_geometric_progression(ForwardIterator first, ForwardIterator last, T value, T ratio) { for(;first != last; ++first) { *first = value; value *= ratio; } } } // namespace utility } // namespace openjij #endif
28.5
104
0.660819
Atsushi-Machida
05234580932f71158425be7736c55e1ee9b8c0b5
1,562
cpp
C++
vendor/bitsery/examples/flexible_syntax.cpp
lateefx01/Aston
0e0a2393eeac3946880c3e601c532d49e2cf3b44
[ "Apache-2.0" ]
null
null
null
vendor/bitsery/examples/flexible_syntax.cpp
lateefx01/Aston
0e0a2393eeac3946880c3e601c532d49e2cf3b44
[ "Apache-2.0" ]
null
null
null
vendor/bitsery/examples/flexible_syntax.cpp
lateefx01/Aston
0e0a2393eeac3946880c3e601c532d49e2cf3b44
[ "Apache-2.0" ]
null
null
null
#include <bitsery/bitsery.h> #include <bitsery/adapter/buffer.h> //include flexible header, to use flexible syntax #include <bitsery/flexible.h> //we also need additional traits to work with container types, //instead of including <bitsery/traits/vector.h> for vector traits, now we also need traits to work with flexible types. //so include everything from <bitsery/flexible/...> instead of <bitsery/traits/...> //otherwise we'll get static assert error, saying to define serialize function. #include <bitsery/flexible/vector.h> enum class MyEnum : uint16_t { V1, V2, V3 }; struct MyStruct { uint32_t i; MyEnum e; std::vector<float> fs; //define serialize function as usual template<typename S> void serialize(S &s) { //now we can use flexible syntax with s.archive(i, e, fs); } }; using namespace bitsery; //some helper types using Buffer = std::vector<uint8_t>; using OutputAdapter = OutputBufferAdapter<Buffer>; using InputAdapter = InputBufferAdapter<Buffer>; int main() { //set some random data MyStruct data{8941, MyEnum::V2, {15.0f, -8.5f, 0.045f}}; MyStruct res{}; //serialization, deserialization flow is unchanged as in basic usage Buffer buffer; auto writtenSize = quickSerialization<OutputAdapter>(buffer, data); auto state = quickDeserialization<InputAdapter>({buffer.begin(), writtenSize}, res); assert(state.first == ReaderError::NoError && state.second); assert(data.fs == res.fs && data.i == res.i && data.e == res.e); }
29.471698
120
0.690141
lateefx01