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
d68d73c809ad2fafa4e1f6c4f0f4ca87255754dd
11,173
cpp
C++
RFlib/src/RandomizedTree.cpp
scanavan/GestureRecognition
f0761978b8f1a85544151adb1f1e30f3a9070984
[ "MIT" ]
2
2016-11-06T15:11:23.000Z
2017-03-09T01:00:01.000Z
RFlib/src/RandomizedTree.cpp
SRI2016/GestureRecognition
f0761978b8f1a85544151adb1f1e30f3a9070984
[ "MIT" ]
null
null
null
RFlib/src/RandomizedTree.cpp
SRI2016/GestureRecognition
f0761978b8f1a85544151adb1f1e30f3a9070984
[ "MIT" ]
3
2016-10-26T00:41:15.000Z
2019-05-13T13:30:16.000Z
/** * @file $URL: svn+ssh://svn_athena/home/svnrepositories/BuildingModeling/branches/Olivier/ML/src/RandomizedTree.cpp $ * @author $Author: teboul $ * @date $Date: 2009-10-16 19:24:19 +0200 (ven., 16 oct. 2009) $ * @brief */ #include <string> #include <fstream> #include "../inc/Histogram.h" #include "../inc/RandomizedTest.h" #include "../inc/LeafNode.h" #include "../inc/RandomizedTree.h" RandomizedTree::RandomizedTree(int depth, int nbLabels, unsigned int vector_size, double minV, double maxV) :m_depth(depth),m_nb_classes(nbLabels),m_vector_size(vector_size),m_min_value(minV),m_max_value(maxV) { m_test = new RandomizedTest(m_vector_size,m_min_value,m_max_value); m_true_child = 0; m_false_child = 0; } RandomizedTree::RandomizedTree(int depth, int nbLabels, const RandomizedTest& test) :m_depth(depth),m_nb_classes(nbLabels),m_vector_size(test.getSize()), m_min_value(test.getMinValue()),m_max_value(test.getMaxValue()) { m_test = new RandomizedTest(test); m_true_child = 0; m_false_child = 0; } RandomizedTree::RandomizedTree(const RandomizedTree& other) :m_depth(other.m_depth),m_nb_classes(other.m_nb_classes), m_vector_size(other.m_vector_size),m_min_value(other.m_min_value),m_max_value(other.m_max_value), m_id(other.m_id) { // copy the test m_test = new RandomizedTest(*other.m_test); // copy the subtrees m_true_child = 0; if(other.m_true_child) { if(! other.m_true_child->isLeaf()) m_true_child = new RandomizedTree(*other.m_true_child); else m_true_child = new LeafNode(*dynamic_cast<LeafNode*>(other.m_true_child)); } m_false_child=0; if(other.m_false_child) { if(! other.m_false_child->isLeaf()) m_false_child = new RandomizedTree(*other.m_false_child); else m_false_child = new LeafNode(*dynamic_cast<LeafNode*>(other.m_false_child)); } } void RandomizedTree::copy(RandomizedTree* other) { m_depth = other->m_depth; m_nb_classes = other->m_nb_classes; m_vector_size = other->m_vector_size; m_min_value = other->m_min_value; m_max_value = other->m_max_value; *m_test = *other->m_test; m_id = other->m_id; // first delete the subtrees if they exists if(m_true_child) { delete m_true_child; m_true_child = 0; } if(m_false_child) { delete m_false_child; m_false_child = 0; } // rebuild the children according to the other tree if(other->m_true_child) { if(! other->m_true_child->isLeaf()) { m_true_child = new RandomizedTree(m_depth-1,m_nb_classes,m_vector_size,m_min_value,m_max_value); } else { m_true_child = new LeafNode(m_nb_classes); } m_true_child->copy(other->m_true_child); } if(other->m_false_child) { if(! other->m_false_child->isLeaf()) { m_false_child = new RandomizedTree(m_depth-1,m_nb_classes,m_vector_size,m_min_value,m_max_value); } else { m_false_child = new LeafNode(m_nb_classes); } m_false_child->copy(other->m_false_child); } } RandomizedTree::~RandomizedTree() { delete m_test; if(m_true_child) { delete m_true_child; m_true_child = 0; } if(m_false_child) { delete m_false_child; m_false_child = 0; } } bool RandomizedTree::isLeaf() const { return false; } void RandomizedTree::train(const IFeatureVector& vector, int label) { train(vector,label,m_depth); } const LeafNode* RandomizedTree::patchToLeaf(const IFeatureVector& vector) const { if(isLeaf()) return dynamic_cast<const LeafNode*>(this); bool test = m_test->process(vector); // vector goes to left child (True) if(test) { if(!m_true_child) { //! return an outlier leaf return NULL; } else { return m_true_child->patchToLeaf(vector); } } // vector goes to right child (False) else { if(!m_false_child) { //! return an outlier leaf return NULL; } return m_false_child->patchToLeaf(vector); } return NULL; } void RandomizedTree::train(const IFeatureVector& vector, int label, int d) { // apply the randomized test bool test = m_test->process(vector); // Patch goes to left child (True) RandomizedTree* childtree; if(test) { if(!m_true_child) { if(d>1) m_true_child = new RandomizedTree(d-1,m_nb_classes,m_vector_size,m_min_value,m_max_value); else m_true_child = new LeafNode(m_nb_classes); } childtree = m_true_child; } // patch goes to right child (False) else { if(!m_false_child) { if(d>1) m_false_child = new RandomizedTree(d-1,m_nb_classes,m_vector_size,m_min_value,m_max_value); else m_false_child = new LeafNode(m_nb_classes); } childtree = m_false_child; } // recursive call childtree->train(vector,label,d-1); } std::ostream& operator<<(std::ostream& out, const RandomizedTree& v) { // turn the tree into a set of nodes and edges std::vector<RandomizedTree*> nodes; std::vector<t_Edge> edges; v.compact(nodes,edges); // dump the global caracteristics of the tree out<<"Tree : depth "<<v.m_depth<<", "<<v.m_nb_classes<<" labels, patch size " <<v.m_vector_size<<" "<<v.m_min_value<<" "<<v.m_max_value<<std::endl; // dump the nodes : id, nature and features out<<v.getNumberNodes()<<" Nodes :"<<std::endl; for(unsigned int i = 0; i<nodes.size();i++) { RandomizedTree& node = *nodes[i]; if(!node.isLeaf()) { out << node.m_id<<" S "<<*node.m_test<<std::endl; } else { out << node.m_id<<" L "; for(int k=0; k<v.m_nb_classes; k++) out<<dynamic_cast<LeafNode&>(node)[k]<<" "; out<<std::endl; } } // dump the edges : topology and left/right out<<"Edges :"<<std::endl; for(unsigned int i=0; i<edges.size(); i++) { out<<edges[i].first.first<<" "<<edges[i].first.second<<" "<<edges[i].second<<std::endl; } return out; } std::istream& operator>>(std::istream& in, RandomizedTree& tree) { std::map<int,RandomizedTree*> nodes; std::string st; for(int i=0; i<3; i++) { in>>st; } // get the global caracteristics of the tree int size, depth, nbclasses; double minV, maxV; in>>depth>>st>>nbclasses>>st>>st>>st>>size>>minV>>maxV; // get the number of nodes in the tree int nbNodes; in>>nbNodes>>st>>st; // create the nodes int id; double b; std::string s; RandomizedTest test; RandomizedTree* root=0; for(int i=0; i<nbNodes; i++) { RandomizedTree* node; in>>id>>s; if(!s.compare("S")) { in>>test; node = new RandomizedTree(depth,nbclasses,test); } else { node = new LeafNode(nbclasses); for(int c = 0; c<nbclasses; c++) { in>>b; (*dynamic_cast<LeafNode*>(node))[c] = b; } } node->m_id = id; nodes.insert(std::pair<int,RandomizedTree*>(id,node)); if(!root) root = node; // the root has the smallest id, it's in fact the first node to be dumped, so the first to be met here } // create the edges in>>st>>st; // read "Edge :" for(int i=0; i<nbNodes-1; i++) { int id1, id2, nature; in>>id1>>id2>>nature; RandomizedTree* node = nodes[id1]; if(nature == 1) { node->m_true_child = nodes[id2]; } else { node->m_false_child = nodes[id2]; } } tree.copy(root); delete root; nodes.clear(); return in; } void RandomizedTree::annotate(int& current_id) { m_id = current_id; current_id++; if(m_true_child) m_true_child->annotate(current_id); if(m_false_child) m_false_child->annotate(current_id); } int RandomizedTree::getNumberNodes() const { int a = 0; int b = 0; if(m_true_child) a = m_true_child->getNumberNodes(); if(m_false_child) b = m_false_child->getNumberNodes(); return 1+a+b; } void RandomizedTree::compact(std::vector<RandomizedTree*>& nodes, std::vector<t_Edge>& edges) const { nodes.push_back(const_cast<RandomizedTree*>(this));// bad cast if(m_true_child) { edges.push_back(std::pair<std::pair<int,int>,int>(std::pair<int,int>(m_id,m_true_child->m_id),1)); m_true_child->compact(nodes,edges); } if(m_false_child) { edges.push_back(std::pair<std::pair<int,int>,int>(std::pair<int,int>(m_id,m_false_child->m_id),0)); m_false_child->compact(nodes,edges); } } void RandomizedTree::expand(std::map<int,RandomizedTree*>& nodes, std::vector<t_Edge>& edges) { // get the id of the children, by traversing the edge list int count=0; for(unsigned int k=0; k<edges.size(); k++) { t_Edge& edge = edges[k]; if(edge.first.first == m_id) { if(edge.second == 1) { count++; m_true_child = nodes[edge.first.second]; //remove edge from edges edges.erase(edges.begin()+k); k--; } else { count++; m_false_child = nodes[edge.first.second]; //remove edge from edges edges.erase(edges.begin()+k); k--; } if(count==2) { // remove node from node break; //should be faster like that } } } if(m_true_child) { m_true_child->expand(nodes,edges); } if(m_false_child) { m_false_child->expand(nodes,edges); } } void RandomizedTree::toDot(const char* filename) { // annotate the tree int current_id = 0; annotate(current_id); std::vector<RandomizedTree*> nodes; std::vector<t_Edge> edges; compact(nodes,edges); std::ofstream outFile(filename); outFile<<"digraph RandomizedTree{"<<std::endl; for(unsigned int i=0; i<nodes.size(); i++) { outFile<<"\tNode"<<nodes[i]->m_id<<"[label = "<<nodes[i]->m_id<<"]"<<std::endl; } for(unsigned int i=0; i<edges.size(); i++) { outFile<<"\tNode"<<edges[i].first.first<<" -> Node"<<edges[i].first.second<<"[color = "; if(edges[i].second) outFile<<"\"#0000ff\"]"<<std::endl; else outFile<<"\"#ff0000\"]"<<std::endl; } outFile<<"}"<<std::endl; outFile.close(); } int RandomizedTree::getID() const { return m_id; } int RandomizedTree::getDepth() const { return m_depth; } int RandomizedTree::getNbClasses() const { return m_nb_classes; } unsigned int RandomizedTree::getVectorSize() const { return m_vector_size; } double RandomizedTree::getMinValue() const { return m_min_value; } double RandomizedTree::getMaxValue() const { return m_max_value; }
23.976395
133
0.600376
scanavan
d6911da8163b4de49fb706010ffb8cc9b120b159
5,960
cpp
C++
imapp_platform_glfw.cpp
remyroez/imgui_app
2e715a3b4a5f2f351b27cc9af02d405d2b483e02
[ "MIT" ]
5
2021-04-07T17:33:35.000Z
2022-03-20T21:18:42.000Z
imapp_platform_glfw.cpp
remyroez/imgui_app
2e715a3b4a5f2f351b27cc9af02d405d2b483e02
[ "MIT" ]
null
null
null
imapp_platform_glfw.cpp
remyroez/imgui_app
2e715a3b4a5f2f351b27cc9af02d405d2b483e02
[ "MIT" ]
null
null
null
// imapp: standalone application starter kit // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) #include "imapp.h" #include "imapp_internal.h" #include "imgui.h" #include "imgui_impl_glfw.h" #if defined(IMAPP_RENDERER_OPENGL) #include "imapp_opengl_loader.h" #endif // Include glfw3.h after our OpenGL definitions #if defined(IMAPP_RENDERER_OPENGL2) #ifdef __APPLE__ #define GL_SILENCE_DEPRECATION #endif #elif defined(IMAPP_RENDERER_VULKAN) #define GLFW_INCLUDE_NONE #define GLFW_INCLUDE_VULKAN #endif #include <GLFW/glfw3.h> // [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to maximize ease of testing and compatibility with old VS compilers. // To link with VS2010-era libraries, VS2015+ requires linking with legacy_stdio_definitions.lib, which we do using this pragma. // Your own project should not be affected, as you are likely to link with a newer binary of GLFW that is adequate for your version of Visual Studio. #if defined(_MSC_VER) && (_MSC_VER >= 1900) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) #pragma comment(lib, "legacy_stdio_definitions") #endif namespace { GLFWwindow* window = NULL; void glfw_error_callback(int error, const char* description) { fprintf(stderr, "Glfw Error %d: %s\n", error, description); } } // namespace namespace ImApp { bool SetupPlatform(const char* name, const ImVec2& size) { bool succeeded = false; // Setup window glfwSetErrorCallback(glfw_error_callback); if (!glfwInit()) { // Error } else { #if defined(IMAPP_RENDERER_OPENGL3) // Decide GL+GLSL versions #if __APPLE__ // GL 3.2 Core + GLSL 150 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Required on Mac #else // GL 3.0 + GLSL 130 //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // 3.0+ only #endif // GL Context version glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, IMAPP_GL_CONTEXT_MAJOR_VERSION); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, IMAPP_GL_CONTEXT_MINOR_VERSION); #elif defined(IMAPP_RENDERER_VULKAN) glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); #endif // Create window with graphics context window = glfwCreateWindow( size.x > 0 ? (int)size.x : 1280, size.y > 0 ? (int)size.y : 720, name, NULL, NULL ); if (window == NULL) { // Error } else { #if defined(IMAPP_RENDERER_OPENGL) glfwMakeContextCurrent(window); glfwSwapInterval(1); // Enable vsync #ifdef IMAPP_RENDERER_OPENGL3 succeeded = InitOpenGLLoader(); #else succeeded = true; #endif #elif defined(IMAPP_RENDERER_VULKAN) succeeded = glfwVulkanSupported(); #endif } } return succeeded; } void ShutdownPlatform() { glfwDestroyWindow(window); window = NULL; glfwTerminate(); } bool InitPlatform() { // Setup Platform bindings #if defined(IMAPP_RENDERER_OPENGL) return ImGui_ImplGlfw_InitForOpenGL(window, true); #elif defined(IMAPP_RENDERER_VULKAN) return ImGui_ImplGlfw_InitForVulkan(window, true); #else return false; #endif } void CleanupPlatform() { ImGui_ImplGlfw_Shutdown(); } void BeginFramePlatform() { ImGui_ImplGlfw_NewFrame(); } void EndFramePlatform() { #ifdef IMAPP_RENDERER_OPENGL glfwSwapBuffers(window); #endif } void UpdateViewportPlatform() { #ifdef IMGUI_HAS_VIEWPORT // Update and Render additional Platform Windows ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { #ifdef IMAPP_RENDERER_OPENGL // (Platform functions may change the current OpenGL context, so we save/restore it to make it easier to paste this code elsewhere. // For this specific demo app we could also call glfwMakeContextCurrent(window) directly) GLFWwindow* backup_current_context = glfwGetCurrentContext(); #endif ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); #ifdef IMAPP_RENDERER_OPENGL glfwMakeContextCurrent(backup_current_context); #endif } #endif } bool ProcessEventPlatform() { // Poll and handle events (inputs, window resize, etc.) // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); if (glfwWindowShouldClose(window)) { RequestQuit(); } return true; } void GetFramebufferSize(int &width, int &height) { glfwGetFramebufferSize(window, &width, &height); } void SetFramebufferSizeCallback(void* callback) { glfwSetFramebufferSizeCallback(window, (GLFWframebuffersizefun)callback); } void *GetProcAddress(const char* proc_name) { return (void *)glfwGetProcAddress(proc_name); } const char** GetInstanceExtensions(unsigned int* extensions_count) { return glfwGetRequiredInstanceExtensions(extensions_count); } void ReleaseInstanceExtensions(const char** extensions) { // not required. } int CreateWindowSurface(void* instance, const void* allocator, void* surface) { #ifdef IMAPP_RENDERER_VULKAN return glfwCreateWindowSurface((VkInstance)instance, window, (const VkAllocationCallbacks*)allocator, (VkSurfaceKHR*)surface);; #else return 0; #endif } }
26.968326
149
0.713423
remyroez
d692135582f44fee33dd8fb3ea7e545fd3e5cd9f
3,466
cpp
C++
src/main.cpp
segmentation-chaos/dynamical-systems
046f239b1be7753dfbe8f3f556030151a528fc0c
[ "BSD-3-Clause" ]
3
2019-09-25T22:20:32.000Z
2019-09-26T14:43:40.000Z
src/main.cpp
segmentation-chaos/dynamical-systems
046f239b1be7753dfbe8f3f556030151a528fc0c
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
segmentation-chaos/dynamical-systems
046f239b1be7753dfbe8f3f556030151a528fc0c
[ "BSD-3-Clause" ]
1
2021-07-21T23:25:45.000Z
2021-07-21T23:25:45.000Z
/* */ /* CLICK SPACE */ /* */ /* An educational application for dy- */ /* namical systems and C++ programmi- */ /* ng. Two applications available: */ /* */ /* 2D maps: */ /* Allows the interaction with a can- */ /* vas from which orbits of 2D maps */ /* can be iterated. */ /* Controls: */ /* Left click (hold): iterate orbit */ /* Right click: open zoom frame */ /* (When zooming) Left click: zoom in */ /* C: total zoom out */ /* X: delete previous orbit */ /* Ctrl + X: delete all orbits */ /* Ctrl + S: Save current orbits */ /* (file in results/map_name/) */ /* Ctrl + Left Click (hold and drag): */ /* Pan Screen */ /* Scrool UP: Zoom in */ /* Scrool DOWN: Zoom out */ /* R: Start line of init. cond. pts */ /* (In line) Scrool up: increase pts */ /* (In line) Scrool down: decrease pts*/ /* (In line) Space bar: run all */ /* (In line) S: exit line */ /* N: Toggle night | light mode color */ /* */ /* */ /* 1D maps: */ /* Allows the interaction with a can- */ /* vas from which cob web orbits are */ /* draw, allowing also the control of */ /* one of the system's parameter */ /* Controls: */ /* Left mouse click: run cob web */ /* W: increase parameter */ /* S: decrease parameter */ /* ESC: back to main menu */ /* */ /* */ /* This program is implemented with */ /* the olcPixelGameEngine, as develo- */ /* ped by Javidx9 (David Bahr). Its */ /* original license and readme file */ /* are shown in LICENSE/, and the en- */ /* gine file in olcPixelGameEngine.h. */ /* Moreover, the code for the main */ /* menu was directly copied from it, */ /* along with small tips and tricks */ /* that Javidx9 brilliantly passes on */ /* to all commom folks willing to le- */ /* arn C++ from his channel (Thank */ /* you Javidx9), although any errors */ /* or bugs are in full responsability */ /* of the developers. */ /* */ /* Designed and manufactured in */ /* Brazil by: */ /* M. Lazarotto */ /* V. Oliveira */ /* M. Palmero */ /* (21/11/2020) */ /* */ /* */ /* To run the program, within a term- */ /* inal compile it by typing: */ /* */ /* make clean && make */ /* */ /* And run it by typing: */ /* */ /* vblank_mode=0 ./click_space */ /* */ #include "clickspace.h" int main() { // App window settings olcClickSpace application; int32_t ScreenWidth = 1400; int32_t ScreenHeight = 1000; // Main game loop if (application.Construct(ScreenWidth, ScreenHeight, 1, 1)) { application.Start(); } return 0; }
36.484211
63
0.430756
segmentation-chaos
d69294da0ec393ccf1749eeb019afcc098d45244
32,472
cpp
C++
client/Classes/View/Layers/NetworkQueueLayer/NetworkQueueLayer.cpp
plankes-projects/BaseWar
693f7d02fa324b917b28be58d33bb77a18d77f26
[ "Apache-2.0" ]
60
2015-01-03T07:31:14.000Z
2021-12-17T02:39:17.000Z
client/Classes/View/Layers/NetworkQueueLayer/NetworkQueueLayer.cpp
plankes-projects/BaseWar
693f7d02fa324b917b28be58d33bb77a18d77f26
[ "Apache-2.0" ]
1
2018-08-17T09:59:30.000Z
2018-08-17T09:59:30.000Z
client/Classes/View/Layers/NetworkQueueLayer/NetworkQueueLayer.cpp
plankes-projects/BaseWar
693f7d02fa324b917b28be58d33bb77a18d77f26
[ "Apache-2.0" ]
27
2015-01-22T06:55:10.000Z
2021-12-17T02:39:23.000Z
#include "NetworkQueueLayer.h" #include "../../../Model/Model.h" #include "../../../SceneControl.h" #include "../../../Network/ServerCommunication.h" #include "../../../Network/NetworkSingleton.h" #include "../../../Tools/Tools.h" #include "../../../Tools/BW_Time.h" #include "../../../Model/GameMode.h" #include "../../../Constants.h" #include "../../../Tools/ViewTools.h" #include "../../../AchievementSystem/AchievementSystem.h" // on "init" you need to initialize your instance bool NetworkQueueLayer::init() { Model::getInstance()->setGameMode(NETWORK); float scaleMult = Model::getInstance()->getGUIElementScaleMultiplicator(); if (!CCLayerColor::initWithColor(ccc4(100, 255, 255, 255))) return false; _gameStarted = false; //adding the background CCSize winSize = CCDirector::sharedDirector()->getWinSize(); cocos2d::CCSprite* backgroundArt = CCSprite::createWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("menuBackground.png")); float bgScale = winSize.height / backgroundArt->getContentSize().height; backgroundArt->setScale(bgScale); float diff = winSize.width - backgroundArt->getContentSize().width * bgScale; float x = backgroundArt->getContentSize().width / 2 * bgScale + diff / 2; float y = backgroundArt->getContentSize().height / 2 * bgScale; backgroundArt->setPosition(ccp(x, y)); addChild(backgroundArt); float button_length = 66 * scaleMult; float button_heigth = 66 * scaleMult; float padding = 10 * scaleMult; _leaveQueue = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("return0.png"), CCSprite::createWithSpriteFrameName("return1.png"), (CCObject*) this, menu_selector(NetworkQueueLayer::leaveQueueTouched)); _leaveQueue->setScaleX(button_length / _leaveQueue->getContentSize().width); _leaveQueue->setScaleY(button_heigth / _leaveQueue->getContentSize().height); CCMenu* menu = CCMenu::create(); menu->addChild(_leaveQueue, 1); menu->alignItemsHorizontallyWithPadding(padding); addChild(menu); _sendingRequest = false; _foundGame = false; _countDown = CCLabelTTF::create("", FONT_NAME, 150 * scaleMult); _countDown->setPosition(ccp(winSize.width / 2, winSize.height / 2)); _countDown->setColor(ccc3(74, 24, 147)); addChild(_countDown); //init server message float label_font_size = 25 * scaleMult; const char* label_font = FONT_NAME; ccColor3B color = ccc3(0, 0, 0); _serverMessage = CCLabelTTF::create("Connecting to basewar.net ...", label_font, label_font_size); _serverMessage->setColor(color); _serverMessage->setPosition(ccp(winSize.width / 2, winSize.height / 2 - (button_heigth / 2 + padding + _serverMessage->getContentSize().height / 2))); this->addChild(_serverMessage); _serverInformation = CCLabelTTF::create("", label_font, label_font_size); _serverInformation->setColor(color); this->addChild(_serverInformation); _loadedServerInformation = false; _loadedPlayerNumInformation = false; _loadedTeamsizeConfig = false; _maxSecToStart = -1; //will be set by server request _playerSet = false; _teamsizeConfig = 1; _queueTimeInSec = BW_Time::getSeconds(); _numOfPlayersOnline = -1; ServerCommunication().sendGameProgress(); this->schedule(schedule_selector(NetworkQueueLayer::update), 1); float offsetDown = ViewTools::addVersionAndCreditInfo(this, scaleMult); ViewTools::addIdleUnitTo(this, offsetDown); return true; } void NetworkQueueLayer::update(float dt) { if (_foundGame) gameCounterPart(); else queuePart(); } void NetworkQueueLayer::gameCounterPart() { if (!_playerSet) { _playerSet = true; CCSize winSize = CCDirector::sharedDirector()->getWinSize(); float scaleMult = Model::getInstance()->getGUIElementScaleMultiplicator(); std::string vsStringPartOne = ""; std::string vsStringPartZwo = ""; std::string vsString = ""; bool second = false; bool playerAtSecond = false; std::vector < std::string > names = NetworkSingleton::getInstance()->_names; int playerIdWrittenLast = -1; bool gotMyName = false; int numGamestats = NetworkSingleton::getInstance()->_gameStats.size(); for (int i = 0; i < numGamestats; i++) { GameStat current = NetworkSingleton::getInstance()->_gameStats[i]; int id = current.getPlayerId(); if (id == (playerIdWrittenLast + 1)) { vsString = names[i] + "\n"; } else { gotMyName = true; playerAtSecond = second; i--; //we need to use this id again vsString = _playerName + "\n"; } if (second) vsStringPartZwo += vsString; else vsStringPartOne += vsString; playerIdWrittenLast++; if (playerIdWrittenLast + 1 == (numGamestats + 1) / 2) second = true; } if (!gotMyName) { //my name was at the end, add it vsStringPartZwo += _playerName + "\n"; playerAtSecond = second; } if (playerAtSecond) { vsString = vsStringPartZwo + "--- vs ---\n" + vsStringPartOne; } else { vsString = vsStringPartOne + "--- vs ---\n" + vsStringPartZwo; } cocos2d::CCLabelTTF* vsInfo = CCLabelTTF::create(vsString.c_str(), FONT_NAME, 25 * scaleMult); vsInfo->setColor(ccc3(0, 0, 0)); vsInfo->setPosition(ccp(vsInfo->getContentSize().width / 2 + 10 * scaleMult, winSize.height / 2)); this->addChild(vsInfo); } int start = NetworkSingleton::getInstance()->_gameStart; int now = BW_Time::getSeconds(); if (start < now) { //fixes a bug on slower devices which results in a double call of this if (_gameStarted) return; _gameStarted = true; NetworkSingleton::getInstance()->_myName = _playerName; SceneControl::replaceScene(SceneControl::gameScene(1, NETWORK), true); return; } int left = start - now; if (left == 0) _countDown->setString("Fight!"); else _countDown->setString(Tools::toString(left).c_str()); CCFiniteTimeAction *scale1 = CCScaleTo::create(0.15f, 1.3f); CCFiniteTimeAction *scale2 = CCScaleTo::create(0.1f, 0.7f); CCFiniteTimeAction *scale3 = CCScaleTo::create(0.05f, 1.0f); _countDown->runAction(CCSequence::create(scale1, scale2, scale3, NULL)); } void NetworkQueueLayer::onQueueCompleted(CCHttpClient *sender, CCHttpResponse *response) { if (!response) return completeQueueRequest(-1, ""); if (!response->isSucceed()) { CCLog("server get queue response failed"); CCLog("error buffer: %s", response->getErrorBuffer()); return completeQueueRequest(-1, ""); } std::string resp = Tools::toString(response->getResponseData()); CCLOG("queue resp: %s", resp.c_str()); //CCLOG("string begin ---------"); //CCLOG(resp.c_str()); //CCLOG("string end ---------"); float recieve_time = BW_Time::getMilliSeconds(); //looking at it line by line std::istringstream f(resp); std::string line; std::getline(f, line); std::string firstServerLine = line; if (firstServerLine == "") return completeQueueRequest(-3, firstServerLine); /** Server returns: joined queue: 0 in queue: 1 Game init: -18 0:1+klaus 1:1+klaus 2:1+123-132-41-12-412-423-1-412-1+klaus 3:1+klaus 4:1+klaus 5 */ NetworkSingleton *ns = NetworkSingleton::getInstance(); ns->reset(); int addLines = -1; while (std::getline(f, line)) { //empty line is last if (line == "") break;; addLines++; //CCLOG("line: %s", line.c_str()); std::size_t found = line.find(":"); if (found == std::string::npos) { //this is my id if (ns->_myGameStat.getPlayerId() == -1) { int id = atoi(line.c_str()); if (id != addLines) //invalid { //CCLOG("inv 1: %i != %i", id, addLines); return completeQueueRequest(-2, firstServerLine); } ns->_myGameStat.setRace(_raceId); ns->_myGameStat.setPlayerId(id); ns->_myGameStat.setRandomRaceString(_randomRaceString); continue; } else { //invalid CCLOG("inv 2: "); return completeQueueRequest(-3, firstServerLine); } } else if (found != 1) { //invalid CCLOG(line.c_str(), 1); return completeQueueRequest(-4, firstServerLine); } found = line.find("+"); if (found != 3) { CCLOG("inv 4"); return completeQueueRequest(-5, firstServerLine); } GameStat gs = GameStat(); int id = line[0] - '0'; if (id != addLines) { //invalid CCLOG("inv 5: %i != %i", id, addLines); return completeQueueRequest(-6, firstServerLine); } gs.setPlayerId(id); int raceId = line[2] - '0'; gs.setRace(raceId); std::string name = line.substr(found + 1); if (raceId == 0) { //there must be a randomRaceString //2:1+123-132-41-12-412-423-1-412-1+klaus found = name.find("+"); if (found == std::string::npos) { CCLOG("inv 6"); return completeQueueRequest(-6, firstServerLine); } std::string randomRaceString = name.substr(0, found); gs.setRandomRaceString(randomRaceString); CCLOG("Name: %s", name.c_str()); name = name.substr(found + 1); CCLOG("RandomRaceString: %s", randomRaceString.c_str()); } ns->_names.push_back(name); ns->_gameStats.push_back(gs); } //check number of players if (ns->_names.size() == 0) return completeQueueRequest(0, firstServerLine); if ((ns->_names.size() + 1) % 2 != 0) //+1 because of my id { CCLOG("inv 7"); return completeQueueRequest(-7, firstServerLine); } //calc starttime int delay = (recieve_time - _send_time) / 2000; //first line is the time to start number ns->_gameStart = BW_Time::getSeconds() + atoi(firstServerLine.c_str()) - delay; /* CCLOG("read some data: -----------"); CCLOG("start: %i", ns->_gameStart); CCLOG("myid: %i", ns->_myGameStat.getPlayerId()); for(int i = 0; i < ns->_names.size(); i++) { CCLOG("Name: %s, id: %i, race: %i", ns->_names[i].c_str(), ns->_gameStats[i].getPlayerId(), ns->_gameStats[i].getRace()); } CCLOG("-----------"); */ return completeQueueRequest(2, firstServerLine); } void NetworkQueueLayer::initAINetworkPlayers() { int allPlayerSize = _teamsizeConfig * 2; if (allPlayerSize < 2 || allPlayerSize > 6) allPlayerSize = 6; NetworkSingleton *ns = NetworkSingleton::getInstance(); ns->reset(); ns->_myGameStat.setRace(_raceId); ns->_myGameStat.setPlayerId(Tools::random(0, allPlayerSize - 1)); ns->_myGameStat.setRandomRaceString(_randomRaceString); //get number of possible races int maxPossibleRaceId = 0; for (Race* r = Race::createRaceWithId(maxPossibleRaceId); r != 0; maxPossibleRaceId++, r = Race::createRaceWithId(maxPossibleRaceId)) { delete r; } maxPossibleRaceId--; //remove not existing id //generate random player names std::vector < std::string > playerNames = getFakePlayerNames(); for (int id = 0; id < allPlayerSize; id++) { if (ns->_myGameStat.getPlayerId() == id) continue; GameStat gs = GameStat(); gs.setPlayerId(id); gs.setRace(Tools::random(0, maxPossibleRaceId)); gs.setRandomRaceString(gs.getRace() == 0 ? Race::createRandomizedRaceString() : ""); int fakePlayerNameIndex = Tools::random(0, playerNames.size() - 1); ns->_names.push_back(playerNames[fakePlayerNameIndex]); playerNames.erase(playerNames.begin() + fakePlayerNameIndex); ns->_gameStats.push_back(gs); } ns->_gameStart = BW_Time::getSeconds() + Tools::random(8, 10); } void NetworkQueueLayer::completeQueueRequest(int code, std::string firstServerLine) { if (code == -1) { _serverMessage->setString("Could not connect to the server (-1)"); CCLOG("Could not connect to the server! (-1)"); } else if (code < -1) { std::string msg = "Server communication error (" + Tools::toString(code) + ")"; _serverMessage->setString(msg.c_str()); CCLOG(msg.c_str(), 1); } else if (code == 2) { CCLOG("Filled the NetworkSingleton! Game created."); _leaveQueue->removeFromParentAndCleanup(true); _serverMessage->removeFromParentAndCleanup(true); _serverMessage = NULL; NetworkSingleton::getInstance()->fakeNetworkGame = false; _foundGame = true; } else if (code == 0) { std::string waiting = Tools::toString(_teamsizeConfig) + " vs " + Tools::toString(_teamsizeConfig); std::string numOfPlayer = "\nPlayers online: " + (_numOfPlayersOnline == -1 ? "-" : Tools::toString(_numOfPlayersOnline)); //Do something with firstServerLine. currently its 1/2 int secLeft = _queueTimeInSec - BW_Time::getSeconds() + _maxSecToStart; std::string estimatedTime = "\nEstimated seconds until start: " + (secLeft < 0 ? "0" : Tools::toString(secLeft)); _serverMessage->setString((waiting + numOfPlayer + estimatedTime).c_str()); if (secLeft <= 0) { initAINetworkPlayers(); _leaveQueue->removeFromParentAndCleanup(true); _serverMessage->removeFromParentAndCleanup(true); _serverMessage = NULL; NetworkSingleton::getInstance()->fakeNetworkGame = true; _foundGame = true; } } if (_serverMessage != NULL) { float scaleMult = Model::getInstance()->getGUIElementScaleMultiplicator(); float padding = 10 * scaleMult; CCSize winSize = CCDirector::sharedDirector()->getWinSize(); float button_heigth = 66 * scaleMult; _serverMessage->setPosition(ccp(winSize.width / 2, winSize.height / 2 - (button_heigth / 2 + padding + _serverMessage->getContentSize().height / 2))); } _sendingRequest = false; } void NetworkQueueLayer::onTeamsizeConfigCompleted(CCHttpClient *sender, CCHttpResponse *response) { if (!response) { CCLog("server team size info response failed - response missing"); _loadedTeamsizeConfig = false; return; } if (!response->isSucceed()) { CCLog("server team size info response failed"); CCLog("error buffer: %s", response->getErrorBuffer()); _loadedTeamsizeConfig = false; return; } std::string resp = Tools::toString(response->getResponseData()); _teamsizeConfig = atoi(resp.c_str()); //we are sure to have server connection here for (int i = 0; i < NUMBER_OF_OFFLINE_GAMES_SEND_AT_ONE_TIME; i++) ServerCommunication().sendOldestOfflineLog(); } void NetworkQueueLayer::onPlayerNumInfoCompleted(CCHttpClient *sender, CCHttpResponse *response) { if (!response) { CCLog("server player num info response failed - response missing"); _loadedPlayerNumInformation = false; return; } if (!response->isSucceed()) { CCLog("server player num info response failed"); CCLog("error buffer: %s", response->getErrorBuffer()); _loadedPlayerNumInformation = false; return; } std::string resp = Tools::toString(response->getResponseData()); std::vector < std::string > playerNumEstimatedTime = Tools::splitStringBy(resp, '-'); if (playerNumEstimatedTime.size() != 2) { CCLOG("[ERROR] Playernum should has the format 'PlayerNum-EstimatedSec'"); _loadedPlayerNumInformation = false; return; } _numOfPlayersOnline = atoi(playerNumEstimatedTime[0].c_str()); _maxSecToStart = atoi(playerNumEstimatedTime[1].c_str()); } void NetworkQueueLayer::onGetServerInfoCompleted(CCHttpClient *sender, CCHttpResponse *response) { if (!response) { CCLog("server get info response failed - response missing"); _loadedServerInformation = false; return; } if (!response->isSucceed()) { CCLog("server get info response failed"); CCLog("error buffer: %s", response->getErrorBuffer()); _loadedServerInformation = false; return; } std::string resp = Tools::toString(response->getResponseData()); std::string basewarflag = "<basewarQueueInfo>"; if (resp.compare(0, basewarflag.size(), basewarflag) != 0) return; //fail script resp.erase(0, resp.find('\n') + 1); //remove first line with server info flag float scaleMult = Model::getInstance()->getGUIElementScaleMultiplicator(); float padding = 10 * scaleMult; CCSize winSize = CCDirector::sharedDirector()->getWinSize(); float button_heigth = 66 * scaleMult; _serverInformation->setString(resp.c_str()); _serverInformation->setPosition( ccp(winSize.width / 2, winSize.height / 2 + (button_heigth / 2 + padding + _serverInformation->getContentSize().height / 2))); } void NetworkQueueLayer::queuePart() { if (_sendingRequest) return; ServerCommunication sc = ServerCommunication(); if (!_loadedServerInformation) { _loadedServerInformation = true; sc.getServerinformation(this, httpresponse_selector(NetworkQueueLayer::onGetServerInfoCompleted)); } if (!_loadedPlayerNumInformation) { _loadedPlayerNumInformation = true; sc.getPlayerNum(this, httpresponse_selector(NetworkQueueLayer::onPlayerNumInfoCompleted)); } if (!_loadedTeamsizeConfig) { _loadedTeamsizeConfig = true; sc.getTeamsizeConfig(this, httpresponse_selector(NetworkQueueLayer::onTeamsizeConfigCompleted)); } //we reset the queued time, do we will not have an invalid seconds in queue time if (_maxSecToStart == -1) _queueTimeInSec = BW_Time::getSeconds(); //first request is send 5 seconds after we joined (and first server contact) if (BW_Time::getSeconds() - _queueTimeInSec < 5) { if (_maxSecToStart != -1) { completeQueueRequest(0, Tools::toString(BW_Time::getSeconds() - _queueTimeInSec)); } return; } _sendingRequest = true; _send_time = BW_Time::getMilliSeconds(); sc.queueMe(_raceId, _playerName, _randomRaceString, this, httpresponse_selector(NetworkQueueLayer::onQueueCompleted)); } void NetworkQueueLayer::leaveQueueTouched(CCObject* pSender) { SceneControl::replaceScene(SceneControl::startMenuScene(), false); } void NetworkQueueLayer::setPlayerName(std::string playerName) { _playerName = playerName; } void NetworkQueueLayer::setRaceId(int raceId) { _raceId = raceId; _randomRaceString = ""; if (_raceId == 0) { _randomRaceString = Race::createRandomizedRaceString(); } } std::vector<std::string> NetworkQueueLayer::getFakePlayerNames() { std::vector < std::string > fakePlayerName; //add some self defined names fakePlayerName.push_back("Rok"); fakePlayerName.push_back("Rock"); fakePlayerName.push_back("Shoroa"); fakePlayerName.push_back("Töpfchen"); //add names from a generator fakePlayerName.push_back("Doozmolt"); fakePlayerName.push_back("Gunkumb"); fakePlayerName.push_back("Froof"); fakePlayerName.push_back("Froob"); fakePlayerName.push_back("Glunphball"); fakePlayerName.push_back("Clunuzz"); fakePlayerName.push_back("Gogwook"); fakePlayerName.push_back("Womph"); fakePlayerName.push_back("Punt"); fakePlayerName.push_back("Kuckbun"); fakePlayerName.push_back("Gobult"); fakePlayerName.push_back("Donkpidiot"); fakePlayerName.push_back("Porkfrub"); fakePlayerName.push_back("Jumfelch"); fakePlayerName.push_back("Poltmorm"); fakePlayerName.push_back("Glunt"); fakePlayerName.push_back("Bookdip"); fakePlayerName.push_back("Klomphnump"); fakePlayerName.push_back("Frelchung"); fakePlayerName.push_back("Cloron"); fakePlayerName.push_back("Wongfumph"); fakePlayerName.push_back("Jidiotgunph"); fakePlayerName.push_back("Gobglunk"); fakePlayerName.push_back("Donkun"); fakePlayerName.push_back("Doofmonk"); fakePlayerName.push_back("Blokjog"); fakePlayerName.push_back("Blumphgoof"); fakePlayerName.push_back("Thobclown"); fakePlayerName.push_back("Brolt"); fakePlayerName.push_back("Porkjunb"); fakePlayerName.push_back("Funph"); fakePlayerName.push_back("Pobbeef"); fakePlayerName.push_back("Gunnit"); fakePlayerName.push_back("Kubfrorm"); fakePlayerName.push_back("Hunphthimble"); fakePlayerName.push_back("Grubbrok"); fakePlayerName.push_back("Bumbdidiot"); fakePlayerName.push_back("Gunankle"); fakePlayerName.push_back("Nuck"); fakePlayerName.push_back("Dobong"); fakePlayerName.push_back("Bump"); fakePlayerName.push_back("Borkmuck"); fakePlayerName.push_back("Kult"); fakePlayerName.push_back("Doowad"); fakePlayerName.push_back("Ghoog"); fakePlayerName.push_back("Nonkdip"); fakePlayerName.push_back("Gob"); fakePlayerName.push_back("Puzz"); fakePlayerName.push_back("Fuck"); fakePlayerName.push_back("Dulfclot"); fakePlayerName.push_back("Grunkum"); fakePlayerName.push_back("Bunkghub"); fakePlayerName.push_back("Ghunkook"); fakePlayerName.push_back("Pormbeef"); fakePlayerName.push_back("Ghomph"); fakePlayerName.push_back("Clumbob"); fakePlayerName.push_back("Dultbridiot"); fakePlayerName.push_back("Jolph"); fakePlayerName.push_back("Fomph"); fakePlayerName.push_back("Pob"); fakePlayerName.push_back("Gunbloaf"); fakePlayerName.push_back("Grorg"); fakePlayerName.push_back("Klok"); fakePlayerName.push_back("Porgoo"); fakePlayerName.push_back("Thelchgog"); fakePlayerName.push_back("Mulfflolt"); fakePlayerName.push_back("Porgknock"); fakePlayerName.push_back("Moob"); fakePlayerName.push_back("Hoobomph"); fakePlayerName.push_back("Huck"); fakePlayerName.push_back("Mummunb"); fakePlayerName.push_back("Puzz"); fakePlayerName.push_back("Klumbdooz"); fakePlayerName.push_back("Fonk"); fakePlayerName.push_back("Mok"); fakePlayerName.push_back("Dolphpolph"); fakePlayerName.push_back("Flolt"); fakePlayerName.push_back("Pook"); fakePlayerName.push_back("Florkporon"); fakePlayerName.push_back("Clok"); fakePlayerName.push_back("Gunph"); fakePlayerName.push_back("Flonk"); fakePlayerName.push_back("Didiot"); fakePlayerName.push_back("Clookgoof"); fakePlayerName.push_back("Moron"); fakePlayerName.push_back("Thugtwit"); fakePlayerName.push_back("Fumb"); fakePlayerName.push_back("Dolph"); fakePlayerName.push_back("Thumb"); fakePlayerName.push_back("Moohead"); fakePlayerName.push_back("Blok"); fakePlayerName.push_back("Koogfumble"); fakePlayerName.push_back("Flob"); fakePlayerName.push_back("Kub"); fakePlayerName.push_back("Dok"); fakePlayerName.push_back("Klunph"); fakePlayerName.push_back("Midiot"); fakePlayerName.push_back("Brubankle"); fakePlayerName.push_back("Bonk"); fakePlayerName.push_back("Mumpface"); fakePlayerName.push_back("Pulf"); fakePlayerName.push_back("Tholphknuckle"); fakePlayerName.push_back("Dunphdip"); fakePlayerName.push_back("Fuck"); fakePlayerName.push_back("Ghunbum"); fakePlayerName.push_back("Nuntgong"); fakePlayerName.push_back("Fumb"); fakePlayerName.push_back("Mongborm"); fakePlayerName.push_back("Floronbrumb"); fakePlayerName.push_back("Clorgdumb"); fakePlayerName.push_back("Ponkknock"); fakePlayerName.push_back("Clunoof"); fakePlayerName.push_back("Buboo"); fakePlayerName.push_back("Jidiotgluzz"); fakePlayerName.push_back("Fumphbult"); fakePlayerName.push_back("Borgug"); fakePlayerName.push_back("Muzz"); fakePlayerName.push_back("Bung"); fakePlayerName.push_back("Book"); fakePlayerName.push_back("Rynot"); fakePlayerName.push_back("Modup"); fakePlayerName.push_back("Xofili"); fakePlayerName.push_back("Hinserererwor"); fakePlayerName.push_back("Achsertorech"); fakePlayerName.push_back("Naldyn"); fakePlayerName.push_back("Emelm"); fakePlayerName.push_back("Hiwar"); fakePlayerName.push_back("Kimvia"); fakePlayerName.push_back("Mostai"); fakePlayerName.push_back("Imlorrad"); fakePlayerName.push_back("Steyz"); fakePlayerName.push_back("Hipolaugh"); fakePlayerName.push_back("Warbom"); fakePlayerName.push_back("Trandtin"); fakePlayerName.push_back("Eldkel"); fakePlayerName.push_back("Ormiss"); fakePlayerName.push_back("Colen"); fakePlayerName.push_back("Veryis"); fakePlayerName.push_back("Ardnque"); fakePlayerName.push_back("Kinnsul"); fakePlayerName.push_back("Lyedralye"); fakePlayerName.push_back("Quedusk"); fakePlayerName.push_back("Schoath"); fakePlayerName.push_back("Cesoh"); fakePlayerName.push_back("Iaro"); fakePlayerName.push_back("Lerkin"); fakePlayerName.push_back("Ineadves"); fakePlayerName.push_back("Chryorran"); fakePlayerName.push_back("Anysu"); fakePlayerName.push_back("Endean"); fakePlayerName.push_back("Timan"); fakePlayerName.push_back("Whialeen"); fakePlayerName.push_back("Untind"); fakePlayerName.push_back("Poiqche"); fakePlayerName.push_back("Iaez"); fakePlayerName.push_back("Ranl"); fakePlayerName.push_back("Eldalemor"); fakePlayerName.push_back("Tiald"); fakePlayerName.push_back("Telyecer"); fakePlayerName.push_back("Rodeld"); fakePlayerName.push_back("Yvory"); fakePlayerName.push_back("Blitor"); fakePlayerName.push_back("Zebese"); fakePlayerName.push_back("Naertough"); fakePlayerName.push_back("Emche"); fakePlayerName.push_back("Ittor"); fakePlayerName.push_back("Radrako"); fakePlayerName.push_back("Lerrothper"); fakePlayerName.push_back("Cheor"); fakePlayerName.push_back("Drianan"); fakePlayerName.push_back("Atidel"); fakePlayerName.push_back("Ustia"); fakePlayerName.push_back("Untther"); fakePlayerName.push_back("Sulwor"); fakePlayerName.push_back("Ranris"); fakePlayerName.push_back("Fotad"); fakePlayerName.push_back("Ranbel"); fakePlayerName.push_back("Essgar"); fakePlayerName.push_back("Lyeip"); fakePlayerName.push_back("Rodol"); fakePlayerName.push_back("Danest"); fakePlayerName.push_back("Yuemest"); fakePlayerName.push_back("Adado"); fakePlayerName.push_back("Enrothdar"); fakePlayerName.push_back("Darzton"); fakePlayerName.push_back("Rayet"); fakePlayerName.push_back("Agehwar"); fakePlayerName.push_back("Vorald"); fakePlayerName.push_back("Engissard"); fakePlayerName.push_back("Burtonine"); fakePlayerName.push_back("Nalbur"); fakePlayerName.push_back("Quetorton"); fakePlayerName.push_back("Chab"); fakePlayerName.push_back("Engem"); fakePlayerName.push_back("Dradarmor"); fakePlayerName.push_back("Dentasa"); fakePlayerName.push_back("Aughirray"); fakePlayerName.push_back("Bataf"); fakePlayerName.push_back("Ilbani"); fakePlayerName.push_back("Urnn"); fakePlayerName.push_back("Titser"); fakePlayerName.push_back("Theusmos"); fakePlayerName.push_back("Aldack"); fakePlayerName.push_back("Estunti"); fakePlayerName.push_back("Untangsam"); fakePlayerName.push_back("Serach"); fakePlayerName.push_back("Lergkin"); fakePlayerName.push_back("Zorary"); fakePlayerName.push_back("Rasec"); fakePlayerName.push_back("Burset"); fakePlayerName.push_back("Querothrak"); fakePlayerName.push_back("Swyves"); fakePlayerName.push_back("Kindel"); fakePlayerName.push_back("Enat"); fakePlayerName.push_back("Urnade"); fakePlayerName.push_back("Athine"); fakePlayerName.push_back("Serozy"); fakePlayerName.push_back("Ineone"); fakePlayerName.push_back("Rayelmmorechdyn"); fakePlayerName.push_back("Iatane"); fakePlayerName.push_back("Worona"); fakePlayerName.push_back("Lathunt"); fakePlayerName.push_back("Untalt"); fakePlayerName.push_back("Ankel"); fakePlayerName.push_back("Ghagom"); fakePlayerName.push_back("Waraldiss"); fakePlayerName.push_back("Marosian"); fakePlayerName.push_back("Lisirrasya"); fakePlayerName.push_back("Sondilsanya"); fakePlayerName.push_back("Lisadar"); fakePlayerName.push_back("Marirrala"); fakePlayerName.push_back("Sondim"); fakePlayerName.push_back("Chrundosia"); fakePlayerName.push_back("Lassosia"); fakePlayerName.push_back("Iskossa"); fakePlayerName.push_back("Lassosiaya"); fakePlayerName.push_back("Chanephi"); fakePlayerName.push_back("Chanirraya"); fakePlayerName.push_back("Frichilsanya"); fakePlayerName.push_back("Chamilsan"); fakePlayerName.push_back("Iskista"); fakePlayerName.push_back("Assast"); fakePlayerName.push_back("Chamilsa"); fakePlayerName.push_back("Assilsa"); fakePlayerName.push_back("Chadossasta"); fakePlayerName.push_back("Frichosia"); fakePlayerName.push_back("Iskastnya"); fakePlayerName.push_back("Chadim"); fakePlayerName.push_back("Lirtassa"); fakePlayerName.push_back("Iladar"); fakePlayerName.push_back("Doistiman"); fakePlayerName.push_back("Sondazoan"); fakePlayerName.push_back("Lisofe"); fakePlayerName.push_back("Sondirra"); fakePlayerName.push_back("Chadosia"); fakePlayerName.push_back("Sundassa"); fakePlayerName.push_back("Lisossanya"); fakePlayerName.push_back("Lassosiasda"); fakePlayerName.push_back("Frichassa"); fakePlayerName.push_back("Marossa"); fakePlayerName.push_back("Sundastya"); fakePlayerName.push_back("Mindossa"); fakePlayerName.push_back("Chanistanya"); fakePlayerName.push_back("Jiskjask"); fakePlayerName.push_back("Sundim"); fakePlayerName.push_back("Assjasksya"); fakePlayerName.push_back("Lisushi"); fakePlayerName.push_back("Lirtjask"); fakePlayerName.push_back("Chanisi"); fakePlayerName.push_back("Jiskadarsda"); fakePlayerName.push_back("Undim"); fakePlayerName.push_back("Jiskosia"); fakePlayerName.push_back("Lirtilsasta"); fakePlayerName.push_back("Loidinna"); fakePlayerName.push_back("Sondossa"); fakePlayerName.push_back("Assassa"); fakePlayerName.push_back("Assosia"); fakePlayerName.push_back("Chamirrasda"); fakePlayerName.push_back("Sundista"); fakePlayerName.push_back("Lisilsan"); fakePlayerName.push_back("Lisassasda"); fakePlayerName.push_back("Chadassa"); fakePlayerName.push_back("Serun"); fakePlayerName.push_back("Ormptor"); fakePlayerName.push_back("Blon"); fakePlayerName.push_back("Vorban"); fakePlayerName.push_back("Ashed"); fakePlayerName.push_back("Toit"); fakePlayerName.push_back("Enthbur"); fakePlayerName.push_back("Inasul"); fakePlayerName.push_back("Zhiwor"); fakePlayerName.push_back("Ardis"); fakePlayerName.push_back("Teer"); fakePlayerName.push_back("Nyath"); fakePlayerName.push_back("Lyetorine"); fakePlayerName.push_back("Etther"); fakePlayerName.push_back("Umvor"); fakePlayerName.push_back("Morth"); fakePlayerName.push_back("Polmser"); fakePlayerName.push_back("Morlkim"); fakePlayerName.push_back("Verurnlor"); fakePlayerName.push_back("Therrod"); fakePlayerName.push_back("Isstora"); fakePlayerName.push_back("Honr"); fakePlayerName.push_back("Aoso"); fakePlayerName.push_back("Worz"); fakePlayerName.push_back("Aechu"); fakePlayerName.push_back("Tozefa"); fakePlayerName.push_back("Rilawim"); fakePlayerName.push_back("Charilhin"); fakePlayerName.push_back("Aldcem"); fakePlayerName.push_back("Ormale"); fakePlayerName.push_back("Beust"); fakePlayerName.push_back("Gilypa"); fakePlayerName.push_back("Hindcha"); fakePlayerName.push_back("Brasam"); fakePlayerName.push_back("Belnys"); fakePlayerName.push_back("Degar"); fakePlayerName.push_back("Elmir"); fakePlayerName.push_back("Hycerale"); fakePlayerName.push_back("Poly"); fakePlayerName.push_back("Yeir"); fakePlayerName.push_back("Yuigshy"); fakePlayerName.push_back("Cherodi"); fakePlayerName.push_back("Ghancer"); fakePlayerName.push_back("Smaphusk"); fakePlayerName.push_back("Athoem"); fakePlayerName.push_back("Rynul"); fakePlayerName.push_back("Enyer"); fakePlayerName.push_back("Ormos"); fakePlayerName.push_back("Tociru"); fakePlayerName.push_back("Smyeld"); fakePlayerName.push_back("Rynas"); fakePlayerName.push_back("Getisa"); fakePlayerName.push_back("Aise"); fakePlayerName.push_back("Inghon"); fakePlayerName.push_back("Chack"); fakePlayerName.push_back("Quemorest"); fakePlayerName.push_back("Echit"); fakePlayerName.push_back("Oschebel"); fakePlayerName.push_back("Tiad"); fakePlayerName.push_back("Estver"); fakePlayerName.push_back("Skel-moryg"); fakePlayerName.push_back("Itqua"); fakePlayerName.push_back("Heegden"); fakePlayerName.push_back("Untos"); fakePlayerName.push_back("Ryage"); fakePlayerName.push_back("Nobyz"); fakePlayerName.push_back("Rakan"); fakePlayerName.push_back("Usken"); fakePlayerName.push_back("Garorm"); fakePlayerName.push_back("Slony"); fakePlayerName.push_back("Atiao"); fakePlayerName.push_back("Inala"); fakePlayerName.push_back("Bekah"); fakePlayerName.push_back("Deathmor"); fakePlayerName.push_back("Angvgha"); fakePlayerName.push_back("Nystas"); fakePlayerName.push_back("Voros"); fakePlayerName.push_back("Hatrayold"); fakePlayerName.push_back("Rilald"); fakePlayerName.push_back("Driesar"); fakePlayerName.push_back("Tanhini"); fakePlayerName.push_back("Ackturu"); fakePlayerName.push_back("Athrisi"); fakePlayerName.push_back("Yosu"); fakePlayerName.push_back("Auskochae"); fakePlayerName.push_back("Koardris"); fakePlayerName.push_back("Eelma"); fakePlayerName.push_back("Endkel"); fakePlayerName.push_back("Angdan"); fakePlayerName.push_back("Tenag"); fakePlayerName.push_back("Issdtia"); fakePlayerName.push_back("Awtintia"); fakePlayerName.push_back("Athuntther"); fakePlayerName.push_back("Swurrlt"); fakePlayerName.push_back("Stokin"); fakePlayerName.push_back("Alen"); fakePlayerName.push_back("Ghaend"); fakePlayerName.push_back("Imagea"); fakePlayerName.push_back("Ighte"); fakePlayerName.push_back("Kelgtai"); fakePlayerName.push_back("Vorril"); fakePlayerName.push_back("Ranag"); fakePlayerName.push_back("Hinart"); fakePlayerName.push_back("Morer"); fakePlayerName.push_back("Snaightser"); fakePlayerName.push_back("Adchabel"); fakePlayerName.push_back("Erbanis"); fakePlayerName.push_back("Untris"); fakePlayerName.push_back("Rothem"); fakePlayerName.push_back("Aswage"); return fakePlayerName; }
34.655283
155
0.743133
plankes-projects
d69336dcb3392e35b0fbca4410068700b664138c
2,497
cpp
C++
cpp/graphs/shortestpaths/dijkstra_custom_heap.cpp
ayushbhatt2000/codelibrary
e1209b5e6195717d20127e12e908839c595c2f4c
[ "Unlicense" ]
1,727
2015-01-01T18:32:37.000Z
2022-03-28T05:56:03.000Z
cpp/graphs/shortestpaths/dijkstra_custom_heap.cpp
ayushbhatt2000/codelibrary
e1209b5e6195717d20127e12e908839c595c2f4c
[ "Unlicense" ]
110
2015-05-03T10:23:18.000Z
2021-07-31T22:44:39.000Z
cpp/graphs/shortestpaths/dijkstra_custom_heap.cpp
ayushbhatt2000/codelibrary
e1209b5e6195717d20127e12e908839c595c2f4c
[ "Unlicense" ]
570
2015-01-01T10:17:11.000Z
2022-03-31T22:23:46.000Z
#include <bits/stdc++.h> using namespace std; const int maxnodes = 200'000; const int maxedges = 1000'000; // graph int edges; int last[maxnodes], head[maxedges], previous[maxedges], len[maxedges]; int prio[maxnodes], pred[maxnodes]; void reset_graph() { fill(last, last + maxnodes, -1); edges = 0; } void add_edge(int u, int v, int length) { head[edges] = v; len[edges] = length; previous[edges] = last[u]; last[u] = edges++; } // heap int h[maxnodes]; int pos2Id[maxnodes]; int id2Pos[maxnodes]; int hsize; void hswap(int i, int j) { swap(h[i], h[j]); swap(pos2Id[i], pos2Id[j]); swap(id2Pos[pos2Id[i]], id2Pos[pos2Id[j]]); } void move_up(int pos) { while (pos > 0) { int parent = (pos - 1) >> 1; if (h[pos] >= h[parent]) { break; } hswap(pos, parent); pos = parent; } } void add(int id, int prio) { h[hsize] = prio; pos2Id[hsize] = id; id2Pos[id] = hsize; move_up(hsize++); } void increase_priority(int id, int prio) { int pos = id2Pos[id]; h[pos] = prio; move_up(pos); } void move_down(int pos) { while (pos < (hsize >> 1)) { int child = 2 * pos + 1; if (child + 1 < hsize && h[child + 1] < h[child]) { ++child; } if (h[pos] <= h[child]) { break; } hswap(pos, child); pos = child; } } int remove_min() { int res = pos2Id[0]; int lastNode = h[--hsize]; if (hsize > 0) { h[0] = lastNode; int id = pos2Id[hsize]; id2Pos[id] = 0; pos2Id[0] = id; move_down(0); } return res; } void dijkstra(int s) { fill(pred, pred + maxnodes, -1); fill(prio, prio + maxnodes, numeric_limits<int>::max()); prio[s] = 0; hsize = 0; add(s, prio[s]); while (hsize) { int u = remove_min(); for (int e = last[u]; e >= 0; e = previous[e]) { int v = head[e]; int nprio = prio[u] + len[e]; if (prio[v] > nprio) { if (prio[v] == numeric_limits<int>::max()) add(v, nprio); else increase_priority(v, nprio); prio[v] = nprio; pred[v] = u; } } } } int main() { reset_graph(); add_edge(0, 1, 10); add_edge(1, 2, -5); add_edge(0, 2, 8); dijkstra(0); for (int i = 0; i < 3; i++) cout << prio[i] << endl; }
20.300813
70
0.486984
ayushbhatt2000
d696e6279fd0a3a19099601c5578deb8b8c697cb
8,111
cpp
C++
src/FFMPEG.cpp
dubhater/D2VWitch
b379384bb6aa7ee475ff7421b0ce5fee9e85d8b6
[ "ISC" ]
35
2016-01-15T08:00:10.000Z
2021-12-22T19:49:49.000Z
src/FFMPEG.cpp
dubhater/D2VWitch
b379384bb6aa7ee475ff7421b0ce5fee9e85d8b6
[ "ISC" ]
11
2016-03-07T00:04:26.000Z
2022-02-09T18:32:54.000Z
src/FFMPEG.cpp
dubhater/D2VWitch
b379384bb6aa7ee475ff7421b0ce5fee9e85d8b6
[ "ISC" ]
5
2016-01-18T12:50:13.000Z
2021-05-01T09:12:02.000Z
/* Copyright (c) 2016, John Smith Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "FFMPEG.h" FFMPEG::FFMPEG() : io_buffer(nullptr) , fctx(nullptr) , avcodec(nullptr) , avctx(nullptr) , parser(nullptr) { } FFMPEG::~FFMPEG() { cleanup(); } const std::string &FFMPEG::getError() const { return error; } bool FFMPEG::initFormat(FakeFile &fake_file) { fctx = avformat_alloc_context(); if (!fctx) { error = "Couldn't allocate AVFormatContext."; return false; } size_t io_buffer_size = 32 * 1024; io_buffer = (uint8_t *)av_malloc(io_buffer_size); if (!io_buffer) { error = "Couldn't allocate " + std::to_string(io_buffer_size) + " bytes for the AVIOContext."; return false; } fctx->pb = avio_alloc_context(io_buffer, io_buffer_size, 0, &fake_file, FakeFile::readPacket, nullptr, FakeFile::seek); if (!fctx->pb) { error = "Couldn't allocate AVIOContext."; return false; } // These two are both needed in order to properly detect the // details of the audio streams from a certain DVD. // Values obtained by trial and error. Increase them if needed. // They add a bit of delay, but what can you do? fctx->probesize = 10 * 1000 * 1000; // bytes fctx->max_analyze_duration = 20 * 1000 * 1000; // microseconds int ret = avformat_open_input(&fctx, fake_file[0].name.c_str(), nullptr, nullptr); if (ret < 0) { error = "avformat_open_input() failed: "; char av_error[AV_ERROR_MAX_STRING_SIZE] = { 0 }; if (!av_strerror(ret, av_error, AV_ERROR_MAX_STRING_SIZE)) error += av_error; else error += strerror(ret); return false; } ret = avformat_find_stream_info(fctx, nullptr); if (ret < 0) { error = "avformat_find_stream_info() failed: "; char av_error[AV_ERROR_MAX_STRING_SIZE] = { 0 }; if (!av_strerror(ret, av_error, AV_ERROR_MAX_STRING_SIZE)) error += av_error; else error += strerror(ret); return false; } return true; } bool FFMPEG::initVideoCodec(int stream_index) { if (!fctx) { error = "Must call initFormat before initVideoCodec."; return false; } deinitVideoCodec(); AVCodecID video_codec_id = fctx->streams[stream_index]->codec->codec_id; avcodec = avcodec_find_decoder(video_codec_id); if (!avcodec) { error = "Couldn't find decoder for "; error += avcodec_get_name(video_codec_id); return false; } avctx = avcodec_alloc_context3(avcodec); if (!avctx) { error = "Couldn't allocate AVCodecContext for the video decoder."; return false; } if (avcodec_copy_context(avctx, fctx->streams[stream_index]->codec) < 0) { error = "Couldn't copy video codec parameters."; return false; } if (avcodec_open2(avctx, avcodec, nullptr) < 0) { error = "Couldn't open AVCodecContext for the video decoder."; return false; } parser = av_parser_init(video_codec_id); if (!parser) { error = "Couldn't initialise parser for "; error += avcodec_get_name(video_codec_id); return false; } parser->flags = PARSER_FLAG_COMPLETE_FRAMES; return true; } bool FFMPEG::initAudioCodec(int stream_index) { if (codecIDRequiresWave64(fctx->streams[stream_index]->codec->codec_id)) { AVCodecContext *ctx = avcodec_alloc_context3(nullptr); if (!ctx) { error = "Couldn't allocate AVCodecContext for an audio decoder."; return false; } if (avcodec_copy_context(ctx, fctx->streams[stream_index]->codec) < 0) { error = "Couldn't copy AVCodecContext for an audio decoder."; return false; } AVCodec *audio_decoder = avcodec_find_decoder(fctx->streams[stream_index]->codec->codec_id); if (!audio_decoder) { error = "Couldn't find decoder for "; error += avcodec_get_name(fctx->streams[stream_index]->codec->codec_id); return false; } if (avcodec_open2(ctx, audio_decoder, nullptr) < 0) { error = "Couldn't open AVCodecContext for an audio decoder."; return false; } audio_ctx.insert({ fctx->streams[stream_index]->index, ctx }); } return true; } bool FFMPEG::initAudioCodecs() { for (unsigned i = 0; i < fctx->nb_streams; i++) { if (!initAudioCodec(i)) return false; } return true; } void FFMPEG::deinitVideoCodec() { if (parser) { av_parser_close(parser); parser = nullptr; } if (avctx) { avcodec_close(avctx); avcodec_free_context(&avctx); } } void FFMPEG::cleanup() { deinitVideoCodec(); if (fctx) { avio_context_free(&fctx->pb); avformat_close_input(&fctx); } for (auto it = audio_ctx.begin(); it != audio_ctx.end(); it++) { avcodec_close(it->second); avcodec_free_context(&it->second); } } AVStream *FFMPEG::selectVideoStreamById(int id) { for (unsigned i = 0; i < fctx->nb_streams; i++) { if (fctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { if (fctx->streams[i]->id == id) { fctx->streams[i]->discard = AVDISCARD_DEFAULT; return fctx->streams[i]; } } } return nullptr; } AVStream *FFMPEG::selectFirstVideoStream() { for (unsigned i = 0; i < fctx->nb_streams; i++) { if (fctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { fctx->streams[i]->discard = AVDISCARD_DEFAULT; return fctx->streams[i]; } } return nullptr; } bool FFMPEG::selectAudioStreamsById(const std::vector<int> &audio_ids, std::vector<int> &missing_audio_ids) { missing_audio_ids = audio_ids; for (int j = missing_audio_ids.size() - 1; j >= 0; j--) { for (unsigned i = 0; i < fctx->nb_streams; i++) { if (fctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) { if (fctx->streams[i]->id == missing_audio_ids[j]) { fctx->streams[i]->discard = AVDISCARD_DEFAULT; missing_audio_ids.erase((missing_audio_ids.begin() + j)); break; } } } } return !missing_audio_ids.size(); } bool FFMPEG::selectAllAudioStreams() { bool okay = false; for (unsigned i = 0; i < fctx->nb_streams; i++) { if (fctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) { fctx->streams[i]->discard = AVDISCARD_DEFAULT; okay = true; } } return okay; } void FFMPEG::deselectAllStreams() { for (unsigned i = 0; i < fctx->nb_streams; i++) fctx->streams[i]->discard = AVDISCARD_ALL; } bool FFMPEG::seek(int64_t position) { int ret = avformat_seek_file(fctx, -1, INT64_MIN, position, INT64_MAX, AVSEEK_FLAG_BYTE); if (ret < 0) { error = "avformat_seek_file() failed to seek to position " + std::to_string(position) + ": "; char av_error[AV_ERROR_MAX_STRING_SIZE] = { 0 }; if (!av_strerror(ret, av_error, AV_ERROR_MAX_STRING_SIZE)) error += av_error; else error += strerror(ret); return false; } return true; }
27.218121
123
0.613858
dubhater
d6988bac367ba60933ba1c7715d28c5e0b71c082
20,315
cc
C++
dcmtract/libsrc/trctrackset.cc
palmerc/dcmtk
716832be091d138f3e119c47a4e1e243f5b261d3
[ "Apache-2.0" ]
4
2017-03-03T13:52:51.000Z
2022-01-04T12:10:15.000Z
dcmtract/libsrc/trctrackset.cc
palmerc/dcmtk
716832be091d138f3e119c47a4e1e243f5b261d3
[ "Apache-2.0" ]
null
null
null
dcmtract/libsrc/trctrackset.cc
palmerc/dcmtk
716832be091d138f3e119c47a4e1e243f5b261d3
[ "Apache-2.0" ]
5
2017-03-06T01:32:13.000Z
2020-05-12T23:53:29.000Z
/* * * Copyright (C) 2016, Open Connections GmbH * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation are maintained by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmtract * * Author: Michael Onken * * Purpose: Class representing a Track Set from a Tractography Results IOD * */ #include "dcmtk/config/osconfig.h" #include "dcmtk/ofstd/ofutil.h" #include "dcmtk/dcmdata/dcuid.h" #include "dcmtk/dcmiod/iodutil.h" #include "dcmtk/dcmtract/trctrackset.h" #include "dcmtk/dcmtract/trctrack.h" #include "dcmtk/dcmtract/trcmeasurement.h" #include "dcmtk/dcmtract/trcstatistic.h" #include "dcmtk/dcmtract/trctypes.h" // default constructor (protected, instance creation via create() function) TrcTrackSet::TrcTrackSet() : IODComponent(), m_Tracks(), m_Anatomy("3", "1"), m_Measurements(), m_TrackStatistics(), m_TrackSetStatistics(), m_DiffusionAcquisitionCode(), m_DiffusionModelCode(), m_TrackingAlgorithmIdentification() { TrcTrackSet::resetRules(); } void TrcTrackSet::resetRules() { // Set rules for the attributes within this component getRules()->addRule(new IODRule(DCM_TrackSetNumber, "1","1", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); getRules()->addRule(new IODRule(DCM_TrackSetLabel, "1","1", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); getRules()->addRule(new IODRule(DCM_TrackSetDescription, "1","3", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); getRules()->addRule(new IODRule(DCM_TrackSetAnatomicalTypeCodeSequence, "1","1", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); getRules()->addRule(new IODRule(DCM_TrackSequence, "1-n","1", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); getRules()->addRule(new IODRule(DCM_RecommendedDisplayCIELabValue, "3","1C", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); getRules()->addRule(new IODRule(DCM_RecommendedLineThickness, "1","3", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); getRules()->addRule(new IODRule(DCM_MeasurementsSequence, "1-n","3", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); getRules()->addRule(new IODRule(DCM_TrackStatisticsSequence, "1-n","3", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); getRules()->addRule(new IODRule(DCM_TrackSetStatisticsSequence, "1-n","3", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); getRules()->addRule(new IODRule(DCM_DiffusionAcquisitionCodeSequence, "1","3", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); getRules()->addRule(new IODRule(DCM_DiffusionModelCodeSequence, "1","1", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); getRules()->addRule(new IODRule(DCM_TrackingAlgorithmIdentificationSequence, "1-n","1", getName(), DcmIODTypes::IE_INSTANCE), OFTrue); } OFCondition TrcTrackSet::create(const OFString& trackSetLabel, const OFString& trackSetDescription, const CodeWithModifiers& trackSetAnatomy, const CodeSequenceMacro& trackSetDiffusionModelCode, const CodeSequenceMacro& trackSetAlgorithmIdentification, TrcTrackSet*& trackSet) { // Track Set Number is set within TrcTractographyResults::addTrackSet() trackSet = new TrcTrackSet(); if (!trackSet) return EC_MemoryExhausted; OFCondition result = trackSet->setTrackSetLabel(trackSetLabel); if (result.good()) result = trackSet->setTrackSetDescription(trackSetDescription); if (result.good()) { result = OFconst_cast(CodeWithModifiers*, &trackSetAnatomy)->check(); if (result.good()) { trackSet->m_Anatomy = trackSetAnatomy; } } if (result.good()) { result = OFconst_cast(CodeSequenceMacro*, &trackSetDiffusionModelCode)->check(); if (result.good()) { trackSet->m_DiffusionModelCode = trackSetDiffusionModelCode; } } if (result.good()) { result = OFconst_cast(CodeSequenceMacro*, &trackSetAlgorithmIdentification)->check(); if (result.good()) { // add deep copy (via IODComponent) of input param trackSet->m_TrackingAlgorithmIdentification.push_back(new CodeSequenceMacro(trackSetAlgorithmIdentification)); } } return result; } OFCondition TrcTrackSet::read(DcmItem& source, const OFBool clearOldData) { if (clearOldData) this->clearData(); // Read as much as possible. In order to return success at minimum the tracks // must be readable. IODComponent::read(source, OFFalse /* we cleared data before */); DcmIODUtil::readSingleItem(source, DCM_TrackSetAnatomicalTypeCodeSequence, m_Anatomy, getRules()->getByTag(DCM_TrackSetAnatomicalTypeCodeSequence)); DcmIODUtil::readSingleItem(source, DCM_DiffusionAcquisitionCodeSequence, m_DiffusionAcquisitionCode, getRules()->getByTag(DCM_DiffusionAcquisitionCodeSequence)); DcmIODUtil::readSingleItem(source, DCM_DiffusionModelCodeSequence, m_DiffusionModelCode, getRules()->getByTag(DCM_DiffusionModelCodeSequence)); DcmIODUtil::readSubSequence(source, DCM_TrackingAlgorithmIdentificationSequence, m_TrackingAlgorithmIdentification, getRules()->getByTag(DCM_TrackingAlgorithmIdentificationSequence)); readTrackStatistics(source); readTrackSetStatistics(source); OFCondition result = readTracks(source); DCMTRACT_DEBUG("Found " << m_Tracks.size() << " Tracks in Track Set"); if (result.good()) { readMeasurements(source); } else { DCMTRACT_ERROR("Could not read tracks from Track Set"); } return result; } OFCondition TrcTrackSet::write(DcmItem& destination) { OFCondition result; DcmIODUtil::writeSingleItem(result, DCM_TrackSetAnatomicalTypeCodeSequence, m_Anatomy, getData(), getRules()->getByTag(DCM_TrackSetAnatomicalTypeCodeSequence)); DcmIODUtil::writeSingleItem(result, DCM_DiffusionAcquisitionCodeSequence, m_DiffusionAcquisitionCode, getData(), getRules()->getByTag(DCM_DiffusionAcquisitionCodeSequence)); DcmIODUtil::writeSingleItem(result, DCM_DiffusionModelCodeSequence, m_DiffusionModelCode, getData(), getRules()->getByTag(DCM_DiffusionModelCodeSequence)); DcmIODUtil::writeSubSequence(result, DCM_TrackingAlgorithmIdentificationSequence, m_TrackingAlgorithmIdentification, getData(), getRules()->getByTag(DCM_TrackingAlgorithmIdentificationSequence)); writeTrackStatistics(result, getData()); writeTrackSetStatistics(result, getData()); writeMeasurements(result, getData()); writeTracks(result, getData()); if (result.good()) result = IODComponent::write(destination); return result; } const OFVector<TrcTrack *>& TrcTrackSet::getTracks() { return m_Tracks; } void TrcTrackSet::clearData() { m_Anatomy.clearData(); DcmIODUtil::freeContainer(m_Tracks); DcmIODUtil::freeContainer(m_Measurements); DcmIODUtil::freeContainer(m_TrackStatistics); DcmIODUtil::freeContainer(m_TrackSetStatistics); DcmIODUtil::freeContainer(m_TrackingAlgorithmIdentification); m_DiffusionAcquisitionCode.clearData(); m_DiffusionModelCode.clearData(); IODComponent::clearData(); } TrcTrackSet::~TrcTrackSet() { clearData(); } OFString TrcTrackSet::getName() const { return "TrackSetSequenceItem"; } void TrcTrackSet::inventMissing() { IODComponent::inventMissing(); // Note: We could also add code to automatic default coloring } OFCondition TrcTrackSet::getTrackSetNumber(Uint16& value, const unsigned long pos) const { return m_Item->findAndGetUint16(DCM_TrackSetNumber, value, pos); } OFCondition TrcTrackSet::getTrackSetLabel(OFString& value, const long signed int pos) const { return DcmIODUtil::getStringValueFromItem(DCM_TrackSetLabel, *m_Item, value, pos); } OFCondition TrcTrackSet::getTrackSetDescription(OFString& value, const long signed int pos) const { return DcmIODUtil::getStringValueFromItem(DCM_TrackSetDescription, *m_Item, value, pos); } OFCondition TrcTrackSet::getRecommendedDisplayCIELabValue(Uint16& L, Uint16& a, Uint16& b) { Uint16 myL, mya, myb; myL = mya = myb = 0; DcmElement *elem = NULL; if (m_Item->findAndGetElement(DCM_RecommendedDisplayCIELabValue, elem).good() ) { if (elem->getUint16(myL, 0).good()) { L = myL; if (elem->getUint16(mya, 1).good()) { a = mya; if (elem->getUint16(myb, 2).good()) { b = myb; return EC_Normal; } } } } return IOD_EC_InvalidElementValue; } OFCondition TrcTrackSet::getRecommendedLineThickness(Float32& value, const long unsigned int pos) { return m_Item->findAndGetFloat32(DCM_RecommendedLineThickness, value, pos); } OFCondition TrcTrackSet::getLaterality(TrcTypes::E_TrackSetLaterality& laterality) { OFCondition result; OFString value, designator; CodeSequenceMacro* mod = m_Anatomy.getModifier(0); if (mod) { mod->getCodingSchemeDesignator(designator); mod->getCodingSchemeDesignator(value); if (value.empty() && designator.empty()) { laterality = TrcTypes::LAT_UNKNOWN; } else if (designator == "SRT") // all laterality codes are from SNOMED { if (value == "G-A100") { laterality = TrcTypes::LAT_RIGHT; } else if (value == "G-A101") { laterality = TrcTypes::LAT_LEFT; } else if (value == "G-A102") { laterality = TrcTypes::LAT_RIGHT_AND_LEFT; } else if (value == "G-A103") { laterality = TrcTypes::LAT_UNILATERAL; } else { laterality = TrcTypes::LAT_ERROR; result = IOD_EC_InvalidLaterality; } } else { laterality = TrcTypes::LAT_ERROR; result = IOD_EC_InvalidLaterality; } } else { laterality = TrcTypes::LAT_UNKNOWN; } return result; } CodeSequenceMacro& TrcTrackSet::getDiffusionAcquisitionCode() { return m_DiffusionAcquisitionCode; } CodeSequenceMacro& TrcTrackSet::getDiffusionModelCode() { return m_DiffusionModelCode; } OFVector<CodeSequenceMacro*>& TrcTrackSet::getTrackingAlgorithmIdentification() { return m_TrackingAlgorithmIdentification; } CodeWithModifiers& TrcTrackSet::getTrackSetAnatomy() { return m_Anatomy; } const OFVector< TrcTrackSetStatistic* >& TrcTrackSet::getTrackSetStatistics() { return m_TrackSetStatistics; } const OFVector< TrcTracksStatistic* >& TrcTrackSet::getTrackStatistics() { return m_TrackStatistics; } size_t TrcTrackSet::getNumberOfTracks() { return m_Tracks.size(); } size_t TrcTrackSet::getNumberOfTrackSetStatistics() { return m_TrackSetStatistics.size(); } size_t TrcTrackSet::getNumberOfTrackStatistics() { return m_TrackStatistics.size(); } size_t TrcTrackSet::getNumberOfMeasurements() { return m_Measurements.size(); } OFCondition TrcTrackSet::findMeasurementsByType(const CodeSequenceMacro& type, OFVector< size_t >& measurementNumbers) { OFVector<TrcMeasurement*>::const_iterator it = m_Measurements.begin(); for (size_t m = 0; it != m_Measurements.end(); m++) { if ( (*it)->getType().compare(type) == 0 ) { measurementNumbers.push_back(m); } it++; } return EC_Normal; } OFCondition TrcTrackSet::getMeasurement(const size_t measurementIndex, const TrcMeasurement*& measurement) { if (measurementIndex > m_Measurements.size() - 1) { return TRC_EC_NoSuchMeasurement; } measurement = m_Measurements[measurementIndex]; return EC_Normal; } void TrcTrackSet::getMeasurementInfos(OFVector< OFPair< CodeSequenceMacro, CodeSequenceMacro > >& typesAndUnits) { OFVector<TrcMeasurement*>::const_iterator it = m_Measurements.begin(); while (it != m_Measurements.end()) { typesAndUnits.push_back( OFMake_pair( (*it)->getType(), (*it)->getUnits() ) ); it++; } } OFCondition TrcTrackSet::addTrack(const Float32* pointData, const size_t numPoints, const Uint16* recommendedCIELabColors, const size_t numColors, TrcTrack*& result) { OFCondition cond = TrcTrack::create(pointData, numPoints, recommendedCIELabColors, numColors, result); if (cond.good()) { m_Tracks.push_back(result); } return cond; } OFCondition TrcTrackSet::addMeasurement(const CodeSequenceMacro& measurementCode, const CodeSequenceMacro& measurementUnitCodes, TrcMeasurement*& measurement) { OFCondition result = TrcMeasurement::create(measurementCode, measurementUnitCodes, measurement); if (result.good()) { m_Measurements.push_back(measurement); } return result; } OFCondition TrcTrackSet::addTrackStatistics(const CodeSequenceMacro& typeCode, const CodeSequenceMacro& typeModifierCode, const CodeSequenceMacro& unitsCode, const Float32* values, const size_t numValues, TrcTracksStatistic*& statistic) { statistic = new TrcTracksStatistic(); if (!statistic) return EC_MemoryExhausted; if (numValues != m_Tracks.size()) { DCMTRACT_ERROR("There must be as many track statistic values as number of tracks (" << m_Tracks.size() << ")"); return TRC_EC_InvalidStatisticData; } OFCondition result = statistic->set(typeCode, typeModifierCode, unitsCode, values, numValues); if (result.good()) { m_TrackStatistics.push_back(statistic); } else { delete statistic; statistic = NULL; } return result; } OFCondition TrcTrackSet::addTrackSetStatistic(const CodeSequenceMacro& typeCode, const CodeSequenceMacro& typeModifierCode, const CodeSequenceMacro& unitsCode, const Float64 value, TrcTrackSetStatistic*& statistic) { statistic = new TrcTrackSetStatistic(); if (!statistic) return EC_MemoryExhausted; OFCondition result = statistic->set(typeCode, typeModifierCode, unitsCode, value); if (result.good()) { m_TrackSetStatistics.push_back(statistic); } else { delete statistic; statistic = NULL; } return result; } OFCondition TrcTrackSet::setTrackSetLabel(const OFString& value, const OFBool checkValue) { OFCondition result = (checkValue) ? DcmLongString::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = m_Item->putAndInsertOFStringArray(DCM_TrackSetLabel, value); return result; } OFCondition TrcTrackSet::setTrackSetDescription(const OFString& value, const OFBool checkValue) { OFCondition result = (checkValue) ? DcmUnlimitedText::checkStringValue(value, "1") : EC_Normal; if (result.good()) result = m_Item->putAndInsertOFStringArray(DCM_TrackSetDescription, value); return result; } OFCondition TrcTrackSet::setRecommendedDisplayCIELabValue(const Uint16 L, const Uint16 a, const Uint16 b) { DcmElement* elem = newDicomElement(DCM_RecommendedDisplayCIELabValue); if (elem) { if (elem->putUint16(L, 0).good()) { if (elem->putUint16(a, 1).good()) { if (elem->putUint16(b, 2).good()) { if (m_Item->insert(elem, OFTrue /* replace old */).good()) { return EC_Normal; } } } } } else { return EC_MemoryExhausted; } return EC_InternalError; } OFCondition TrcTrackSet::setRecommendedLineThickness(const Float32& value, const OFBool checkValue) { (void)checkValue; return m_Item->putAndInsertFloat32(DCM_RecommendedLineThickness, value, 0); } OFCondition TrcTrackSet::readTracks(DcmItem& source) { return DcmIODUtil::readSubSequence(source, DCM_TrackSequence, m_Tracks, getRules()->getByTag(DCM_TrackSequence)); } OFCondition TrcTrackSet::readMeasurements(DcmItem& source) { DcmIODUtil::readSubSequence(source, DCM_MeasurementsSequence, m_Measurements, getRules()->getByTag(DCM_MeasurementsSequence)); if (checkMeasurements().bad()) { DCMTRACT_WARN("Ignoring missing or superfluous Measurements"); } return EC_Normal; } OFCondition TrcTrackSet::setLaterality(const TrcTypes::E_TrackSetLaterality value, const OFBool checkValue) { (void)checkValue; CodeSequenceMacro anatomy; switch(value) { case TrcTypes::LAT_RIGHT: anatomy.set("G-A100", "SRT", "Right"); break; case TrcTypes::LAT_LEFT: anatomy.set("G-A101", "SRT", "Left"); break; case TrcTypes::LAT_RIGHT_AND_LEFT: anatomy.set("G-A102", "SRT", "Right and left"); break; case TrcTypes::LAT_UNILATERAL: anatomy.set("G-A103", "SRT", "Unilateral"); break; default: return IOD_EC_InvalidLaterality; } CodeSequenceMacro* mod = m_Anatomy.getModifier(0); if (!mod) { mod = new CodeSequenceMacro(); if (!mod) { return EC_MemoryExhausted; } *mod = anatomy; m_Anatomy.addModifier(*mod); } else { *mod = anatomy; } return EC_Normal;; } OFCondition TrcTrackSet::checkMeasurements() { size_t numTracks = m_Tracks.size(); for (size_t i = 0; i < m_Measurements.size(); i++) { TrcMeasurement *m = m_Measurements[i]; size_t numEntries = m->getValues().size(); if (numEntries < numTracks) { DCMTRACT_WARN("Measurement #" << i << " misses data for " << numTracks - numEntries << " tracks"); return TRC_EC_MeasurementDataMissing; } else if (numEntries > numTracks) { DCMTRACT_WARN("Measurement #" << i << " has data for " << numEntries - numTracks << " too many tracks"); return TRC_EC_MeasurementDataMissing; } } return EC_Normal; } OFCondition TrcTrackSet::readTrackSetStatistics(DcmItem& source) { (void)source; DcmIODUtil::readSubSequence(source, DCM_TrackSetStatisticsSequence, m_TrackSetStatistics, m_Rules->getByTag(DCM_TrackSetStatisticsSequence)); return EC_Normal; } OFCondition TrcTrackSet::readTrackStatistics(DcmItem& source) { (void)source; DcmIODUtil::readSubSequence(source, DCM_TrackStatisticsSequence, m_TrackStatistics, m_Rules->getByTag(DCM_TrackStatisticsSequence)); return EC_Normal; } OFCondition TrcTrackSet::writeTracks(OFCondition& result, DcmItem& destination) { if (result.good()) { DcmIODUtil::writeSubSequence(result, DCM_TrackSequence, m_Tracks, destination, getRules()->getByTag(DCM_TrackSequence)); } return result; } OFCondition TrcTrackSet::writeMeasurements(OFCondition& result, DcmItem& destination) { if (result.good()) { result = checkMeasurements(); if (result.bad()) { DCMTRACT_ERROR("Measurements have too much or to less data"); return result; } DcmIODUtil::writeSubSequence(result, DCM_MeasurementsSequence, m_Measurements, destination, getRules()->getByTag(DCM_MeasurementsSequence)); } return result; } void TrcTrackSet::writeTrackSetStatistics(OFCondition& result, DcmItem& destination) { DcmIODUtil::writeSubSequence(result, DCM_TrackSetStatisticsSequence, m_TrackSetStatistics, destination, m_Rules->getByTag(DCM_TrackSetStatisticsSequence)); } void TrcTrackSet::writeTrackStatistics(OFCondition& result, DcmItem& destination) { DcmIODUtil::writeSubSequence(result, DCM_TrackStatisticsSequence, m_TrackStatistics, destination, m_Rules->getByTag(DCM_TrackStatisticsSequence)); }
30.007386
197
0.673837
palmerc
d69bd4e87451980d1397581d4bd8a84cb9ad90ae
5,915
cpp
C++
src/bazel/bazel.cpp
cppan/cppan
b4bbdf5e56f9d237f2820301152b7024ca10907b
[ "Apache-2.0" ]
117
2016-03-14T08:26:32.000Z
2021-12-09T10:17:34.000Z
src/bazel/bazel.cpp
fuyanbin/cppan
77e0f8d6f3e372cd191e9b3af1704403f824c0de
[ "Apache-2.0" ]
55
2016-06-30T10:01:27.000Z
2019-08-10T19:18:37.000Z
src/bazel/bazel.cpp
fuyanbin/cppan
77e0f8d6f3e372cd191e9b3af1704403f824c0de
[ "Apache-2.0" ]
25
2017-04-21T06:38:17.000Z
2022-02-02T05:02:25.000Z
/* * Copyright (C) 2016-2017, Egor Pugin * * 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 "bazel.h" #include "driver.h" #include "../common/yaml.h" #include <boost/algorithm/string.hpp> #include <primitives/filesystem.h> #include <pystring.h> #include <algorithm> #include <regex> namespace { void trimQuotes(std::string &s) { if (s.empty()) return; if (s.front() == '\"') s = s.substr(1); if (s.empty()) return; if (s.back() == '\"') s = s.substr(0, s.size() - 1); //s = s.substr(s.find_first_not_of("\"")); //s = s.substr(0, s.find_last_not_of("\"") + 1); } std::string prepare_project_name(const std::string &s) { std::string t = s; std::replace(t.begin(), t.end(), '-', '_'); std::replace(t.begin(), t.end(), '+', 'p'); return t; } } namespace bazel { void Parameter::trimQuotes() { ::trimQuotes(name); Values vls; for (auto &v : values) { auto s = v; ::trimQuotes(s); vls.insert(s); } values = vls; } void Function::trimQuotes() { ::trimQuotes(name); for (auto &p : parameters) p.trimQuotes(); } void File::trimQuotes() { for (auto &f : functions) f.trimQuotes(); } Values File::getFiles(const Name &name, const std::string &bazel_target_function) { Values values; for (auto &f : functions) { if (!( pystring::endswith(f.name, "cc_library") || pystring::endswith(f.name, "cc_binary") || pystring::endswith(f.name, bazel_target_function) )) continue; auto i = std::find_if(f.parameters.begin(), f.parameters.end(), [](const auto &p) { return "name" == p.name; }); if (i == f.parameters.end() || i->values.empty() || (prepare_project_name(*i->values.begin()) != name && *i->values.begin() != name)) continue; for (auto &n : { "hdrs", "public_hdrs" }) { i = std::find_if(f.parameters.begin(), f.parameters.end(), [&n](const auto &p) { return p.name == n; }); if (i != f.parameters.end()) { // check if we has a variable for (auto &v : i->values) { auto p = parameters.find(v); if (p != parameters.end()) values.insert(p->second.values.begin(), p->second.values.end()); else values.insert(i->values.begin(), i->values.end()); } } } i = std::find_if(f.parameters.begin(), f.parameters.end(), [](const auto &p) { return "srcs" == p.name; }); if (i != f.parameters.end()) { // check if we has a variable for (auto &v : i->values) { auto p = parameters.find(v); if (p != parameters.end()) values.insert(p->second.values.begin(), p->second.values.end()); else values.insert(i->values.begin(), i->values.end()); } } } return values; } File parse(const std::string &s) { BazelParserDriver pd; pd.parse(s); pd.bazel_file.trimQuotes(); return pd.bazel_file; } } // namespace bazel void process_bazel(const path &p, const std::string &libname = "cc_library", const std::string &binname = "cc_binary") { auto prepare_dep_name = [](auto s) { //if (s.find("//") == 0) //return std::string(); prepare_project_name(s); boost::replace_all(s, ":", ""); boost::replace_all(s, "+", "p"); return s; }; auto b = read_file(p); auto file = bazel::parse(b); yaml root; auto projects = root["projects"]; for (auto &f : file.functions) { enum { unk, lib, bin, }; int type = unk; if (pystring::endswith(f.name, libname)) type = lib; else if (pystring::endswith(f.name, binname)) type = bin; else continue; auto i = std::find_if(f.parameters.begin(), f.parameters.end(), [](const auto &p) { return "name" == p.name; }); if (i == f.parameters.end() || i->values.empty()) continue; auto pname = prepare_project_name(*i->values.begin()); auto project = projects[pname]; if (type == lib) project["type"] = "lib"; project["import_from_bazel"] = true; project["bazel_target_name"] = *i->values.begin(); project["bazel_target_function"] = type == lib ? libname : binname; for (auto &n : { "deps", "external_deps" }) { i = std::find_if(f.parameters.begin(), f.parameters.end(), [&n](const auto &p) { return n == p.name; }); if (!(i == f.parameters.end() || i->values.empty())) { for (auto &d : i->values) { auto d2 = prepare_dep_name(d); if (!d2.empty()) project["dependencies"].push_back(d2); } } } } std::cout << dump_yaml_config(root); }
26.524664
118
0.503804
cppan
d6a70cf1677b668a8b9b1d6a1a8f5fe6c2711a1f
1,757
hpp
C++
Yannq/Serializers/SerializeRBM.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/Serializers/SerializeRBM.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
Yannq/Serializers/SerializeRBM.hpp
cecri/yannq
b78c1f86a255059f06b34dd5e538449e7261d0ee
[ "BSD-3-Clause" ]
null
null
null
#ifndef YANNQ_SEREALIZAERS_SERIALIZERBM_HPP #define YANNQ_SEREALIZAERS_SERIALIZERBM_HPP #include <cereal/access.hpp> #include <cereal/types/memory.hpp> #include "Machines/RBM.hpp" CEREAL_CLASS_VERSION(yannq::RBM<float>, 1); CEREAL_CLASS_VERSION(yannq::RBM<std::complex<float>>, 1); CEREAL_CLASS_VERSION(yannq::RBM<double>, 1); CEREAL_CLASS_VERSION(yannq::RBM<std::complex<double>>, 1); CEREAL_CLASS_VERSION(yannq::RBM<long double>, 1); CEREAL_CLASS_VERSION(yannq::RBM<std::complex<long double>>, 1); namespace cereal { template<class Archive, typename T> void save(Archive & ar, const yannq::RBM<T>& m, uint32_t const /*version*/) { bool useBias = m.useBias(); ar(useBias); ar(m.getN(),m.getM()); ar(m.getW()); if(!useBias) return ; ar(m.getA(),m.getB()); } template<class Archive, typename T> void load(Archive & ar, yannq::RBM<T>& m, uint32_t const /*version*/) { bool useBias; ar(useBias); m.setUseBias(useBias); int N, M; ar(N, M); m.resize(N, M); typename yannq::RBM<T>::Matrix W; ar(W); m.setW(W); if(!useBias) return ; typename yannq::RBM<T>::Vector A, B; ar(A, B); m.setA(A); m.setB(B); } template <typename T> struct LoadAndConstruct<yannq::RBM<T> > { template<class Archive> static void load_and_construct(Archive& ar, cereal::construct<yannq::RBM<T> >& construct, uint32_t const /*version*/) { bool useBias; ar(useBias); int n,m; ar(n, m); construct(n, m, useBias); Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> W; ar(W); construct->setW(W); if(!useBias) return ; Eigen::Matrix<T, Eigen::Dynamic, 1> A; Eigen::Matrix<T, Eigen::Dynamic, 1> B; ar(A, B); construct->setA(A); construct->setB(B); } }; }//namespace cereal #endif//YANNQ_SEREALIZAERS_SERIALIZERBM_HPP
20.430233
119
0.684121
cecri
d6ab23a4c48bc2f8cadc95a726f4aff1166dfa3d
2,164
hpp
C++
libs/python/include/python/math/py_tensor.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
3
2019-07-11T08:49:27.000Z
2021-09-07T16:49:15.000Z
libs/python/include/python/math/py_tensor.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
null
null
null
libs/python/include/python/math/py_tensor.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
2
2019-07-13T12:45:22.000Z
2021-03-12T08:48:57.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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/tensor.hpp" #include "python/fetch_pybind.hpp" namespace py = pybind11; namespace fetch { namespace math { template <typename T> void BuildTensor(std::string const &custom_name, pybind11::module &module) { using ArrayType = typename fetch::math::Tensor<T>; py::class_<ArrayType, std::shared_ptr<ArrayType>>(module, custom_name.c_str()) .def(py::init<std::vector<SizeType> const &>()) .def("ToString", &ArrayType::ToString) .def("Size", &ArrayType::size) .def("Fill", [](ArrayType &a, T val) { return a.Fill(val); }) .def("Slice", [](ArrayType &a, SizeType i) { return a.Slice(i); }) .def("Slice", [](ArrayType const &a, SizeType i) { return a.Slice(i); }) .def("At", [](ArrayType &a, SizeType i) { return a.At(i); }) // TODO (private 877) .def("Set", (void (ArrayType::*)(SizeType const &, T)) & ArrayType::Set) .def("Set", (void (ArrayType::*)(SizeType const &, SizeType const &, T)) & ArrayType::Set) .def("Set", (void (ArrayType::*)(SizeType const &, SizeType const &, SizeType const &, T)) & ArrayType::Set) .def("Set", (void (ArrayType::*)(SizeType const &, SizeType const &, SizeType const &, SizeType const &, T)) & ArrayType::Set); } } // namespace math } // namespace fetch
40.830189
98
0.581793
devjsc
d6ad493472925a996ded91157d873f53c5300317
4,335
cpp
C++
Coconuts/src/editor/standalone/panels/SceneOverview.cpp
filhoDaMain/Coconuts
007cfdea11e2bc7bbb8ffa38747629b111b4e196
[ "Apache-2.0" ]
3
2020-05-02T15:18:19.000Z
2022-01-26T06:18:18.000Z
Coconuts/src/editor/standalone/panels/SceneOverview.cpp
filhoDaMain/Coconuts
007cfdea11e2bc7bbb8ffa38747629b111b4e196
[ "Apache-2.0" ]
4
2021-07-19T21:55:59.000Z
2021-10-04T20:19:17.000Z
Coconuts/src/editor/standalone/panels/SceneOverview.cpp
filhoDaMain/Coconuts
007cfdea11e2bc7bbb8ffa38747629b111b4e196
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 Andre Temprilho * * 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 "SceneOverview.h" #include <coconuts/editor.h> #include <string> #include <coconuts/Logger.h> // ECS Components #include <coconuts/ecs/components/TagComponent.h> #include <coconuts/ecs/components/OrthoCameraComponent.h> #include <coconuts/ecs/components/TransformComponent.h> #include <coconuts/ecs/components/SpriteComponent.h> #include <coconuts/ecs/components/BehaviorComponent.h> namespace Coconuts { namespace Panels { bool SceneOverview::Init(GameLayer*& gameLayer, ComponentInspector* componentInspector) { m_GameLayerPtr = gameLayer; m_ComponentInspectorPtr = componentInspector; m_CurrentSelectedEntityPtr = new Coconuts::Entity(); return true; } void SceneOverview::Draw() { if ( m_GameLayerPtr->IsActiveSceneUpdated() ) { GetLastSceneUpdate(); } ImGui::Begin("Scene Overview"); for (Entity thisEntity : sceneEntities) { /* Draw all entities */ if (DrawNode(thisEntity)) { /** * thisEntity is currently selected. * Update Component Inspector panel context to draw its * components. */ /* Avoid spawn of unnecessary context-changes */ if (m_CurrentSelectedEntityPtr->GetId() != thisEntity.GetId()) { *m_CurrentSelectedEntityPtr = thisEntity; m_ComponentInspectorPtr->ChangeContext(m_CurrentSelectedEntityPtr); } } ImGui::Spacing(); } ImGui::End(); } void SceneOverview::GetLastSceneUpdate() { /* Get tmp vector from Game Layer with al entities */ std::vector<Entity> last = m_GameLayerPtr->GetActiveSceneEntities(); /* Free heap vector and re-allocate */ sceneEntities = std::vector<Entity>(); sceneEntities.resize(last.size()); /* Copy */ sceneEntities = last; } bool SceneOverview::DrawNode(Entity& entity) { std::string tag = entity.GetComponent<TagComponent>().tag; static uint64_t context_id = 0; ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_OpenOnArrow; flags |= context_id == entity.GetId() ? ImGuiTreeNodeFlags_Selected : 0; bool open = ImGui::TreeNodeEx(tag.c_str() , flags); if (ImGui::IsItemClicked()) { context_id = entity.GetId(); } /* Draw simple components */ if (open) { ImGui::TextDisabled("ID: %llu", entity.GetId()); /* Camera */ if (entity.HasComponent<OrthoCameraComponent>()) { ImGui::Text("Camera"); } /* Transform */ if (entity.HasComponent<TransformComponent>()) { ImGui::Text("Transform"); } /* Sprite */ if (entity.HasComponent<SpriteComponent>()) { ImGui::Text("Sprite"); } /* Behavior */ if (entity.HasComponent<BehaviorComponent>()) { ImGui::Text("Behavior"); } ImGui::TreePop(); } /** * This entity is currently selected. */ if (flags & ImGuiTreeNodeFlags_Selected) { return true; } return false; } } }
29.691781
102
0.551788
filhoDaMain
d6b08477bf23e331ade748dcf013b997dff9fe83
1,751
cpp
C++
Source/ToolExampleEditor/CustomDataType/ReimportExampleDataFactory.cpp
ScottKirvan/ToolExample
71f90211b70bdebbf7e171f127b9b6d103735889
[ "MIT" ]
3
2021-03-10T21:00:13.000Z
2021-12-11T12:33:17.000Z
Source/ToolExampleEditor/CustomDataType/ReimportExampleDataFactory.cpp
ScottKirvan/ToolExample
71f90211b70bdebbf7e171f127b9b6d103735889
[ "MIT" ]
1
2021-02-08T02:34:07.000Z
2021-02-08T02:44:58.000Z
Source/ToolExampleEditor/CustomDataType/ReimportExampleDataFactory.cpp
ScottKirvan/ToolExample
71f90211b70bdebbf7e171f127b9b6d103735889
[ "MIT" ]
3
2021-03-11T10:13:30.000Z
2021-08-18T13:30:57.000Z
#include "ReimportExampleDataFactory.h" #include "ToolExampleEditor/ToolExampleEditor.h" #include "ExampleDataFactory.h" #include "ToolExample/CustomDataType/ExampleData.h" bool UReimportExampleDataFactory::CanReimport(UObject* Obj, TArray<FString>& OutFilenames) { UExampleData* ExampleData = Cast<UExampleData>(Obj); if (ExampleData) { OutFilenames.Add(UAssetImportData::ResolveImportFilename(ExampleData->SourceFilePath, ExampleData->GetOutermost())); return true; } return false; } void UReimportExampleDataFactory::SetReimportPaths(UObject* Obj, const TArray<FString>& NewReimportPaths) { UExampleData* ExampleData = Cast<UExampleData>(Obj); if (ExampleData && ensure(NewReimportPaths.Num() == 1)) { ExampleData->SourceFilePath = UAssetImportData::SanitizeImportFilename(NewReimportPaths[0], ExampleData->GetOutermost()); } } EReimportResult::Type UReimportExampleDataFactory::Reimport(UObject* Obj) { UExampleData* ExampleData = Cast<UExampleData>(Obj); if (!ExampleData) { return EReimportResult::Failed; } const FString Filename = UAssetImportData::ResolveImportFilename(ExampleData->SourceFilePath, ExampleData->GetOutermost()); if (!FPaths::GetExtension(Filename).Equals(TEXT("xmp"))) { return EReimportResult::Failed; } CurrentFilename = Filename; FString Data; if (FFileHelper::LoadFileToString(Data, *CurrentFilename)) { const TCHAR* Ptr = *Data; ExampleData->Modify(); ExampleData->MarkPackageDirty(); UExampleDataFactory::MakeExampleDataFromText(ExampleData, Ptr, Ptr + Data.Len()); // save the source file path and timestamp ExampleData->SourceFilePath = UAssetImportData::SanitizeImportFilename(CurrentFilename, ExampleData->GetOutermost()); } return EReimportResult::Succeeded; }
31.267857
124
0.780126
ScottKirvan
d6b8056d8c7995f7ae69b3cd1d986d6217a82df1
2,711
hpp
C++
modules/filter/include/filter/parallel.hpp
aversiveplusplus/aversiveplusplus
5f5fe9faca50197fd6207e2c816efa7e9af6c804
[ "BSD-3-Clause" ]
29
2016-01-27T09:43:44.000Z
2020-03-12T04:16:02.000Z
modules/filter/include/filter/parallel.hpp
aversiveplusplus/aversiveplusplus
5f5fe9faca50197fd6207e2c816efa7e9af6c804
[ "BSD-3-Clause" ]
20
2016-01-22T15:59:33.000Z
2016-10-28T10:22:45.000Z
modules/filter/include/filter/parallel.hpp
aversiveplusplus/aversiveplusplus
5f5fe9faca50197fd6207e2c816efa7e9af6c804
[ "BSD-3-Clause" ]
6
2016-02-11T14:09:04.000Z
2018-03-17T00:18:35.000Z
/* Copyright (c) 2015, Xenomorphales All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Aversive++ 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 HOLDER 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. */ #ifndef FILTER_PARALLEL_HPP #define FILTER_PARALLEL_HPP #include <base/type_traits.hpp> #include <filter/filter.hpp> namespace Aversive { namespace Filter { template <class First, class Second> class Parallel : public AdaptableFilter<typename First::InputType, typename First::OutputType, Parallel<First, Second>> { public: using InputType = typename First::InputType; using OutputType = typename First::OutputType; static_assert( TypeEqual<typename First::InputType, typename Second::InputType>::VALUE && TypeEqual<typename First::OutputType, typename Second::OutputType>::VALUE, "ERROR : incompatibles filters in parallel" ); private: using FirstFilter = AdaptableFilter<typename First::InputType, typename First::OutputType, First>; using SecondFilter = AdaptableFilter<typename Second::InputType, typename Second::OutputType, Second>; FirstFilter& first; SecondFilter& second; public: inline Parallel(FirstFilter& first, SecondFilter& second) : first(first), second(second) { } inline OutputType operator()(InputType value) { return second(value) + first(value); } }; } } #endif//FILTER_PARALLEL_HPP
35.671053
110
0.766138
aversiveplusplus
d6b86363a81241a571f4c5376de9bf63ad60c01b
3,893
cpp
C++
src/Graphics/Window.cpp
jkbz64/Zadymka
16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7
[ "MIT" ]
2
2020-03-18T16:13:04.000Z
2021-07-30T12:18:52.000Z
src/Graphics/Window.cpp
jkbz64/Zadymka
16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7
[ "MIT" ]
null
null
null
src/Graphics/Window.cpp
jkbz64/Zadymka
16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7
[ "MIT" ]
null
null
null
#include <Graphics/Window.hpp> #include <Graphics/Shader.hpp> #include <Graphics/Drawable.hpp> #include <Input.hpp> #include <glad/glad.h> #include <GLFW/glfw3.h> #include <Graphics/DefaultRenderer.hpp> #include <ImGui.hpp> namespace { template <typename T> constexpr float normalize(T value) { return value < 0 ? 0 : static_cast<float>(value) / 255.f; } } Window::Window() : RenderTarget(new DefaultRenderer(m_camera)), m_window(nullptr), m_isOpen(false), m_style(Window::Style::Windowed) { } Window::~Window() { Input::setWindow(nullptr); ImGUI::setWindow(nullptr); if(m_window) glfwDestroyWindow(getNativeWindow()); } GLFWwindow* Window::getNativeWindow() { return m_window; } void Window::create(const glm::uvec2& size, const std::string& title, const Style& style) { if(size.x == 0 || size.y == 0) { m_isOpen = false; throw std::runtime_error("Window size must be > 0"); } m_size = size; m_title = title; m_style = style; if(m_window) glfwDestroyWindow(getNativeWindow()); switch(m_style) { case Style::Windowed: m_window = glfwCreateWindow(m_size.x, m_size.y, title.c_str(), NULL, NULL); break; case Style::Fullscreen: m_window = glfwCreateWindow(m_size.x, m_size.y, title.c_str(), glfwGetPrimaryMonitor(), NULL); break; case Style::FullscreenWindowed: auto monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(monitor); glfwWindowHint(GLFW_RED_BITS, mode->redBits); glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); m_window = glfwCreateWindow(mode->width, mode->height, title.c_str(), monitor, NULL); break; } m_isOpen = true; glfwMakeContextCurrent(getNativeWindow()); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSetWindowUserPointer(getNativeWindow(), this); glfwSetFramebufferSizeCallback(getNativeWindow(), [](GLFWwindow* window, int width, int height) { auto w = static_cast<Window*>(glfwGetWindowUserPointer(window)); w->m_size.x = width; w->m_size.y = height; glViewport(0, 0, width, height); }); Input::setWindow(getNativeWindow()); ImGUI::setWindow(getNativeWindow()); } bool Window::isOpen() { if(m_window) return !glfwWindowShouldClose(getNativeWindow()) && m_isOpen; return false; } void Window::clear(unsigned int r, unsigned int g, unsigned int b, unsigned int a) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(normalize(r), normalize(g), normalize(b), normalize(a)); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Window::display() { glfwSwapBuffers(getNativeWindow()); glfwPollEvents(); } void Window::close() { if(m_isOpen) m_isOpen = false; } const std::string& Window::title() const { return m_title; } void Window::setTitle(const std::string& title) { m_title = title; if(m_isOpen) glfwSetWindowTitle(getNativeWindow(), m_title.c_str()); } void Window::resize(const glm::uvec2& size) { if(size.x == 0 || size.y == 0) return; m_size = size; if(m_isOpen) glfwSetWindowSize(getNativeWindow(), m_size.x, m_size.y); } const glm::uvec2& Window::size() { return m_size; } glm::vec2 Window::mapToWorld(const glm::vec2 &pos) { auto& camera = m_camera; const auto cameraSize = glm::vec2(camera.size()); auto halfSize = cameraSize; halfSize /= 2.f; const auto& cameraCenter = camera.center(); const glm::vec2 factor = glm::vec2(pos.x / m_size.x, pos.y / m_size.y); return (cameraCenter - halfSize) + cameraSize * factor; }
25.279221
102
0.660416
jkbz64
d6bbe5228a57754b9883e9a03e40c79b7ab2b10e
3,640
cpp
C++
_Deprecated/Db_2021/EntryPoint/EntryPoint.cpp
DexterDreeeam/DxtSdk2021
2dd8807b4ebe1d65221095191eaa7938bc5e9e78
[ "MIT" ]
1
2021-11-18T03:57:54.000Z
2021-11-18T03:57:54.000Z
_Deprecated/Db_2021/EntryPoint/EntryPoint.cpp
DexterDreeeam/P9
2dd8807b4ebe1d65221095191eaa7938bc5e9e78
[ "MIT" ]
null
null
null
_Deprecated/Db_2021/EntryPoint/EntryPoint.cpp
DexterDreeeam/P9
2dd8807b4ebe1d65221095191eaa7938bc5e9e78
[ "MIT" ]
null
null
null
#include "../DbCore/Interface.hpp" const s64 port = 39901; const char* ip; struct client_context { network_connect connect; ref<P9::Platform::platform> platform; }; static void client_handler(void* p) { client_context* p_context = (client_context*)p; network_connect connect = p_context->connect; auto r_platform = p_context->platform; char* buf = new char[2048]; escape_function ef = [=]() mutable { delete[] buf; delete p_context; connect.destroy(); print("Client disconnect to server.\n"); }; while (1) { print("Waiting client query....\n"); s64 msg_len; boole checker; checker = connect.receive(buf, msg_len); if (!checker || msg_len <= 0) { break; } string query = buf; string rst; boole is_error_happens = boole::False; print("Received client query, start process...\n"); try { auto op1 = r_platform->parse_operation_message(query); rst = r_platform->handle_operation(op1); } catch (P9_assert_exception ex) { is_error_happens = boole::True; rst = "Assert error happens when process query."; err(rst.data()); err("error_code: %ll, expected_condition: %s, information: %s, file: %s, line: ll.", ex.error_code, ex.expect_condition, ex.information, ex.file, ex.line); print("%s\n", rst.data()); } catch (...) { is_error_happens = boole::True; rst = "Unknown error happens when process query."; log(rst.data()); print("%s\n", rst.data()); } print("Finish client query, send result back to client...\n"); if (rst.size() == 0 || !connect.send(rst.data(), rst.size() + 1)) { is_error_happens = boole::True; log("Error happens when send result back."); print("Error happens when send result back.\n"); } print("Complete query.\n"); } } void server_entry_point() { print("Init DB server...\n"); auto r_platfrom = ref<P9::Platform::platform>::new_instance(); r_platfrom->load(P9_FOLDER "p1/"); network_server ns; ns.init(port); print("Complete DB init...\n"); print("Waiting Client connect...\n"); while (!am_i_terminated()) { client_context* p_context = new client_context(); ns.new_connect(p_context->connect); print("Client connected to server.\n"); p_context->platform = r_platfrom; thread t; t.init(client_handler); t.start(p_context); t.uninit(); object::report(); } ns.uninit(); } void read_file_send_query(const char* path) { char buf[8000]; file f; f.init_input(path); s64 len; f.input(buf, 8000, len); buf[len] = 0; f.uninit(); string query(buf); network_client nc; nc.init(ip, port); nc.send(query.data(), query.size() + 1); nc.receive(buf, len); print("Result: %s.\n", buf); nc.uninit(); } void client_entry_point(const char* json_file_path) { read_file_send_query(json_file_path); } int main(int argc, char* argv[]) { if (argc == 2 && str_equal_case_insensitive(argv[1], "host")) { server_entry_point(); return 0; } else if (argc == 3) { ip = argv[1]; client_entry_point(argv[2]); return 0; } print("input parameters: \n \"Host\" or \"20.40.99.127 ./json_query_file.json\"\n"); return -1; }
25.277778
96
0.560989
DexterDreeeam
d6bda410f7f9f02b5a01512c65e6da0b164d22a5
968
cpp
C++
Tutorial2/12.Menghitung_Kalimat.cpp
azminawwar/tutorial_cpp
0ec79e9c7f5f77bab38bc23dfc9e81a70897faa8
[ "MIT" ]
12
2020-03-06T04:18:13.000Z
2021-11-02T01:28:21.000Z
Tutorial2/12.Menghitung_Kalimat.cpp
azminawwar/tutorial_cpp
0ec79e9c7f5f77bab38bc23dfc9e81a70897faa8
[ "MIT" ]
1
2020-10-02T10:02:37.000Z
2020-10-02T10:02:37.000Z
Tutorial2/12.Menghitung_Kalimat.cpp
azminawwar/tutorial_cpp
0ec79e9c7f5f77bab38bc23dfc9e81a70897faa8
[ "MIT" ]
9
2019-11-02T09:33:47.000Z
2021-12-16T14:24:49.000Z
#include <iostream> using namespace std; //deklarasi fungsi int itungKalimat(string x); int itungKata(string x); int main() { //membuat variabel dan pointernya string kalimat; string *pointer_kalimat = &kalimat; cout<<"Masukkan Kalimat Anda = "; //input beserta spasi getline(cin,kalimat); //pemanggilan fungsi cout<<"Jumlah Kalimat Anda Adalah = "<<itungKalimat(*pointer_kalimat)<<endl; cout<<"Jumlah Karakter Anda Adalah = "<<itungKata(*pointer_kalimat)<<endl; } int itungKalimat(string x){ //inisialisator spasi sebagai 1 kalimat int spasi = 1; //foreach kata menjadi char array for (char cacah : x){ //hitung spasi if (isspace(cacah,cin.getloc())){ ++spasi; } } return spasi; } int itungKata(string x){ int karakter = 0; //foreach kata menjadi array for (char cacah : x){ //dihitung berapa kali loop karakter++; } return karakter; }
26.162162
80
0.637397
azminawwar
d6c0283daa7ab3e68424f8c9ecd3e391294f8f2d
1,562
hpp
C++
include/RED4ext/Types/generated/game/ui/SideScrollerMiniGameLogicControllerAdvanced.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/game/ui/SideScrollerMiniGameLogicControllerAdvanced.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/game/ui/SideScrollerMiniGameLogicControllerAdvanced.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/CName.hpp> #include <RED4ext/DynArray.hpp> #include <RED4ext/Types/generated/Vector2.hpp> #include <RED4ext/Types/generated/game/ui/SideScrollerCheatCode.hpp> #include <RED4ext/Types/generated/ink/CompoundWidgetReference.hpp> #include <RED4ext/Types/generated/ink/WidgetLogicController.hpp> #include <RED4ext/Types/generated/ink/WidgetReference.hpp> namespace RED4ext { namespace game::ui { struct SideScrollerMiniGameLogicControllerAdvanced : ink::WidgetLogicController { static constexpr const char* NAME = "gameuiSideScrollerMiniGameLogicControllerAdvanced"; static constexpr const char* ALIAS = "MinigameLogicControllerAdvanced"; uint8_t unk68[0xB0 - 0x68]; // 68 float baseSpeed; // B0 Vector2 playerColliderPositionOffset; // B4 Vector2 playerColliderSizeOffset; // BC uint8_t unkC4[0xC8 - 0xC4]; // C4 ink::CompoundWidgetReference gameplayRoot; // C8 CName playerLibraryName; // E0 DynArray<ink::WidgetReference> layers; // E8 DynArray<game::ui::SideScrollerCheatCode> cheatCodes; // F8 uint8_t unk108[0x120 - 0x108]; // 108 DynArray<CName> acceptableCheatKeys; // 120 uint8_t unk130[0x138 - 0x130]; // 130 }; RED4EXT_ASSERT_SIZE(SideScrollerMiniGameLogicControllerAdvanced, 0x138); } // namespace game::ui using MinigameLogicControllerAdvanced = game::ui::SideScrollerMiniGameLogicControllerAdvanced; } // namespace RED4ext
38.097561
94
0.772087
Cyberpunk-Extended-Development-Team
d6c066061dc148d9477d273b723084296c5ca0a9
3,135
cxx
C++
Victre/generation/createDuct.cxx
DIDSR/VICTRE_PIPELINE
e4108430705ad0e4c8d51fe360f999929dcc9a92
[ "CC0-1.0" ]
4
2021-06-24T23:57:56.000Z
2022-03-17T01:23:04.000Z
Victre/generation/createDuct.cxx
DIDSR/VICTRE_PIPELINE
e4108430705ad0e4c8d51fe360f999929dcc9a92
[ "CC0-1.0" ]
null
null
null
Victre/generation/createDuct.cxx
DIDSR/VICTRE_PIPELINE
e4108430705ad0e4c8d51fe360f999929dcc9a92
[ "CC0-1.0" ]
5
2021-05-22T18:53:12.000Z
2022-03-27T20:34:15.000Z
/* * create_duct.cxx * * Created on: Dec 22, 2014 * Author: cgg */ #include "createDuct.hxx" using namespace std; namespace po = boost::program_options; /* This function creates a duct tree within a given compartment, inserts it into the segmented * breast and saves the tree */ void generate_duct(vtkImageData* breast, po::variables_map vm, vtkPoints* TDLUloc, vtkDoubleArray* TDLUattr, unsigned char compartmentId, int* boundBox, tissueStruct* tissue, double* sposPtr, double* sdirPtr, int seed){ double spos[3]; double sdir[3]; for(int i=0; i<3; i++){ spos[i] = sposPtr[i]; sdir[i] = sdirPtr[i]; } // declare ductTreeInit struct and fill information ductTreeInit treeInit; treeInit.seed = seed; // bounds of duct simulation derived from breast structure int startInd[3] = {boundBox[0], boundBox[2], boundBox[4]}; int endInd[3] = {boundBox[1], boundBox[3], boundBox[5]}; //startPos breast->GetPoint(breast->ComputePointId(startInd), treeInit.startPos); //endPos breast->GetPoint(breast->ComputePointId(endInd), treeInit.endPos); // size of voxels treeInit.nVox[0] = boundBox[1]-boundBox[0]; treeInit.nVox[1] = boundBox[3]-boundBox[2]; treeInit.nVox[2] = boundBox[5]-boundBox[4]; treeInit.nFill[0] = vm["ductTree.nFillX"].as<uint>(); treeInit.nFill[1] = vm["ductTree.nFillY"].as<uint>(); treeInit.nFill[2] = vm["ductTree.nFillZ"].as<uint>(); for(int i=0; i<3; i++){ treeInit.prefDir[i] = sdir[i]; } treeInit.boundBox = boundBox; treeInit.compartmentId = compartmentId; treeInit.tissue = tissue; treeInit.breast = breast; treeInit.TDLUloc = TDLUloc; treeInit.TDLUattr = TDLUattr; ductTree myTree(vm, &treeInit); // root of tree double srad = vm["ductTree.initRad"].as<double>(); // initialize fill map based on distance to start position int fillExtent[6]; myTree.fill->GetExtent(fillExtent); #pragma omp parallel for for(int a=fillExtent[0]; a<=fillExtent[1]; a++){ for(int b=fillExtent[2]; b<=fillExtent[3]; b++){ for(int c=fillExtent[4]; c<=fillExtent[5]; c++){ double* v = static_cast<double*>(myTree.fill->GetScalarPointer(a,b,c)); // set distance to 0 if fill voxel is not in compartment, otherwise // initialize with squared distance to tree base // fill voxel location vtkIdType id; int coord[3]; coord[0] = a; coord[1] = b; coord[2] = c; id = myTree.fill->ComputePointId(coord); // get spatial coordinates of fill voxel double pos[3]; myTree.fill->GetPoint(id,pos); // compare to nearest breast voxel id unsigned char* breastVal = static_cast<unsigned char *>(breast->GetScalarPointer()); if(breastVal[breast->FindPoint(pos)] == compartmentId){ // inside compartment v[0] = vtkMath::Distance2BetweenPoints(spos, pos); } else { // outside compartment, set distance to zero v[0] = 0.0; } } } } myTree.head = new ductBr(spos, sdir, srad, &myTree); //cout << "Finished duct tree " << myTree.id << " with " << myTree.TDLUloc->GetNumberOfPoints() << " TDLUs, " << // myTree.numBranch << " branches created\n"; return; }
24.685039
115
0.67177
DIDSR
d6c1460fa282081f4dc5ec2f5ee957c06181edd9
22,926
cpp
C++
src/libandroidfw/LoadedArsc.cpp
mnlsm/aapt
86553bc9bc0edacaf15cc4cbea278e6c641f93be
[ "Apache-2.0" ]
null
null
null
src/libandroidfw/LoadedArsc.cpp
mnlsm/aapt
86553bc9bc0edacaf15cc4cbea278e6c641f93be
[ "Apache-2.0" ]
null
null
null
src/libandroidfw/LoadedArsc.cpp
mnlsm/aapt
86553bc9bc0edacaf15cc4cbea278e6c641f93be
[ "Apache-2.0" ]
1
2019-06-22T09:06:34.000Z
2019-06-22T09:06:34.000Z
/* * Copyright (C) 2016 The Android Open Source Project * * 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. */ #define ATRACE_TAG ATRACE_TAG_RESOURCES #include "androidfw/LoadedArsc.h" #include <cstddef> #include <limits> //#include "android-base/logging.h" #include "android-base/stringprintf.h" #include "utils/ByteOrder.h" #include "utils/Trace.h" #ifdef _WIN32 #include <windows.h> #ifdef ERROR #undef ERROR #endif #endif #include "androidfw/ByteBucketArray.h" #include "androidfw/Chunk.h" #include "androidfw/ResourceUtils.h" #include "androidfw/Util.h" using android::base::StringPrintf; namespace android { static const int kAppPackageId = 0x7f; // Element of a TypeSpec array. See TypeSpec. struct Type { // The configuration for which this type defines entries. // This is already converted to host endianness. ResTable_config configuration; // Pointer to the mmapped data where entry definitions are kept. const ResTable_type* type; }; // TypeSpec is going to be immediately proceeded by // an array of Type structs, all in the same block of memory. struct TypeSpec { // Pointer to the mmapped data where flags are kept. // Flags denote whether the resource entry is public // and under which configurations it varies. const ResTable_typeSpec* type_spec; // The number of types that follow this struct. // There is a type for each configuration // that entries are defined for. size_t type_count; // Trick to easily access a variable number of Type structs // proceeding this struct, and to ensure their alignment. const Type types[0]; }; // TypeSpecPtr points to the block of memory that holds // a TypeSpec struct, followed by an array of Type structs. // TypeSpecPtr is a managed pointer that knows how to delete // itself. using TypeSpecPtr = util::unique_cptr<TypeSpec>; namespace { // Builder that helps accumulate Type structs and then create a single // contiguous block of memory to store both the TypeSpec struct and // the Type structs. class TypeSpecPtrBuilder { public: TypeSpecPtrBuilder(const ResTable_typeSpec* header) : header_(header) {} void AddType(const ResTable_type* type) { ResTable_config config; config.copyFromDtoH(type->config); types_.push_back(Type{config, type}); } TypeSpecPtr Build() { // Check for overflow. if ((UINT_MAX - sizeof(TypeSpec)) / sizeof(Type) < types_.size()) { return {}; } TypeSpec* type_spec = (TypeSpec*)::malloc(sizeof(TypeSpec) + (types_.size() * sizeof(Type))); type_spec->type_spec = header_; type_spec->type_count = types_.size(); memcpy(type_spec + 1, types_.data(), types_.size() * sizeof(Type)); return TypeSpecPtr(type_spec); } private: DISALLOW_COPY_AND_ASSIGN(TypeSpecPtrBuilder); const ResTable_typeSpec* header_; std::vector<Type> types_; }; } // namespace bool LoadedPackage::FindEntry(uint8_t type_idx, uint16_t entry_idx, const ResTable_config& config, LoadedArscEntry* out_entry, ResTable_config* out_selected_config, uint32_t* out_flags) const { ATRACE_CALL(); // If the type IDs are offset in this package, we need to take that into account when searching // for a type. const TypeSpecPtr& ptr = type_specs_[type_idx - type_id_offset_]; if (ptr == nullptr) { return false; } // Don't bother checking if the entry ID is larger than // the number of entries. if (entry_idx >= dtohl(ptr->type_spec->entryCount)) { return false; } const ResTable_config* best_config = nullptr; const ResTable_type* best_type = nullptr; uint32_t best_offset = 0; for (uint32_t i = 0; i < ptr->type_count; i++) { const Type* type = &ptr->types[i]; if (type->configuration.match(config) && (best_config == nullptr || type->configuration.isBetterThan(*best_config, &config))) { // The configuration matches and is better than the previous selection. // Find the entry value if it exists for this configuration. size_t entry_count = dtohl(type->type->entryCount); if (entry_idx < entry_count) { const uint32_t* entry_offsets = reinterpret_cast<const uint32_t*>( reinterpret_cast<const uint8_t*>(type->type) + dtohs(type->type->header.headerSize)); const uint32_t offset = dtohl(entry_offsets[entry_idx]); if (offset != ResTable_type::NO_ENTRY) { // There is an entry for this resource, record it. best_config = &type->configuration; best_type = type->type; best_offset = offset + dtohl(type->type->entriesStart); } } } } if (best_type == nullptr) { return false; } const uint32_t* flags = reinterpret_cast<const uint32_t*>(ptr->type_spec + 1); *out_flags = dtohl(flags[entry_idx]); *out_selected_config = *best_config; const ResTable_entry* best_entry = reinterpret_cast<const ResTable_entry*>( reinterpret_cast<const uint8_t*>(best_type) + best_offset); out_entry->entry = best_entry; out_entry->type_string_ref = StringPoolRef(&type_string_pool_, best_type->id - 1); out_entry->entry_string_ref = StringPoolRef(&key_string_pool_, dtohl(best_entry->key.index)); return true; } // The destructor gets generated into arbitrary translation units // if left implicit, which causes the compiler to complain about // forward declarations and incomplete types. LoadedArsc::~LoadedArsc() {} bool LoadedArsc::FindEntry(uint32_t resid, const ResTable_config& config, LoadedArscEntry* out_entry, ResTable_config* out_selected_config, uint32_t* out_flags) const { ATRACE_CALL(); const uint8_t package_id = get_package_id(resid); const uint8_t type_id = get_type_id(resid); const uint16_t entry_id = get_entry_id(resid); if (type_id == 0) { return false; } for (const auto& loaded_package : packages_) { if (loaded_package->package_id_ == package_id) { return loaded_package->FindEntry(type_id - 1, entry_id, config, out_entry, out_selected_config, out_flags); } } return false; } const LoadedPackage* LoadedArsc::GetPackageForId(uint32_t resid) const { const uint8_t package_id = get_package_id(resid); for (const auto& loaded_package : packages_) { if (loaded_package->package_id_ == package_id) { return loaded_package.get(); } } return nullptr; } static bool VerifyType(const Chunk& chunk) { ATRACE_CALL(); const ResTable_type* header = chunk.header<ResTable_type, kResTableTypeMinSize>(); const size_t entry_count = dtohl(header->entryCount); if (entry_count > USHRT_MAX) { return false; } // Make sure that there is enough room for the entry offsets. const size_t offsets_offset = chunk.header_size(); const size_t entries_offset = dtohl(header->entriesStart); const size_t offsets_length = sizeof(uint32_t) * entry_count; if (offsets_offset + offsets_length > entries_offset) { return false; } if (entries_offset > chunk.size()) { return false; } if (entries_offset & 0x03) { return false; } // Check each entry offset. const uint32_t* offsets = reinterpret_cast<const uint32_t*>(reinterpret_cast<const uint8_t*>(header) + offsets_offset); for (size_t i = 0; i < entry_count; i++) { uint32_t offset = dtohl(offsets[i]); if (offset != ResTable_type::NO_ENTRY) { // Check that the offset is aligned. if (offset & 0x03) { return false; } // Check that the offset doesn't overflow. if (offset > UINT_MAX - entries_offset) { // Overflow in offset. return false; } offset += entries_offset; if (offset > chunk.size() - sizeof(ResTable_entry)) { return false; } const ResTable_entry* entry = reinterpret_cast<const ResTable_entry*>( reinterpret_cast<const uint8_t*>(header) + offset); const size_t entry_size = dtohs(entry->size); if (entry_size < sizeof(*entry)) { return false; } // Check the declared entrySize. if (entry_size > chunk.size() || offset > chunk.size() - entry_size) { return false; } // If this is a map entry, then keep validating. if (entry_size >= sizeof(ResTable_map_entry)) { const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry); const size_t map_entry_count = dtohl(map->count); size_t map_entries_start = offset + entry_size; if (map_entries_start & 0x03) { return false; } // Each entry is sizeof(ResTable_map) big. if (map_entry_count > ((chunk.size() - map_entries_start) / sizeof(ResTable_map))) { return false; } // Great, all the map entries fit!. } else { // There needs to be room for one Res_value struct. if (offset + entry_size > chunk.size() - sizeof(Res_value)) { return false; } const Res_value* value = reinterpret_cast<const Res_value*>( reinterpret_cast<const uint8_t*>(entry) + entry_size); const size_t value_size = dtohs(value->size); if (value_size < sizeof(Res_value)) { return false; } if (value_size > chunk.size() || offset + entry_size > chunk.size() - value_size) { return false; } } } } return true; } void LoadedPackage::CollectConfigurations(bool exclude_mipmap, std::set<ResTable_config>* out_configs) const { char16_t mipmap[] = { 'm', 'i', 'p', 'm', 'a', 'p', '\0' }; const std::u16string kMipMap(mipmap); const size_t type_count = type_specs_.size(); for (size_t i = 0; i < type_count; i++) { const util::unique_cptr<TypeSpec>& type_spec = type_specs_[i]; if (type_spec != nullptr) { if (exclude_mipmap) { const int type_idx = type_spec->type_spec->id - 1; size_t type_name_len; const char16_t* type_name16 = type_string_pool_.stringAt(type_idx, &type_name_len); if (type_name16 != nullptr) { if (kMipMap.compare(0, std::u16string::npos, type_name16, type_name_len) == 0) { // This is a mipmap type, skip collection. continue; } } const char* type_name = type_string_pool_.string8At(type_idx, &type_name_len); if (type_name != nullptr) { if (strncmp(type_name, "mipmap", type_name_len) == 0) { // This is a mipmap type, skip collection. continue; } } } for (size_t j = 0; j < type_spec->type_count; j++) { out_configs->insert(type_spec->types[j].configuration); } } } } void LoadedPackage::CollectLocales(bool canonicalize, std::set<std::string>* out_locales) const { char temp_locale[RESTABLE_MAX_LOCALE_LEN]; const size_t type_count = type_specs_.size(); for (size_t i = 0; i < type_count; i++) { const util::unique_cptr<TypeSpec>& type_spec = type_specs_[i]; if (type_spec != nullptr) { for (size_t j = 0; j < type_spec->type_count; j++) { const ResTable_config& configuration = type_spec->types[j].configuration; if (configuration.locale != 0) { configuration.getBcp47Locale(temp_locale, canonicalize); std::string locale(temp_locale); out_locales->insert(std::move(locale)); } } } } } uint32_t LoadedPackage::FindEntryByName(const std::u16string& type_name, const std::u16string& entry_name) const { ssize_t type_idx = type_string_pool_.indexOfString(type_name.data(), type_name.size()); if (type_idx < 0) { return 0u; } ssize_t key_idx = key_string_pool_.indexOfString(entry_name.data(), entry_name.size()); if (key_idx < 0) { return 0u; } const TypeSpec* type_spec = type_specs_[type_idx].get(); if (type_spec == nullptr) { return 0u; } for (size_t ti = 0; ti < type_spec->type_count; ti++) { const Type* type = &type_spec->types[ti]; size_t entry_count = dtohl(type->type->entryCount); for (size_t entry_idx = 0; entry_idx < entry_count; entry_idx++) { const uint32_t* entry_offsets = reinterpret_cast<const uint32_t*>( reinterpret_cast<const uint8_t*>(type->type) + dtohs(type->type->header.headerSize)); const uint32_t offset = dtohl(entry_offsets[entry_idx]); if (offset != ResTable_type::NO_ENTRY) { const ResTable_entry* entry = reinterpret_cast<const ResTable_entry*>(reinterpret_cast<const uint8_t*>(type->type) + dtohl(type->type->entriesStart) + offset); if (dtohl(entry->key.index) == static_cast<uint32_t>(key_idx)) { // The package ID will be overridden by the caller (due to runtime assignment of package // IDs for shared libraries). return make_resid(0x00, type_idx + type_id_offset_ + 1, entry_idx); } } } } return 0u; } std::unique_ptr<LoadedPackage> LoadedPackage::Load(const Chunk& chunk) { ATRACE_CALL(); std::unique_ptr<LoadedPackage> loaded_package{new LoadedPackage()}; const size_t kMinPackageSize = sizeof(ResTable_package) - sizeof(decltype(ResTable_package::typeIdOffset)); const ResTable_package* header = chunk.header<ResTable_package, kMinPackageSize>(); if (header == nullptr) { return {}; } loaded_package->package_id_ = dtohl(header->id); if (loaded_package->package_id_ == 0) { // Package ID of 0 means this is a shared library. loaded_package->dynamic_ = true; } if (header->header.headerSize >= sizeof(ResTable_package)) { uint32_t type_id_offset = dtohl(header->typeIdOffset); if (type_id_offset > UCHAR_MAX) { return {}; } loaded_package->type_id_offset_ = static_cast<int>(type_id_offset); } util::ReadUtf16StringFromDevice(header->name, arraysize(header->name), &loaded_package->package_name_); // A TypeSpec builder. We use this to accumulate the set of Types // available for a TypeSpec, and later build a single, contiguous block // of memory that holds all the Types together with the TypeSpec. std::unique_ptr<TypeSpecPtrBuilder> types_builder; // Keep track of the last seen type index. Since type IDs are 1-based, // this records their index, which is 0-based (type ID - 1). uint8_t last_type_idx = 0; ChunkIterator iter(chunk.data_ptr(), chunk.data_size()); while (iter.HasNext()) { const Chunk child_chunk = iter.Next(); switch (child_chunk.type()) { case RES_STRING_POOL_TYPE: { const uintptr_t pool_address = reinterpret_cast<uintptr_t>(child_chunk.header<ResChunk_header>()); const uintptr_t header_address = reinterpret_cast<uintptr_t>(header); if (pool_address == header_address + dtohl(header->typeStrings)) { // This string pool is the type string pool. status_t err = loaded_package->type_string_pool_.setTo( child_chunk.header<ResStringPool_header>(), child_chunk.size()); if (err != NO_ERROR) { return {}; } } else if (pool_address == header_address + dtohl(header->keyStrings)) { // This string pool is the key string pool. status_t err = loaded_package->key_string_pool_.setTo( child_chunk.header<ResStringPool_header>(), child_chunk.size()); if (err != NO_ERROR) { return {}; } } else { } } break; case RES_TABLE_TYPE_SPEC_TYPE: { ATRACE_NAME("LoadTableTypeSpec"); // Starting a new TypeSpec, so finish the old one if there was one. if (types_builder) { TypeSpecPtr type_spec_ptr = types_builder->Build(); if (type_spec_ptr == nullptr) { return {}; } loaded_package->type_specs_.editItemAt(last_type_idx) = std::move(type_spec_ptr); types_builder = {}; last_type_idx = 0; } const ResTable_typeSpec* type_spec = child_chunk.header<ResTable_typeSpec>(); if (type_spec == nullptr) { return {}; } if (type_spec->id == 0) { return {}; } if (loaded_package->type_id_offset_ + static_cast<int>(type_spec->id) > UCHAR_MAX) { return {}; } // The data portion of this chunk contains entry_count 32bit entries, // each one representing a set of flags. // Here we only validate that the chunk is well formed. const size_t entry_count = dtohl(type_spec->entryCount); // There can only be 2^16 entries in a type, because that is the ID // space for entries (EEEE) in the resource ID 0xPPTTEEEE. if (entry_count > UCHAR_MAX) { return {}; } if (entry_count * sizeof(uint32_t) > chunk.data_size()) { return {}; } last_type_idx = type_spec->id - 1; types_builder = util::make_unique<TypeSpecPtrBuilder>(type_spec); } break; case RES_TABLE_TYPE_TYPE: { const ResTable_type* type = child_chunk.header<ResTable_type, kResTableTypeMinSize>(); if (type == nullptr) { return {}; } if (type->id == 0) { return {}; } // Type chunks must be preceded by their TypeSpec chunks. if (!types_builder || type->id - 1 != last_type_idx) { return {}; } if (!VerifyType(child_chunk)) { return {}; } types_builder->AddType(type); } break; case RES_TABLE_LIBRARY_TYPE: { const ResTable_lib_header* lib = child_chunk.header<ResTable_lib_header>(); if (lib == nullptr) { return {}; } if (child_chunk.data_size() / sizeof(ResTable_lib_entry) < dtohl(lib->count)) { return {}; } loaded_package->dynamic_package_map_.reserve(dtohl(lib->count)); const ResTable_lib_entry* const entry_begin = reinterpret_cast<const ResTable_lib_entry*>(child_chunk.data_ptr()); const ResTable_lib_entry* const entry_end = entry_begin + dtohl(lib->count); for (auto entry_iter = entry_begin; entry_iter != entry_end; ++entry_iter) { std::string package_name; util::ReadUtf16StringFromDevice(entry_iter->packageName, arraysize(entry_iter->packageName), &package_name); if (dtohl(entry_iter->packageId) >= UCHAR_MAX) { return {}; } loaded_package->dynamic_package_map_.emplace_back(std::move(package_name), dtohl(entry_iter->packageId)); } } break; default: break; } } // Finish the last TypeSpec. if (types_builder) { TypeSpecPtr type_spec_ptr = types_builder->Build(); if (type_spec_ptr == nullptr) { return {}; } loaded_package->type_specs_.editItemAt(last_type_idx) = std::move(type_spec_ptr); } if (iter.HadError()) { return {}; } return loaded_package; } bool LoadedArsc::LoadTable(const Chunk& chunk, bool load_as_shared_library) { ATRACE_CALL(); const ResTable_header* header = chunk.header<ResTable_header>(); if (header == nullptr) { return false; } const size_t package_count = dtohl(header->packageCount); size_t packages_seen = 0; packages_.reserve(package_count); ChunkIterator iter(chunk.data_ptr(), chunk.data_size()); while (iter.HasNext()) { const Chunk child_chunk = iter.Next(); switch (child_chunk.type()) { case RES_STRING_POOL_TYPE: // Only use the first string pool. Ignore others. if (global_string_pool_.getError() == NO_INIT) { status_t err = global_string_pool_.setTo(child_chunk.header<ResStringPool_header>(), child_chunk.size()); if (err != NO_ERROR) { return false; } } else { } break; case RES_TABLE_PACKAGE_TYPE: { if (packages_seen + 1 > package_count) { return false; } packages_seen++; std::unique_ptr<LoadedPackage> loaded_package = LoadedPackage::Load(child_chunk); if (!loaded_package) { return false; } // Mark the package as dynamic if we are forcefully loading the Apk as a shared library. if (loaded_package->package_id_ == kAppPackageId) { loaded_package->dynamic_ = load_as_shared_library; } loaded_package->system_ = system_; packages_.push_back(std::move(loaded_package)); } break; default: break; } } if (iter.HadError()) { return false; } return true; } std::unique_ptr<const LoadedArsc> LoadedArsc::Load(const void* data, size_t len, bool system, bool load_as_shared_library) { ATRACE_CALL(); // Not using make_unique because the constructor is private. std::unique_ptr<LoadedArsc> loaded_arsc(new LoadedArsc()); loaded_arsc->system_ = system; ChunkIterator iter(data, len); while (iter.HasNext()) { const Chunk chunk = iter.Next(); switch (chunk.type()) { case RES_TABLE_TYPE: if (!loaded_arsc->LoadTable(chunk, load_as_shared_library)) { return {}; } break; default: break; } } if (iter.HadError()) { return {}; } // Need to force a move for mingw32. return std::move(loaded_arsc); } } // namespace android
33.964444
100
0.62379
mnlsm
d6c287728f25639f7599e72c752eba49a3fa691f
4,455
cpp
C++
src/DriveTrain.cpp
shiruz/SampleCode
2fb3d8701bbb86f6609341a636f05134132b2efd
[ "MIT" ]
null
null
null
src/DriveTrain.cpp
shiruz/SampleCode
2fb3d8701bbb86f6609341a636f05134132b2efd
[ "MIT" ]
null
null
null
src/DriveTrain.cpp
shiruz/SampleCode
2fb3d8701bbb86f6609341a636f05134132b2efd
[ "MIT" ]
null
null
null
#include "main.h" //Veriables for tweaking the drive train. bool IsBreaking = false; bool IsForward = true; //Returns true/false as to wheter the drive wheels have //reached their position goal set by driveForDistance bool AtDistanceDriveGoal(int threshold) { return (abs(FLMotor.get_position() - FLMotor.get_target_position()) < threshold) &&(abs(FLMotor.get_position() - FLMotor.get_target_position()) < threshold); } //Sets drive trains target, but does not wait for them to reach their target void Drive(double leftInches, double rightInches, int speed) { FRMotor.move_relative(leftInches, speed); BRMotor.move_relative(rightInches, -speed); pros::delay(10); FLMotor.move_relative(rightInches, speed); BLMotor.move_relative(leftInches, -speed); } //Turns the robot to the target position void Rotate(double turn, int speed) { FLMotor.move_relative(turn , speed); FRMotor.move_relative(-turn, speed); BLMotor.move_relative(turn, speed); BRMotor.move_relative(-turn, speed); } //Function for setting the drive trian breaks void BrakeDriveTrain() { IsBreaking = true; FLMotor.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD); FRMotor.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD); BLMotor.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD); BRMotor.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD); FLMotor.move_relative(0,200); FRMotor.move_relative(0,200); BLMotor.move_relative(0,200); BRMotor.move_relative(0,200); } //Function for releasing the drive train breaks void UnBrakeDriveTrain() { IsBreaking = false; FLMotor.set_brake_mode(pros::E_MOTOR_BRAKE_COAST); FRMotor.set_brake_mode(pros::E_MOTOR_BRAKE_COAST); BLMotor.set_brake_mode(pros::E_MOTOR_BRAKE_COAST); BRMotor.set_brake_mode(pros::E_MOTOR_BRAKE_COAST); } //Function for seting the cap flipper side to be the front side void SetBackwords() { FLMotor.set_reversed(true); FRMotor.set_reversed(false); BLMotor.set_reversed(true); BRMotor.set_reversed(false); IsForward = false; } //Function for seting the ball shooter side to be the front side void SetForwards() { FLMotor.set_reversed(false); FRMotor.set_reversed(true); BLMotor.set_reversed(false); BRMotor.set_reversed(true); IsForward = true; } //Thread for all drive train controls. void DriveTrain_fn(void* param) { int LeftControls = master.get_analog(ANALOG_LEFT_Y); int RightControls = master.get_analog(ANALOG_RIGHT_Y); //Setting the right motors to be reversed FLMotor.set_reversed(false); FRMotor.set_reversed(true); BLMotor.set_reversed(false); BRMotor.set_reversed(true); while (true) { //Gets the joistics position and maps them to a veriable. LeftControls = master.get_analog(ANALOG_LEFT_Y); RightControls = master.get_analog(ANALOG_RIGHT_Y); //Switches the motor sides if the drive train is reversed. if (IsBreaking != true) { if (IsForward == true) { FLMotor.move(LeftControls); BLMotor.move(LeftControls); FRMotor.move(RightControls); BRMotor.move(RightControls); } else { FLMotor.move(RightControls); BLMotor.move(RightControls); FRMotor.move(LeftControls); BRMotor.move(LeftControls); } } if (master.get_digital_new_press(DIGITAL_UP)) { if (IsBreaking == true) { UnBrakeDriveTrain(); } else { BrakeDriveTrain(); } } //Drive train break controls. if (master.get_digital_new_press(DIGITAL_DOWN)) { if (IsBreaking == true) { UnBrakeDriveTrain(); Rotate(1580, 50); } else { BrakeDriveTrain(); Rotate(1580, 50); } } //Drive train directional controls. if (master.get_digital_new_press(DIGITAL_L1)) { SetBackwords(); } if (master.get_digital_new_press(DIGITAL_R1)) { SetForwards(); } if (IsForward == true) { //Rotate 90 if (master.get_digital_new_press(DIGITAL_LEFT)) { Rotate(790, 50); pros::delay(1200); } else if (master.get_digital_new_press(DIGITAL_RIGHT)) { Rotate(-790, 50); pros::delay(1200); } } else { //Rotate 90 if (master.get_digital_new_press(DIGITAL_LEFT)) { Rotate(-790, 50); pros::delay(1200); } else if (master.get_digital_new_press(DIGITAL_RIGHT)) { Rotate(790, 50); pros::delay(1200); } } } }
27
159
0.683726
shiruz
d6c312ae5a2cd1de1511c43c115d350036a0fd58
2,019
cpp
C++
Amazon/14 - Burning Tree.cpp
thisisbipin/-6Companies30days
5d4b8a10cb00f395f3f12812de82588d10fb2426
[ "MIT" ]
null
null
null
Amazon/14 - Burning Tree.cpp
thisisbipin/-6Companies30days
5d4b8a10cb00f395f3f12812de82588d10fb2426
[ "MIT" ]
null
null
null
Amazon/14 - Burning Tree.cpp
thisisbipin/-6Companies30days
5d4b8a10cb00f395f3f12812de82588d10fb2426
[ "MIT" ]
null
null
null
class Solution { unordered_map<Node*, Node*> parent; public: Node* populate(Node* root, int target) { queue<Node*> q; q.push(root); Node* tar = NULL; bool check = 0; while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; i++) { Node* temp = q.front(); q.pop(); if (temp->data == target && check == 0) { tar = temp; check = 1; } if (temp->left != NULL) { parent[temp->left] = temp; q.push(temp->left); } if (temp->right != NULL) { parent[temp->right] = temp; q.push(temp->right); } } } return tar; } int minTime(Node* root, int target) { Node* getval = populate(root, target); if (getval == NULL) return 0; unordered_set<Node*> vis; int res = 0; queue<Node*> q; q.push(getval); while (!q.empty()) { int qs = q.size(); bool found = false; while (qs--) { Node* temp = q.front(); q.pop(); vis.insert(temp); if ((parent[temp]) && (vis.find(parent[temp]) == vis.end())) { q.push(parent[temp]); found = true; } if ((temp->left != NULL) && (vis.find(temp->left) == vis.end())) { q.push(temp->left); found = true; } if ((temp->right != NULL) && (vis.find(temp->right) == vis.end())) { q.push(temp->right); found = true; } } if (found) res++; } return res; } };
30.590909
85
0.34522
thisisbipin
d6cccc0fe0c90e787c54b72f2308bbb21f75a1ee
13,313
cpp
C++
overlay/HardHook_x86.cpp
bogie/mumble
48c3a19aba885177e2b7a17f90bf5617104b18fa
[ "BSD-3-Clause" ]
2
2016-03-08T07:57:21.000Z
2017-12-30T22:01:10.000Z
overlay/HardHook_x86.cpp
bogie/mumble
48c3a19aba885177e2b7a17f90bf5617104b18fa
[ "BSD-3-Clause" ]
null
null
null
overlay/HardHook_x86.cpp
bogie/mumble
48c3a19aba885177e2b7a17f90bf5617104b18fa
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2005-2011, Thorvald Natvig <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Mumble Developers 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 FOUNDATION 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 "HardHook.h" #include "ods.h" void *HardHook::pCode = NULL; unsigned int HardHook::uiCode = 0; const int HardHook::CODEREPLACESIZE = 6; const int HardHook::CODEPROTECTSIZE = 16; /** * @brief Constructs a new hook without actually injecting. */ HardHook::HardHook() : bTrampoline(false), call(0), baseptr(NULL) { for (int i = 0; i < CODEREPLACESIZE; ++i) { orig[i] = replace[i] = 0; } // assert(CODEREPLACESIZE == sizeof(orig) / sizeof(orig[0])); // assert(CODEREPLACESIZE == sizeof(replace) / sizeof(replace[0])); } /** * @brief Constructs a new hook by injecting given replacement function into func. * @see HardHook::setup * @param func Funktion to inject replacement into. * @param replacement Function to inject into func. */ HardHook::HardHook(voidFunc func, voidFunc replacement) : bTrampoline(false), call(0), baseptr(NULL) { for (int i = 0; i < CODEREPLACESIZE; ++i) orig[i] = replace[i] = 0; setup(func, replacement); } /** * @return Number of extra bytes. */ static unsigned int modrmbytes(unsigned char a, unsigned char b) { unsigned char lower = (a & 0x0f); if (a >= 0xc0) { return 0; } else if (a >= 0x80) { if ((lower == 4) || (lower == 12)) return 5; else return 4; } else if (a >= 0x40) { if ((lower == 4) || (lower == 12)) return 2; else return 1; } else { if ((lower == 4) || (lower == 12)) { if ((b & 0x07) == 0x05) return 5; else return 1; } else if ((lower == 5) || (lower == 13)) return 4; return 0; } } /** * @brief Tries to construct a trampoline from original code. * * A trampoline is the replacement code that features the original code plus * a jump back to the original instructions that follow. * It is called to execute the original behavior. As it is a replacement for * the original, the original can then be overwritten. * The size of the trampoline is at least CODEREPLACESIZE. Thus, CODEREPLACESIZE * bytes of the original code can afterwards be overwritten (and the trampoline * called after those instructions for the original logic). * CODEREPLACESIZE has to be smaller than CODEPROTECTSIZE. * * As commands must not be destroyed they have to be disassembled to get their length. * All encountered commands will be part of the trampoline and stored in pCode (shared * for all trampolines). * * If code is encountered that can not be moved into the trampoline (conditionals etc.) * construction fails and NULL is returned. If enough commands can be saved the * trampoline is finalized by appending a jump back to the original code. The return value * in this case will be the address of the newly constructed trampoline. * * pCode + offset to trampoline: * [SAVED CODE FROM ORIGINAL which is >= CODEREPLACESIZE bytes][JUMP BACK TO ORIGINAL CODE] * * @param porig Original code * @return Pointer to trampoline on success. NULL if trampoline construction failed. */ void *HardHook::cloneCode(void **porig) { if (! pCode || uiCode > 4000) { pCode = VirtualAlloc(NULL, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); uiCode = 0; } // If we have no memory to clone to, return. if (! pCode) { return NULL; } unsigned char *o = (unsigned char *) *porig; DWORD origProtect; if (!VirtualProtect(o, CODEPROTECTSIZE, PAGE_EXECUTE_READ, &origProtect)) { fods("HardHook: CloneCode failed; failed to make original code read and executable"); return NULL; } // Follow relative jumps to next instruction. On execution it doesn't make // a difference if we actually perform all the jumps or directly jump to the // end of the chain. Hence these jumps need not be part of the trampoline. while (*o == 0xe9) { // JMP unsigned char *tmp = o; int *iptr = reinterpret_cast<int *>(o+1); o += *iptr + 5; fods("HardHook: CloneCode: Skipping jump from %p to %p", *porig, o); *porig = o; // Assume jump took us out of our read enabled zone, get rights for the new one DWORD tempProtect; VirtualProtect(tmp, CODEPROTECTSIZE, origProtect, &tempProtect); if (!VirtualProtect(o, CODEPROTECTSIZE, PAGE_EXECUTE_READ, &origProtect)) { fods("HardHook: CloneCode failed; failed to make jump target code read and executable"); return NULL; } } unsigned char *n = (unsigned char *) pCode; n += uiCode; unsigned int idx = 0; do { unsigned char opcode = o[idx]; unsigned char a = o[idx+1]; unsigned char b = o[idx+2]; unsigned int extra = 0; switch (opcode) { case 0x50: // PUSH case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: // POP case 0x59: case 0x5a: case 0x5b: case 0x5c: case 0x5d: case 0x5e: case 0x5f: break; case 0x6a: // PUSH immediate extra = 1; break; case 0x68: // PUSH immediate extra = 4; break; case 0x81: // CMP immediate extra = modrmbytes(a,b) + 5; break; case 0x83: // CMP extra = modrmbytes(a,b) + 2; break; case 0x8b: // MOV extra = modrmbytes(a,b) + 1; break; default: { int rmop = ((a>>3) & 7); if (opcode == 0xff && rmop == 6) { // PUSH memory extra = modrmbytes(a,b) + 1; break; } fods("HardHook: CloneCode failed; Unknown opcode %02x at %d: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x", opcode, idx, o[0], o[1], o[2], o[3], o[4], o[5], o[6], o[7], o[8], o[9], o[10], o[11]); DWORD tempProtect; VirtualProtect(o, CODEPROTECTSIZE, origProtect, &tempProtect); return NULL; break; } } n[idx] = opcode; ++idx; for (unsigned int i = 0; i < extra; ++i) n[idx+i] = o[idx+i]; idx += extra; } while (idx < CODEREPLACESIZE); DWORD tempProtect; VirtualProtect(o, CODEPROTECTSIZE, origProtect, &tempProtect); // Add a relative jmp back to the original code, to after the copied code n[idx++] = 0xe9; int *iptr = reinterpret_cast<int *>(&n[idx]); const int JMP_OP_SIZE = 5; int offs = o - n - JMP_OP_SIZE; *iptr = offs; idx += 4; uiCode += idx; FlushInstructionCache(GetCurrentProcess(), n, idx); fods("HardHook: trampoline creation successful at %p", n); return n; } /** * @brief Makes sure the given replacement function is run once func is called. * * Tries to construct a trampoline for the given function (@see HardHook::cloneCode) * and then injects replacement function calling code into the first 6 bytes of the * original function (@see HardHook::inject). * * @param func Pointer to function to redirect. * @param replacement Pointer to code to redirect to. */ void HardHook::setup(voidFunc func, voidFunc replacement) { if (baseptr) return; fods("HardHook: Setup: Asked to replace %p with %p", func, replacement); unsigned char *fptr = reinterpret_cast<unsigned char *>(func); unsigned char *nptr = reinterpret_cast<unsigned char *>(replacement); call = (voidFunc) cloneCode((void **) &fptr); if (call) { bTrampoline = true; } else { // Could not create a trampoline. Use alternative method instead. // This alternative method is dependant on the replacement code // restoring before calling the original. Otherwise we get a jump recursion bTrampoline = false; call = func; } DWORD origProtect; if (VirtualProtect(fptr, CODEPROTECTSIZE, PAGE_EXECUTE_READ, &origProtect)) { replace[0] = 0x68; // PUSH immediate 1 Byte unsigned char **iptr = reinterpret_cast<unsigned char **>(&replace[1]); *iptr = nptr; // (imm. value = nptr) 4 Byte replace[5] = 0xc3; // RETN 1 Byte // Save original 6 bytes at start of original function for (int i = 0; i < CODEREPLACESIZE; ++i) orig[i] = fptr[i]; baseptr = fptr; inject(true); DWORD tempProtect; VirtualProtect(fptr, CODEPROTECTSIZE, origProtect, &tempProtect); } else { fods("HardHook: setup failed; failed to make original code read and executable"); } } void HardHook::setupInterface(IUnknown *unkn, LONG funcoffset, voidFunc replacement) { fods("HardHook: setupInterface: Replacing %p function #%ld", unkn, funcoffset); void **ptr = reinterpret_cast<void **>(unkn); ptr = reinterpret_cast<void **>(ptr[0]); setup(reinterpret_cast<voidFunc>(ptr[funcoffset]), replacement); } void HardHook::reset() { baseptr = 0; bTrampoline = false; call = NULL; for (int i = 0; i < CODEREPLACESIZE; ++i) { orig[i] = replace[i] = 0; } } /** * @brief Injects redirection code into the target function. * * Replaces the first 6 Bytes of the function indicated by baseptr * with the replacement code previously generated (usually a jump * to mumble code). If a trampoline is available this injection is not needed * as control flow was already permanently redirected by HardHook::setup . * * @param force Perform injection even when trampoline is available. */ void HardHook::inject(bool force) { if (! baseptr) return; if (! force && bTrampoline) return; DWORD origProtect; if (VirtualProtect(baseptr, CODEREPLACESIZE, PAGE_EXECUTE_READWRITE, &origProtect)) { for (int i = 0; i < CODEREPLACESIZE; ++i) { baseptr[i] = replace[i]; // Replace with jump to new code } DWORD tempProtect; VirtualProtect(baseptr, CODEREPLACESIZE, origProtect, &tempProtect); FlushInstructionCache(GetCurrentProcess(), baseptr, CODEREPLACESIZE); } // Verify that the injection was successful for (int i = 0; i < CODEREPLACESIZE; ++i) { if (baseptr[i] != replace[i]) { fods("HardHook: Injection failure noticed at byte %d", i); } } } /** * @brief Restores the original code in a target function. * * Restores the first 6 Bytes of the function indicated by baseptr * from previously stored original code in orig. If a trampoline is available this * restoration is not needed as trampoline will correctly restore control * flow. * * @param force If true injection will be reverted even when trampoline is available. */ void HardHook::restore(bool force) { if (! baseptr) return; if (! force && bTrampoline) return; DWORD origProtect; if (VirtualProtect(baseptr, CODEREPLACESIZE, PAGE_EXECUTE_READWRITE, &origProtect)) { for (int i = 0; i < CODEREPLACESIZE; ++i) baseptr[i] = orig[i]; DWORD tempProtect; VirtualProtect(baseptr, CODEREPLACESIZE, origProtect, &tempProtect); FlushInstructionCache(GetCurrentProcess(), baseptr, CODEREPLACESIZE); } } void HardHook::print() { fods("HardHook: code replacement: %02x %02x %02x %02x %02x => %02x %02x %02x %02x %02x (currently effective: %02x %02x %02x %02x %02x)", orig[0], orig[1], orig[2], orig[3], orig[4], replace[0], replace[1], replace[2], replace[3], replace[4], baseptr[0], baseptr[1], baseptr[2], baseptr[3], baseptr[4]); } /** * @brief Checks whether injected code is in good shape and injects if not yet injected. * * If injected code is not found injection is attempted unless 3rd party overwrote * original code at injection location. */ void HardHook::check() { if (memcmp(baseptr, replace, CODEREPLACESIZE) != 0) { // The instructions do not match our replacement instructions // If they match the original code, inject our hook. if (memcmp(baseptr, orig, CODEREPLACESIZE) == 0) { fods("HardHook: Reinjecting hook into function %p", baseptr); inject(true); } else { fods("HardHook: Function %p replaced by third party. Lost injected hook."); } } }
32.710074
138
0.670247
bogie
d6d4069bf1a6d7a131bcb24d305e2772a1fd8a2a
3,774
hpp
C++
libff/algebra/fields/binary/gf192.hpp
FardeenFindora/libff
9be5f23075f9723840eb2ceb0016d24d69dfea8f
[ "MIT" ]
115
2016-07-21T02:49:47.000Z
2022-03-29T21:08:23.000Z
libff/algebra/fields/binary/gf192.hpp
FardeenFindora/libff
9be5f23075f9723840eb2ceb0016d24d69dfea8f
[ "MIT" ]
78
2017-03-08T16:43:56.000Z
2022-02-01T03:12:35.000Z
libff/algebra/fields/binary/gf192.hpp
FardeenFindora/libff
9be5f23075f9723840eb2ceb0016d24d69dfea8f
[ "MIT" ]
72
2016-07-22T06:49:42.000Z
2022-03-29T08:48:28.000Z
/**@file ***************************************************************************** Declaration of GF(2^192) finite field. ***************************************************************************** * @author This file is part of libff (see AUTHORS), migrated from libiop * @copyright MIT license (see LICENSE file) *****************************************************************************/ #ifndef LIBFF_ALGEBRA_GF192_HPP_ #define LIBFF_ALGEBRA_GF192_HPP_ #include <cstddef> #include <cstdint> #include <vector> #include <libff/algebra/field_utils/bigint.hpp> namespace libff { /* gf192 implements the field GF(2)/(x^192 + x^7 + x^2 + x + 1). Elements are represented internally with three uint64s */ class gf192 { public: #ifdef PROFILE_OP_COUNTS // NOTE: op counts are affected when you exponentiate with ^ static long long add_cnt; static long long sub_cnt; static long long mul_cnt; static long long sqr_cnt; static long long inv_cnt; #endif // x^192 + x^7 + x^2 + x + 1 static const constexpr uint64_t modulus_ = 0b10000111; static const constexpr uint64_t num_bits = 192; explicit gf192(); /* we need a constructor that only initializes the low half of value_ to be able to do gf192(0) and gf192(1). */ explicit gf192(const uint64_t value_low); explicit gf192(const uint64_t value_high, const uint64_t value_mid, const uint64_t value_low); gf192& operator+=(const gf192 &other); gf192& operator-=(const gf192 &other); gf192& operator*=(const gf192 &other); gf192& operator^=(const unsigned long pow); template<mp_size_t m> gf192& operator^=(const bigint<m> &pow); gf192& square(); gf192& invert(); gf192 operator+(const gf192 &other) const; gf192 operator-(const gf192 &other) const; gf192 operator-() const; gf192 operator*(const gf192 &other) const; gf192 operator^(const unsigned long pow) const; template<mp_size_t m> gf192 operator^(const bigint<m> &pow) const; gf192 squared() const; gf192 inverse() const; gf192 sqrt() const; /** * Returns the constituent bits in 64 bit words, in little-endian order. * Only the right-most ceil_size_in_bits() bits are used; other bits are 0. */ std::vector<uint64_t> to_words() const; /** * Sets the field element from the given bits in 64 bit words, in little-endian order. * Only the right-most ceil_size_in_bits() bits are used; other bits are ignored. * Should always return true since the right-most bits are always valid. */ bool from_words(std::vector<uint64_t> words); void randomize(); void clear(); bool operator==(const gf192 &other) const; bool operator!=(const gf192 &other) const; bool is_zero() const; void print() const; static gf192 random_element(); static gf192 zero(); static gf192 one(); static gf192 multiplicative_generator; // generator of gf192^* static std::size_t ceil_size_in_bits() { return num_bits; } static std::size_t floor_size_in_bits() { return num_bits; } static constexpr std::size_t extension_degree() { return 192; } template<mp_size_t n> static constexpr bigint<n> field_char() { return bigint<n>(2); } friend std::ostream& operator<<(std::ostream &out, const gf192 &el); friend std::istream& operator>>(std::istream &in, gf192 &el); private: /* little-endian */ uint64_t value_[3]; }; #ifdef PROFILE_OP_COUNTS long long gf192::add_cnt = 0; long long gf192::sub_cnt = 0; long long gf192::mul_cnt = 0; long long gf192::sqr_cnt = 0; long long gf192::inv_cnt = 0; #endif } // namespace libff #include <libff/algebra/fields/binary/gf192.tcc> #endif // namespace libff_ALGEBRA_GF192_HPP_
33.105263
98
0.646264
FardeenFindora
d6d4b7cc7b461f90d1cd27b769f2522ffc06152f
5,426
cpp
C++
src/open_pulse/pulse_utils.cpp
jakelishman/qiskit-aer
7512ecede820e0d2bc7ad7b6704bcf06a861ca3a
[ "Apache-2.0" ]
313
2018-12-19T09:19:12.000Z
2022-03-21T18:15:41.000Z
src/open_pulse/pulse_utils.cpp
jakelishman/qiskit-aer
7512ecede820e0d2bc7ad7b6704bcf06a861ca3a
[ "Apache-2.0" ]
933
2018-12-21T02:56:49.000Z
2022-03-30T01:19:54.000Z
src/open_pulse/pulse_utils.cpp
jakelishman/qiskit-aer
7512ecede820e0d2bc7ad7b6704bcf06a861ca3a
[ "Apache-2.0" ]
313
2018-12-19T14:52:55.000Z
2022-02-28T20:20:14.000Z
#include "pulse_utils.hpp" #include "zspmv.hpp" complex_t internal_expect_psi_csr(const py::array_t<complex_t>& data, const py::array_t<int>& ind, const py::array_t<int>& ptr, const py::array_t<complex_t>& vec) { auto data_raw = data.unchecked<1>(); auto vec_raw = vec.unchecked<1>(); auto ind_raw = ind.unchecked<1>(); auto ptr_raw = ptr.unchecked<1>(); auto nrows = vec.shape(0); complex_t temp, expt = 0; for (decltype(nrows) row = 0; row < nrows; row++) { temp = 0; auto vec_conj = std::conj(vec_raw[row]); for (auto j = ptr_raw[row]; j < ptr_raw[row + 1]; j++) { temp += data_raw[j] * vec_raw[ind_raw[j]]; } expt += vec_conj * temp; } return expt; } complex_t internal_expect_psi(const py::array_t<complex_t>& data, const py::array_t<complex_t>& vec) { auto data_raw = data.unchecked<2>(); auto vec_raw = vec.unchecked<1>(); auto nrows = data.shape(0); auto ncols = data.shape(1); complex_t temp, expt = 0; for (decltype(nrows) i = 0; i < nrows; i++) { temp = 0; auto vec_conj = std::conj(vec_raw[i]); for (auto j = 0; j < ncols; j++) { temp += data_raw(i, j) * vec_raw[j]; } expt += vec_conj * temp; } return expt; } py::object expect_psi_csr(py::array_t<complex_t> data, py::array_t<int> ind, py::array_t<int> ptr, py::array_t<complex_t> vec, bool isherm){ complex_t expt = internal_expect_psi_csr(data, ind, ptr, vec); if(isherm){ return py::cast(std::real(expt)); } return py::cast(expt); } py::object expect_psi(py::array_t<complex_t> data, py::array_t<complex_t> vec, bool isherm){ complex_t expt = internal_expect_psi(data, vec); if(isherm){ return py::cast(std::real(expt)); } return py::cast(expt); } py::array_t<double> occ_probabilities(py::array_t<int> qubits, py::array_t<complex_t> state, py::list meas_ops){ auto meas_size = meas_ops.size(); py::array_t<double> probs(meas_size); auto probs_raw = probs.mutable_unchecked<1>(); for(decltype(meas_size) i=0; i < meas_size; i++){ auto data = meas_ops[i].attr("data").attr("data").cast<py::array_t<complex_t>>(); probs_raw[i] = std::real(internal_expect_psi(data, state)); } return probs; } void write_shots_memory(py::array_t<unsigned char> mem, py::array_t<unsigned int> mem_slots, py::array_t<double> probs, py::array_t<double> rand_vals) { auto nrows = mem.shape(0); auto nprobs = probs.shape(0); unsigned char temp; auto mem_raw = mem.mutable_unchecked<2>(); auto mem_slots_raw = mem_slots.unchecked<1>(); auto probs_raw = probs.unchecked<1>(); auto rand_vals_raw = rand_vals.unchecked<1>(); for(decltype(nrows) i = 0; i < nrows; i++){ for(decltype(nprobs) j = 0; j < nprobs; j++) { temp = static_cast<unsigned char>(probs_raw[j] > rand_vals_raw[nprobs*i+j]); if(temp) { mem_raw(i, mem_slots_raw[j]) = temp; } } } } void oplist_to_array(py::list A, py::array_t<complex_t> B, int start_idx) { auto lenA = A.size(); if((start_idx+lenA) > B.shape(0)) { throw std::runtime_error(std::string("Input list does not fit into array if start_idx is ") + std::to_string(start_idx) + "."); } auto B_raw = B.mutable_unchecked<1>(); for(decltype(lenA) kk=0; kk < lenA; kk++){ auto item = A[kk].cast<py::list>(); B_raw[start_idx+kk] = complex_t(item[0].cast<double>(), item[1].cast<double>()); } } template <typename T> T * get_raw_data(py::array_t<T> array) { return static_cast<T *>(array.request().ptr); } py::array_t<complex_t> spmv_csr(py::array_t<complex_t> data, py::array_t<int> ind, py::array_t<int> ptr, py::array_t<complex_t> vec) { auto data_raw = get_raw_data(data); auto ind_raw = get_raw_data(ind); auto ptr_raw = get_raw_data(ptr); auto vec_raw = get_raw_data(vec); auto num_rows = vec.shape(0); py::array_t<complex_t> out(num_rows); auto out_raw = get_raw_data(out); memset(&out_raw[0], 0, num_rows * sizeof(complex_t)); zspmvpy(data_raw, ind_raw, ptr_raw, vec_raw, 1.0, out_raw, num_rows); return out; } py::array_t<complex_t> spmv(py::array_t<complex_t> data, py::array_t<complex_t> vec) { auto data_raw = get_raw_data(data); auto vec_raw = get_raw_data(vec); auto num_columns = data.shape(0); auto num_rows = data.shape(1); py::array_t<complex_t> out(num_rows); auto out_raw = get_raw_data(out); memset(&out_raw[0], 0, num_rows * sizeof(complex_t)); for (auto row=0; row < num_rows; row++) { for (auto jj=0; jj <num_columns; jj++) { out_raw[row] += data_raw[row*num_columns + jj]*vec_raw[jj]; } } return out; }
31.546512
135
0.555474
jakelishman
d6d804e4cd407177e48858dd881f754f70a19c87
7,482
cpp
C++
alvr/server/cpp/alvr_server/OvrViveTrackerProxy.cpp
Firepal/ALVR
834cac75663832638a129a6ba6b2901a7e8dd2ed
[ "MIT" ]
1,562
2020-12-01T15:02:21.000Z
2022-03-31T13:37:51.000Z
alvr/server/cpp/alvr_server/OvrViveTrackerProxy.cpp
Firepal/ALVR
834cac75663832638a129a6ba6b2901a7e8dd2ed
[ "MIT" ]
562
2020-12-01T20:10:13.000Z
2022-03-31T22:57:13.000Z
alvr/server/cpp/alvr_server/OvrViveTrackerProxy.cpp
Firepal/ALVR
834cac75663832638a129a6ba6b2901a7e8dd2ed
[ "MIT" ]
184
2020-12-01T15:02:24.000Z
2022-03-31T06:18:18.000Z
#include "OvrViveTrackerProxy.h" #include "Settings.h" #include "OvrHMD.h" #include <cassert> OvrViveTrackerProxy::OvrViveTrackerProxy(OvrHmd& owner) : m_unObjectId(vr::k_unTrackedDeviceIndexInvalid), m_HMDOwner(&owner) {} vr::DriverPose_t OvrViveTrackerProxy::GetPose() { assert(m_HMDOwner != nullptr); return m_HMDOwner->GetPose(); } vr::EVRInitError OvrViveTrackerProxy::Activate( vr::TrackedDeviceIndex_t unObjectId ) { m_unObjectId = unObjectId; assert(m_unObjectId != vr::k_unTrackedDeviceIndexInvalid); const auto propertyContainer = vr::VRProperties()->TrackedDeviceToPropertyContainer( m_unObjectId ); // Normally a vive tracker emulator would (logically) always set the tracking system to "lighthouse" but in order to do space calibration // with existing tools such as OpenVR Space calibrator and be able to calibrate to/from ALVR HMD (and the proxy tracker) space to/from // a native HMD/tracked device which is already using "lighthouse" as the tracking system the proxy tracker needs to be in a different // tracking system to treat them differently and prevent those tools doing the same space transform to the proxy tracker. vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_TrackingSystemName_String, Settings::Instance().mTrackingSystemName.c_str());//"lighthouse"); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_ModelNumber_String, "Vive Tracker Pro MV"); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_SerialNumber_String, GetSerialNumber()); // Changed vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_RenderModelName_String, "{htc}vr_tracker_vive_1_0"); vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_WillDriftInYaw_Bool, false); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_ManufacturerName_String, "HTC"); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_TrackingFirmwareVersion_String, "1541800000 RUNNER-WATCHMAN$runner-watchman@runner-watchman 2018-01-01 FPGA 512(2.56/0/0) BL 0 VRC 1541800000 Radio 1518800000"); // Changed vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_HardwareRevision_String, "product 128 rev 2.5.6 lot 2000/0/0 0"); // Changed vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_ConnectedWirelessDongle_String, "D0000BE000"); // Changed vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_DeviceIsWireless_Bool, true); vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_DeviceIsCharging_Bool, false); vr::VRProperties()->SetFloatProperty(propertyContainer, vr::Prop_DeviceBatteryPercentage_Float, 1.f); // Always charged vr::HmdMatrix34_t l_transform = { -1.f, 0.f, 0.f, 0.f, 0.f, 0.f, -1.f, 0.f, 0.f, -1.f, 0.f, 0.f }; vr::VRProperties()->SetProperty(propertyContainer, vr::Prop_StatusDisplayTransform_Matrix34, &l_transform, sizeof(vr::HmdMatrix34_t), vr::k_unHmdMatrix34PropertyTag); vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_Firmware_UpdateAvailable_Bool, false); vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_Firmware_ManualUpdate_Bool, false); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_Firmware_ManualUpdateURL_String, "https://developer.valvesoftware.com/wiki/SteamVR/HowTo_Update_Firmware"); vr::VRProperties()->SetUint64Property(propertyContainer, vr::Prop_HardwareRevision_Uint64, 2214720000); // Changed vr::VRProperties()->SetUint64Property(propertyContainer, vr::Prop_FirmwareVersion_Uint64, 1541800000); // Changed vr::VRProperties()->SetUint64Property(propertyContainer, vr::Prop_FPGAVersion_Uint64, 512); // Changed vr::VRProperties()->SetUint64Property(propertyContainer, vr::Prop_VRCVersion_Uint64, 1514800000); // Changed vr::VRProperties()->SetUint64Property(propertyContainer, vr::Prop_RadioVersion_Uint64, 1518800000); // Changed vr::VRProperties()->SetUint64Property(propertyContainer, vr::Prop_DongleVersion_Uint64, 8933539758); // Changed, based on vr::Prop_ConnectedWirelessDongle_String above vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_DeviceProvidesBatteryStatus_Bool, true); vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_DeviceCanPowerOff_Bool, true); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_Firmware_ProgrammingTarget_String, GetSerialNumber()); vr::VRProperties()->SetInt32Property(propertyContainer, vr::Prop_DeviceClass_Int32, vr::TrackedDeviceClass_GenericTracker); vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_Firmware_ForceUpdateRequired_Bool, false); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_ResourceRoot_String, "htc"); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_RegisteredDeviceType_String, "ALVR/tracker/hmd_proxy"); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_InputProfilePath_String, "{htc}/input/vive_tracker_profile.json"); vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_Identifiable_Bool, false); vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_Firmware_RemindUpdate_Bool, false); vr::VRProperties()->SetInt32Property(propertyContainer, vr::Prop_ControllerRoleHint_Int32, vr::TrackedControllerRole_Invalid); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_ControllerType_String, "vive_tracker_waist"); vr::VRProperties()->SetInt32Property(propertyContainer, vr::Prop_ControllerHandSelectionPriority_Int32, -1); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceOff_String, "{htc}/icons/tracker_status_off.png"); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceSearching_String, "{htc}/icons/tracker_status_searching.gif"); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceSearchingAlert_String, "{htc}/icons/tracker_status_searching_alert.gif"); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceReady_String, "{htc}/icons/tracker_status_ready.png"); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceReadyAlert_String, "{htc}/icons/tracker_status_ready_alert.png"); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceNotReady_String, "{htc}/icons/tracker_status_error.png"); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceStandby_String, "{htc}/icons/tracker_status_standby.png"); vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceAlertLow_String, "{htc}/icons/tracker_status_ready_low.png"); vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_HasDisplayComponent_Bool, false); vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_HasCameraComponent_Bool, false); vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_HasDriverDirectModeComponent_Bool, false); vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_HasVirtualDisplayComponent_Bool, false); return vr::VRInitError_None; } void OvrViveTrackerProxy::update() { auto newPose = GetPose(); vr::VRServerDriverHost()->TrackedDevicePoseUpdated(m_unObjectId, newPose, sizeof(vr::DriverPose_t)); }
88.023529
242
0.794306
Firepal
d6e7b4954d0d1c6ed0c89635596a5faa622770b6
341
cpp
C++
demos/processtofile/main.cpp
artoka/libsshqt
5c69fbf478a1514380308e72815dbe02f2b290e6
[ "MIT" ]
6
2015-04-21T07:13:05.000Z
2022-03-08T01:26:49.000Z
demos/processtofile/main.cpp
artoka/libsshqt
5c69fbf478a1514380308e72815dbe02f2b290e6
[ "MIT" ]
null
null
null
demos/processtofile/main.cpp
artoka/libsshqt
5c69fbf478a1514380308e72815dbe02f2b290e6
[ "MIT" ]
4
2017-09-26T20:00:13.000Z
2021-11-10T18:54:02.000Z
#include <QtCore/QCoreApplication> #include <QTimer> #include "processtofile.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); ProcessToFile *processtofile = new ProcessToFile; QTimer::singleShot(0, processtofile, SLOT(processToFile())); int ret = a.exec(); delete processtofile; return ret; }
21.3125
64
0.697947
artoka
d6ee72390b730292076a2f928e2b6f4074bbbc76
39,892
cpp
C++
webkit/WebCore/loader/appcache/ApplicationCacheStorage.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
webkit/WebCore/loader/appcache/ApplicationCacheStorage.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
webkit/WebCore/loader/appcache/ApplicationCacheStorage.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * Copyright (C) 2008, 2009 Apple Inc. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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" #include "ApplicationCacheStorage.h" #if ENABLE(OFFLINE_WEB_APPLICATIONS) #include "ApplicationCache.h" #include "ApplicationCacheHost.h" #include "ApplicationCacheGroup.h" #include "ApplicationCacheResource.h" #include "CString.h" #include "FileSystem.h" #include "KURL.h" #include "SQLiteStatement.h" #include "SQLiteTransaction.h" #include <wtf/StdLibExtras.h> #include <wtf/StringExtras.h> using namespace std; namespace WebCore { template <class T> class StorageIDJournal { public: ~StorageIDJournal() { size_t size = m_records.size(); for (size_t i = 0; i < size; ++i) m_records[i].restore(); } void add(T* resource, unsigned storageID) { m_records.append(Record(resource, storageID)); } void commit() { m_records.clear(); } private: class Record { public: Record() : m_resource(0), m_storageID(0) { } Record(T* resource, unsigned storageID) : m_resource(resource), m_storageID(storageID) { } void restore() { m_resource->setStorageID(m_storageID); } private: T* m_resource; unsigned m_storageID; }; Vector<Record> m_records; }; static unsigned urlHostHash(const KURL& url) { unsigned hostStart = url.hostStart(); unsigned hostEnd = url.hostEnd(); return AlreadyHashed::avoidDeletedValue(StringImpl::computeHash(url.string().characters() + hostStart, hostEnd - hostStart)); } ApplicationCacheGroup* ApplicationCacheStorage::loadCacheGroup(const KURL& manifestURL) { openDatabase(false); if (!m_database.isOpen()) return 0; SQLiteStatement statement(m_database, "SELECT id, manifestURL, newestCache FROM CacheGroups WHERE newestCache IS NOT NULL AND manifestURL=?"); if (statement.prepare() != SQLResultOk) return 0; statement.bindText(1, manifestURL); int result = statement.step(); if (result == SQLResultDone) return 0; if (result != SQLResultRow) { LOG_ERROR("Could not load cache group, error \"%s\"", m_database.lastErrorMsg()); return 0; } unsigned newestCacheStorageID = static_cast<unsigned>(statement.getColumnInt64(2)); RefPtr<ApplicationCache> cache = loadCache(newestCacheStorageID); if (!cache) return 0; ApplicationCacheGroup* group = new ApplicationCacheGroup(manifestURL); group->setStorageID(static_cast<unsigned>(statement.getColumnInt64(0))); group->setNewestCache(cache.release()); return group; } ApplicationCacheGroup* ApplicationCacheStorage::findOrCreateCacheGroup(const KURL& manifestURL) { ASSERT(!manifestURL.hasFragmentIdentifier()); std::pair<CacheGroupMap::iterator, bool> result = m_cachesInMemory.add(manifestURL, 0); if (!result.second) { ASSERT(result.first->second); return result.first->second; } // Look up the group in the database ApplicationCacheGroup* group = loadCacheGroup(manifestURL); // If the group was not found we need to create it if (!group) { group = new ApplicationCacheGroup(manifestURL); m_cacheHostSet.add(urlHostHash(manifestURL)); } result.first->second = group; return group; } void ApplicationCacheStorage::loadManifestHostHashes() { static bool hasLoadedHashes = false; if (hasLoadedHashes) return; // We set this flag to true before the database has been opened // to avoid trying to open the database over and over if it doesn't exist. hasLoadedHashes = true; openDatabase(false); if (!m_database.isOpen()) return; // Fetch the host hashes. SQLiteStatement statement(m_database, "SELECT manifestHostHash FROM CacheGroups"); if (statement.prepare() != SQLResultOk) return; int result; while ((result = statement.step()) == SQLResultRow) m_cacheHostSet.add(static_cast<unsigned>(statement.getColumnInt64(0))); } ApplicationCacheGroup* ApplicationCacheStorage::cacheGroupForURL(const KURL& url) { ASSERT(!url.hasFragmentIdentifier()); loadManifestHostHashes(); // Hash the host name and see if there's a manifest with the same host. if (!m_cacheHostSet.contains(urlHostHash(url))) return 0; // Check if a cache already exists in memory. CacheGroupMap::const_iterator end = m_cachesInMemory.end(); for (CacheGroupMap::const_iterator it = m_cachesInMemory.begin(); it != end; ++it) { ApplicationCacheGroup* group = it->second; ASSERT(!group->isObsolete()); if (!protocolHostAndPortAreEqual(url, group->manifestURL())) continue; if (ApplicationCache* cache = group->newestCache()) { ApplicationCacheResource* resource = cache->resourceForURL(url); if (!resource) continue; if (resource->type() & ApplicationCacheResource::Foreign) continue; return group; } } if (!m_database.isOpen()) return 0; // Check the database. Look for all cache groups with a newest cache. SQLiteStatement statement(m_database, "SELECT id, manifestURL, newestCache FROM CacheGroups WHERE newestCache IS NOT NULL"); if (statement.prepare() != SQLResultOk) return 0; int result; while ((result = statement.step()) == SQLResultRow) { KURL manifestURL = KURL(ParsedURLString, statement.getColumnText(1)); if (m_cachesInMemory.contains(manifestURL)) continue; if (!protocolHostAndPortAreEqual(url, manifestURL)) continue; // We found a cache group that matches. Now check if the newest cache has a resource with // a matching URL. unsigned newestCacheID = static_cast<unsigned>(statement.getColumnInt64(2)); RefPtr<ApplicationCache> cache = loadCache(newestCacheID); if (!cache) continue; ApplicationCacheResource* resource = cache->resourceForURL(url); if (!resource) continue; if (resource->type() & ApplicationCacheResource::Foreign) continue; ApplicationCacheGroup* group = new ApplicationCacheGroup(manifestURL); group->setStorageID(static_cast<unsigned>(statement.getColumnInt64(0))); group->setNewestCache(cache.release()); m_cachesInMemory.set(group->manifestURL(), group); return group; } if (result != SQLResultDone) LOG_ERROR("Could not load cache group, error \"%s\"", m_database.lastErrorMsg()); return 0; } ApplicationCacheGroup* ApplicationCacheStorage::fallbackCacheGroupForURL(const KURL& url) { ASSERT(!url.hasFragmentIdentifier()); // Check if an appropriate cache already exists in memory. CacheGroupMap::const_iterator end = m_cachesInMemory.end(); for (CacheGroupMap::const_iterator it = m_cachesInMemory.begin(); it != end; ++it) { ApplicationCacheGroup* group = it->second; ASSERT(!group->isObsolete()); if (ApplicationCache* cache = group->newestCache()) { KURL fallbackURL; if (!cache->urlMatchesFallbackNamespace(url, &fallbackURL)) continue; if (cache->resourceForURL(fallbackURL)->type() & ApplicationCacheResource::Foreign) continue; return group; } } if (!m_database.isOpen()) return 0; // Check the database. Look for all cache groups with a newest cache. SQLiteStatement statement(m_database, "SELECT id, manifestURL, newestCache FROM CacheGroups WHERE newestCache IS NOT NULL"); if (statement.prepare() != SQLResultOk) return 0; int result; while ((result = statement.step()) == SQLResultRow) { KURL manifestURL = KURL(ParsedURLString, statement.getColumnText(1)); if (m_cachesInMemory.contains(manifestURL)) continue; // Fallback namespaces always have the same origin as manifest URL, so we can avoid loading caches that cannot match. if (!protocolHostAndPortAreEqual(url, manifestURL)) continue; // We found a cache group that matches. Now check if the newest cache has a resource with // a matching fallback namespace. unsigned newestCacheID = static_cast<unsigned>(statement.getColumnInt64(2)); RefPtr<ApplicationCache> cache = loadCache(newestCacheID); KURL fallbackURL; if (!cache->urlMatchesFallbackNamespace(url, &fallbackURL)) continue; if (cache->resourceForURL(fallbackURL)->type() & ApplicationCacheResource::Foreign) continue; ApplicationCacheGroup* group = new ApplicationCacheGroup(manifestURL); group->setStorageID(static_cast<unsigned>(statement.getColumnInt64(0))); group->setNewestCache(cache.release()); m_cachesInMemory.set(group->manifestURL(), group); return group; } if (result != SQLResultDone) LOG_ERROR("Could not load cache group, error \"%s\"", m_database.lastErrorMsg()); return 0; } void ApplicationCacheStorage::cacheGroupDestroyed(ApplicationCacheGroup* group) { if (group->isObsolete()) { ASSERT(!group->storageID()); ASSERT(m_cachesInMemory.get(group->manifestURL()) != group); return; } ASSERT(m_cachesInMemory.get(group->manifestURL()) == group); m_cachesInMemory.remove(group->manifestURL()); // If the cache group is half-created, we don't want it in the saved set (as it is not stored in database). if (!group->storageID()) m_cacheHostSet.remove(urlHostHash(group->manifestURL())); } void ApplicationCacheStorage::cacheGroupMadeObsolete(ApplicationCacheGroup* group) { ASSERT(m_cachesInMemory.get(group->manifestURL()) == group); ASSERT(m_cacheHostSet.contains(urlHostHash(group->manifestURL()))); if (ApplicationCache* newestCache = group->newestCache()) remove(newestCache); m_cachesInMemory.remove(group->manifestURL()); m_cacheHostSet.remove(urlHostHash(group->manifestURL())); } void ApplicationCacheStorage::setCacheDirectory(const String& cacheDirectory) { ASSERT(m_cacheDirectory.isNull()); ASSERT(!cacheDirectory.isNull()); m_cacheDirectory = cacheDirectory; } const String& ApplicationCacheStorage::cacheDirectory() const { return m_cacheDirectory; } void ApplicationCacheStorage::setMaximumSize(int64_t size) { m_maximumSize = size; } int64_t ApplicationCacheStorage::maximumSize() const { return m_maximumSize; } bool ApplicationCacheStorage::isMaximumSizeReached() const { return m_isMaximumSizeReached; } int64_t ApplicationCacheStorage::spaceNeeded(int64_t cacheToSave) { int64_t spaceNeeded = 0; long long fileSize = 0; if (!getFileSize(m_cacheFile, fileSize)) return 0; int64_t currentSize = fileSize; // Determine the amount of free space we have available. int64_t totalAvailableSize = 0; if (m_maximumSize < currentSize) { // The max size is smaller than the actual size of the app cache file. // This can happen if the client previously imposed a larger max size // value and the app cache file has already grown beyond the current // max size value. // The amount of free space is just the amount of free space inside // the database file. Note that this is always 0 if SQLite is compiled // with AUTO_VACUUM = 1. totalAvailableSize = m_database.freeSpaceSize(); } else { // The max size is the same or larger than the current size. // The amount of free space available is the amount of free space // inside the database file plus the amount we can grow until we hit // the max size. totalAvailableSize = (m_maximumSize - currentSize) + m_database.freeSpaceSize(); } // The space needed to be freed in order to accomodate the failed cache is // the size of the failed cache minus any already available free space. spaceNeeded = cacheToSave - totalAvailableSize; // The space needed value must be positive (or else the total already // available free space would be larger than the size of the failed cache and // saving of the cache should have never failed). ASSERT(spaceNeeded); return spaceNeeded; } bool ApplicationCacheStorage::executeSQLCommand(const String& sql) { ASSERT(m_database.isOpen()); bool result = m_database.executeCommand(sql); if (!result) LOG_ERROR("Application Cache Storage: failed to execute statement \"%s\" error \"%s\"", sql.utf8().data(), m_database.lastErrorMsg()); return result; } static const int schemaVersion = 5; void ApplicationCacheStorage::verifySchemaVersion() { int version = SQLiteStatement(m_database, "PRAGMA user_version").getColumnInt(0); if (version == schemaVersion) return; m_database.clearAllTables(); // Update user version. SQLiteTransaction setDatabaseVersion(m_database); setDatabaseVersion.begin(); char userVersionSQL[32]; int unusedNumBytes = snprintf(userVersionSQL, sizeof(userVersionSQL), "PRAGMA user_version=%d", schemaVersion); ASSERT_UNUSED(unusedNumBytes, static_cast<int>(sizeof(userVersionSQL)) >= unusedNumBytes); SQLiteStatement statement(m_database, userVersionSQL); if (statement.prepare() != SQLResultOk) return; executeStatement(statement); setDatabaseVersion.commit(); } void ApplicationCacheStorage::openDatabase(bool createIfDoesNotExist) { if (m_database.isOpen()) return; // The cache directory should never be null, but if it for some weird reason is we bail out. if (m_cacheDirectory.isNull()) return; m_cacheFile = pathByAppendingComponent(m_cacheDirectory, "ApplicationCache.db"); if (!createIfDoesNotExist && !fileExists(m_cacheFile)) return; makeAllDirectories(m_cacheDirectory); m_database.open(m_cacheFile); if (!m_database.isOpen()) return; verifySchemaVersion(); // Create tables executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheGroups (id INTEGER PRIMARY KEY AUTOINCREMENT, " "manifestHostHash INTEGER NOT NULL ON CONFLICT FAIL, manifestURL TEXT UNIQUE ON CONFLICT FAIL, newestCache INTEGER)"); executeSQLCommand("CREATE TABLE IF NOT EXISTS Caches (id INTEGER PRIMARY KEY AUTOINCREMENT, cacheGroup INTEGER, size INTEGER)"); executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheWhitelistURLs (url TEXT NOT NULL ON CONFLICT FAIL, cache INTEGER NOT NULL ON CONFLICT FAIL)"); executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheAllowsAllNetworkRequests (wildcard INTEGER NOT NULL ON CONFLICT FAIL, cache INTEGER NOT NULL ON CONFLICT FAIL)"); executeSQLCommand("CREATE TABLE IF NOT EXISTS FallbackURLs (namespace TEXT NOT NULL ON CONFLICT FAIL, fallbackURL TEXT NOT NULL ON CONFLICT FAIL, " "cache INTEGER NOT NULL ON CONFLICT FAIL)"); executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheEntries (cache INTEGER NOT NULL ON CONFLICT FAIL, type INTEGER, resource INTEGER NOT NULL)"); executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheResources (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL ON CONFLICT FAIL, " "statusCode INTEGER NOT NULL, responseURL TEXT NOT NULL, mimeType TEXT, textEncodingName TEXT, headers TEXT, data INTEGER NOT NULL ON CONFLICT FAIL)"); executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheResourceData (id INTEGER PRIMARY KEY AUTOINCREMENT, data BLOB)"); // When a cache is deleted, all its entries and its whitelist should be deleted. executeSQLCommand("CREATE TRIGGER IF NOT EXISTS CacheDeleted AFTER DELETE ON Caches" " FOR EACH ROW BEGIN" " DELETE FROM CacheEntries WHERE cache = OLD.id;" " DELETE FROM CacheWhitelistURLs WHERE cache = OLD.id;" " DELETE FROM CacheAllowsAllNetworkRequests WHERE cache = OLD.id;" " DELETE FROM FallbackURLs WHERE cache = OLD.id;" " END"); // When a cache entry is deleted, its resource should also be deleted. executeSQLCommand("CREATE TRIGGER IF NOT EXISTS CacheEntryDeleted AFTER DELETE ON CacheEntries" " FOR EACH ROW BEGIN" " DELETE FROM CacheResources WHERE id = OLD.resource;" " END"); // When a cache resource is deleted, its data blob should also be deleted. executeSQLCommand("CREATE TRIGGER IF NOT EXISTS CacheResourceDeleted AFTER DELETE ON CacheResources" " FOR EACH ROW BEGIN" " DELETE FROM CacheResourceData WHERE id = OLD.data;" " END"); } bool ApplicationCacheStorage::executeStatement(SQLiteStatement& statement) { bool result = statement.executeCommand(); if (!result) LOG_ERROR("Application Cache Storage: failed to execute statement \"%s\" error \"%s\"", statement.query().utf8().data(), m_database.lastErrorMsg()); return result; } bool ApplicationCacheStorage::store(ApplicationCacheGroup* group, GroupStorageIDJournal* journal) { ASSERT(group->storageID() == 0); ASSERT(journal); SQLiteStatement statement(m_database, "INSERT INTO CacheGroups (manifestHostHash, manifestURL) VALUES (?, ?)"); if (statement.prepare() != SQLResultOk) return false; statement.bindInt64(1, urlHostHash(group->manifestURL())); statement.bindText(2, group->manifestURL()); if (!executeStatement(statement)) return false; group->setStorageID(static_cast<unsigned>(m_database.lastInsertRowID())); journal->add(group, 0); return true; } bool ApplicationCacheStorage::store(ApplicationCache* cache, ResourceStorageIDJournal* storageIDJournal) { ASSERT(cache->storageID() == 0); ASSERT(cache->group()->storageID() != 0); ASSERT(storageIDJournal); SQLiteStatement statement(m_database, "INSERT INTO Caches (cacheGroup, size) VALUES (?, ?)"); if (statement.prepare() != SQLResultOk) return false; statement.bindInt64(1, cache->group()->storageID()); statement.bindInt64(2, cache->estimatedSizeInStorage()); if (!executeStatement(statement)) return false; unsigned cacheStorageID = static_cast<unsigned>(m_database.lastInsertRowID()); // Store all resources { ApplicationCache::ResourceMap::const_iterator end = cache->end(); for (ApplicationCache::ResourceMap::const_iterator it = cache->begin(); it != end; ++it) { unsigned oldStorageID = it->second->storageID(); if (!store(it->second.get(), cacheStorageID)) return false; // Storing the resource succeeded. Log its old storageID in case // it needs to be restored later. storageIDJournal->add(it->second.get(), oldStorageID); } } // Store the online whitelist const Vector<KURL>& onlineWhitelist = cache->onlineWhitelist(); { size_t whitelistSize = onlineWhitelist.size(); for (size_t i = 0; i < whitelistSize; ++i) { SQLiteStatement statement(m_database, "INSERT INTO CacheWhitelistURLs (url, cache) VALUES (?, ?)"); statement.prepare(); statement.bindText(1, onlineWhitelist[i]); statement.bindInt64(2, cacheStorageID); if (!executeStatement(statement)) return false; } } // Store online whitelist wildcard flag. { SQLiteStatement statement(m_database, "INSERT INTO CacheAllowsAllNetworkRequests (wildcard, cache) VALUES (?, ?)"); statement.prepare(); statement.bindInt64(1, cache->allowsAllNetworkRequests()); statement.bindInt64(2, cacheStorageID); if (!executeStatement(statement)) return false; } // Store fallback URLs. const FallbackURLVector& fallbackURLs = cache->fallbackURLs(); { size_t fallbackCount = fallbackURLs.size(); for (size_t i = 0; i < fallbackCount; ++i) { SQLiteStatement statement(m_database, "INSERT INTO FallbackURLs (namespace, fallbackURL, cache) VALUES (?, ?, ?)"); statement.prepare(); statement.bindText(1, fallbackURLs[i].first); statement.bindText(2, fallbackURLs[i].second); statement.bindInt64(3, cacheStorageID); if (!executeStatement(statement)) return false; } } cache->setStorageID(cacheStorageID); return true; } bool ApplicationCacheStorage::store(ApplicationCacheResource* resource, unsigned cacheStorageID) { ASSERT(cacheStorageID); ASSERT(!resource->storageID()); openDatabase(true); // First, insert the data SQLiteStatement dataStatement(m_database, "INSERT INTO CacheResourceData (data) VALUES (?)"); if (dataStatement.prepare() != SQLResultOk) return false; if (resource->data()->size()) dataStatement.bindBlob(1, resource->data()->data(), resource->data()->size()); if (!dataStatement.executeCommand()) return false; unsigned dataId = static_cast<unsigned>(m_database.lastInsertRowID()); // Then, insert the resource // Serialize the headers Vector<UChar> stringBuilder; HTTPHeaderMap::const_iterator end = resource->response().httpHeaderFields().end(); for (HTTPHeaderMap::const_iterator it = resource->response().httpHeaderFields().begin(); it!= end; ++it) { stringBuilder.append(it->first.characters(), it->first.length()); stringBuilder.append((UChar)':'); stringBuilder.append(it->second.characters(), it->second.length()); stringBuilder.append((UChar)'\n'); } String headers = String::adopt(stringBuilder); SQLiteStatement resourceStatement(m_database, "INSERT INTO CacheResources (url, statusCode, responseURL, headers, data, mimeType, textEncodingName) VALUES (?, ?, ?, ?, ?, ?, ?)"); if (resourceStatement.prepare() != SQLResultOk) return false; // The same ApplicationCacheResource are used in ApplicationCacheResource::size() // to calculate the approximate size of an ApplicationCacheResource object. If // you change the code below, please also change ApplicationCacheResource::size(). resourceStatement.bindText(1, resource->url()); resourceStatement.bindInt64(2, resource->response().httpStatusCode()); resourceStatement.bindText(3, resource->response().url()); resourceStatement.bindText(4, headers); resourceStatement.bindInt64(5, dataId); resourceStatement.bindText(6, resource->response().mimeType()); resourceStatement.bindText(7, resource->response().textEncodingName()); if (!executeStatement(resourceStatement)) return false; unsigned resourceId = static_cast<unsigned>(m_database.lastInsertRowID()); // Finally, insert the cache entry SQLiteStatement entryStatement(m_database, "INSERT INTO CacheEntries (cache, type, resource) VALUES (?, ?, ?)"); if (entryStatement.prepare() != SQLResultOk) return false; entryStatement.bindInt64(1, cacheStorageID); entryStatement.bindInt64(2, resource->type()); entryStatement.bindInt64(3, resourceId); if (!executeStatement(entryStatement)) return false; resource->setStorageID(resourceId); return true; } bool ApplicationCacheStorage::storeUpdatedType(ApplicationCacheResource* resource, ApplicationCache* cache) { ASSERT_UNUSED(cache, cache->storageID()); ASSERT(resource->storageID()); // First, insert the data SQLiteStatement entryStatement(m_database, "UPDATE CacheEntries SET type=? WHERE resource=?"); if (entryStatement.prepare() != SQLResultOk) return false; entryStatement.bindInt64(1, resource->type()); entryStatement.bindInt64(2, resource->storageID()); return executeStatement(entryStatement); } bool ApplicationCacheStorage::store(ApplicationCacheResource* resource, ApplicationCache* cache) { ASSERT(cache->storageID()); openDatabase(true); m_isMaximumSizeReached = false; m_database.setMaximumSize(m_maximumSize); SQLiteTransaction storeResourceTransaction(m_database); storeResourceTransaction.begin(); if (!store(resource, cache->storageID())) { checkForMaxSizeReached(); return false; } // A resource was added to the cache. Update the total data size for the cache. SQLiteStatement sizeUpdateStatement(m_database, "UPDATE Caches SET size=size+? WHERE id=?"); if (sizeUpdateStatement.prepare() != SQLResultOk) return false; sizeUpdateStatement.bindInt64(1, resource->estimatedSizeInStorage()); sizeUpdateStatement.bindInt64(2, cache->storageID()); if (!executeStatement(sizeUpdateStatement)) return false; storeResourceTransaction.commit(); return true; } bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup* group) { openDatabase(true); m_isMaximumSizeReached = false; m_database.setMaximumSize(m_maximumSize); SQLiteTransaction storeCacheTransaction(m_database); storeCacheTransaction.begin(); GroupStorageIDJournal groupStorageIDJournal; if (!group->storageID()) { // Store the group if (!store(group, &groupStorageIDJournal)) { checkForMaxSizeReached(); return false; } } ASSERT(group->newestCache()); ASSERT(!group->isObsolete()); ASSERT(!group->newestCache()->storageID()); // Log the storageID changes to the in-memory resource objects. The journal // object will roll them back automatically in case a database operation // fails and this method returns early. ResourceStorageIDJournal resourceStorageIDJournal; // Store the newest cache if (!store(group->newestCache(), &resourceStorageIDJournal)) { checkForMaxSizeReached(); return false; } // Update the newest cache in the group. SQLiteStatement statement(m_database, "UPDATE CacheGroups SET newestCache=? WHERE id=?"); if (statement.prepare() != SQLResultOk) return false; statement.bindInt64(1, group->newestCache()->storageID()); statement.bindInt64(2, group->storageID()); if (!executeStatement(statement)) return false; groupStorageIDJournal.commit(); resourceStorageIDJournal.commit(); storeCacheTransaction.commit(); return true; } static inline void parseHeader(const UChar* header, size_t headerLength, ResourceResponse& response) { int pos = find(header, headerLength, ':'); ASSERT(pos != -1); AtomicString headerName = AtomicString(header, pos); String headerValue = String(header + pos + 1, headerLength - pos - 1); response.setHTTPHeaderField(headerName, headerValue); } static inline void parseHeaders(const String& headers, ResourceResponse& response) { int startPos = 0; int endPos; while ((endPos = headers.find('\n', startPos)) != -1) { ASSERT(startPos != endPos); parseHeader(headers.characters() + startPos, endPos - startPos, response); startPos = endPos + 1; } if (startPos != static_cast<int>(headers.length())) parseHeader(headers.characters(), headers.length(), response); } PassRefPtr<ApplicationCache> ApplicationCacheStorage::loadCache(unsigned storageID) { SQLiteStatement cacheStatement(m_database, "SELECT url, type, mimeType, textEncodingName, headers, CacheResourceData.data FROM CacheEntries INNER JOIN CacheResources ON CacheEntries.resource=CacheResources.id " "INNER JOIN CacheResourceData ON CacheResourceData.id=CacheResources.data WHERE CacheEntries.cache=?"); if (cacheStatement.prepare() != SQLResultOk) { LOG_ERROR("Could not prepare cache statement, error \"%s\"", m_database.lastErrorMsg()); return 0; } cacheStatement.bindInt64(1, storageID); RefPtr<ApplicationCache> cache = ApplicationCache::create(); int result; while ((result = cacheStatement.step()) == SQLResultRow) { KURL url(ParsedURLString, cacheStatement.getColumnText(0)); unsigned type = static_cast<unsigned>(cacheStatement.getColumnInt64(1)); Vector<char> blob; cacheStatement.getColumnBlobAsVector(5, blob); RefPtr<SharedBuffer> data = SharedBuffer::adoptVector(blob); String mimeType = cacheStatement.getColumnText(2); String textEncodingName = cacheStatement.getColumnText(3); ResourceResponse response(url, mimeType, data->size(), textEncodingName, ""); String headers = cacheStatement.getColumnText(4); parseHeaders(headers, response); RefPtr<ApplicationCacheResource> resource = ApplicationCacheResource::create(url, response, type, data.release()); if (type & ApplicationCacheResource::Manifest) cache->setManifestResource(resource.release()); else cache->addResource(resource.release()); } if (result != SQLResultDone) LOG_ERROR("Could not load cache resources, error \"%s\"", m_database.lastErrorMsg()); // Load the online whitelist SQLiteStatement whitelistStatement(m_database, "SELECT url FROM CacheWhitelistURLs WHERE cache=?"); if (whitelistStatement.prepare() != SQLResultOk) return 0; whitelistStatement.bindInt64(1, storageID); Vector<KURL> whitelist; while ((result = whitelistStatement.step()) == SQLResultRow) whitelist.append(KURL(ParsedURLString, whitelistStatement.getColumnText(0))); if (result != SQLResultDone) LOG_ERROR("Could not load cache online whitelist, error \"%s\"", m_database.lastErrorMsg()); cache->setOnlineWhitelist(whitelist); // Load online whitelist wildcard flag. SQLiteStatement whitelistWildcardStatement(m_database, "SELECT wildcard FROM CacheAllowsAllNetworkRequests WHERE cache=?"); if (whitelistWildcardStatement.prepare() != SQLResultOk) return 0; whitelistWildcardStatement.bindInt64(1, storageID); result = whitelistWildcardStatement.step(); if (result != SQLResultRow) LOG_ERROR("Could not load cache online whitelist wildcard flag, error \"%s\"", m_database.lastErrorMsg()); cache->setAllowsAllNetworkRequests(whitelistWildcardStatement.getColumnInt64(0)); if (whitelistWildcardStatement.step() != SQLResultDone) LOG_ERROR("Too many rows for online whitelist wildcard flag"); // Load fallback URLs. SQLiteStatement fallbackStatement(m_database, "SELECT namespace, fallbackURL FROM FallbackURLs WHERE cache=?"); if (fallbackStatement.prepare() != SQLResultOk) return 0; fallbackStatement.bindInt64(1, storageID); FallbackURLVector fallbackURLs; while ((result = fallbackStatement.step()) == SQLResultRow) fallbackURLs.append(make_pair(KURL(ParsedURLString, fallbackStatement.getColumnText(0)), KURL(ParsedURLString, fallbackStatement.getColumnText(1)))); if (result != SQLResultDone) LOG_ERROR("Could not load fallback URLs, error \"%s\"", m_database.lastErrorMsg()); cache->setFallbackURLs(fallbackURLs); cache->setStorageID(storageID); return cache.release(); } void ApplicationCacheStorage::remove(ApplicationCache* cache) { if (!cache->storageID()) return; openDatabase(false); if (!m_database.isOpen()) return; ASSERT(cache->group()); ASSERT(cache->group()->storageID()); // All associated data will be deleted by database triggers. SQLiteStatement statement(m_database, "DELETE FROM Caches WHERE id=?"); if (statement.prepare() != SQLResultOk) return; statement.bindInt64(1, cache->storageID()); executeStatement(statement); cache->clearStorageID(); if (cache->group()->newestCache() == cache) { // Currently, there are no triggers on the cache group, which is why the cache had to be removed separately above. SQLiteStatement groupStatement(m_database, "DELETE FROM CacheGroups WHERE id=?"); if (groupStatement.prepare() != SQLResultOk) return; groupStatement.bindInt64(1, cache->group()->storageID()); executeStatement(groupStatement); cache->group()->clearStorageID(); } } void ApplicationCacheStorage::empty() { openDatabase(false); if (!m_database.isOpen()) return; // Clear cache groups, caches and cache resources. executeSQLCommand("DELETE FROM CacheGroups"); executeSQLCommand("DELETE FROM Caches"); // Clear the storage IDs for the caches in memory. // The caches will still work, but cached resources will not be saved to disk // until a cache update process has been initiated. CacheGroupMap::const_iterator end = m_cachesInMemory.end(); for (CacheGroupMap::const_iterator it = m_cachesInMemory.begin(); it != end; ++it) it->second->clearStorageID(); } bool ApplicationCacheStorage::storeCopyOfCache(const String& cacheDirectory, ApplicationCacheHost* cacheHost) { ApplicationCache* cache = cacheHost->applicationCache(); if (!cache) return true; // Create a new cache. RefPtr<ApplicationCache> cacheCopy = ApplicationCache::create(); cacheCopy->setOnlineWhitelist(cache->onlineWhitelist()); cacheCopy->setFallbackURLs(cache->fallbackURLs()); // Traverse the cache and add copies of all resources. ApplicationCache::ResourceMap::const_iterator end = cache->end(); for (ApplicationCache::ResourceMap::const_iterator it = cache->begin(); it != end; ++it) { ApplicationCacheResource* resource = it->second.get(); RefPtr<ApplicationCacheResource> resourceCopy = ApplicationCacheResource::create(resource->url(), resource->response(), resource->type(), resource->data()); cacheCopy->addResource(resourceCopy.release()); } // Now create a new cache group. OwnPtr<ApplicationCacheGroup> groupCopy(new ApplicationCacheGroup(cache->group()->manifestURL(), true)); groupCopy->setNewestCache(cacheCopy); ApplicationCacheStorage copyStorage; copyStorage.setCacheDirectory(cacheDirectory); // Empty the cache in case something was there before. copyStorage.empty(); return copyStorage.storeNewestCache(groupCopy.get()); } bool ApplicationCacheStorage::manifestURLs(Vector<KURL>* urls) { ASSERT(urls); openDatabase(false); if (!m_database.isOpen()) return false; SQLiteStatement selectURLs(m_database, "SELECT manifestURL FROM CacheGroups"); if (selectURLs.prepare() != SQLResultOk) return false; while (selectURLs.step() == SQLResultRow) urls->append(KURL(ParsedURLString, selectURLs.getColumnText(0))); return true; } bool ApplicationCacheStorage::cacheGroupSize(const String& manifestURL, int64_t* size) { ASSERT(size); openDatabase(false); if (!m_database.isOpen()) return false; SQLiteStatement statement(m_database, "SELECT sum(Caches.size) FROM Caches INNER JOIN CacheGroups ON Caches.cacheGroup=CacheGroups.id WHERE CacheGroups.manifestURL=?"); if (statement.prepare() != SQLResultOk) return false; statement.bindText(1, manifestURL); int result = statement.step(); if (result == SQLResultDone) return false; if (result != SQLResultRow) { LOG_ERROR("Could not get the size of the cache group, error \"%s\"", m_database.lastErrorMsg()); return false; } *size = statement.getColumnInt64(0); return true; } bool ApplicationCacheStorage::deleteCacheGroup(const String& manifestURL) { SQLiteTransaction deleteTransaction(m_database); // Check to see if the group is in memory. ApplicationCacheGroup* group = m_cachesInMemory.get(manifestURL); if (group) cacheGroupMadeObsolete(group); else { // The cache group is not in memory, so remove it from the disk. openDatabase(false); if (!m_database.isOpen()) return false; SQLiteStatement idStatement(m_database, "SELECT id FROM CacheGroups WHERE manifestURL=?"); if (idStatement.prepare() != SQLResultOk) return false; idStatement.bindText(1, manifestURL); int result = idStatement.step(); if (result == SQLResultDone) return false; if (result != SQLResultRow) { LOG_ERROR("Could not load cache group id, error \"%s\"", m_database.lastErrorMsg()); return false; } int64_t groupId = idStatement.getColumnInt64(0); SQLiteStatement cacheStatement(m_database, "DELETE FROM Caches WHERE cacheGroup=?"); if (cacheStatement.prepare() != SQLResultOk) return false; SQLiteStatement groupStatement(m_database, "DELETE FROM CacheGroups WHERE id=?"); if (groupStatement.prepare() != SQLResultOk) return false; cacheStatement.bindInt64(1, groupId); executeStatement(cacheStatement); groupStatement.bindInt64(1, groupId); executeStatement(groupStatement); } deleteTransaction.commit(); return true; } void ApplicationCacheStorage::vacuumDatabaseFile() { openDatabase(false); if (!m_database.isOpen()) return; m_database.runVacuumCommand(); } void ApplicationCacheStorage::checkForMaxSizeReached() { if (m_database.lastError() == SQLResultFull) m_isMaximumSizeReached = true; } ApplicationCacheStorage::ApplicationCacheStorage() : m_maximumSize(INT_MAX) , m_isMaximumSizeReached(false) { } ApplicationCacheStorage& cacheStorage() { DEFINE_STATIC_LOCAL(ApplicationCacheStorage, storage, ()); return storage; } } // namespace WebCore #endif // ENABLE(OFFLINE_WEB_APPLICATIONS)
35.333924
202
0.678382
s1rcheese
d6f1e2628fa53a0efacbe63f0d9860ddb47dc44f
36,248
hpp
C++
lisp/c++/tealang.hpp
Teaonly/tealang
a83e2feeb0331768a6c396930f4fcb10cccd6f85
[ "MIT" ]
2
2019-09-26T02:43:35.000Z
2019-10-09T13:25:42.000Z
lisp/c++/tealang.hpp
Teaonly/tealang
a83e2feeb0331768a6c396930f4fcb10cccd6f85
[ "MIT" ]
null
null
null
lisp/c++/tealang.hpp
Teaonly/tealang
a83e2feeb0331768a6c396930f4fcb10cccd6f85
[ "MIT" ]
null
null
null
#pragma once #include <assert.h> #include <string> #include <memory> #include <list> #include <vector> #include <map> #include <iterator> #include <iostream> #include <sstream> namespace tea { using namespace std; struct _TeaExtern {}; typedef struct _TeaExtern TeaExtern; struct TeaEnvironment; struct TeaObject; struct TeaResult; typedef shared_ptr<TeaObject> tobject; typedef shared_ptr<TeaEnvironment> tenv; typedef TeaResult (*TeaFunc) (vector<tobject> &args, tenv &env); struct TeaLambda { vector<tobject> head; tobject body; shared_ptr<map<string, tobject>> closure; TeaLambda() { } }; struct TeaObject { enum TeaType { T_NULL, T_INT, T_FLOAT, T_BOOL, T_PATTERN, T_LIST, T_MAP, T_EXT, T_SYMBOL, T_LAMBDA, T_FUNC, }; const TeaType type; // user values int64_t v_int; float v_float; bool v_bool; const string v_string; const shared_ptr<vector<tobject>> v_list; const shared_ptr<map<string, tobject>> v_map; const shared_ptr<TeaExtern> v_ext; // internal values const shared_ptr<TeaLambda> v_lambda; TeaFunc v_func; TeaObject():type(T_NULL) {} TeaObject(int64_t value):type(T_INT) {v_int = value;} TeaObject(float value):type(T_FLOAT) {v_float = value;} TeaObject(bool value):type(T_BOOL), v_bool(value) {} TeaObject(const string& value):type(T_PATTERN), v_string(value) {} TeaObject(shared_ptr<vector<tobject>> value):type(T_LIST), v_list(value) {} TeaObject(shared_ptr<map<string, tobject>> value):type(T_MAP), v_map(value) {} TeaObject(shared_ptr<TeaExtern> value):type(T_EXT), v_ext(value) {} TeaObject(shared_ptr<TeaLambda> value):type(T_LAMBDA), v_lambda(value) {} TeaObject(TeaFunc value):type(T_FUNC) {v_func = value;} TeaObject(TeaType t, const string& symbol):type(T_SYMBOL), v_string(symbol) { assert(t == T_SYMBOL); } string to_string() { stringstream ss; if (type == T_NULL) { return "(nil)"; } if (type == T_INT) { ss << v_int; } if (type == T_FLOAT) { ss << v_float; } if (type == T_BOOL) { ss << v_bool; } if (type == T_PATTERN) { ss << "@" << v_string; } if (type == T_EXT) { ss << "(extern)"; } if (type == T_LIST) { ss << "(list with " << v_list->size() << " items)"; } if (type == T_MAP) { ss << "(map with " << v_map->size() << " items)"; } if (type == T_SYMBOL) { ss << v_string; } if (type == T_FUNC) { ss << "(func)"; } if (type == T_LAMBDA) { ss << "(lambda)"; } return ss.str(); } static tobject build(const TeaObject& obj) { return std::make_shared<TeaObject>(obj); } }; const auto tea_null = TeaObject::build(TeaObject()); const auto tea_true = TeaObject::build(TeaObject(true)); const auto tea_false = TeaObject::build(TeaObject(false)); struct TeaEnvironment { shared_ptr<map<string, tobject>> global; shared_ptr<map<string, tobject>> closure; shared_ptr<map<string, tobject>> data; // global enviroment TeaEnvironment() { data = make_shared<map<string, tobject>>(); } // new env for lambda TeaEnvironment(tenv& out_env, shared_ptr<map<string, tobject>> lambda_closue) { if (out_env->is_global()) { global = out_env->data; } else { global = out_env->global; } closure = lambda_closue; data = make_shared<map<string, tobject>>(); } bool is_global() { if (global == nullptr) { return true; } return false; } void set(const string& key, tobject obj) { (*data)[key] = obj; } tobject get(const string& key) { auto query = data->find(key); if (query != data->end()) { return query->second; } if (closure != nullptr) { auto query = closure->find(key); if (query != closure->end() ) { return query->second; } } if (global != nullptr) { auto query = global->find(key); if (query != global->end() ) { return query->second; } } return tea_null; } }; struct TeaResult { vector<string> trace;; tobject result; bool is_error() { if (trace.size() == 0) { return false; } return true; } bool is_ok() { return !is_error(); } TeaResult(tobject obj) { result = obj; } TeaResult(string err_message) { trace.push_back(err_message); } TeaResult(TeaResult& r, string& err_message) { trace = r.trace; trace.push_back(err_message); } }; struct TeaLang { private: // main functions static void init(shared_ptr<map<string, tobject>> data_) { map<string, tobject>& data(*data_); data["+"] = build_fobj(TeaLang::add); data["-"] = build_fobj(TeaLang::sub); data["*"] = build_fobj(TeaLang::mul); data["/"] = build_fobj(TeaLang::div); data["%"] = build_fobj(TeaLang::mod); data["++"] = build_fobj(TeaLang::inc); data["--"] = build_fobj(TeaLang::dec); data[">"] = build_fobj(TeaLang::more); data["<"] = build_fobj(TeaLang::less); data[">="] = build_fobj(TeaLang::moreeq); data["<="] = build_fobj(TeaLang::lesseq); data["=="] = build_fobj(TeaLang::eqeq); data["!"] = build_fobj(TeaLang::notnot); data["size"] = build_fobj(TeaLang::size); data["push"] = build_fobj(TeaLang::push); data["pop"] = build_fobj(TeaLang::pop); data["nth"] = build_fobj(TeaLang::nth); data["set"] = build_fobj(TeaLang::set); data["has"] = build_fobj(TeaLang::has); data["rm"] = build_fobj(TeaLang::rm); } static tobject build_fobj(TeaFunc f) { return TeaObject::build(f); } // math static TeaResult add(vector<tobject> &args, tenv& env) { if (args.size() == 0) { return TeaResult("+ func synatax error, need more items"); } if (args[0]->type == TeaObject::T_INT) { int64_t sum = 0; for (size_t i = 0; i < args.size(); i++) { if ( args[i]->type != TeaObject::T_INT) { return TeaResult("+ func synatax error, only support int/float"); } sum += args[i]->v_int; } return TeaObject::build(sum); } if (args[0]->type == TeaObject::T_FLOAT) { float sum = 0.0; for (size_t i = 0; i < args.size(); i++) { if ( args[i]->type != TeaObject::T_FLOAT) { return TeaResult("+ func synatax error, only support int/float"); } sum += args[i]->v_float; } return TeaObject::build(sum); } return TeaResult("+ func synatax error, only support int/float"); } static TeaResult sub(vector<tobject> &args, tenv& env) { if (args.size() != 2) { return TeaResult("- func synatax error, need two items"); } if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) { auto result = args[0]->v_int - args[1]->v_int; return TeaObject::build(result); } if (args[0]->type == TeaObject::T_FLOAT && args[1]->type == TeaObject::T_FLOAT) { auto result = args[0]->v_float - args[1]->v_float; return TeaObject::build(result); } return TeaResult("+ func synatax error, only support int/float"); } static TeaResult mul(vector<tobject> &args, tenv& env) { if (args.size() == 0) { return TeaResult("* func synatax error, need more items"); } if (args[0]->type == TeaObject::T_INT) { int64_t result = 1; for (size_t i = 0; i < args.size(); i++) { if (args[i]->type != TeaObject::T_INT) { return TeaResult("* func synatax error, only support int/float"); } result *= args[i]->v_int; } return TeaObject::build(result); } if (args[0]->type == TeaObject::T_FLOAT) { float result = 1.0; for (size_t i = 0; i < args.size(); i++) { if (args[i]->type != TeaObject::T_FLOAT) { return TeaResult("* func synatax error, only support int/float"); } result *= args[i]->v_float; } return TeaObject::build(result); } return TeaResult("* func synatax error, only support int/float"); } static TeaResult div(vector<tobject> &args, tenv& env) { if (args.size() != 2) { return TeaResult("/ func synatax error, need two items"); } if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) { auto result = args[0]->v_int / args[1]->v_int; return TeaObject::build(result); } if (args[0]->type == TeaObject::T_FLOAT && args[1]->type == TeaObject::T_FLOAT) { auto result = args[0]->v_float / args[1]->v_float; return TeaObject::build(result); } return TeaResult("/ func synatax error, only support int/float"); } static TeaResult mod(vector<tobject> &args, tenv& env) { if (args.size() != 2) { return TeaResult("mod func synatax error, need two items"); } if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) { auto result = args[0]->v_int % args[1]->v_int; return TeaObject::build(result); } return TeaResult("mod func synatax error, only support int/float"); } static TeaResult inc(vector<tobject> &args, tenv& env) { if (args.size() != 1) { return TeaResult("++ func synatax error, only support one items"); } if (args[0]->type == TeaObject::T_INT) { args[0]->v_int = args[0]->v_int + 1; return args[0]; } return TeaResult("++ func synatax error, only support int"); } static TeaResult dec(vector<tobject> &args, tenv& env) { if (args.size() != 1) { return TeaResult("-- func synatax error, only support one items"); } if (args[0]->type == TeaObject::T_INT) { args[0]->v_int = args[0]->v_int - 1; return args[0]; } return TeaResult("-- func synatax error, only support int"); } // comapir static TeaResult less(vector<tobject> &args, tenv& env) { if (args.size() != 2) { return TeaResult("< func synatax error, need two items"); } if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) { bool result = args[0]->v_int < args[1]->v_int; if (result == true) { return tea_true; } else { return tea_false; } } if (args[0]->type == TeaObject::T_FLOAT && args[1]->type == TeaObject::T_FLOAT) { bool result = args[0]->v_float < args[1]->v_float; if (result == true) { return tea_true; } else { return tea_false; } } return TeaResult("< func synatax error, only support int/float"); } static TeaResult more(vector<tobject> &args, tenv& env) { if (args.size() != 2) { return TeaResult("> func synatax error, need two items"); } if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) { bool result = args[0]->v_int > args[1]->v_int; if (result == true) { return tea_true; } else { return tea_false; } } if (args[0]->type == TeaObject::T_FLOAT && args[1]->type == TeaObject::T_FLOAT) { bool result = args[0]->v_float > args[1]->v_float; if (result == true) { return tea_true; } else { return tea_false; } } return TeaResult("> func synatax error, only support int/float"); } static TeaResult lesseq(vector<tobject> &args, tenv& env) { if (args.size() != 2) { return TeaResult("<= func synatax error, need two items"); } if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) { bool result = args[0]->v_int <= args[1]->v_int; if (result == true) { return tea_true; } else { return tea_false; } } return TeaResult("<= func synatax error, only support int"); } static TeaResult moreeq(vector<tobject> &args, tenv& env) { if (args.size() != 2) { return TeaResult(">= func synatax error, need two items"); } if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) { bool result = args[0]->v_int >= args[1]->v_int; if (result == true) { return tea_true; } else { return tea_false; } } return TeaResult(">= func synatax error, only support int"); } static TeaResult eqeq(vector<tobject> &args, tenv& env) { if (args.size() != 2) { return TeaResult(">= func synatax error, need two items"); } if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) { bool result = args[0]->v_int == args[1]->v_int; if (result == true) { return tea_true; } else { return tea_false; } } if (args[0]->type == TeaObject::T_FLOAT && args[1]->type == TeaObject::T_FLOAT) { bool result = args[0]->v_float == args[1]->v_float; if (result == true) { return tea_true; } else { return tea_false; } } if (args[0]->type == TeaObject::T_BOOL && args[1]->type == TeaObject::T_BOOL) { bool result = args[0]->v_bool == args[1]->v_bool; if (result == true) { return tea_true; } else { return tea_false; } } if (args[0]->type == TeaObject::T_PATTERN && args[1]->type == TeaObject::T_PATTERN) { bool result = args[0]->v_string == args[1]->v_string; if (result == true) { return tea_true; } else { return tea_false; } } return TeaResult(">= func synatax error, only support int/float/bool/pattern"); } // logic static TeaResult notnot(vector<tobject> &args, tenv& env) { if (args.size() != 1) { return TeaResult("! func synatax error, only support one items"); } if (args[0]->type == TeaObject::T_BOOL) { if (args[0]->v_bool == true) { return tea_false; } else { return tea_true; } } return TeaResult("-- func synatax error, only support bool"); } // list&map operation static TeaResult size(vector<tobject> &args, tenv& env) { if (args.size() != 1) { return TeaResult("size func synatax error, only support one items"); } if (args[0]->type == TeaObject::T_LIST) { int64_t n = args[0]->v_list->size(); return TeaObject::build(n); } if (args[0]->type == TeaObject::T_MAP) { int64_t n = args[0]->v_map->size(); return TeaObject::build(n); } return TeaResult("size func synatax error, only support list/map"); } static TeaResult push(vector<tobject> &args, tenv& env) { if (args.size() < 2) { return TeaResult("push func synatax error, only support two more items"); } if (args[0]->type == TeaObject::T_LIST) { auto lst = args[0]->v_list; for (size_t i = 1; i < args.size(); i++) { lst->push_back(args[i]); } return tea_null; } return TeaResult("push func synatax error, only support list"); } static TeaResult pop(vector<tobject> &args, tenv& env) { if (args.size() != 1) { return TeaResult("pop func synatax error, only support one"); } if (args[0]->type == TeaObject::T_LIST) { auto lst = args[0]->v_list; if (lst->size() > 0) { auto last = lst->back(); lst->pop_back(); return last; } return tea_null; } return TeaResult("pop func synatax error, only support list"); } static TeaResult nth(vector<tobject> &args, tenv& env) { if (args.size() != 2) { return TeaResult("push func synatax error, only support two items"); } if (args[0]->type == TeaObject::T_LIST) { auto lst = args[0]->v_list; if (args[1]->type == TeaObject::T_INT) { auto pos = args[1]->v_int; return (*lst)[pos]; } } return TeaResult("nth func synatax error!"); } static TeaResult set(vector<tobject> &args, tenv& env) { if (args.size() != 3) { return TeaResult("set func synatax error, only support two items"); } if (args[0]->type == TeaObject::T_MAP) { auto hash = args[0]->v_map; if (args[1]->type == TeaObject::T_PATTERN) { auto &key = args[1]->v_string; (*hash)[key] = args[2]; return tea_null; } } return TeaResult("set func synatax error!"); } static TeaResult has(vector<tobject> &args, tenv& env) { if (args.size() != 2) { return TeaResult("has func synatax error, only support two items"); } if (args[0]->type == TeaObject::T_MAP) { auto hash = args[0]->v_map; if (args[1]->type == TeaObject::T_PATTERN) { auto &key = args[1]->v_string; if (hash->find(key) == hash->end()) { return tea_false; } else { return tea_true; } } } return TeaResult("has func synatax error!"); } static TeaResult rm(vector<tobject> &args, tenv& env) { if (args.size() != 2) { return TeaResult("rm func synatax error, only support two items"); } if (args[0]->type == TeaObject::T_MAP) { auto hash = args[0]->v_map; if (args[1]->type == TeaObject::T_PATTERN) { auto &key = args[1]->v_string; hash->erase(key); return tea_null; } } return TeaResult("set func synatax error!"); } private: // core implementation static bool is_builtin(const string& symbol) { if ( symbol == "if" || symbol == "def" || symbol == "begin" || symbol == "while" || symbol == "map" || symbol == "list" || symbol == "&&" || symbol == "||" || symbol == "fn" ) { return true; } return false; } static TeaResult eval_builtin(vector<tobject>& lst, tenv& env) { assert(lst.size() > 0); tobject head = lst[0]; string symbol = lst[0]->v_string; if (symbol == "begin") { return eval_begin(lst, env); } if (symbol == "if") { return eval_if(lst, env); } if (symbol == "def") { return eval_def(lst, env); } if (symbol == "while") { return eval_while(lst, env); } if (symbol == "map") { return eval_map(lst, env); } if (symbol == "list") { return eval_list(lst, env); } if (symbol == "&&") { return eval_and(lst, env); } if (symbol == "||") { return eval_or(lst, env); } if (symbol == "fn") { return eval_fn(lst, env); } return TeaResult("Bug, code can't reach here!"); } static TeaResult eval_fn(vector<tobject>& lst, tenv& env) { TeaLambda lambda; if ( lst.size() == 3) { return TeaResult("(fn) synatax error: args body"); } if ( lst[1]->type != TeaObject::T_LIST ) { return TeaResult("(fn) synatax error: args should be a list"); } for (size_t i = 0; i < lst[1]->v_list->size(); i++) { assert( (*lst[1]->v_list)[i]->type == TeaObject::T_SYMBOL); lambda.head.push_back( (*lst[1]->v_list)[i] ); } lambda.body = lst[2]; auto obj = TeaObject( make_shared<TeaLambda>(lambda) ); auto tobj = make_shared<TeaObject>(obj); return TeaResult(tobj); } static TeaResult eval_and(vector<tobject>& lst, tenv& env) { if ( lst.size() < 3) { return TeaResult("(&&) synatax error: need 3 items at least"); } bool result = true; for (size_t i = 1; i < lst.size(); ) { TeaResult r = eval(lst[i], env); if (r.is_error()) { return r; } if (r.result->type != TeaObject::T_BOOL) { return TeaResult("(&&) synatax error: item must be bool "); } result = result && r.result->v_bool; if (result == false) { break; } } if (result) { return TeaResult(tea_true); } return TeaResult(tea_false); } static TeaResult eval_or(vector<tobject>& lst, tenv& env) { if ( lst.size() < 3) { return TeaResult("(&&) synatax error: need 3 items at least"); } bool result = false; for (size_t i = 1; i < lst.size(); ) { TeaResult r = eval(lst[i], env); if (r.is_error()) { return r; } if (r.result->type != TeaObject::T_BOOL) { return TeaResult("(&&) synatax error: item must be bool "); } result = result || r.result->v_bool; if (result == true) { break; } } if (result) { return TeaResult(tea_true); } return TeaResult(tea_false); } static TeaResult eval_list(vector<tobject>& lst, tenv& env) { vector<tobject> new_lst; for (size_t i = 1; i < lst.size(); ) { TeaResult r = eval(lst[i], env); if (r.is_error()) { return r; } new_lst.push_back(r.result); } auto obj = TeaObject( make_shared<vector<tobject>>(new_lst) ); return TeaResult( make_shared<TeaObject>(obj) ); } static TeaResult eval_map(vector<tobject>& lst, tenv& env) { if ( (lst.size() % 2) != 1) { return TeaResult("'(map)' synatax error, must include @pattern/value pair"); } map<string, tobject> hash; for (size_t i = 1; i < lst.size(); ) { assert(lst[i]->type == TeaObject::T_PATTERN); TeaResult r = eval(lst[i+1], env); if (r.is_error()) { return r; } hash[lst[i]->v_string] = r.result; i += 2; } auto obj = TeaObject( make_shared<map<string, tobject>>(hash) ); return TeaResult( make_shared<TeaObject>(obj) ); } static TeaResult eval_while(vector<tobject>& lst, tenv& env) { if (lst.size() < 2) { return TeaResult("'(while)' synatax error, must include condition"); } for(;;) { TeaResult r = eval(lst[2], env); if (r.is_error()) { return r; } auto cond = r.result; if ( cond->type != TeaObject::T_BOOL ) { return TeaResult("'(while)' synatax error, first item should reutrn bool!"); } if (cond->v_bool == false) { break; } for (size_t i = 2; i < lst.size(); i++) { TeaResult r = eval(lst[2], env); if (r.is_error()) { return r; } } } return TeaResult(tea_null); } static TeaResult eval_def(vector<tobject>& lst, tenv& env) { if (lst.size() == 3) { TeaResult r = eval(lst[2], env); if (r.is_error()) { return r; } assert(lst[1]->type == TeaObject::T_SYMBOL); env->set(lst[1]->v_string, r.result); return TeaResult(tea_null); } return TeaResult("'(def)' synatax error!"); } static TeaResult eval_if(vector<tobject>& lst, tenv& env) { if (lst.size() >= 3) { TeaResult r = eval(lst[1], env); if (r.is_error()) { return r; } auto cond = r.result; if ( cond->type != TeaObject::T_BOOL ) { return TeaResult("'(if)' synatax error, first item should reutrn bool!"); } if (cond->v_bool == true) { return eval(lst[2], env); } if (lst.size() == 3) { return TeaResult(tea_null); } if (lst.size() == 4) { return eval(lst[3], env); } } return TeaResult("'(if)' synatax error!"); } static TeaResult eval_begin(vector<tobject>& lst, tenv& env) { if (lst.size() == 1) { return TeaResult(tea_null); } for ( size_t i = 1; i < lst.size() - 1; i++) { TeaResult r = eval(lst[i], env); if (r.is_error()) { return r; } } return eval(lst[lst.size()-1], env); } static TeaResult eval_lambda(tobject& head, vector<tobject>& args, tenv& env) { assert(head->type == TeaObject::T_LAMBDA); auto lambda = head->v_lambda; TeaEnvironment new_env(env, lambda->closure); for (size_t i = 0; i < lambda->head.size(); i++) { assert(lambda->head[i]->type == TeaObject::T_SYMBOL); if ( i >= args.size() ) { new_env.set(lambda->head[i]->v_string, tea_null); } else { new_env.set(lambda->head[i]->v_string, args[i]); } } auto tenv = make_shared<TeaEnvironment>(new_env); return eval(lambda->body, tenv); } static TeaResult eval(tobject& obj, tenv& env) { if ( obj->type == TeaObject::T_NULL || obj->type == TeaObject::T_BOOL || obj->type == TeaObject::T_INT || obj->type == TeaObject::T_FLOAT || obj->type == TeaObject::T_PATTERN || obj->type == TeaObject::T_MAP || obj->type == TeaObject::T_EXT || obj->type == TeaObject::T_LAMBDA) { return TeaResult(obj); } if ( obj->type == TeaObject::T_SYMBOL ) { return TeaResult( env->get(obj->v_string)); } // execute list if ( obj->type == TeaObject::T_LIST ) { // empty list return null if (obj->v_list->size() == 0) { return TeaResult( tea_null ); } // get head of list vector<tobject>& lst(*obj->v_list); tobject head = lst[0]; assert(head->type == TeaObject::T_SYMBOL); if (is_builtin(head->v_string)) { // step.1 check builtin call or eval auto tresult = eval_builtin(lst, env); if (tresult.is_error()){ tresult.trace.push_back(obj->to_string()); } return tresult; } else { // step.2 eval head of list auto tresult = eval(head, env); if (tresult.is_error()) { tresult.trace.push_back(obj->to_string()); return tresult; } head = tresult.result; } // step.3 eval all the args vector<tobject> args; for (size_t i = 1; i < lst.size(); i++) { TeaResult tresult = eval(lst[i], env); if (tresult.is_error()) { tresult.trace.push_back(obj->to_string()); return tresult; } args.push_back(tresult.result); } // step.4 check PATTERN & FUNC & LAMBODA if ( head->type == TeaObject::T_PATTERN ) { if (args.size() == 1) { if (args[0]->type == TeaObject::T_MAP) { auto query = args[0]->v_map->find(head->v_string); if (query == args[0]->v_map->end()) { string msg = "Can't find " + head->v_string + " in map!"; auto tresult = TeaResult(msg); tresult.trace.push_back(obj->to_string()); return tresult; } else { return TeaResult(query->second); } } } auto tresult = TeaResult("query map synatax error!"); tresult.trace.push_back(obj->to_string()); return tresult; } if ( head->type == TeaObject::T_FUNC ) { auto tresult = head->v_func(args, env); if ( tresult.is_error() ) { tresult.trace.push_back(obj->to_string()); } return tresult; } if ( head->type == TeaObject::T_LAMBDA ) { auto tresult = eval_lambda(head, args, env); if ( tresult.is_error() ) { tresult.trace.push_back(obj->to_string()); } return tresult; } } auto tresult = TeaResult("BUG!"); if ( tresult.is_error() ) { tresult.trace.push_back(obj->to_string()); } return tresult; } static TeaResult eval_all(vector<tobject>& codes, tenv& env) { int last = codes.size() - 1; if (last < 0) { return TeaResult(tea_null); } for (int i = 0; i < last; i++) { auto r = eval(codes[i], env); if (r.is_error()) { return r; } } return eval(codes[last], env); } private: // parser, compiler static tobject parse_atom(const string& token) { // true or false if (token == "true") { return tea_true; } if (token == "false") { return tea_false; } // number if (isdigit(token.at(0)) || (token.at(0) == '-' && token.length() >= 2 && isdigit(token.at(1)))) { if (token.find('.') != string::npos || token.find('e') != string::npos) { // double float value = atof(token.c_str()); return TeaObject::build(value); } else { int64_t value = atol(token.c_str()); return TeaObject::build(value); } } // pattern if (token.at(0) == '@') { string pattern = token; pattern.erase(0, 1); if (pattern == "") { pattern = " "; } return TeaObject::build(pattern); } // symbol return make_shared<TeaObject>( TeaObject(TeaObject::T_SYMBOL, token) ); } static tobject parse_tokens(const vector<string>& tokens, size_t pos, size_t &next_pos) { size_t i = pos; if ( tokens[i] != "(") { return nullptr; } auto ret = make_shared<vector<tobject>>(); i = i + 1; for (;;) { if ( i >= tokens.size() ) { break; } // 0. check is end of a list const string& token(tokens[i]); if (token == ")") { next_pos = i + 1; return TeaObject::build(ret); } // 1. an new list begin if (token == "(") { size_t end_pos = 0; auto next = parse_tokens(tokens, i, end_pos); if (next == nullptr) { return nullptr; } ret->push_back(next); i = end_pos; } // 2. an new symbol ret->push_back( parse_atom(tokens[i]) ); i++; } return nullptr; } static string parse_and_compile(string& code, tenv& env, vector<tobject>& codes) { struct _ { static void findAndReplaceAll(std::string & data, const std::string toSearch, const std::string replaceStr) { size_t pos = data.find(toSearch); while( pos != std::string::npos){ data.replace(pos, toSearch.size(), replaceStr); pos =data.find(toSearch, pos + replaceStr.size()); } } static void tokenize(std::string const &str, const char delim, std::vector<std::string> &out) { size_t start; size_t end = 0; while ((start = str.find_first_not_of(delim, end)) != std::string::npos) { end = str.find(delim, start); out.push_back(str.substr(start, end - start)); } } }; _::findAndReplaceAll(code, "{", "(map"); _::findAndReplaceAll(code, "}", ")"); _::findAndReplaceAll(code, "[", "(list"); _::findAndReplaceAll(code, "]", ")"); _::findAndReplaceAll(code, "(", " ( "); _::findAndReplaceAll(code, ")", " ) "); _::findAndReplaceAll(code, "\n"," "); vector<string> tokens; _::tokenize(code, ' ', tokens); codes.clear(); if (tokens.size() == 1) { codes.push_back( parse_atom( tokens[0] )); } else { size_t i = 0; while ( i < tokens.size() ) { size_t next = 0; auto ret = parse_tokens(tokens, i, next); if (ret == nullptr) { return "parse token error!"; } codes.push_back(ret); i = next; } } return ""; } public: static tenv new_env() { auto env = TeaEnvironment(); init(env.data); return make_shared<TeaEnvironment>(env); } static string run(string& code, tenv& env) { vector<tobject> codes; auto result = parse_and_compile(code, env, codes); if (result != "") { return result; } auto ret = eval_all(codes, env); if (ret.is_error()) { return ret.trace[0]; } return ret.result->to_string(); } }; }
32.277827
119
0.478454
Teaonly
d6f23e5f9d43143eed1469a6c8f879af2cbd9592
3,155
hpp
C++
libs/ml/include/ml/state_dict.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
3
2019-07-11T08:49:27.000Z
2021-09-07T16:49:15.000Z
libs/ml/include/ml/state_dict.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
null
null
null
libs/ml/include/ml/state_dict.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
2
2019-07-13T12:45:22.000Z
2021-03-12T08:48:57.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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/tensor.hpp" #include <list> namespace fetch { namespace ml { /** * A utility class to extract the network trainable parameter and serialize them for saving / * sharing * @tparam T */ template <class T> struct StateDict { using ArrayType = T; using ArrayPtrType = std::shared_ptr<ArrayType>; ArrayPtrType weights_; std::map<std::string, StateDict<T>> dict_; bool operator==(StateDict<T> const &o) const { return !((bool(weights_) ^ bool(o.weights_)) || (weights_ && (*weights_ != *(o.weights_))) || (dict_ != o.dict_)); } void InlineDivide(typename ArrayType::Type n) { if (weights_) { weights_->InlineDivide(n); } for (auto &kvp : dict_) { kvp.second.InlineDivide(n); } } void InlineAdd(StateDict const &o, bool strict = true) { if (o.weights_ && !weights_ && !strict) { weights_ = std::make_shared<ArrayType>(o.weights_->shape()); } assert(!((bool(weights_) ^ bool(o.weights_)))); if (weights_) { weights_->InlineAdd(*(o.weights_)); } for (auto const &kvp : o.dict_) { dict_[kvp.first].InlineAdd(kvp.second, strict); } } /** * Used to merge a list of state dict together into a new object * All are weighted equally -- Usefull for averaging weights of multiple similar models * @param stateDictList */ static StateDict MergeList(std::list<StateDict> const &stateDictList) { StateDict ret; for (auto const &sd : stateDictList) { ret.InlineAdd(sd, false); } ret.InlineDivide(static_cast<typename ArrayType::Type>(stateDictList.size())); return ret; } /** * Used to merge a stateDict into another * @param o -- The stateDict to merge into this * @param ratio -- this = this * ration + o * (1 - ratio) */ StateDict &Merge(StateDict const &o, float ratio = .5f) { assert(ratio >= 0.0f && ratio <= 1.0f); if (ratio > 0) { if (weights_) { weights_->InlineMultiply(typename ArrayType::Type(1.0f - ratio)); weights_->InlineAdd(o.weights_->Copy().InlineMultiply(typename ArrayType::Type(ratio))); } for (auto &e : dict_) { e.second.Merge(o.dict_.at(e.first)); } } return *this; } }; } // namespace ml } // namespace fetch
27.198276
97
0.594612
devjsc
d6f2ae1a29cefd6c05e7c927067c982a20a0aa0f
4,028
cpp
C++
LoganEngine/old/lPhys2/lpRigidBody/lpBox.cpp
sereslorant/logan_engine
a596b4128d0a58236be00f93064e276e43484017
[ "MIT" ]
1
2019-12-26T13:22:29.000Z
2019-12-26T13:22:29.000Z
LoganEngine/old/lPhys2/lpRigidBody/lpBox.cpp
sereslorant/logan_engine
a596b4128d0a58236be00f93064e276e43484017
[ "MIT" ]
null
null
null
LoganEngine/old/lPhys2/lpRigidBody/lpBox.cpp
sereslorant/logan_engine
a596b4128d0a58236be00f93064e276e43484017
[ "MIT" ]
null
null
null
#include "lpBox.h" void lpBox::CalculateBoxInertiaTensor() { InertiaTensor[0][0] = 1.0/12.0 * Mass * (Height*Height + Depth*Depth); InertiaTensor[1][0] = 0.0; InertiaTensor[2][0] = 0.0; InertiaTensor[0][1] = 0.0; InertiaTensor[1][1] = 1.0/12.0 * Mass * (Width*Width + Depth*Depth); InertiaTensor[2][1] = 0.0; InertiaTensor[0][2] = 0.0; InertiaTensor[1][2] = 0.0; InertiaTensor[2][2] = 1.0/12.0 * Mass * (Width*Width + Height*Height); if(Mass != 0.0) { InertiaTensor.Invert(InvInertiaTensor); } } void lpBox::RecalculateMesh() { //lmScalar BoundingSphereRadius = std::sqrt((Width/2.0)*(Width/2.0) + (Height/2.0)*(Height/2.0) + (Depth/2.0)*(Depth/2.0)); //BoundingSphere->SetRadius(BoundingSphereRadius); /* * Generating vertices */ //Front Vertices[0] = {-Width/2.0, Height/2.0, Depth/2.0}; Vertices[1] = {-Width/2.0,-Height/2.0, Depth/2.0}; Vertices[2] = { Width/2.0,-Height/2.0, Depth/2.0}; Vertices[3] = { Width/2.0, Height/2.0, Depth/2.0}; //Back Vertices[4] = {-Width/2.0, Height/2.0,-Depth/2.0}; Vertices[5] = {-Width/2.0,-Height/2.0,-Depth/2.0}; Vertices[6] = { Width/2.0,-Height/2.0,-Depth/2.0}; Vertices[7] = { Width/2.0, Height/2.0,-Depth/2.0}; GenerateBoundingSphere(); } lpBox::lpBox(bool ghost,lmScalar mass,liRigidBody::liState *state,lmScalar width,lmScalar height,lmScalar depth) :lpMesh(ghost,mass,state,LP_BOX),Width(width),Height(height),Depth(depth) { /* * Generating normals */ /* Normals.push_back(lmVector3D( 0.0, 0.0, 1.0));//Front face Normals.push_back(lmVector3D( 1.0, 0.0, 0.0));//Left face Normals.push_back(lmVector3D( 0.0, 0.0,-1.0));//Back face Normals.push_back(lmVector3D(-1.0, 0.0, 0.0));//Right face Normals.push_back(lmVector3D( 0.0, 1.0, 0.0));//Top face Normals.push_back(lmVector3D( 0.0,-1.0, 0.0));//Bottom face */ Normals = {{ 0.0, 0.0, 1.0}, { 1.0, 0.0, 0.0}, { 0.0, 0.0,-1.0}, {-1.0, 0.0, 0.0}, { 0.0, 1.0, 0.0}, { 0.0,-1.0, 0.0} }; /* * Generating triangles */ /* Triangles.push_back({0,1,2,0});Triangles.push_back({0,3,2,0});//Front face Triangles.push_back({2,3,6,1});Triangles.push_back({3,7,6,1});//Left face Triangles.push_back({4,5,6,2});Triangles.push_back({4,7,6,2});//Back face Triangles.push_back({0,1,5,3});Triangles.push_back({0,5,4,3});//Right face Triangles.push_back({0,3,4,4});Triangles.push_back({3,4,7,4});//Top face Triangles.push_back({1,2,6,5});Triangles.push_back({1,5,6,5});//Bottom face */ Triangles = {{0,1,2,0},{0,3,2,0},//Front face {2,3,6,1},{3,7,6,1},//Left face {4,5,6,2},{4,7,6,2},//Back face {0,1,5,3},{0,5,4,3},//Right face {0,3,4,4},{3,4,7,4},//Top face {1,2,6,5},{1,5,6,5}//Bottom face }; Vertices.resize(8); RecalculateMesh(); for(int i=0;i < Triangles.size();i++) { lmVector3D Cukcsy = lmCross(Vertices[Triangles[i].V[2]] - Vertices[Triangles[i].V[0]],Vertices[Triangles[i].V[1]] - Vertices[Triangles[i].V[0]]); if(lmDot(Normals[Triangles[i].Normal],Cukcsy) < 0.0) { unsigned int Tmp = Triangles[i].V[1]; Triangles[i].V[1] = Triangles[i].V[2]; Triangles[i].V[2] = Tmp; /* std::cout << i << std::endl; Cukcsy = lmCross(Vertices[Triangles[i].V3] - Vertices[Triangles[i].V1],Vertices[Triangles[i].V2] - Vertices[Triangles[i].V1]); if(!(lmDot(Normals[Triangles[i].Normal],Cukcsy) < 0.0)) { std::cout << "Győzelem!" << std::endl; } */ } } CalculateBoxInertiaTensor(); } lmScalar lpBox::GetWidth() { return Width; } lmScalar lpBox::GetHeight() { return Height; } lmScalar lpBox::GetDepth() { return Depth; } void lpBox::SetWidth(lmScalar width) { Width = width; RecalculateMesh(); CalculateBoxInertiaTensor(); } void lpBox::SetHeight(lmScalar height) { Height = height; RecalculateMesh(); CalculateBoxInertiaTensor(); } void lpBox::SetDepth(lmScalar depth) { Depth = depth; RecalculateMesh(); CalculateBoxInertiaTensor(); }
27.77931
194
0.611221
sereslorant
d6f385b24d883e60228a8aa546f3808fd794dabf
9,929
cpp
C++
src/TGUI/Signal.cpp
Bayonetta5/tgui
87d0e9e53895347b04cf15c94be89473548769f3
[ "Zlib" ]
null
null
null
src/TGUI/Signal.cpp
Bayonetta5/tgui
87d0e9e53895347b04cf15c94be89473548769f3
[ "Zlib" ]
null
null
null
src/TGUI/Signal.cpp
Bayonetta5/tgui
87d0e9e53895347b04cf15c94be89473548769f3
[ "Zlib" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TGUI - Texus' Graphical User Interface // Copyright (C) 2012-2017 Bruno Van de Velde ([email protected]) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <TGUI/Signal.hpp> #include <TGUI/Widget.hpp> #include <TGUI/Widgets/ChildWindow.hpp> #include <TGUI/to_string.hpp> #include <cassert> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace { unsigned int lastId = 0; unsigned int generateUniqueId() { return ++lastId; } template <typename Type> const Type& dereference(const void* obj) { return *static_cast<const Type*>(obj); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace tgui { std::vector<const void*> Signal::m_parameters(3, nullptr); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Signal::Signal(const Signal& other) : m_name {other.m_name}, m_handlers{} // signal handlers are not copied with the widget { } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Signal& Signal::operator=(const Signal& other) { if (this != &other) { m_name = other.m_name; m_handlers.clear(); // signal handlers are not copied with the widget } return *this; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int Signal::connect(const Delegate& handler) { const auto id = generateUniqueId(); m_handlers[id] = handler; return id; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int Signal::connect(const DelegateEx& handler) { const auto id = generateUniqueId(); m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name); }; return id; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Signal::disconnect(unsigned int id) { return m_handlers.erase(id) == 0; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Signal::disconnectAll() { m_handlers.clear(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// tgui::Widget::Ptr Signal::getWidget() { return dereference<Widget*>(m_parameters[0])->shared_from_this(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(TypeName, Type) \ unsigned int Signal##TypeName::connect(const Delegate##TypeName& handler) \ { \ const auto id = generateUniqueId(); \ m_handlers[id] = [handler](){ handler(dereference<Type>(m_parameters[1])); }; \ return id; \ } \ \ unsigned int Signal##TypeName::connect(const Delegate##TypeName##Ex& handler) \ { \ const auto id = generateUniqueId(); \ m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name, dereference<Type>(m_parameters[1])); }; \ return id; \ } TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(Int, int) TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(UInt, unsigned int) TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(Bool, bool) TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(Float, float) TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(String, sf::String) TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(Vector2f, sf::Vector2f) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int SignalChildWindow::connect(const DelegateChildWindow& handler) { const auto id = generateUniqueId(); m_handlers[id] = [handler](){ handler(std::static_pointer_cast<ChildWindow>(dereference<ChildWindow*>(m_parameters[1])->shared_from_this())); }; return id; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int SignalChildWindow::connect(const DelegateChildWindowEx& handler) { const auto id = generateUniqueId(); m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name, std::static_pointer_cast<ChildWindow>(dereference<ChildWindow*>(m_parameters[1])->shared_from_this())); }; return id; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool SignalChildWindow::emit(const ChildWindow* childWindow) { if (m_handlers.empty()) return false; m_parameters[1] = static_cast<const void*>(&childWindow); return Signal::emit(childWindow); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int SignalItem::connect(const DelegateItem& handler) { const auto id = generateUniqueId(); m_handlers[id] = [handler](){ handler(dereference<sf::String>(m_parameters[1])); }; return id; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int SignalItem::connect(const DelegateItemEx& handler) { const auto id = generateUniqueId(); m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name, dereference<sf::String>(m_parameters[1])); }; return id; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int SignalItem::connect(const DelegateItemAndId& handler) { const auto id = generateUniqueId(); m_handlers[id] = [handler](){ handler(dereference<sf::String>(m_parameters[1]), dereference<sf::String>(m_parameters[2])); }; return id; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int SignalItem::connect(const DelegateItemAndIdEx& handler) { const auto id = generateUniqueId(); m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name, dereference<sf::String>(m_parameters[1]), dereference<sf::String>(m_parameters[2])); }; return id; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int SignalMenuItem::connect(const DelegateMenuItem& handler) { const auto id = generateUniqueId(); m_handlers[id] = [handler](){ handler(dereference<sf::String>(m_parameters[1])); }; return id; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int SignalMenuItem::connect(const DelegateMenuItemEx& handler) { const auto id = generateUniqueId(); m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name, dereference<sf::String>(m_parameters[1])); }; return id; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int SignalMenuItem::connect(const DelegateMenuItemFull& handler) { const auto id = generateUniqueId(); m_handlers[id] = [handler](){ handler(dereference<std::vector<sf::String>>(m_parameters[2])); }; return id; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int SignalMenuItem::connect(const DelegateMenuItemFullEx& handler) { const auto id = generateUniqueId(); m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name, dereference<std::vector<sf::String>>(m_parameters[2])); }; return id; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
40.526531
184
0.434988
Bayonetta5
d6f512daa20b8ce86475f8486b8c413f54b9932a
784
cpp
C++
src/classwork/04_assign/main.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-SageElephant
6fa25968c9c57263be2700f4c39892d863e5e78f
[ "MIT" ]
null
null
null
src/classwork/04_assign/main.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-SageElephant
6fa25968c9c57263be2700f4c39892d863e5e78f
[ "MIT" ]
null
null
null
src/classwork/04_assign/main.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-SageElephant
6fa25968c9c57263be2700f4c39892d863e5e78f
[ "MIT" ]
null
null
null
//write includes statements #include <iostream> #include "loops.h" //write using statements for cin and cout using std::cin; using std::cout; /* Use a do while loop to prompt the user for a number, call the factorial function, and display the number's factorial. Also, loop continues as long as user wants to. */ int main() { int num; char go_again; do { do { cout << "Enter an integer number between 1 and 10: \n"; cin >> num; } while (!(num >= 1 && num <= 10)); cout << "The factorial of " << num << " is " << factorial(num) << "\n"; cout << "Would you like to enter another number? Type 'Y' to continue."; cin >> go_again; } while (go_again == 'Y'); cout << "Thanks! The program has finished. \n"; return 0; }
21.777778
76
0.604592
acc-cosc-1337-spring-2021
d6fae5859b1906929543bf4d4b27827b90a8394e
6,962
cpp
C++
source/JsMaterialX/JsMaterialXCore/JsDocument.cpp
sdunkel/MaterialX
e76a27d01be379929b9adb3cad6d89aa570511ab
[ "BSD-3-Clause" ]
1
2021-11-20T20:56:27.000Z
2021-11-20T20:56:27.000Z
source/JsMaterialX/JsMaterialXCore/JsDocument.cpp
testpassword/MaterialX
7c69782196b11fa43c67aee0707801983bb81e6c
[ "BSD-3-Clause" ]
null
null
null
source/JsMaterialX/JsMaterialXCore/JsDocument.cpp
testpassword/MaterialX
7c69782196b11fa43c67aee0707801983bb81e6c
[ "BSD-3-Clause" ]
null
null
null
// // TM & (c) 2021 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #include "../VectorHelper.h" #include "../Helpers.h" #include <MaterialXCore/Document.h> #include <emscripten/bind.h> namespace ems = emscripten; namespace mx = MaterialX; EMSCRIPTEN_BINDINGS(document) { ems::function("createDocument", &mx::createDocument); ems::class_<mx::Document, ems::base<mx::GraphElement>>("Document") .smart_ptr_constructor("Document", &std::make_shared<mx::Document, mx::ElementPtr, const std::string &>) .smart_ptr<std::shared_ptr<const mx::Document>>("Document") // At the moment only the Document type is used. Once more types are added this binding needs to be adapted accordingly. .class_function("createDocument", &mx::Document::createDocument<mx::Document>) .function("initialize", &mx::Document::initialize) .function("copy", &mx::Document::copy) .function("importLibrary", &mx::Document::importLibrary) .function("getReferencedSourceUris", ems::optional_override([](mx::Document &self) { mx::StringSet set = self.getReferencedSourceUris(); return ems::val::array(set.begin(), set.end()); })) BIND_MEMBER_FUNC("addNodeGraph", mx::Document, addNodeGraph, 0, 1, stRef) .function("getNodeGraph", &mx::Document::getNodeGraph) .function("getNodeGraphs", &mx::Document::getNodeGraphs) .function("removeNodeGraph", &mx::Document::removeNodeGraph) .function("getMatchingPorts", &mx::Document::getMatchingPorts) BIND_MEMBER_FUNC("addGeomInfo", mx::Document, addGeomInfo, 0, 2, stRef, stRef) .function("getGeomInfo", &mx::Document::getGeomInfo) .function("getGeomInfos", &mx::Document::getGeomInfos) .function("removeGeomInfo", &mx::Document::removeGeomInfo) BIND_MEMBER_FUNC("getGeomPropValue", mx::Document, getGeomPropValue, 1, 2, stRef, stRef) .function("addGeomPropDef", &mx::Document::addGeomPropDef) .function("getGeomPropDef", &mx::Document::getGeomPropDef) .function("getGeomPropDefs", &mx::Document::getGeomPropDefs) .function("removeGeomPropDef", &mx::Document::removeGeomPropDef) BIND_MEMBER_FUNC("addLook", mx::Document, addLook, 0, 1, stRef) .function("getLook", &mx::Document::getLook) .function("getLooks", &mx::Document::getLooks) .function("removeLook", &mx::Document::removeLook) .function("mergeLooks", &mx::Document::mergeLooks) BIND_MEMBER_FUNC("addLookGroup", mx::Document, addLookGroup, 0, 1, stRef) .function("getLookGroup", &mx::Document::getLookGroup) .function("getLookGroups", &mx::Document::getLookGroups) .function("removeLookGroup", &mx::Document::removeLookGroup) BIND_MEMBER_FUNC("addCollection", mx::Document, addCollection, 0, 1, stRef) .function("getCollection", &mx::Document::getCollection) .function("getCollections", &mx::Document::getCollections) .function("removeCollection", &mx::Document::removeCollection) .function("addTypeDef", &mx::Document::addTypeDef) .function("getTypeDef", &mx::Document::getTypeDef) .function("getTypeDefs", &mx::Document::getTypeDefs) .function("removeTypeDef", &mx::Document::removeTypeDef) BIND_MEMBER_FUNC("addNodeDef", mx::Document, addNodeDef, 0, 3, stRef, stRef, stRef) BIND_MEMBER_FUNC("addNodeDefFromGraph", mx::Document, addNodeDefFromGraph, 7, 8, const mx::NodeGraphPtr, stRef, stRef, stRef, bool, stRef, std::string, stRef) .function("getNodeDef", &mx::Document::getNodeDef) .function("getNodeDefs", &mx::Document::getNodeDefs) .function("removeNodeDef", &mx::Document::removeNodeDef) .function("getMatchingNodeDefs", &mx::Document::getMatchingNodeDefs) BIND_MEMBER_FUNC("addAttributeDef", mx::Document, addAttributeDef, 0, 1, stRef) .function("getAttributeDef", &mx::Document::getAttributeDef) .function("getAttributeDefs", &mx::Document::getAttributeDefs) .function("removeAttributeDef", &mx::Document::removeAttributeDef) BIND_MEMBER_FUNC("addTargetDef", mx::Document, addTargetDef, 0, 1, stRef) .function("getTargetDef", &mx::Document::getTargetDef) .function("getTargetDefs", &mx::Document::getTargetDefs) .function("removeTargetDef", &mx::Document::removeTargetDef) BIND_MEMBER_FUNC("addPropertySet", mx::Document, addPropertySet, 0, 1, stRef) .function("getPropertySet", &mx::Document::getPropertySet) .function("getPropertySets", &mx::Document::getPropertySets) .function("removePropertySet", &mx::Document::removePropertySet) BIND_MEMBER_FUNC("addVariantSet", mx::Document, addVariantSet, 0, 1, stRef) .function("getVariantSet", &mx::Document::getVariantSet) .function("getVariantSets", &mx::Document::getVariantSets) .function("removeVariantSet", &mx::Document::removeVariantSet) BIND_MEMBER_FUNC("addImplementation", mx::Document, addImplementation, 0, 1, stRef) .function("getImplementation", &mx::Document::getImplementation) .function("getImplementations", &mx::Document::getImplementations) .function("removeImplementation", &mx::Document::removeImplementation) .function("getMatchingImplementations", &mx::Document::getMatchingImplementations) .function("addUnitDef", &mx::Document::addUnitDef) .function("getUnitDef", &mx::Document::getUnitDef) .function("getUnitDefs", &mx::Document::getUnitDefs) .function("removeUnitDef", &mx::Document::removeUnitDef) .function("addUnitTypeDef", &mx::Document::addUnitTypeDef) .function("getUnitTypeDef", &mx::Document::getUnitTypeDef) .function("getUnitTypeDefs", &mx::Document::getUnitTypeDefs) .function("removeUnitTypeDef", &mx::Document::removeUnitTypeDef) .function("getVersionIntegers", &mx::Document::getVersionIntegers) .function("upgradeVersion", &mx::Document::upgradeVersion) .function("setColorManagementSystem", &mx::Document::setColorManagementSystem) .function("hasColorManagementSystem", &mx::Document::hasColorManagementSystem) .function("getColorManagementSystem", &mx::Document::getColorManagementSystem) .function("setColorManagementConfig", &mx::Document::setColorManagementConfig) .function("hasColorManagementConfig", &mx::Document::hasColorManagementConfig) .function("getColorManagementConfig", &mx::Document::getColorManagementConfig) .function("invalidateCache", &mx::Document::invalidateCache) .class_property("CATEGORY", &mx::Document::CATEGORY) .class_property("CMS_ATTRIBUTE", &mx::Document::CMS_ATTRIBUTE) .class_property("CMS_CONFIG_ATTRIBUTE", &mx::Document::CMS_CONFIG_ATTRIBUTE); }
62.720721
132
0.692473
sdunkel
d6fcb97a5580e130b76fe3944853ae93cd1b1ceb
1,314
cpp
C++
object_recognition/src/object.cpp
Birkehoj/vis3
70e71f1763a8818680bc9eea8d5fc041d4ec8075
[ "BSD-2-Clause" ]
2
2015-11-11T12:39:26.000Z
2021-07-04T13:16:30.000Z
object_recognition/src/object.cpp
Birkehoj/vis3
70e71f1763a8818680bc9eea8d5fc041d4ec8075
[ "BSD-2-Clause" ]
null
null
null
object_recognition/src/object.cpp
Birkehoj/vis3
70e71f1763a8818680bc9eea8d5fc041d4ec8075
[ "BSD-2-Clause" ]
2
2017-04-04T13:47:28.000Z
2019-05-14T14:30:11.000Z
#include "object.h" #include <pcl/io/obj_io.h> #include <fstream> using std::ifstream; Object::Object(const std::string& object_folder_path, const std::string& file_name) : Feature_cloud(file_name.substr(0,file_name.find_last_of("."))) { CloudT::Ptr xyz(new CloudT); pcl::io::loadOBJFile<PointT>(object_folder_path+"/" + file_name, *xyz); for (pcl::PointCloud<PointT>::iterator i = xyz->begin(); i != xyz->end(); i++) { i->z *= mm_to_m_factor; i->y *= mm_to_m_factor; i->x *= mm_to_m_factor; } computeFeatures(xyz); setGrasps(object_folder_path); } void Object::setGrasps(const string& object_folder_path) { const string grasp_folder_name = "grasps"; string grasp_file_path = object_folder_path + '/' + grasp_folder_name + '/' + name + ".txt"; cout << "loading grasps from: " << grasp_file_path << endl; std::ifstream fs(grasp_file_path.c_str()); if(fs.is_open()) { while(fs.good()) { Eigen::Matrix4f grasp; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { fs >> grasp(i,j); } } //cout << endl << name << "'s grasp = " << endl << grasp << endl; grasps.push_back(grasp); } grasps.pop_back(); // one too much added?? fs.close(); } else { PCL_ERROR("Unable to open grasp file\n"); } }
29.863636
94
0.611872
Birkehoj
d90096bf47ed042bbdd91a0f413286d866c6394d
9,033
cpp
C++
lite/mach.cpp
richardkchapman/nlp-engine
393d9f2b6352f6c41c3aa79ed5f7075cd93950c4
[ "MIT" ]
3
2021-01-08T19:14:43.000Z
2021-06-08T04:52:22.000Z
lite/mach.cpp
richardkchapman/nlp-engine
393d9f2b6352f6c41c3aa79ed5f7075cd93950c4
[ "MIT" ]
62
2020-06-04T02:37:12.000Z
2022-03-12T12:43:39.000Z
lite/mach.cpp
richardkchapman/nlp-engine
393d9f2b6352f6c41c3aa79ed5f7075cd93950c4
[ "MIT" ]
7
2019-07-18T19:58:27.000Z
2022-02-02T13:21:20.000Z
/******************************************************************************* Copyright (c) 2001-2010 by Text Analysis International, Inc. All rights reserved. ******************************************************************************** * * NAME: MACH.CPP * FILE: lite\mach.cpp * CR: 10/29/98 AM. * SUBJ: Things that may be machine specific. * *******************************************************************************/ #include "StdAfx.h" #include <time.h> #ifndef LINUX #include <direct.h> #endif #include <sys/types.h> // WORKAROUND. // 02/25/00 AM. #include <sys/timeb.h> // WORKAROUND. // 02/25/00 AM. #include "machine.h" // 10/25/06 AM. #include "prim/libprim.h" // 01/24/06 AM. #include "u_out.h" // 01/24/06 AM. #include "lite/global.h" #include "inline.h" // 09/26/01 AM. #include "lite/mach.h" #include "lite/dir.h" /******************************************** * FN: TODAY * CR: 10/29/98 AM. * SUBJ: Get the current date and time. * NOTE: Annoying that ctime includes a carriage return at end of string. ********************************************/ LITE_API _TCHAR *today() { static _TCHAR buf[64]; _TCHAR *tptr; // Debugging mem leak. // 02/25/00 AM. time_t ltime; struct tm *newtime; // FIX MEM LEAK!! // 02/25/00 AM. time(&ltime); newtime = localtime(&ltime); // TRYING. // 02/25/00 AM. tptr = _tasctime(newtime); // TRYING. // 02/25/00 AM. //tptr = ctime(&ltime); // 02/25/00 AM. _tcscpy(buf, tptr); // 02/25/00 AM. _TCHAR *ptr; ptr = _tcschr(buf, '\n'); if (ptr) *ptr = '\0'; // Wipe out first newline. return buf; } /************************************************** * DATE_STR * FUN: date_str * SUBJ: Get current date-time, nicely formatted. * CR: 10/7/95 AM. * RET: str - formatted date-time. * NOTE: 04/20/99 AM. Taken from LIBPRIM (Consh&Conan), so as to remove * the mach.cpp file from that library. * **************************************************/ LITE_API void date_str( _TCHAR str[], /* Buffer to fill with date-time. */ int siz /* Max size of buffer. */ ) { time_t now; struct tm *date; /* Get the current calendar time. */ time(&now); /* Break down time. */ date = localtime(&now); /* Convert to string. */ _tcsftime(str, siz, _T("%x %H:%M"), date); } /******************************************** * FN: DOSREADARGS * CR: 11/30/98 AM. * SUBJ: Get command line arguments. * RET: True if ok read, else false if failed. ********************************************/ LITE_API bool dosReadargs( int argc, _TCHAR *argv[], /*UP*/ _TCHAR* &input, // Input file from args. _TCHAR* &output, // Output file from args. bool &develop, // Development mode (output intermediate files). bool &compiled // true - compiled ana. false=interp(DEFAULT). ) { _TCHAR *ptr; _TCHAR **parg; bool f_in = false; bool f_out = false; bool flag = false; bool compiledck = false; // If compiled/interp arg seen. // 07/05/00 AM. input = output = 0; develop = false; // Default is not development mode. // 12/25/98 AM. compiled = false; // INTERP ANALYZER BY DEFAULT. // 07/05/00 AM. for (--argc, parg = &(argv[1]); argc > 0; --argc, ++parg) { // For each command line argument. //*gout << "command arg=" << *parg << endl; ptr = *parg; if (*ptr == '/' || *ptr == '-') // DOS or UNIX style arg. { if (flag) { _t_strstream gerrStr; gerrStr << _T("[Error in command line args for ") << argv[0] << _T("]") << ends; errOut(&gerrStr,false); return false; } ++ptr; if (!strcmp_i(ptr, _T("in"))) f_in = flag = true; // Expecting input file. else if (!strcmp_i(ptr, _T("out"))) f_out = flag = true; // Expecting output file. else if (!strcmp_i(ptr, _T("dev"))) // 12/25/98 AM. develop = true; // Development mode. else if (!strcmp_i(ptr, _T("interp"))) // Run interpreted analyzer. { if (compiledck) { _t_strstream gerrStr; gerrStr << _T("[Ignoring extra /compiled or /interp flag.]") << ends; errOut(&gerrStr,false); } else { compiledck = true; compiled = false; } } else if (!strcmp_i(ptr, _T("compiled"))) // Run compiled analyzer. { if (compiledck) { _t_strstream gerrStr; gerrStr << _T("[Ignoring extra /compiled or /interp flag.]") << ends; errOut(&gerrStr,false); } else { compiledck = true; compiled = true; } } } else if (flag) // Expected an argument value. { if (f_in) { if (input) { _t_strstream gerrStr; gerrStr << _T("[") << argv[0] << _T(": Input file specified twice.]") << ends; errOut(&gerrStr,false); dosHelpargs(argv[0]); return false; } // Grab value as input file. input = ptr; f_in = flag = false; } else if (f_out) { if (output) { _t_strstream gerrStr; gerrStr << _T("[") << argv[0] << _T(": Output file specified twice.]") << ends; errOut(&gerrStr,false); dosHelpargs(argv[0]); return false; } // Grab value as output file. output = ptr; f_out = flag = false; } } else // Got a "floating" value. { if (input && output) { _t_strstream gerrStr; gerrStr << _T("[") << argv[0] << _T(": Extra arguments.]") << ends; errOut(&gerrStr,false); dosHelpargs(argv[0]); return false; } else if (input) output = ptr; else input = ptr; } } return true; } /******************************************** * FN: DOSHELPARGS * CR: 11/30/98 AM. * SUBJ: Print command line argument help. * RET: True if ok read, else false if failed. ********************************************/ LITE_API void dosHelpargs(_TCHAR *name) { _t_cout << name << _T(" [/INTERP][/COMPILED][/IN infile] [/OUT outfile] [/DEV] [infile [outfile]]") << endl << _T("Note: /INTERP, the interpreted analyzer, is default.") << endl; } //////////////////////////////////////////////////////////// #ifdef TIMING_REFERENCE_ #include <stdio.h> #include <stdlib.h> #include <time.h> void _tmain( void ){ time_t start, finish; long loop; double result, elapsed_time; _tprintf( _T("Multiplying 2 floating point numbers 10 million times...\n") ); time( &start ); for( loop = 0; loop < 10000000; loop++ ) result = 3.63 * 5.27; time( &finish ); elapsed_time = difftime( finish, start ); _tprintf( _T("\nProgram takes %6.0f seconds.\n"), elapsed_time ); } #endif //////////////////////////////////////////////////////////////// /******************************************** * FN: DIR_EXISTS * CR: 03/10/99 AM. * SUBJ: See if given directory exists. * RET: True if exists. * OPT: Probably not the most efficient or principled method. ********************************************/ LITE_API bool dir_exists(_TCHAR *name) { _TCHAR cwd[MAXSTR]; /* Get the current working directory: */ #ifndef LINUX if(_tgetcwd( cwd, MAXSTR) == NULL) { _t_strstream gerrStr; gerrStr << _T("[dir_exists: Couldn't get working dir.]") << ends; errOut(&gerrStr,false); return false; } if(_tchdir(name)) return false; // Was able to change to it. Now change back. _tchdir(cwd); #endif return true; } /******************************************** * FN: MAKE_DIR * CR: 03/10/99 AM. * SUBJ: Make given directory. * RET: True if exists. * OPT: Probably not the most efficient or principled method. ********************************************/ LITE_API bool make_dir(_TCHAR *name) { #ifndef LINUX if(_tmkdir(name) == 0) return true; #endif return false; } /******************************************** * FN: RM_DIR * CR: 03/10/99 AM. * SUBJ: Remove given directory. Must be empty. * RET: True if exists. * OPT: Probably not the most efficient or principled method. ********************************************/ LITE_API bool rm_dir(_TCHAR *name) { #ifndef LINUX if(_trmdir(name) == 0) return true; #endif return false; } /******************************************** * FN: REMOVE_PATH * CR: 03/10/99 AM. * SUBJ: Remove given path. * RET: True if success. * NOTE: Remove file or remove directory. ********************************************/ LITE_API bool remove_path(_TCHAR *name) { if (!safe_dir(name)) return false; if(_tremove(name) == 0) return true; return false; } /******************************************** * FN: TODAY1 * CR: 02/25/00 AM. * SUBJ: Get the current date and time. * NOTE: Trying workaround to spurious error message from Purify 6.5, * about memory leak in asctime when that fn is in a dll. ********************************************/ LITE_API _TCHAR *today1() { static _TCHAR buf[256]; _TCHAR tmpbuf1[128], tmpbuf2[128]; /* Set time zone from TZ environment variable. If TZ is not set, * the operating system is queried to obtain the default value * for the variable. */ #ifndef LINUX _tzset(); /* Display operating system-style date and time. */ _tstrtime( tmpbuf1 ); _tstrdate( tmpbuf2 ); _stprintf(buf, _T("%s %s"), tmpbuf1, tmpbuf2); return buf; #else return today(); #endif }
24.217158
83
0.539577
richardkchapman
d901c987854d1faa741cf947dd691b10ca83570a
2,604
cpp
C++
Board.cpp
Stav-Nof/-messageboard-b
ef98415c0aca9c8c3472a96a8970be092749990e
[ "MIT" ]
null
null
null
Board.cpp
Stav-Nof/-messageboard-b
ef98415c0aca9c8c3472a96a8970be092749990e
[ "MIT" ]
null
null
null
Board.cpp
Stav-Nof/-messageboard-b
ef98415c0aca9c8c3472a96a8970be092749990e
[ "MIT" ]
null
null
null
#include "Board.hpp" #include <iostream> #include <string> #include <array> #include <limits.h> #include <stdexcept> #include <map> using namespace std; namespace ariel{ unsigned int max_colums; unsigned int min_colums; unsigned int max_row; unsigned int min_row; Board::Board(){ min_row = INT_MAX; max_row = 0; min_colums = INT_MAX; max_colums = 0; } void Board::post(unsigned int row, unsigned int column, enum Direction d, const string &s){ if (d == Direction::Horizontal){ for(unsigned int i=0; i<s.length(); i++){ b[row][column + i] = s[i]; } min_row = min(min_row,row); max_row = max(max_row,row); min_colums = min(min_colums,column); max_colums = max((column + unsigned(s.length())), max_colums); } else { for(unsigned int i=0; i<s.length(); i++) { b[row + i][column] = s[i]; } min_row = min(min_row,row); max_row = max((row + unsigned(s.length())), max_row); min_colums = min(min_colums,column); max_colums = max(min_colums,column); } } string Board::read(unsigned int row, unsigned int column , enum Direction d, unsigned int num){ string ans; for(unsigned int i=0; i<num; i++) { if (d == Direction::Horizontal) { if(b[row][column+i] == 0) { ans += "_"; } else { ans += b[row][column+i]; } } else { if(b[row+i][column] == 0) { ans += "_"; } else { ans += b[row+i][column]; } } } return ans; } void Board::show(){ unsigned int display_rows = (max_row - min_row) + 1; unsigned int display_cols = (max_colums - min_colums); for(unsigned int i = 0; i<display_rows; i++) { for(unsigned int j = 0; j<display_cols; j++) { if(b[i][j] != 0) { cout << b[i][j]; } else { cout << "_"; } } cout << endl; } } Board::~Board(){ } }
25.782178
99
0.409754
Stav-Nof
d902f59288b89d7e73930197565603c8cce54a72
1,243
cpp
C++
HANGCAYMAXMIN.cpp
phuongnam2002/testlib
a5cb8e2be7ac7a7e7dca7942a79ec20076f5d1aa
[ "MIT" ]
2
2022-01-14T13:34:09.000Z
2022-02-21T07:27:29.000Z
HANGCAYMAXMIN.cpp
phuongnam2002/testlib
a5cb8e2be7ac7a7e7dca7942a79ec20076f5d1aa
[ "MIT" ]
null
null
null
HANGCAYMAXMIN.cpp
phuongnam2002/testlib
a5cb8e2be7ac7a7e7dca7942a79ec20076f5d1aa
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int ssXau (string a, string b) { while (1) { if (a.length()==b.length()) break; if (a.length()>b.length()) b='0'+b; else a='0'+a; } for (int i=0; i<a.length(); i++) { int soA=a[i]-'0'; int soB=b[i]-'0'; if (soA>soB) return 1; else if (soA<soB) return -1; } return 0; } string chXau (string a) { int vt=-1; for (int i=0; i<a.length(); i++) { if (a[i]!='0') { vt=i; break; } } if (vt==-1) return "0"; else { string b=""; for (int i=vt; i<a.length(); i++) { b+=a[i]; } return b; } } //chuan hoa xau-> int main () { int N; int t=0; while (1) { cin>>N; if (N==0) break; t++; string Min="", Max=""; string a; int kt=0; for (int i=1; i<=N; i++) { cin>>a; if (i==1) { Min=a; Max=a; } else { if (ssXau (a, Max)==1) { Max=a; kt=1; } if (ssXau (a, Min)==-1) { Min=a; kt=1; } } } if (kt==1) cout<<"Case "<<t<<": "<<chXau (Min)<<" "<<chXau(Max)<<endl; else cout<<"Case "<<t<<": "<<"There is a row of trees having equal height."<<endl; } return 0; }
14.453488
85
0.43041
phuongnam2002
d90b701176a4b0010470310f7743f9263b20b028
5,237
hpp
C++
src/xalanc/XSLT/ElemUse.hpp
kidaa/xalan-c
bb666d0ab3d0a192410823e6857c203d83c27b16
[ "Apache-2.0" ]
null
null
null
src/xalanc/XSLT/ElemUse.hpp
kidaa/xalan-c
bb666d0ab3d0a192410823e6857c203d83c27b16
[ "Apache-2.0" ]
1
2021-08-18T12:32:31.000Z
2021-08-18T12:32:31.000Z
src/xalanc/XSLT/ElemUse.hpp
AaronNGray/xalan
6741bbdcb64a9d33df8bd7e21b558d66bb4292ec
[ "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. */ #if !defined(XALAN_ELEMUSE_HEADER_GUARD) #define XALAN_ELEMUSE_HEADER_GUARD // Base include file. Must be first. #include "XSLTDefinitions.hpp" // Base class header file. #include "ElemTemplateElement.hpp" XALAN_CPP_NAMESPACE_BEGIN class ElemUse : public ElemTemplateElement { public: #if defined(XALAN_STRICT_ANSI_HEADERS) typedef std::size_t size_type; #else typedef size_t size_type; #endif /** * Construct an object corresponding to an "use-attribute-sets" attribute. * This is a base class for "xsl:element," "xsl:copy" and * "xsl:attribute-set" elements, which may specify attribute sets to use. * * @param constructionContext context for construction of object * @param stylesheetTree stylesheet containing element * @param atts list of attributes for element * @param lineNumber line number in document * @param columnNumber column number in document */ ElemUse( StylesheetConstructionContext& constructionContext, Stylesheet& stylesheetTree, XalanFileLoc lineNumber, XalanFileLoc columnNumber, int xslToken); virtual ~ElemUse(); /** * See if this is a use-attribute-sets attribute, and, if so, process it. * * @param attrName qualified name of attribute * @param atts attribute list where the element comes from (not used at * this time) * @param which index into the attribute list (not used at this time) * @return true if this is a use-attribute-sets attribute */ bool processUseAttributeSets( StylesheetConstructionContext& constructionContext, const XalanDOMChar* attrName, const AttributeListType& atts, XalanSize_t which); // These methods are inherited from ElemTemplateElement ... virtual const XalanDOMString& getElementName() const; virtual void postConstruction( StylesheetConstructionContext& constructionContext, const NamespacesHandler& theParentHandler); #if !defined(XALAN_RECURSIVE_STYLESHEET_EXECUTION) virtual const ElemTemplateElement* startElement(StylesheetExecutionContext& executionContext) const; virtual void endElement(StylesheetExecutionContext& executionContext) const; virtual const ElemTemplateElement* getNextChildElemToExecute( StylesheetExecutionContext& executionContext, const ElemTemplateElement* currentElem) const; virtual const ElemTemplateElement* getFirstChildElemToExecute( StylesheetExecutionContext& executionContext) const; #else virtual void execute(StylesheetExecutionContext& executionContext) const; #endif protected: #if !defined(XALAN_RECURSIVE_STYLESHEET_EXECUTION) /** * Get the next attribute set to execute. * * @param executionContext context to execute this element * @returns a pointer to the attribute set element, 0 if no more attribute sets */ const ElemTemplateElement* getNextAttributeSet( StylesheetExecutionContext& executionContext) const; /** * Evalute the AVTs for this element * * @param executionContext context to execute this element */ virtual void evaluateAVTs( StylesheetExecutionContext& executionContext) const; #else /** * Execute and conditionally apply any attribute sets. To be used * by deriving classes who want ElemUse to do any default execution * but skip applying attribute sets. Typically, this would be done * when attempting to recover from an error. * * @param executionContext The current execution context. * @param applyAttributeSets If true, attribute sets will be applied. */ virtual void doExecute( StylesheetExecutionContext& executionContext, bool applyAttributeSets) const; #endif private: const XalanQName** m_attributeSetsNames; size_type m_attributeSetsNamesCount; }; XALAN_CPP_NAMESPACE_END #endif // XALAN_ELEMUSE_HEADER_GUARD
31.548193
84
0.670422
kidaa
d90c918ef58420e11cb3ae0ae69ff15b92b81acd
1,349
cpp
C++
Codeforces-Code/Codeforces Round 338 (Div. 2)/D.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
Codeforces-Code/Codeforces Round 338 (Div. 2)/D.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
Codeforces-Code/Codeforces Round 338 (Div. 2)/D.cpp
PrayStarJirachi/Exercise-Code
801a5926eccc971ab2182e5e99e3a0746bd6a7f0
[ "MIT" ]
null
null
null
#include <cstdio> #include <vector> #include <numeric> #include <iostream> #include <algorithm> const double EPS = 1e-7; const double PI = 3.1415926535897932384626; const int MAXN = 222222; const int MOD = 1000000007; int n, a[MAXN], pred[MAXN], succ[MAXN]; std::vector<std::pair<int, int> > group; int fpm(int a, long long b) { int ret = 1; for (; b; b >>= 1) { if (b & 1) ret = 1ll * ret * a % MOD; a = 1ll * a * a % MOD; } return ret; } int main() { std::cin >> n; for (int i = 1; i <= n; i++) std::cin >> a[i]; std::sort(a + 1, a + n + 1); for (int i = 1; i <= n; i++) { int z = i; while (i < n && a[i] == a[i + 1]) { i++; } group.push_back(std::make_pair(a[i], i - z + 1)); } for (int i = 0; i < group.size(); i++) { pred[i] = 1ll * ((i == 0) ? 1 : pred[i - 1]) * (group[i].second + 1) % (MOD - 1); } succ[group.size()] = 1; for (int i = (int)group.size() - 1; i >= 0; i--) { succ[i] = 1ll * succ[i + 1] * (group[i].second + 1) % (MOD - 1); } int answer = 1; for (int i = 0, size = group.size(); i < size; i++) { long long exp = 0; exp = (1ll * group[i].second * (group[i].second + 1) >> 1) % (MOD - 1); exp = 1ll * exp * (i == 0 ? 1 : pred[i - 1]) % (MOD - 1) * succ[i + 1] % (MOD - 1); answer = 1ll * answer * fpm(group[i].first, exp) % MOD; } std::cout << answer << std::endl; return 0; }
25.45283
85
0.509266
PrayStarJirachi
d90da9b7701d58a3058b3ff1a8882c291e23b7d9
2,174
cpp
C++
src/database/overlay/SoXipAngle.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
2
2020-05-21T07:06:07.000Z
2021-06-28T02:14:34.000Z
src/database/overlay/SoXipAngle.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
null
null
null
src/database/overlay/SoXipAngle.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
6
2016-03-21T19:53:18.000Z
2021-06-08T18:06:03.000Z
/* Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation All rights reserved. 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 <Inventor/actions/SoGLRenderAction.h> #include <Inventor/nodes/SoSeparator.h> #include <Inventor/sensors/SoFieldSensor.h> #include "SoXipAngle.h" #include "SoXipLine.h" #include "geomutils.h" SO_NODE_SOURCE( SoXipAngle ); SoXipAngle::SoXipAngle() { SO_NODE_CONSTRUCTOR( SoXipAngle ); addChild( new SoXipLine ); addChild( new SoXipLine ); setCreationChild(1); setUpConnections( TRUE, TRUE ); } SoXipAngle::~SoXipAngle() { } void SoXipAngle::initClass() { SO_NODE_INIT_CLASS( SoXipAngle, SoXipShapeGroup, "SoXipShapeGroup" ); } void SoXipAngle::GLRender( SoGLRenderAction* action ) { if( !on.getValue() ) return ; computeAngle(); SoXipShapeGroup::GLRender( action ); } void SoXipAngle::computeAngle() { SoXipLine* line0 = (SoXipLine *) getChild(0); SoXipLine* line1 = (SoXipLine *) getChild(1); if( line0->point.getNum() == 2 && line1->point.getNum() == 2 ) { SbVec3f u = line0->point[1] - line0->point[0]; SbVec3f v = line1->point[1] - line1->point[0]; float angle = 0; if( u.length() && v.length() ) { angle = angleBetweenVectors( u, v, u.cross(v) ); } // Convert to degrees angle = angle * 180. / M_PI; if(angle > 180) angle = 360 - angle; char stringName[1024]; sprintf( stringName, "%.0f deg.", angle); line0->caption.setValue( stringName ); } } void SoXipAngle::setRank( int rank ) { ((SoXipShape *) getChild(1))->rank.setValue( rank ); } void SoXipAngle::setCaption( const SbString& caption ) { ((SoXipShape *) getChild(1))->caption.setValue( caption ); }
21.74
81
0.709292
OpenXIP
d90eddb2b04218f80a7fa06500d1ce8d8f0675d4
545
hpp
C++
ui/include/xaml/ui/qt5/control.hpp
Berrysoft/XamlCpp
cc7da0cf83892ceb88926292b7c90b9f8da6128d
[ "MIT" ]
27
2020-01-02T07:40:57.000Z
2022-03-09T14:43:56.000Z
ui/include/xaml/ui/qt5/control.hpp
Berrysoft/XamlCpp
cc7da0cf83892ceb88926292b7c90b9f8da6128d
[ "MIT" ]
null
null
null
ui/include/xaml/ui/qt5/control.hpp
Berrysoft/XamlCpp
cc7da0cf83892ceb88926292b7c90b9f8da6128d
[ "MIT" ]
3
2020-05-21T07:02:08.000Z
2021-07-01T00:56:38.000Z
#ifndef XAML_UI_QT_CONTROL_H #define XAML_UI_QT_CONTROL_H #include <QWidget> #include <memory> #include <xaml/meta/meta_macros.h> XAML_CLASS(xaml_qt5_control, { 0x0cafa395, 0x4050, 0x4b84, { 0x8f, 0xeb, 0x02, 0xaa, 0xa1, 0x27, 0x21, 0x7b } }) #define XAML_QT5_CONTROL_VTBL(type) \ XAML_VTBL_INHERIT(XAML_OBJECT_VTBL(type)); \ XAML_PROP(handle, type, QWidget**, QWidget*) XAML_DECL_INTERFACE_(xaml_qt5_control, xaml_object) { XAML_DECL_VTBL(xaml_qt5_control, XAML_QT5_CONTROL_VTBL); }; #endif // !XAML_UI_QT_CONTROL_H
27.25
112
0.752294
Berrysoft
d90f3248dd4979fbd4bbc8bfc8a78cad4d6c4c91
982
cpp
C++
Source/Boids/Systems/Persistent/BoidsDebugDrawSystem.cpp
PsichiX/Unreal-Systems-Architecture
fb2ccb243c8e79b0890736d611db7ba536937a93
[ "Apache-2.0" ]
5
2022-02-09T21:19:03.000Z
2022-03-03T01:53:03.000Z
Source/Boids/Systems/Persistent/BoidsDebugDrawSystem.cpp
PsichiX/Unreal-Systems-Architecture
fb2ccb243c8e79b0890736d611db7ba536937a93
[ "Apache-2.0" ]
null
null
null
Source/Boids/Systems/Persistent/BoidsDebugDrawSystem.cpp
PsichiX/Unreal-Systems-Architecture
fb2ccb243c8e79b0890736d611db7ba536937a93
[ "Apache-2.0" ]
null
null
null
#include "Boids/Systems/Persistent/BoidsDebugDrawSystem.h" #include "DrawDebugHelpers.h" #include "Shared/Components/VelocityComponent.h" #include "Systems/Public/SystemsWorld.h" #include "Boids/Components/BoidComponent.h" #include "Boids/Resources/BoidsSystemsRunCriteria.h" const float ARROW_LENGTH = 20; const float THICKNESS = 8; void BoidsDebugDrawSystem(USystemsWorld& Systems) { const auto* BoidsSystemsRunCriteria = Systems.Resource<UBoidsSystemsRunCriteria>(); if (IsValid(BoidsSystemsRunCriteria) && BoidsSystemsRunCriteria->bRunDebugDraw == false) { return; } Systems.Query<UVelocityComponent, UBoidComponent>().ForEach( [&](const auto& QueryItem) { const auto* Actor = QueryItem.Get<0>(); const auto* Velocity = QueryItem.Get<1>(); const auto From = Actor->GetActorLocation(); const auto To = From + Velocity->Value; DrawDebugDirectionalArrow( Systems.GetWorld(), From, To, ARROW_LENGTH, FColor::Red, false, 0, 0, THICKNESS); }); }
29.757576
89
0.751527
PsichiX
d90f49d66b25b39b21b9533521b95f866bb7a6f0
2,570
hpp
C++
time.hpp
komasaru/calc_greenwich_time
af45776181c2a457a944cd472e1b5069589aa2d8
[ "MIT" ]
null
null
null
time.hpp
komasaru/calc_greenwich_time
af45776181c2a457a944cd472e1b5069589aa2d8
[ "MIT" ]
null
null
null
time.hpp
komasaru/calc_greenwich_time
af45776181c2a457a944cd472e1b5069589aa2d8
[ "MIT" ]
null
null
null
#ifndef CALC_GREENWICH_TIME_HPP_ #define CALC_GREENWICH_TIME_HPP_ #include "delta_t.hpp" #include "file.hpp" #include <cmath> #include <ctime> #include <fstream> #include <iomanip> #include <sstream> #include <string> #include <vector> namespace calc_greenwich { struct timespec jst2utc(struct timespec); // JST -> UTC 変換 std::string gen_time_str(struct timespec); // 日時文字列生成 class Time { static std::vector<std::vector<std::string>> l_ls; // List of Leap Second static std::vector<std::vector<std::string>> l_dut; // List of DUT1 struct timespec ts; // timespec of UTC struct timespec ts_tai; // timespec of TAI struct timespec ts_ut1; // timespec of UT1 struct timespec ts_tt; // timespec of TT struct timespec ts_tcg; // timespec of TCG struct timespec ts_tcb; // timespec of TCB struct timespec ts_tdb; // timespec of TDB double jd; // JD (ユリウス日) double t; // T (ユリウス世紀数) double dut1; // UTC - TAI (協定世界時と国際原子時の差 = うるう秒の総和) double dlt_t; // ΔT (TT(地球時) と UT1(世界時1)の差) int utc_tai; // UTC - TAI (協定世界時と国際原子時の差 = うるう秒の総和) public: Time(struct timespec); // コンストラクタ struct timespec calc_jst(); // 計算: JST (日本標準時) double calc_jd(); // 計算: JD (ユリウス日) double calc_t(); // 計算: T (ユリウス世紀数) int calc_utc_tai(); // 計算: UTC - TAI (協定世界時と国際原子時の差 = うるう秒の総和) double calc_dut1(); // 計算: DUT1 (UT1(世界時1) と UTC(協定世界時)の差) double calc_dlt_t(); // 計算: ΔT (TT(地球時) と UT1(世界時1)の差) struct timespec calc_tai(); // 計算: TAI (国際原子時) struct timespec calc_ut1(); // 計算: UT1 (世界時1) struct timespec calc_tt(); // 計算: TT (地球時) struct timespec calc_tcg(); // 計算: TCG (地球重心座標時) struct timespec calc_tcb(); // 計算: TCB (太陽系重心座標時) struct timespec calc_tdb(); // 計算: TDB (太陽系力学時) private: struct timespec utc2jst(struct timespec); // UTC -> JST double gc2jd(struct timespec); // GC -> JD double jd2t(double); // JD -> T int get_utc_tai(struct timespec); // UTC -> UTC - TAI double get_dut1(struct timespec); // UTC -> DUT1 struct timespec utc2tai(struct timespec); // UTC -> TAI struct timespec utc2ut1(struct timespec); // UTC -> UT1 struct timespec tai2tt(struct timespec); // TAI -> TT struct timespec tt2tcg(struct timespec); // TT -> TCG struct timespec tt2tcb(struct timespec); // TT -> TCB struct timespec tcb2tdb(struct timespec); // TCB -> TDB }; } // namespace calc_greenwich #endif
37.246377
77
0.62607
komasaru
d911c6933e9ea1fef855ebe910662962014816ff
1,314
hpp
C++
src/rooms/task.hpp
snailbaron/rooms
03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa
[ "MIT" ]
null
null
null
src/rooms/task.hpp
snailbaron/rooms
03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa
[ "MIT" ]
null
null
null
src/rooms/task.hpp
snailbaron/rooms
03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa
[ "MIT" ]
null
null
null
#pragma once #include <cmath> #include <functional> #include <memory> #include <type_traits> #include <utility> #include <vector> enum class TaskState { Running, Finished, }; class TaskPool { public: void addTask(std::function<TaskState(float)>&& task) { _tasks.push_back(std::move(task)); } void update(float delta) { for (size_t i = 0; i < _tasks.size(); ) { auto state = _tasks[i](delta); if (state == TaskState::Finished) { std::swap(_tasks[i], _tasks.back()); _tasks.resize(_tasks.size() - 1); } else { i++; } } } private: std::vector<std::function<TaskState(float)>> _tasks; }; class SwayTask { public: SwayTask( float period, std::function<void(float value)>&& setter) : _period(period) , _setter(std::move(setter)) { } TaskState operator()(float delta) { _point = std::fmod(_point * _period + delta, _period) / _period; float value = 0.5f + std::sin(static_cast<float>(_point * 2 * M_PI)) / 2; _setter(value); return TaskState::Running; } private: const float _period; const std::function<void(float value)> _setter; float _point = 0; };
21.540984
81
0.554795
snailbaron
d9150398e1d9d41dbfd7c16f8ac0d0a9c395dd3c
7,081
hpp
C++
Drivers/BuR/Implementation/libmcdriver_bur_connector.hpp
alexanderoster/AutodeskMachineControlFramework
17aec986c2cb3c9ea46bbe583bdc0e766e6f980b
[ "BSD-3-Clause" ]
15
2020-11-10T17:22:39.000Z
2021-12-16T14:45:11.000Z
Drivers/BuR/Implementation/libmcdriver_bur_connector.hpp
alexanderoster/AutodeskMachineControlFramework
17aec986c2cb3c9ea46bbe583bdc0e766e6f980b
[ "BSD-3-Clause" ]
5
2021-08-30T06:58:52.000Z
2022-03-09T15:25:49.000Z
Drivers/BuR/Implementation/libmcdriver_bur_connector.hpp
alexanderoster/AutodeskMachineControlFramework
17aec986c2cb3c9ea46bbe583bdc0e766e6f980b
[ "BSD-3-Clause" ]
20
2020-08-06T15:53:34.000Z
2022-02-09T13:49:59.000Z
/*++ Copyright (C) 2020 Autodesk Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Autodesk Inc. 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 AUTODESK INC. 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. Abstract: This is the class declaration of CDriver_BuR */ #ifndef __LIBMCDRIVER_BUR_CONNECTOR #define __LIBMCDRIVER_BUR_CONNECTOR #include "libmcdriver_bur_connector.hpp" #include "libmcdriver_bur_definitions.hpp" // Include custom headers here. #include <mutex> #include <map> #include <memory> #include <queue> #include <functional> #define BUR_MINCUSTOMCOMMANDID 1024 #define BUR_MAXCUSTOMCOMMANDID 65535 #define BUR_COMMAND_DIRECT_INIT 100 #define BUR_COMMAND_DIRECT_BEGINLIST 101 #define BUR_COMMAND_DIRECT_FINISHLIST 102 #define BUR_COMMAND_DIRECT_EXECUTELIST 103 #define BUR_COMMAND_DIRECT_PAUSELIST 104 #define BUR_COMMAND_DIRECT_LISTSTATUS 105 #define BUR_COMMAND_DIRECT_ABORTLIST 106 #define BUR_COMMAND_DIRECT_RESUMELIST 107 #define BUR_COMMAND_DIRECT_MACHINESTATUS 108 #define BUR_COMMAND_DIRECT_JOURNALSTART 109 #define BUR_COMMAND_DIRECT_JOURNALSTOP 110 #define BUR_COMMAND_DIRECT_JOURNALRETRIEVE 111 namespace LibMCDriver_BuR { namespace Impl { class CDriver_BuRSocketConnection; #pragma pack(push) #pragma pack(1) struct sAMCFToPLCPacket { uint32_t m_nSignature; uint8_t m_nMajorVersion; uint8_t m_nMinorVersion; uint8_t m_nPatchVersion; uint8_t m_nBuildVersion; uint32_t m_nClientID; uint32_t m_nSequenceID; uint32_t m_nCommandID; sAMCFToPLCPacketPayload m_Payload; uint32_t m_nChecksum; }; struct sPLCToAMCFPacket { uint32_t m_nSignature; uint8_t m_nMajorVersion; uint8_t m_nMinorVersion; uint8_t m_nPatchVersion; uint8_t m_nBuildVersion; uint32_t m_nClientID; uint32_t m_nSequenceID; uint32_t m_nErrorCode; uint32_t m_nCommandID; uint32_t m_nMessageLen; uint32_t m_nHeaderChecksum; uint32_t m_nDataChecksum; }; #pragma pack(pop) /************************************************************************************************************************* Class declaration of CDriver_BuR **************************************************************************************************************************/ class CDriver_BuRPacket { private: uint32_t m_nCommandID; uint32_t m_nStatusCode; std::vector<uint8_t> m_Data; public: CDriver_BuRPacket(uint32_t nCommandID, uint32_t nStatusCode); ~CDriver_BuRPacket(); uint32_t getCommandID(); uint32_t getStatusCode(); uint32_t readUInt32(uint32_t nAddress); uint16_t readUInt16(uint32_t nAddress); uint8_t readUInt8(uint32_t nAddress); float readFloat(uint32_t nAddress); double readDouble(uint32_t nAddress); bool readBool(uint32_t nAddress); std::string readString(uint32_t nAddress, uint32_t nLength); std::vector<uint8_t> & getDataBuffer (); }; typedef std::shared_ptr<CDriver_BuRPacket> PDriver_BuRPacket; class CDriver_BuRSendInfo; typedef std::function<void(CDriver_BuRSendInfo * pSendInfo, CDriver_BuRPacket * pPacket)> BurSendCallback; class CDriver_BuRSendInfo { private: uint32_t m_nCommandID; uint32_t m_nSequenceID; uint32_t m_nClientID; uint64_t m_nTimeStamp; BurSendCallback m_Callback; public: CDriver_BuRSendInfo(uint32_t nCommandID, uint32_t nSequenceID, uint32_t nClientID, uint64_t nTimeStamp, BurSendCallback sendCallback); ~CDriver_BuRSendInfo(); uint32_t getCommandID(); uint32_t getSequenceID(); uint32_t getClientID(); uint64_t getTimeStamp(); void resetCallback(); void triggerCallback(CDriver_BuRPacket* pPacket); }; typedef std::shared_ptr<CDriver_BuRSendInfo> PDriver_BuRSendInfo; class CDriver_BuRConnector { private: protected: uint32_t m_nWorkerThreadCount; uint32_t m_nMaxReceiveBufferSize; uint32_t m_nMajorVersion; uint32_t m_nMinorVersion; uint32_t m_nPatchVersion; uint32_t m_nBuildVersion; uint32_t m_nMaxPacketQueueSize; uint32_t m_nSequenceID; bool m_StartJournaling; std::shared_ptr<CDriver_BuRSocketConnection> m_pCurrentConnection; std::map<uint32_t, PDriver_BuRSendInfo> m_SentPacketQueue; std::queue<sAMCFToPLCPacket> m_PacketsToSend; std::mutex m_ConnectionMutex; std::mutex m_SequenceMapMutex; std::list<PDriver_BuRValue> m_DriverParameters; std::map<std::string, PDriver_BuRValue> m_DriverParameterMap; std::map<std::string, PDriver_BuRCommandDefinition> m_CommandDefinitions; std::map<std::string, PDriver_BuRValue> m_ControlParameterMap; PDriver_BuRPacket receiveCommandFromPLCEx (CDriver_BuRSocketConnection* pConnection); void handlePacket(); public: CDriver_BuRConnector (uint32_t nWorkerThreadCount, uint32_t nMaxReceiveBufferSize, uint32_t nMajorVersion, uint32_t nMinorVersion, uint32_t nPatchVersion, uint32_t nBuildVersion, uint32_t nMaxPacketQueueSize); void queryParameters(uint64_t nTimeStamp, BurSendCallback pCallback); void refreshJournal(); void connect(const std::string& sIPAddress, const uint32_t nPort, const uint32_t nTimeout); void disconnect(); uint32_t sendCommandToPLC(uint32_t nCommandID, sAMCFToPLCPacketPayload payLoad, uint64_t nTimeStamp, BurSendCallback pCallback); uint32_t sendSimpleCommandToPLC(uint32_t nCommandID, uint64_t nTimeStamp, BurSendCallback pCallback, uint32_t nParameter0 = 0, uint32_t nParameter1 = 0, uint32_t nParameter2 = 0); void unregisterSendCallback(uint32_t nSequenceID); }; typedef std::shared_ptr<CDriver_BuRConnector> PDriver_BuRConnector; } // namespace Impl } // namespace LibMCDriver_BuR #endif // __LIBMCDRIVER_BUR_CONNECTOR
31.471111
210
0.751306
alexanderoster
d917a216ecb2c10ea9b4d9922ee47ac8cdd93c13
12,314
cpp
C++
CrashRpt/reporting/crashsender/DetailDlg.cpp
codereba/bittrace
6826559565aaafc9412d20427d21b73e23febcfe
[ "Unlicense" ]
10
2018-11-09T01:08:15.000Z
2020-06-21T05:39:54.000Z
CrashRpt/reporting/crashsender/DetailDlg.cpp
codereba/bittrace
6826559565aaafc9412d20427d21b73e23febcfe
[ "Unlicense" ]
null
null
null
CrashRpt/reporting/crashsender/DetailDlg.cpp
codereba/bittrace
6826559565aaafc9412d20427d21b73e23febcfe
[ "Unlicense" ]
4
2018-11-09T03:29:52.000Z
2021-07-23T03:30:03.000Z
/************************************************************************************* This file is a part of CrashRpt library. Copyright (c) 2003, Michael Carruth All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author 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 HOLDER 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 "stdafx.h" #include "DetailDlg.h" #include "Utility.h" #include "CrashInfoReader.h" #include "ErrorReportSender.h" #include "strconv.h" LRESULT CDetailDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { DlgResize_Init(); // Mirror this window if RTL language is in use CString sRTL = Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("Settings"), _T("RTLReading")); if(sRTL.CompareNoCase(_T("1"))==0) { Utility::SetLayoutRTL(m_hWnd); } SetWindowText(Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("DlgCaption"))); m_previewMode = PREVIEW_AUTO; m_filePreview.SubclassWindow(GetDlgItem(IDC_PREVIEW)); m_filePreview.SetBytesPerLine(10); m_filePreview.SetEmptyMessage(Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("NoDataToDisplay"))); // Init "Privacy Policy" link m_linkPrivacyPolicy.SubclassWindow(GetDlgItem(IDC_PRIVACYPOLICY)); m_linkPrivacyPolicy.SetHyperLink(g_CrashInfo.m_sPrivacyPolicyURL); m_linkPrivacyPolicy.SetLabel(Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("PrivacyPolicy"))); if(!g_CrashInfo.m_sPrivacyPolicyURL.IsEmpty()) m_linkPrivacyPolicy.ShowWindow(SW_SHOW); else m_linkPrivacyPolicy.ShowWindow(SW_HIDE); CStatic statHeader = GetDlgItem(IDC_HEADERTEXT); statHeader.SetWindowText(Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("DoubleClickAnItem"))); m_list = GetDlgItem(IDC_FILE_LIST); m_list.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT); m_list.InsertColumn(0, Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("FieldName")), LVCFMT_LEFT, 150); m_list.InsertColumn(1, Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("FieldDescription")), LVCFMT_LEFT, 180); m_list.InsertColumn(3, Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("FieldSize")), LVCFMT_RIGHT, 60); m_iconList.Create(16, 16, ILC_COLOR32|ILC_MASK, 3, 1); m_list.SetImageList(m_iconList, LVSIL_SMALL); // Insert items to the list WIN32_FIND_DATA findFileData = {0}; HANDLE hFind = NULL; CString sSize; std::map<CString, ERIFileItem>::iterator p; unsigned i; for (i = 0, p = g_CrashInfo.GetReport(m_nCurReport).m_FileItems.begin(); p != g_CrashInfo.GetReport(m_nCurReport).m_FileItems.end(); p++, i++) { CString sDestFile = p->first; CString sSrcFile = p->second.m_sSrcFile; CString sFileDesc = p->second.m_sDesc; SHFILEINFO sfi; SHGetFileInfo(sSrcFile, 0, &sfi, sizeof(sfi), SHGFI_DISPLAYNAME | SHGFI_ICON | SHGFI_TYPENAME | SHGFI_SMALLICON); int iImage = -1; if(sfi.hIcon) { iImage = m_iconList.AddIcon(sfi.hIcon); DestroyIcon(sfi.hIcon); } int nItem = m_list.InsertItem(i, sDestFile, iImage); CString sFileType = sfi.szTypeName; m_list.SetItemText(nItem, 1, sFileDesc); hFind = FindFirstFile(sSrcFile, &findFileData); if (INVALID_HANDLE_VALUE != hFind) { FindClose(hFind); ULARGE_INTEGER lFileSize; lFileSize.LowPart = findFileData.nFileSizeLow; lFileSize.HighPart = findFileData.nFileSizeHigh; sSize = Utility::FileSizeToStr(lFileSize.QuadPart); m_list.SetItemText(nItem, 2, sSize); } } // Select the first list item m_list.SetItemState(0, LVIS_SELECTED, LVIS_SELECTED); // Init "Preview" static control m_statPreview = GetDlgItem(IDC_PREVIEWTEXT); m_statPreview.SetWindowText(Utility::GetINIString( g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("Preview"))); // Init "OK" button m_btnClose = GetDlgItem(IDOK); m_btnClose.SetWindowText(Utility::GetINIString( g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("Close"))); // Init "Export..." button m_btnExport = GetDlgItem(IDC_EXPORT); m_btnExport.SetWindowText(Utility::GetINIString( g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("Export"))); // center the dialog on the screen CenterWindow(); return TRUE; } LRESULT CDetailDlg::OnItemChanged(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/) { LPNMLISTVIEW lpItem = (LPNMLISTVIEW)pnmh; int iItem = lpItem->iItem; if (lpItem->uChanged & LVIF_STATE && lpItem->uNewState & LVIS_SELECTED) { SelectItem(iItem); } return 0; } LRESULT CDetailDlg::OnItemDblClicked(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/) { LPNMLISTVIEW lpItem = (LPNMLISTVIEW)pnmh; int iItem = lpItem->iItem; DWORD_PTR dwRet = 0; if (iItem < 0 || (int)g_CrashInfo.GetReport(m_nCurReport).m_FileItems.size() < iItem) return 0; std::map<CString, ERIFileItem>::iterator p = g_CrashInfo.GetReport(m_nCurReport).m_FileItems.begin(); for (int i = 0; i < iItem; i++, p++); CString sFileName = p->second.m_sSrcFile; dwRet = (DWORD_PTR)::ShellExecute(0, _T("open"), sFileName, 0, 0, SW_SHOWNORMAL); ATLASSERT(dwRet > 32); return 0; } void CDetailDlg::SelectItem(int iItem) { // Sanity check if (iItem < 0 || (int)g_CrashInfo.GetReport(m_nCurReport).m_FileItems.size() < iItem) return; std::map<CString, ERIFileItem>::iterator p = g_CrashInfo.GetReport(m_nCurReport).m_FileItems.begin(); for (int i = 0; i < iItem; i++, p++); m_previewMode = PREVIEW_AUTO; m_textEncoding = ENC_AUTO; m_filePreview.SetFile(p->second.m_sSrcFile, m_previewMode); } LRESULT CDetailDlg::OnOK(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { EndDialog(0); return 0; } LRESULT CDetailDlg::OnExport(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { CString sFileName = g_CrashInfo.GetReport(m_nCurReport).m_sCrashGUID + _T(".zip"); CFileDialog dlg(FALSE, _T("*.zip"), sFileName, OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT, _T("ZIP Files (*.zip)\0*.zip\0All Files (*.*)\0*.*\0\0"), m_hWnd); INT_PTR result = dlg.DoModal(); if(result==IDOK) { CString sExportFileName = dlg.m_szFileName; g_ErrorReportSender.SetExportFlag(TRUE, sExportFileName); g_ErrorReportSender.DoWork(COMPRESS_REPORT); } return 0; } LRESULT CDetailDlg::OnPreviewRClick(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) { CPoint pt; GetCursorPos(&pt); CMenu menu; menu.LoadMenu(IDR_POPUPMENU); CMenu submenu = menu.GetSubMenu(1); MENUITEMINFO mii; memset(&mii, 0, sizeof(MENUITEMINFO)); mii.cbSize = sizeof(MENUITEMINFO); mii.fMask = MIIM_STRING; strconv_t strconv; CString sAuto = Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("PreviewAuto")); CString sText = Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("PreviewText")); CString sHex = Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("PreviewHex")); CString sImage = Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("PreviewImage")); CString sEncoding = Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("Encoding")); mii.dwTypeData = sAuto.GetBuffer(0); submenu.SetMenuItemInfo(ID_PREVIEW_AUTO, FALSE, &mii); mii.dwTypeData = sHex.GetBuffer(0); submenu.SetMenuItemInfo(ID_PREVIEW_HEX, FALSE, &mii); mii.dwTypeData = sText.GetBuffer(0); submenu.SetMenuItemInfo(ID_PREVIEW_TEXT, FALSE, &mii); mii.dwTypeData = sImage.GetBuffer(0); submenu.SetMenuItemInfo(ID_PREVIEW_IMAGE, FALSE, &mii); UINT uItem = ID_PREVIEW_AUTO; if(m_previewMode==PREVIEW_HEX) uItem = ID_PREVIEW_HEX; else if(m_previewMode==PREVIEW_TEXT) uItem = ID_PREVIEW_TEXT; else if(m_previewMode==PREVIEW_IMAGE) uItem = ID_PREVIEW_IMAGE; submenu.CheckMenuRadioItem(ID_PREVIEW_AUTO, ID_PREVIEW_IMAGE, uItem, MF_BYCOMMAND); if(m_filePreview.GetPreviewMode()!=PREVIEW_TEXT) { submenu.DeleteMenu(5, MF_BYPOSITION); submenu.DeleteMenu(4, MF_BYPOSITION); } else { CMenuHandle TextEncMenu = submenu.GetSubMenu(5); mii.dwTypeData = sEncoding.GetBuffer(0); submenu.SetMenuItemInfo(5, TRUE, &mii); UINT uItem2 = ID_ENCODING_AUTO; if(m_textEncoding==ENC_AUTO) uItem2 = ID_ENCODING_AUTO; else if(m_textEncoding==ENC_ASCII) uItem2 = ID_ENCODING_ASCII; else if(m_textEncoding==ENC_UTF8) uItem2 = ID_ENCODING_UTF8; else if(m_textEncoding==ENC_UTF16_LE) uItem2 = ID_ENCODING_UTF16; else if(m_textEncoding==ENC_UTF16_BE) uItem2 = ID_ENCODING_UTF16BE; TextEncMenu.CheckMenuRadioItem(ID_ENCODING_AUTO, ID_ENCODING_UTF16BE, uItem2, MF_BYCOMMAND); } submenu.TrackPopupMenu(TPM_LEFTBUTTON, pt.x, pt.y, m_hWnd); return 0; } LRESULT CDetailDlg::OnPreviewModeChanged(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { PreviewMode mode = PREVIEW_AUTO; if(wID==ID_PREVIEW_TEXT) mode = PREVIEW_TEXT; else if(wID==ID_PREVIEW_HEX) mode = PREVIEW_HEX; else if(wID==ID_PREVIEW_IMAGE) mode = PREVIEW_IMAGE; m_previewMode = mode; m_textEncoding = ENC_AUTO; m_filePreview.SetPreviewMode(mode); return 0; } LRESULT CDetailDlg::OnTextEncodingChanged(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { TextEncoding enc = ENC_AUTO; if(wID==ID_ENCODING_AUTO) enc = ENC_AUTO; else if(wID==ID_ENCODING_ASCII) enc = ENC_ASCII; else if(wID==ID_ENCODING_UTF8) enc = ENC_UTF8; else if(wID==ID_ENCODING_UTF16) enc = ENC_UTF16_LE; else if(wID==ID_ENCODING_UTF16BE) enc = ENC_UTF16_BE; m_textEncoding = enc; m_filePreview.SetTextEncoding(enc); return 0; }
36.868263
112
0.65592
codereba
0bab5e0055eeaa98b65af6f542e804b4d693c9d5
651
cpp
C++
src/utf8.cpp
dfdchain/fc
fed8efa292e8c6ffccb2153887a73038ae6700d8
[ "MIT" ]
66
2017-09-29T07:09:59.000Z
2020-01-12T06:45:08.000Z
src/utf8.cpp
dfdchain/fc
fed8efa292e8c6ffccb2153887a73038ae6700d8
[ "MIT" ]
5
2017-12-13T13:12:05.000Z
2018-01-18T10:34:02.000Z
src/utf8.cpp
dfdchain/fc
fed8efa292e8c6ffccb2153887a73038ae6700d8
[ "MIT" ]
11
2017-12-05T07:02:05.000Z
2018-01-28T02:52:50.000Z
#include "fc/utf8.hpp" #include "utf8/checked.h" #include "utf8/core.h" #include "utf8/unchecked.h" #include <assert.h> namespace fc { bool is_utf8( const std::string& str ) { return utf8::is_valid( str.begin(), str.end() ); } void decodeUtf8(const std::string& input, std::wstring* storage) { assert(storage != nullptr); utf8::utf8to32(input.begin(), input.end(), std::back_inserter(*storage)); } void encodeUtf8(const std::wstring& input, std::string* storage) { assert(storage != nullptr); utf8::utf32to8(input.begin(), input.end(), std::back_inserter(*storage)); } } ///namespace fc
19.727273
78
0.635945
dfdchain
0bae1863be3083185ef6ca8cb82fb1ba80eff93f
17,567
cc
C++
elements/ip/directiplookup.cc
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
129
2015-10-08T14:38:35.000Z
2022-03-06T14:54:44.000Z
elements/ip/directiplookup.cc
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
241
2016-02-17T16:17:58.000Z
2022-03-15T09:08:33.000Z
elements/ip/directiplookup.cc
BorisPis/asplos22-nicmem-fastclick
ab4df08ee056ed48a4c534ec5f8536a958f756b5
[ "BSD-3-Clause-Clear" ]
61
2015-12-17T01:46:58.000Z
2022-02-07T22:25:19.000Z
// -*- c-basic-offset: 4 -*- /* * directiplookup.{cc,hh} -- lookup for output port and next-hop gateway * in one to max. two DRAM accesses with potential CPU cache / TLB misses * Marko Zec * * Copyright (c) 2005 International Computer Science Institute * Copyright (c) 2005 University of Zagreb * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include "directiplookup.hh" #include <click/ipaddress.hh> #include <click/straccum.hh> #include <click/router.hh> #include <click/error.hh> CLICK_DECLS // DIRECTIPLOOKUP::TABLE // The DirectIPLookup table must be stored in a sub-object in the Linux // kernel, because it's too large to be allocated all at once. int DirectIPLookup::Table::initialize() { assert(!_tbl_0_23 && !_tbl_24_31 && !_vport && !_rtable && !_rt_hashtbl && !_tbl_0_23_plen && !_tbl_24_31_plen); _tbl_24_31_capacity = 4096; _vport_capacity = 1024; _rtable_capacity = 2048; if ((_tbl_0_23 = (uint16_t *) CLICK_LALLOC((sizeof(uint16_t) + sizeof(uint8_t)) * (1 << 24))) && (_tbl_24_31 = (uint16_t *) CLICK_LALLOC((sizeof(uint16_t) + sizeof(uint8_t)) * _tbl_24_31_capacity)) && (_vport = (VirtualPort *) CLICK_LALLOC(sizeof(VirtualPort) * _vport_capacity)) && (_rtable = (CleartextEntry *) CLICK_LALLOC(sizeof(CleartextEntry) * _rtable_capacity)) && (_rt_hashtbl = (int *) CLICK_LALLOC(sizeof(int) * PREF_HASHSIZE))) { _tbl_0_23_plen = (uint8_t *) (_tbl_0_23 + (1 << 24)); _tbl_24_31_plen = (uint8_t *) (_tbl_24_31 + _tbl_24_31_capacity); return 0; } else return -ENOMEM; } void DirectIPLookup::Table::cleanup() { CLICK_LFREE(_tbl_0_23, (sizeof(uint16_t) + sizeof(uint8_t)) * (1 << 24)); CLICK_LFREE(_tbl_24_31, (sizeof(uint16_t) + sizeof(uint8_t)) * _tbl_24_31_capacity); CLICK_LFREE(_vport, sizeof(VirtualPort) * _vport_capacity); CLICK_LFREE(_rtable, sizeof(CleartextEntry) * _rtable_capacity); CLICK_LFREE(_rt_hashtbl, sizeof(int) * PREF_HASHSIZE); _tbl_0_23 = _tbl_24_31 = 0; _vport = 0; _rtable = 0; _tbl_0_23_plen = _tbl_24_31_plen = 0; _rt_hashtbl = 0; } inline uint32_t DirectIPLookup::Table::prefix_hash(uint32_t prefix, uint32_t len) { // An arbitrary hash function - it'd better be good... uint32_t hash = prefix ^ (len << 5) ^ ((prefix >> (len >> 2)) - len); hash ^= (hash >> 23) ^ ((hash >> 15) * len) ^ ((prefix >> 17) * 53); hash -= (prefix >> 3) ^ ((hash >> len) * 7) ^ ((hash >> 11) * 103); hash = (hash ^ (hash >> 17)) & (PREF_HASHSIZE - 1); return hash; } void DirectIPLookup::Table::flush() { memset(_rt_hashtbl, -1, sizeof(int) * PREF_HASHSIZE); // _vport[0] is our "discard" port _vport_head = 0; _vport[0].ll_prev = -1; _vport[0].ll_next = -1; _vport[0].refcount = 1; // _rtable[0] will point to _vport[0] _vport[0].gw = IPAddress(0); _vport[0].port = DISCARD_PORT; _vport_size = 1; _vport_empty_head = -1; // _rtable[0] is the default route entry _rt_hashtbl[prefix_hash(0, 0)] = 0; _rtable[0].ll_prev = -1; _rtable[0].ll_next = -1; _rtable[0].prefix = 0; _rtable[0].plen = 0; _rtable[0].vport = 0; _rtable_size = 1; _rt_empty_head = -1; // Bzeroed lookup tables resolve 0.0.0.0/0 to _vport[0] memset(_tbl_0_23, 0, (sizeof(uint16_t) + sizeof(uint8_t)) * (1 << 24)); _tbl_24_31_size = 0; _tbl_24_31_empty_head = 0x8000; } String DirectIPLookup::Table::dump() const { StringAccum sa; for (uint32_t i = 0; i < PREF_HASHSIZE; i++) for (int rt_i = _rt_hashtbl[i]; rt_i >= 0; rt_i = _rtable[rt_i].ll_next) { const CleartextEntry &rt = _rtable[rt_i]; if (_vport[rt.vport].port != -1) { IPRoute route = IPRoute(IPAddress(htonl(rt.prefix)), IPAddress::make_prefix(rt.plen), _vport[rt.vport].gw, _vport[rt.vport].port); route.unparse(sa, true) << '\n'; } } return sa.take_string(); } int DirectIPLookup::Table::vport_find(IPAddress gw, int16_t port) { for (int vp = _vport_head; vp >= 0; vp = _vport[vp].ll_next) if (_vport[vp].gw == gw && _vport[vp].port == port) return vp; if (_vport_empty_head < 0 && _vport_size == _vport_capacity) { if (_vport_capacity == vport_capacity_limit) return -ENOMEM; VirtualPort *new_vport = (VirtualPort *) CLICK_LALLOC(sizeof(VirtualPort) * 2 * _vport_capacity); if (!new_vport) return -ENOMEM; memcpy(new_vport, _vport, sizeof(VirtualPort) * _vport_capacity); CLICK_LFREE(_vport, sizeof(VirtualPort) * _vport_capacity); _vport = new_vport; _vport_capacity *= 2; } if (_vport_empty_head < 0) { _vport[_vport_size].ll_next = _vport_empty_head; _vport_empty_head = _vport_size; ++_vport_size; } _vport[_vport_empty_head].refcount = 0; return _vport_empty_head; } void DirectIPLookup::Table::vport_unref(uint16_t vport_i) { if (--_vport[vport_i].refcount == 0) { int16_t prev, next; // Prune our entry from the vport list prev = _vport[vport_i].ll_prev; next = _vport[vport_i].ll_next; if (prev >= 0) _vport[prev].ll_next = next; else _vport_head = next; if (next >= 0) _vport[next].ll_prev = prev; // Add the entry to empty vports list _vport[vport_i].ll_next = _vport_empty_head; _vport_empty_head = vport_i; } } int DirectIPLookup::Table::find_entry(uint32_t prefix, uint32_t plen) const { int hash = prefix_hash(prefix, plen); for (int rt_i = _rt_hashtbl[hash]; rt_i >= 0; rt_i = _rtable[rt_i].ll_next) if (_rtable[rt_i].prefix == prefix && _rtable[rt_i].plen == plen) return rt_i; return -1; } int DirectIPLookup::Table::add_route(const IPRoute& route, bool allow_replace, IPRoute* old_route, ErrorHandler *errh) { uint32_t prefix = ntohl(route.addr.addr()); uint32_t plen = route.prefix_len(); int rt_i = find_entry(prefix, plen); if (rt_i >= 0) { // Attempt to replace an existing route. // Save the old route if requested so that a rollback can be performed. if ((rt_i != 0 || (rt_i == 0 && _vport[0].port != DISCARD_PORT)) && old_route) *old_route = IPRoute(IPAddress(htonl(_rtable[rt_i].prefix)), IPAddress::make_prefix(_rtable[rt_i].plen), _vport[_rtable[rt_i].vport].gw, _vport[_rtable[rt_i].vport].port); if (rt_i == 0) { // We actually only update the vport entry for the default route if (_vport[0].port != DISCARD_PORT && !allow_replace) return -EEXIST; _vport[0].gw = route.gw; _vport[0].port = route.port; return 0; } // Check if we allow for atomic route replacements at all if (!allow_replace) return -EEXIST; vport_unref(_rtable[rt_i].vport); } else { // Attempt to allocate a new _rtable[] entry. if (_rt_empty_head < 0 && _rtable_size == _rtable_capacity) { CleartextEntry *new_rtable = (CleartextEntry *) CLICK_LALLOC(sizeof(CleartextEntry) * _rtable_capacity * 2); if (!new_rtable) return -ENOMEM; memcpy(new_rtable, _rtable, sizeof(CleartextEntry) * _rtable_capacity); CLICK_LFREE(_rtable, sizeof(CleartextEntry) * _rtable_capacity); _rtable = new_rtable; _rtable_capacity *= 2; } if (_rt_empty_head < 0) { _rtable[_rtable_size].ll_next = _rt_empty_head; _rt_empty_head = _rtable_size; ++_rtable_size; } rt_i = _rt_empty_head; } // find vport index int vport_i = vport_find(route.gw, route.port); if (vport_i < 0) return vport_i; // find overflow table space int start = prefix >> 8; int end = start + (plen < 24 ? 1 << (24 - plen) : 1); if (plen > 24 && !(_tbl_0_23[start] & 0x8000) && (_tbl_24_31_empty_head & 0x8000) != 0) { if (_tbl_24_31_size == _tbl_24_31_capacity && _tbl_24_31_capacity >= tbl_24_31_capacity_limit) return -ENOMEM; if (_tbl_24_31_size == _tbl_24_31_capacity) { uint16_t *new_tbl = (uint16_t *) CLICK_LALLOC((sizeof(uint16_t) + sizeof(uint8_t)) * 2 * _tbl_24_31_capacity); if (!new_tbl) return -ENOMEM; memcpy(new_tbl, _tbl_24_31, sizeof(uint16_t) * _tbl_24_31_capacity); memcpy(new_tbl + _tbl_24_31_capacity, _tbl_24_31_plen, sizeof(uint8_t) * _tbl_24_31_capacity); CLICK_LFREE(_tbl_24_31, (sizeof(uint16_t) + sizeof(uint8_t)) * _tbl_24_31_capacity); _tbl_24_31 = new_tbl; _tbl_24_31_plen = (uint8_t *) (new_tbl + 2 * _tbl_24_31_capacity); _tbl_24_31_capacity *= 2; } _tbl_24_31_empty_head = _tbl_24_31_size >> 8; _tbl_24_31[_tbl_24_31_empty_head << 8] = 0x8000; _tbl_24_31_size += 256; } // At this point we have successfully allocated all memory. if (rt_i == _rt_empty_head) { _rt_empty_head = _rtable[rt_i].ll_next; _rtable[rt_i].prefix = prefix; // in host-order format _rtable[rt_i].plen = plen; // Insert the new entry in our hashtable uint32_t hash = prefix_hash(prefix, plen); _rtable[rt_i].ll_prev = -1; _rtable[rt_i].ll_next = _rt_hashtbl[hash]; if (_rt_hashtbl[hash] >= 0) _rtable[_rt_hashtbl[hash]].ll_prev = rt_i; _rt_hashtbl[hash] = rt_i; } if (vport_i == _vport_empty_head) { _vport_empty_head = _vport[vport_i].ll_next; _vport[vport_i].refcount = 0; _vport[vport_i].gw = route.gw; _vport[vport_i].port = route.port; // Add the entry to the vport linked list _vport[vport_i].ll_prev = -1; _vport[vport_i].ll_next = _vport_head; if (_vport_head >= 0) _vport[_vport_head].ll_prev = vport_i; _vport_head = vport_i; } ++_vport[vport_i].refcount; _rtable[rt_i].vport = vport_i; for (int i = start; i < end; i++) { if (_tbl_0_23[i] & 0x8000) { // Entries with plen > 24 already there in _tbl_24_31[]! int sec_i = (_tbl_0_23[i] & 0x7fff) << 8, sec_start, sec_end; if (plen > 24) { sec_start = prefix & 0xFF; sec_end = sec_start + (1 << (32 - plen)); } else { sec_start = 0; sec_end = 256; } for (int j = sec_i + sec_start; j < sec_i + sec_end; j++) { if (plen > _tbl_24_31_plen[j]) { _tbl_24_31[j] = vport_i; _tbl_24_31_plen[j] = plen; } else if (plen < _tbl_24_31_plen[j]) { // Skip a sequence of more-specific entries if (_tbl_24_31_plen[j] > 24) { j |= 0x000000ff >> (_tbl_24_31_plen[j] - 24); } else { i |= 0x00ffffff >> _tbl_24_31_plen[j]; break; } } else if (allow_replace) { _tbl_24_31[j] = vport_i; } else { // plen == _tbl_24_31_plen[j] -> damn! return errh->error("BUG: _tbl_24_31[%08X] collision", j); } } } else { if (plen > _tbl_0_23_plen[i]) { if (plen > 24) { // Allocate a new _tbl_24_31[] entry and populate it assert(!(_tbl_24_31_empty_head & 0x8000)); int sec_i = _tbl_24_31_empty_head << 8; _tbl_24_31_empty_head = _tbl_24_31[sec_i]; int sec_start = prefix & 0xFF; int sec_end = sec_start + (1 << (32 - plen)); for (int j = 0; j < 256; j++) { if (j >= sec_start && j < sec_end) { _tbl_24_31[sec_i + j] = vport_i; _tbl_24_31_plen[sec_i + j] = plen; } else { _tbl_24_31[sec_i + j] = _tbl_0_23[i]; _tbl_24_31_plen[sec_i + j] = _tbl_0_23_plen[i]; } } _tbl_0_23[i] = (sec_i >> 8) | 0x8000; } else { _tbl_0_23[i] = vport_i; _tbl_0_23_plen[i] = plen; } } else if (plen < _tbl_0_23_plen[i]) { // Skip a sequence of more-specific entries i |= 0x00ffffff >> _tbl_0_23_plen[i]; } else if (allow_replace) { _tbl_0_23[i] = vport_i; } else { // plen == _tbl_0_23_plen[i] - must never happen!!! return errh->error("BUG: _tbl_0_23[%08X] collision", i); } } } return 0; } int DirectIPLookup::Table::remove_route(const IPRoute& route, IPRoute* old_route, ErrorHandler *errh) { uint32_t prefix = ntohl(route.addr.addr()); uint32_t plen = route.prefix_len(); int rt_i = find_entry(prefix, plen); IPRoute found_route; if (rt_i < 0 || (rt_i == 0 && _vport[0].port == DISCARD_PORT)) return -ENOENT; found_route = IPRoute(IPAddress(htonl(_rtable[rt_i].prefix)), IPAddress::make_prefix(_rtable[rt_i].plen), _vport[_rtable[rt_i].vport].gw, _vport[_rtable[rt_i].vport].port); if (!route.match(found_route)) return -ENOENT; if (old_route) *old_route = found_route; if (plen == 0) { // Default route is a special case. We never remove it from lookup // tables, but instead only point it to the "discard port". if (rt_i > 0) // Must never happen, checking it just in case... return errh->error("BUG: default route rt_i=%d, should be 0", rt_i); _vport[0].port = DISCARD_PORT; } else { uint32_t start, end, i, j, sec_i, sec_start, sec_end; int newent = -1; int newmask, prev, next; vport_unref(_rtable[rt_i].vport); // Prune our entry from the prefix/len hashtable prev = _rtable[rt_i].ll_prev; next = _rtable[rt_i].ll_next; if (prev >= 0) _rtable[prev].ll_next = next; else _rt_hashtbl[prefix_hash(prefix, plen)] = next; if (next >= 0) _rtable[next].ll_prev = prev; // Add entry to the list of empty _rtable entries _rtable[rt_i].ll_next = _rt_empty_head; _rt_empty_head = rt_i; // Find an entry covering current prefix/len with the longest prefix. for (newmask = plen - 1 ; newmask >= 0 ; newmask--) if (newmask == 0) { newent = 0; // rtable[0] is always the default route break; } else { newent = find_entry(prefix & (0xffffffff << (32 - newmask)), newmask); if (newent > 0) break; } // Replace prefix/plen with newent/mask in lookup tables start = prefix >> 8; if (plen >= 24) end = start + 1; else end = start + (1 << (24 - plen)); for (i = start; i < end; i++) { if (_tbl_0_23[i] & 0x8000) { sec_i = (_tbl_0_23[i] & 0x7fff) << 8; if (plen > 24) { sec_start = prefix & 0xFF; sec_end = sec_start + (1 << (32 - plen)); } else { sec_start = 0; sec_end = 256; } for (j = sec_i + sec_start; j < sec_i + sec_end; j++) { if (plen == _tbl_24_31_plen[j]) { _tbl_24_31[j] = _rtable[newent].vport; _tbl_24_31_plen[j] = newmask; } else if (plen < _tbl_24_31_plen[j]) { // Skip a sequence of more-specific entries if (_tbl_24_31_plen[j] > 24) { j |= 0x000000ff >> (_tbl_24_31_plen[j] - 24); } else { i |= 0x00ffffff >> _tbl_24_31_plen[j]; break; } } else { // plen > _tbl_24_31_plen[j] -> damn! return errh->error("BUG: _tbl_24_31[%08X] inconsistency", j); } } // Check if we can prune the entire secondary table range? for (j = sec_i ; j < sec_i + 255; j++) if (_tbl_24_31_plen[j] != _tbl_24_31_plen[j+1]) break; if (j == sec_i + 255) { // Yup, adjust entries in primary tables... _tbl_0_23[i] = _tbl_24_31[sec_i]; _tbl_0_23_plen[i] = _tbl_24_31_plen[sec_i]; // ... and free up the entry (adding it to free space list) _tbl_24_31[sec_i] = _tbl_24_31_empty_head; _tbl_24_31_empty_head = sec_i >> 8; } } else { if (plen == _tbl_0_23_plen[i]) { _tbl_0_23[i] = _rtable[newent].vport; _tbl_0_23_plen[i] = newmask; } else if (plen < _tbl_0_23_plen[i]) { // Skip a sequence of more-specific entries i |= 0x00ffffff >> _tbl_0_23_plen[i]; } } } } return 0; } // DIRECTIPLOOKUP DirectIPLookup::DirectIPLookup() { #if HAVE_BATCH // TODO: Remove this when push_batch() will actually be implemented in_batch_mode = BATCH_MODE_NO; #endif } DirectIPLookup::~DirectIPLookup() { } int DirectIPLookup::configure(Vector<String> &conf, ErrorHandler *errh) { int r; if ((r = _t.initialize()) < 0) return r; _t.flush(); return IPRouteTable::configure(conf, errh); } void DirectIPLookup::cleanup(CleanupStage) { _t.cleanup(); } void DirectIPLookup::push(int, Packet *p) { IPAddress gw; int port = lookup_route(p->dst_ip_anno(), gw); if (port >= 0) { if (gw) p->set_dst_ip_anno(gw); output(port).push(p); } else p->kill(); } int DirectIPLookup::lookup_route(IPAddress dest, IPAddress &gw) const { uint32_t ip_addr = ntohl(dest.addr()); uint16_t vport_i = _t._tbl_0_23[ip_addr >> 8]; if (vport_i & 0x8000) vport_i = _t._tbl_24_31[((vport_i & 0x7fff) << 8) | (ip_addr & 0xff)]; gw = _t._vport[vport_i].gw; return _t._vport[vport_i].port; } int DirectIPLookup::add_route(const IPRoute& route, bool allow_replace, IPRoute* old_route, ErrorHandler *errh) { return _t.add_route(route, allow_replace, old_route, errh); } int DirectIPLookup::remove_route(const IPRoute& route, IPRoute* old_route, ErrorHandler *errh) { return _t.remove_route(route, old_route, errh); } int DirectIPLookup::flush_handler(const String &, Element *e, void *, ErrorHandler *) { DirectIPLookup *t = static_cast<DirectIPLookup *>(e); t->_t.flush(); return 0; } String DirectIPLookup::dump_routes() { return _t.dump(); } void DirectIPLookup::add_handlers() { IPRouteTable::add_handlers(); add_write_handler("flush", flush_handler, 0, Handler::BUTTON); } CLICK_ENDDECLS ELEMENT_REQUIRES(IPRouteTable userlevel|bsdmodule) EXPORT_ELEMENT(DirectIPLookup)
30.183849
132
0.65384
BorisPis
0bafd0a68d765f2a38a60e3633f40b9a452056f2
3,604
cpp
C++
Game/Source/Earth.cpp
oscarrep/ApolloMission
4335dbbf19b1835bdd9c22e57ea71f6b66c08370
[ "MIT" ]
null
null
null
Game/Source/Earth.cpp
oscarrep/ApolloMission
4335dbbf19b1835bdd9c22e57ea71f6b66c08370
[ "MIT" ]
null
null
null
Game/Source/Earth.cpp
oscarrep/ApolloMission
4335dbbf19b1835bdd9c22e57ea71f6b66c08370
[ "MIT" ]
null
null
null
#include "Defs.h" #include "Earth.h" #include "App.h" #include "Render.h" #include "Textures.h" #include "Scene.h" #include "Animation.h" #include "Window.h" #include "SString.h" Earth::Earth() : Module() { LoadAnim(); } bool Earth::Awake() { return true; } bool Earth::Start() { earthTex = app->tex->Load("Assets/textures/earth.png"); rect.x = 950; rect.y = 5600; rect.w = 300; rect.h = 300; colliderEarth = app->physicsEngine->AddCollider(rect, ColliderType::COLLIDER_EARTH, this); //colliderEarth = app->physicsEngine->AddColliderCircle(900, 5600, 300, ColliderType::COLLIDER_EARTH, this); return true; } bool Earth::PreUpdate() { currentAnim = &earthAnim; return true; } bool Earth::Update(float dt) { return true; } bool Earth::PostUpdate() { app->render->DrawTexture(earthTex, (int)spawnPos.x, (int)spawnPos.y, &currentAnim->GetCurrentFrame(), 1.0f); //colliderEarth->SetPos(rect.x, rect.y); return true; } bool Earth::CleanUp() { app->tex->UnLoad(earthTex); /*if (colliderPlayer != nullptr) colliderPlayer->toDelete = true;*/ return true; } iPoint Earth::GetPos() const { return spawnPos; } void Earth::OnCollision(Collider* col1, Collider* col2) { app->physicsEngine->doCollisions(col1, col2); } void Earth::LoadAnim() { earthAnim.PushBack({ 0, 0, 300, 300 }); earthAnim.PushBack({ 300, 0, 300, 300 }); earthAnim.PushBack({ 600, 0, 300, 300 }); earthAnim.PushBack({ 900, 0, 300, 300 }); earthAnim.PushBack({ 1200, 0, 300, 300 }); earthAnim.PushBack({ 1500, 0, 300, 300 }); earthAnim.PushBack({ 1800, 0, 300, 300 }); earthAnim.PushBack({ 2100, 0, 300, 300 }); earthAnim.PushBack({ 2400, 0, 300, 300 }); earthAnim.PushBack({ 2700, 0, 300, 300 }); earthAnim.PushBack({ 3000, 0, 300, 300 }); earthAnim.PushBack({ 3300, 0, 300, 300 }); earthAnim.PushBack({ 3600, 0, 300, 300 }); earthAnim.PushBack({ 3900, 0, 300, 300 }); earthAnim.PushBack({ 4200, 0, 300, 300 }); earthAnim.PushBack({ 4500, 0, 300, 300 }); earthAnim.PushBack({ 4800, 0, 300, 300 }); earthAnim.PushBack({ 5100, 0, 300, 300 }); earthAnim.PushBack({ 5400, 0, 300, 300 }); earthAnim.PushBack({ 5700, 0, 300, 300 }); earthAnim.PushBack({ 6000, 0, 300, 300 }); earthAnim.PushBack({ 6300, 0, 300, 300 }); earthAnim.PushBack({ 6600, 0, 300, 300 }); earthAnim.PushBack({ 6900, 0, 300, 300 }); earthAnim.PushBack({ 7200, 0, 300, 300 }); earthAnim.PushBack({ 7500, 0, 300, 300 }); earthAnim.PushBack({ 7800, 0, 300, 300 }); earthAnim.PushBack({ 8100, 0, 300, 300 }); earthAnim.PushBack({ 8400, 0, 300, 300 }); earthAnim.PushBack({ 8700, 0, 300, 300 }); earthAnim.PushBack({ 9000, 0, 300, 300 }); earthAnim.PushBack({ 9300, 0, 300, 300 }); earthAnim.PushBack({ 9600, 0, 300, 300 }); earthAnim.PushBack({ 9900, 0, 300, 300 }); earthAnim.PushBack({ 10200, 0, 300, 300 }); earthAnim.PushBack({ 10500, 0, 300, 300 }); earthAnim.PushBack({ 10800, 0, 300, 300 }); earthAnim.PushBack({ 11100, 0, 300, 300 }); earthAnim.PushBack({ 11400, 0, 300, 300 }); earthAnim.PushBack({ 11700, 0, 300, 300 }); earthAnim.PushBack({ 12000, 0, 300, 300 }); earthAnim.PushBack({ 12300, 0, 300, 300 }); earthAnim.PushBack({ 12600, 0, 300, 300 }); earthAnim.PushBack({ 12900, 0, 300, 300 }); earthAnim.PushBack({ 13200, 0, 300, 300 }); earthAnim.PushBack({ 13500, 0, 300, 300 }); earthAnim.PushBack({ 13800, 0, 300, 300 }); earthAnim.PushBack({ 14100, 0, 300, 300 }); earthAnim.PushBack({ 14400, 0, 300, 300 }); earthAnim.PushBack({ 14700, 0, 300, 300 }); earthAnim.speed = 0.05f; }
26.696296
109
0.639567
oscarrep
0bbbfc67d67914a3522ef4cf89049db97ac5f82f
401
inl
C++
src/ace/ACE_wrappers/ace/Token_Manager.inl
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
8
2017-06-05T08:56:27.000Z
2020-04-08T16:50:11.000Z
src/ace/ACE_wrappers/ace/Token_Manager.inl
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
null
null
null
src/ace/ACE_wrappers/ace/Token_Manager.inl
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
17
2017-06-05T08:54:27.000Z
2021-08-29T14:19:12.000Z
// -*- C++ -*- #if defined (ACE_HAS_TOKENS_LIBRARY) ACE_BEGIN_VERSIONED_NAMESPACE_DECL ACE_INLINE ACE_TOKEN_CONST::MUTEX & ACE_Token_Manager::mutex (void) { ACE_TRACE ("ACE_Token_Manager::mutex"); return lock_; } ACE_INLINE void ACE_Token_Manager::debug (bool d) { ACE_TRACE ("ACE_Token_Manager::debug"); debug_ = d; } ACE_END_VERSIONED_NAMESPACE_DECL #endif /* ACE_HAS_TOKENS_LIBRARY */
17.434783
41
0.753117
wfnex
0bbe34b7b9a7544c1845a05e3975c9d1b5d51525
15,308
cpp
C++
dp/sg/core/src/Group.cpp
siddharthuniv/nv-propipeline
1553a1aebdbef6cd5c7557574a7e4bdfcf17e0ef
[ "BSD-3-Clause" ]
null
null
null
dp/sg/core/src/Group.cpp
siddharthuniv/nv-propipeline
1553a1aebdbef6cd5c7557574a7e4bdfcf17e0ef
[ "BSD-3-Clause" ]
null
null
null
dp/sg/core/src/Group.cpp
siddharthuniv/nv-propipeline
1553a1aebdbef6cd5c7557574a7e4bdfcf17e0ef
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2002-2016, NVIDIA CORPORATION. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION 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 ``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 <dp/sg/core/Group.h> #include <dp/sg/core/ClipPlane.h> #include <dp/sg/core/LightSource.h> using namespace dp::math; namespace dp { namespace sg { namespace core { BEGIN_REFLECTION_INFO( Group ) DERIVE_STATIC_PROPERTIES( Group, Node ) END_REFLECTION_INFO GroupSharedPtr Group::create() { return( std::shared_ptr<Group>( new Group() ) ); } HandledObjectSharedPtr Group::clone() const { return( std::shared_ptr<Group>( new Group( *this ) ) ); } Group::Group() { m_objectCode = ObjectCode::GROUP; } Group::Group(const Group& rhs) : Node(rhs) { m_objectCode = ObjectCode::GROUP; copyChildren(rhs.m_children); copyClipPlanes(rhs.m_clipPlanes); } Group::~Group() { removeChildren(); removeClipPlanes(); } void Group::preRemoveChild(unsigned int index) { notify( Event( this->getSharedPtr<Group>(), Event::Type::PRE_CHILD_REMOVE, m_children[index], index ) ); } void Group::postRemoveChild(unsigned int index) { } void Group::preAddChild(unsigned int index) { } void Group::postAddChild(unsigned int index) { notify( Event( this->getSharedPtr<Group>(), Event::Type::POST_CHILD_ADD, m_children[index], index ) ); } Group::ChildrenContainer::iterator Group::doInsertChild( const ChildrenContainer::iterator & gcci, const NodeSharedPtr & child ) { DP_ASSERT( child ); unsigned int idx = dp::checked_cast<unsigned int>(std::distance( m_children.begin(), gcci )); preAddChild( idx ); ChildrenContainer::iterator position = m_children.insert( gcci, child ); child->attach( this ); postAddChild( idx ); return( position ); } Group::ChildrenContainer::iterator Group::doRemoveChild( const ChildrenContainer::iterator & cci ) { unsigned int idx = dp::checked_cast<unsigned int>(std::distance<ChildrenContainer::iterator>( m_children.begin(), cci )); preRemoveChild( idx ); (*cci)->detach( this ); ChildrenContainer::iterator ret = m_children.erase( cci ); postRemoveChild( idx ); return( ret ); } Group::ChildrenContainer::iterator Group::doReplaceChild( ChildrenContainer::iterator & cci, const NodeSharedPtr & newChild ) { DP_ASSERT( newChild ); newChild->attach( this ); (*cci)->detach( this ); unsigned int idx = dp::checked_cast<unsigned int>(std::distance<ChildrenContainer::iterator>( m_children.begin(), cci )); notify( Event( this->getSharedPtr<Group>(), Event::Type::PRE_CHILD_REMOVE, m_children[idx], idx ) ); *cci = newChild; notify( Event( this->getSharedPtr<Group>(), Event::Type::POST_CHILD_ADD, m_children[idx], idx ) ); return( cci ); } Group::ChildrenIterator Group::insertChild( const ChildrenIterator & gci, const NodeSharedPtr & child ) { return( ChildrenIterator( doInsertChild( gci.m_iter, child ) ) ); } bool Group::removeChild( const NodeSharedPtr & child ) { bool removed = false; for ( ChildrenContainer::iterator cci = find( m_children.begin(), m_children.end(), child ) ; cci != m_children.end() ; cci = find( cci, m_children.end(), child ) // continue searching to find all occurrences ) { cci = doRemoveChild( cci ); removed = true; } return( removed ); } Group::ChildrenIterator Group::removeChild( const ChildrenIterator & ci ) { return( ChildrenIterator( ci.m_iter != m_children.end() ? doRemoveChild( ci.m_iter ) : m_children.end() ) ); } bool Group::replaceChild( const NodeSharedPtr & newChild, const NodeSharedPtr & oldChild ) { if ( newChild != oldChild ) { bool replaced = false; for ( ChildrenContainer::iterator cci = find( m_children.begin(), m_children.end(), oldChild ) ; cci != m_children.end() ; cci = find( cci, m_children.end(), oldChild ) // continue searching to find all occurrences ) { cci = doReplaceChild( cci, newChild ); replaced = true; } return( replaced ); } return( false ); } bool Group::replaceChild( const NodeSharedPtr & newChild, ChildrenIterator & oldChildIterator ) { if ( ( oldChildIterator.m_iter != m_children.end() ) && ( newChild != *oldChildIterator ) ) { doReplaceChild( oldChildIterator.m_iter, newChild ); return( true ); } return( false ); } void Group::clearChildren() { for ( ChildrenContainer::iterator cci = m_children.begin() ; cci != m_children.end() ; ++cci ) { // this is nearly a nop if the bounding volumes are already dirty and cheap in comparison to what happens int he background // if the observer calls getBounding*() it's necessary that the dirty flag has already been set. notify( Event( this->getSharedPtr<Group>(), Event::Type::PRE_CHILD_REMOVE, m_children[0], 0 ) ); (*cci)->detach( this ); } m_children.clear(); } Box3f Group::calculateBoundingBox() const { Box3f bbox; for ( ChildrenContainer::const_iterator it = m_children.begin() ; it!=m_children.end() ; ++it ) { bbox = boundingBox(bbox, (*it)->getBoundingBox()); } return( bbox ); } Sphere3f Group::calculateBoundingSphere() const { Sphere3f sphere; if ( ! m_children.empty() ) { std::vector<dp::math::Sphere3f> spheres; spheres.reserve( m_children.size() ); for ( ChildrenContainer::const_iterator it = m_children.begin() ; it!=m_children.end() ; ++it ) { spheres.push_back( (*it)->getBoundingSphere() ); } sphere = boundingSphere( &spheres[0], dp::checked_cast<unsigned int>(spheres.size()) ); } return( sphere ); } unsigned int Group::determineHintsContainment( unsigned int hints ) const { unsigned int containment = Node::determineHintsContainment( hints ); for ( size_t i=0 ; ( (containment & hints ) != hints ) && i<m_children.size() ; i++ ) { containment |= m_children[i]->getContainedHints( hints ); } return( containment ); } void Group::copyChildren(const ChildrenContainer & children) { DP_ASSERT(m_children.empty()); // copy children from source object and add reference for each m_children.resize(children.size()); // allocate destination range for ( size_t i=0; i<children.size(); ++i ) { m_children[i] = std::static_pointer_cast<dp::sg::core::Node>(children[i]->clone()); m_children[i]->attach( this ); } } void Group::copyClipPlanes(const ClipPlaneContainer & clipPlanes) { DP_ASSERT(m_clipPlanes.empty()); // copy clipping planes from source object and add reference for each m_clipPlanes.resize(clipPlanes.size()); // allocate destination range for ( size_t i=0 ; i<clipPlanes.size() ; i++ ) { m_clipPlanes[i] = std::static_pointer_cast<dp::sg::core::ClipPlane>(clipPlanes[i]->clone()); m_clipPlanes[i]->attach( this ); } } Group & Group::operator=(const Group & rhs) { if (&rhs != this) { Node::operator=(rhs); removeChildren(); removeClipPlanes(); copyChildren(rhs.m_children); copyClipPlanes(rhs.m_clipPlanes); notify( Event( this->getSharedPtr<Group>(), Event::Type::POST_GROUP_EXCHANGED ) ); } return *this; } bool Group::isEquivalent( ObjectSharedPtr const& object, bool ignoreNames, bool deepCompare ) const { if ( object.get() == this ) { return( true ); } bool equi = std::dynamic_pointer_cast<Group>(object) && Node::isEquivalent( object, ignoreNames, deepCompare ); if ( equi ) { GroupSharedPtr const& g = std::static_pointer_cast<Group>(object); equi = ( m_children.size() == g->m_children.size() ) && ( m_clipPlanes.size() == g->m_clipPlanes.size() ); if ( deepCompare ) { for ( ChildrenContainer::const_iterator lhsit = m_children.begin() ; equi && lhsit != m_children.end() ; ++lhsit ) { bool found = false; for ( ChildrenContainer::const_iterator rhsit = g->m_children.begin() ; !found && rhsit != g->m_children.end() ; ++rhsit ) { found = (*lhsit)->isEquivalent( *rhsit, ignoreNames, true ); } equi = found; } for ( ClipPlaneContainer::const_iterator lhsit = m_clipPlanes.begin() ; equi && lhsit != m_clipPlanes.end() ; ++lhsit ) { bool found = false; for ( ClipPlaneContainer::const_iterator rhsit = g->m_clipPlanes.begin() ; !found && rhsit != g->m_clipPlanes.end() ; ++rhsit ) { found = (*lhsit)->isEquivalent( *rhsit, ignoreNames, true ); } equi = found; } } else { for ( ChildrenContainer::const_iterator lhsit = m_children.begin() ; equi && lhsit != m_children.end() ; ++lhsit ) { bool found = false; for ( ChildrenContainer::const_iterator rhsit = g->m_children.begin() ; !found && rhsit != g->m_children.end() ; ++rhsit ) { found = ( *lhsit == *rhsit ); } equi = found; } for ( ClipPlaneContainer::const_iterator lhsit = m_clipPlanes.begin() ; equi && lhsit != m_clipPlanes.end() ; ++lhsit ) { bool found = false; for ( ClipPlaneContainer::const_iterator rhsit = g->m_clipPlanes.begin() ; !found && rhsit != g->m_clipPlanes.end() ; ++rhsit ) { found = ( *lhsit == *rhsit ); } equi = found; } } } return( equi ); } unsigned int Group::getNumberOfActiveClipPlanes() const { unsigned int noacp = 0; DP_ASSERT( m_clipPlanes.size() <= UINT_MAX ); for ( unsigned int i=0 ; i<m_clipPlanes.size() ; i++ ) { if ( m_clipPlanes[i]->isEnabled() ) { noacp++; } } return( noacp ); } Group::ClipPlaneIterator Group::addClipPlane( const ClipPlaneSharedPtr & plane ) { ClipPlaneContainer::iterator cpci = find( m_clipPlanes.begin(), m_clipPlanes.end(), plane ); if ( cpci == m_clipPlanes.end() ) { plane->attach( this ); m_clipPlanes.push_back( plane ); cpci = m_clipPlanes.end() - 1; notify( Group::Event( this->getSharedPtr<Group>(), Group::Event::Type::CLIP_PLANES_CHANGED ) ); } return( ClipPlaneIterator( cpci ) ); } Group::ClipPlaneContainer::iterator Group::doRemoveClipPlane( const ClipPlaneContainer::iterator & cpci ) { (*cpci)->detach( this ); Group::ClipPlaneContainer::iterator it = m_clipPlanes.erase( cpci ); notify( Group::Event( this->getSharedPtr<Group>(), Group::Event::Type::CLIP_PLANES_CHANGED ) ); return it; } bool Group::removeClipPlane( const ClipPlaneSharedPtr & plane ) { DP_ASSERT( plane ); ClipPlaneContainer::iterator cpci = find( m_clipPlanes.begin(), m_clipPlanes.end(), plane ); if ( cpci != m_clipPlanes.end() ) { doRemoveClipPlane( cpci ); return( true ); } return( false ); } Group::ClipPlaneIterator Group::removeClipPlane( const ClipPlaneIterator & cpi ) { if ( cpi.m_iter != m_clipPlanes.end() ) { return( ClipPlaneIterator( doRemoveClipPlane( cpi.m_iter ) ) ); } return( cpi ); } void Group::clearClipPlanes() { unsigned int dirtyBits = 0; for ( ClipPlaneContainer::iterator cpci = m_clipPlanes.begin() ; cpci != m_clipPlanes.end() ; ++cpci ) { (*cpci)->detach( this ); } m_clipPlanes.clear(); notify( Group::Event( this->getSharedPtr<Group>(), Group::Event::Type::CLIP_PLANES_CHANGED ) ); } void Group::removeChildren() { for ( ChildrenContainer::iterator it = m_children.begin(); it != m_children.end(); ++it ) { (*it)->detach( this ); } m_children.clear(); } void Group::removeClipPlanes() { for ( ClipPlaneContainer::iterator it = m_clipPlanes.begin(); it != m_clipPlanes.end(); ++it ) { (*it)->detach( this ); } m_clipPlanes.clear(); } void Group::feedHashGenerator( util::HashGenerator & hg ) const { Node::feedHashGenerator( hg ); for ( size_t i=0 ; i<m_children.size() ; ++i ) { hg.update( m_children[i] ); } for ( size_t i=0 ; i<m_clipPlanes.size() ; ++i ) { hg.update( m_clipPlanes[i] ); } } } // namespace core } // namespace sg } // namespace dp
35.271889
141
0.580611
siddharthuniv
0bc051eb40fb091fb2efb19ecfc629f49dc6072a
402
hpp
C++
ProxyServer/ServerConnection.hpp
pentaflops/MP.Proxy-server
95e01f0af9bcda6d3b5973f60529940213e7426c
[ "MIT" ]
null
null
null
ProxyServer/ServerConnection.hpp
pentaflops/MP.Proxy-server
95e01f0af9bcda6d3b5973f60529940213e7426c
[ "MIT" ]
null
null
null
ProxyServer/ServerConnection.hpp
pentaflops/MP.Proxy-server
95e01f0af9bcda6d3b5973f60529940213e7426c
[ "MIT" ]
null
null
null
#pragma once #include "IConnection.hpp" class ServerConnection : public IConnection { public: ServerConnection(sockaddr_in sock_addr) : IConnection(INVALID_SOCKET, sock_addr, false) {}; ~ServerConnection() { closesocket(_socket); } int Connecting(); int GetData(char *buffer, int size_of_buffer, Event *_Event = nullptr); void SendData(const char *buffer, int len, Event *_Event = nullptr); };
26.8
92
0.753731
pentaflops
0bc184976766e9d7faafab07a0a561918faa1994
1,185
hpp
C++
src/interfaces/blkInterfaces.hpp
lhb8125/HSF
f0cea44691a0e41bdeb5613a2d5a6cd7cda0a999
[ "Apache-2.0" ]
null
null
null
src/interfaces/blkInterfaces.hpp
lhb8125/HSF
f0cea44691a0e41bdeb5613a2d5a6cd7cda0a999
[ "Apache-2.0" ]
null
null
null
src/interfaces/blkInterfaces.hpp
lhb8125/HSF
f0cea44691a0e41bdeb5613a2d5a6cd7cda0a999
[ "Apache-2.0" ]
null
null
null
/** * @file: blkInterfaces.hpp * @author: Liu Hongbin * @brief: block topology interfaces * @date: 2019-11-11 10:56:28 * @last Modified by: lhb8125 * @last Modified time: 2020-05-27 10:52:53 */ #ifndef BLKINTERFACES_HPP #define BLKINTERFACES_HPP #include "interface.hpp" #include "utilities.hpp" #include "mesh.hpp" extern "C" { void get_ele_blk_num_(label *ele_blk_num); void get_ele_blk_pos_(label *ele_blk_pos); void get_ele_blk_type_(label *ele_blk_type); void get_ele_2_ele_blk_(label *ele_2_ele); void get_ele_2_face_blk_(label *ele_2_face); void get_ele_2_node_blk_(label *ele_2_node); void get_inn_face_blk_num_(label *face_blk_num); void get_inn_face_blk_pos_(label *face_blk_pos); void get_inn_face_blk_type_(label *face_blk_type); void get_inn_face_2_node_blk_(label *face_2_node); void get_inn_face_2_ele_blk_(label *face_2_ele); void get_bnd_face_blk_num_(label *bnd_face_blk_num); void get_bnd_face_blk_pos_(label *bnd_face_blk_pos); void get_bnd_face_blk_type_(label *bnd_face_blk_type); void get_bnd_face_2_node_blk_(label *bnd_face_2_node); void get_bnd_face_2_ele_blk_(label *bnd_face_2_ele); void get_bnd_type_(label *bnd_type); } #endif
20.084746
54
0.795781
lhb8125
0bc56f7850f9328451792dc7772a87e25c650411
43,836
hpp
C++
lualite.hpp
user1095108/lualite
17c2d07f1fa315129cdb32ad000ca305488fac39
[ "Unlicense" ]
58
2016-09-24T13:08:08.000Z
2022-02-07T04:17:53.000Z
lualite.hpp
user1095108/lualite
17c2d07f1fa315129cdb32ad000ca305488fac39
[ "Unlicense" ]
2
2015-05-27T03:39:53.000Z
2016-06-15T10:07:32.000Z
lualite.hpp
user1095108/lualite
17c2d07f1fa315129cdb32ad000ca305488fac39
[ "Unlicense" ]
4
2016-11-25T04:40:57.000Z
2019-10-14T21:28:01.000Z
/* ** This is free and unencumbered software released into the public domain. ** Anyone is free to copy, modify, publish, use, compile, sell, or ** distribute this software, either in source code form or as a compiled ** binary, for any purpose, commercial or non-commercial, and by any ** means. ** In jurisdictions that recognize copyright laws, the author or authors ** of this software dedicate any and all copyright interest in the ** software to the public domain. We make this dedication for the benefit ** of the public at large and to the detriment of our heirs and ** successors. We intend this dedication to be an overt act of ** relinquishment in perpetuity of all present and future rights to this ** software under copyright law. ** 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 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. ** For more information, please refer to <http://unlicense.org/> */ #ifndef LUALITE_HPP # define LUALITE_HPP # pragma once #if __cplusplus < 201402L # error "You need a C++14 compiler to use lualite" #endif // __cplusplus #include <cassert> #include <cstring> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <vector> #ifndef LUALITE_NO_STD_CONTAINERS #include <array> #include <deque> #include <forward_list> #include <list> #include <map> #include <set> #include <string> #include <tuple> #include <utility> #endif // LUALITE_NO_STD_CONTAINERS extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } namespace lualite { #ifndef LLFUNC # define LLFUNC(f) decltype(&f),&f #endif // LLFUNC struct any { }; class scope; template <class C> class class_; static constexpr auto const default_nrec = 10; namespace { template <typename T> using is_function_pointer = std::integral_constant<bool, std::is_pointer<T>{} && std::is_function<std::remove_pointer_t<T>>{} >; template <typename T> using is_nc_reference = std::integral_constant<bool, std::is_reference<T>{} && !std::is_const<std::remove_reference_t<T>>{} >; struct swallow { template <typename ...T> constexpr explicit swallow(T&& ...) noexcept { } }; // key is at the top of the stack inline void rawgetfield(lua_State* const L, int const index, char const* const key) noexcept { auto const i(lua_absindex(L, index)); lua_pushstring(L, key); lua_rawget(L, i); } // value is at the top of the stack, key is shifted below the top inline void rawsetfield(lua_State* const L, int const index, char const* const key) noexcept { auto const i(lua_absindex(L, index)); lua_pushstring(L, key); lua_insert(L, -2); lua_rawset(L, i); } constexpr inline auto hash(char const* s, std::size_t h = {}) noexcept { while (*s) { h ^= (h << 5) + (h >> 2) + static_cast<unsigned char>(*s++); } return h; } struct str_eq { bool operator()(char const* const s1, char const* const s2) const noexcept { return !std::strcmp(s1, s2); } }; struct str_hash { constexpr std::size_t operator()(char const* s) const noexcept { return hash(s); } }; template <typename T> class scope_exit { T const f_; public: explicit scope_exit(T&& f) noexcept : f_(std::forward<T>(f)) { static_assert(noexcept(f_()), "throwing functors are unsupported"); } ~scope_exit() noexcept { f_(); } }; template <typename T> inline scope_exit<T> make_scope_exit(T&& f) noexcept { return scope_exit<T>(std::forward<T>(f)); } } enum property_type : unsigned { BOOLEAN, INTEGER, NUMBER, STRING, OTHER }; struct constant_info_type { enum property_type type; union { bool boolean; lua_Integer integer; lua_Number number; char const* string; } u; }; using constants_type = std::vector<std::pair<char const* const, struct constant_info_type> >; struct func_info_type { char const* const name; lua_CFunction const callback; }; using map_member_info_type = lua_CFunction; using member_info_type = func_info_type; template <class C> int getter(lua_State* const L) { assert(2 == lua_gettop(L)); auto const i(lualite::class_<C>::getters().find(lua_tostring(L, 2))); if (lualite::class_<C>::getters().end() == i) { return {}; } else { auto const uvi(lua_upvalueindex(2)); void* p(lua_touserdata(L, uvi)); auto const q(p); for (auto const f: std::get<0>(i->second)) { p = f(p); } lua_pushlightuserdata(L, p); lua_replace(L, uvi); auto const se( make_scope_exit( [&]() noexcept { lua_pushlightuserdata(L, q); lua_replace(L, uvi); } ) ); return std::get<1>(i->second)(L); } } template <class C> int setter(lua_State* const L) { assert(3 == lua_gettop(L)); auto const i(lualite::class_<C>::setters().find(lua_tostring(L, 2))); if (lualite::class_<C>::setters().end() != i) { auto const uvi(lua_upvalueindex(2)); void* p(lua_touserdata(L, uvi)); auto const q(p); for (auto const f: std::get<0>(i->second)) { p = f(p); } lua_pushlightuserdata(L, p); lua_replace(L, uvi); auto const se(make_scope_exit([&]() noexcept { lua_pushlightuserdata(L, q); lua_replace(L, uvi);}) ); std::get<1>(i->second)(L); } // else do nothing return {}; } template <class C> inline void create_wrapper_table(lua_State* const L, C* const instance) { auto const uvi(lua_upvalueindex(1)); lua_pushvalue(L, uvi); if (lua_isnil(L, -1)) { lua_createtable(L, 0, default_nrec); for (auto& mi: lualite::class_<C>::defs()) { assert(lua_istable(L, -1)); lua_pushnil(L); void* p(instance); for (auto const f: mi.first) { p = f(p); } lua_pushlightuserdata(L, p); lua_pushcclosure(L, mi.second.callback, 2); rawsetfield(L, -2, mi.second.name); } // metatable assert(lua_istable(L, -1)); lua_createtable(L, 0, 2); // getters assert(lua_istable(L, -1)); lua_pushnil(L); lua_pushlightuserdata(L, instance); lua_pushcclosure(L, getter<C>, 2); rawsetfield(L, -2, "__index"); // setters assert(lua_istable(L, -1)); lua_pushnil(L); lua_pushlightuserdata(L, instance); lua_pushcclosure(L, setter<C>, 2); rawsetfield(L, -2, "__newindex"); lua_setmetatable(L, -2); lua_copy(L, -1, uvi); } // else do nothing assert(lua_istable(L, uvi)); assert(lua_istable(L, -1)); } template <typename T> inline std::enable_if_t< std::is_floating_point<std::decay_t<T>>{} && !is_nc_reference<T>{}, int > set(lua_State* const L, T&& v) noexcept { lua_pushnumber(L, v); return 1; } template <typename T> inline std::enable_if_t< std::is_integral<std::decay_t<T>>{} && !std::is_same<std::decay_t<T>, bool>{} && !is_nc_reference<T>{}, int > set(lua_State* const L, T&& v) noexcept { lua_pushinteger(L, v); return 1; } template <typename T> inline std::enable_if_t< std::is_same<std::decay_t<T>, bool>{} && !is_nc_reference<T>{}, int > set(lua_State* const L, T&& v) noexcept { lua_pushboolean(L, v); return 1; } template <typename T> inline std::enable_if_t< std::is_same<std::decay_t<T>, char const*>{} && !is_nc_reference<T>{}, int > set(lua_State* const L, T&& v) noexcept { lua_pushstring(L, v); return 1; } template <typename T> inline std::enable_if_t< std::is_same<std::decay_t<T>, void const*>{} && !is_nc_reference<T>{}, int > set(lua_State* const L, T&& v) noexcept { lua_pushlightuserdata(L, const_cast<void*>(v)); return 1; } template <typename T> inline std::enable_if_t< std::is_pointer<T>{} && !std::is_const<std::remove_pointer_t<T>>{} && !std::is_class<std::remove_pointer_t<T>>{}, int > set(lua_State* const L, T&& v) noexcept { lua_pushlightuserdata(L, v); return 1; } template <typename T> inline std::enable_if_t< is_nc_reference<T>{} && !std::is_class<std::decay_t<T>>{}, int > set(lua_State* const L, T&& v) noexcept { lua_pushlightuserdata(L, &v); return 1; } template <typename T> inline std::enable_if_t< std::is_pointer<std::decay_t<T>>{} && !std::is_const<std::remove_pointer_t<T>>{} && std::is_class<std::remove_pointer_t<std::decay_t<T>>>{}, int > set(lua_State* const L, T&& v) noexcept { create_wrapper_table(L, v); return 1; } template <typename T> inline std::enable_if_t< is_nc_reference<T>{} && std::is_class<std::decay_t<T>>{}, int > set(lua_State* const L, T&& v) noexcept { create_wrapper_table(L, &v); return 1; } template <typename T> inline std::enable_if_t< std::is_same<std::decay_t<T>, any>{} && !is_nc_reference<T>{}, int > set(lua_State* const, T&&) noexcept { return 1; } template <int I, typename T> inline std::enable_if_t< std::is_floating_point<std::decay_t<T>>{} && !is_nc_reference<T>{}, std::decay_t<T> > get(lua_State* const L) noexcept { assert(lua_isnumber(L, I)); return lua_tonumber(L, I); } template <int I, typename T> inline std::enable_if_t< std::is_integral<std::decay_t<T>>{} && !std::is_same<std::decay_t<T>, bool>{} && !is_nc_reference<T>{}, std::decay_t<T> > get(lua_State* const L) noexcept { assert(lua_isnumber(L, I)); return lua_tointeger(L, I); } template <int I, typename T> inline std::enable_if_t< std::is_same<std::decay_t<T>, bool>{} && !is_nc_reference<T>{}, std::decay_t<T> > get(lua_State* const L) noexcept { assert(lua_isboolean(L, I)); return lua_toboolean(L, I); } template <int I, typename T> inline std::enable_if_t< std::is_same<std::decay_t<T>, char const*>{} && !is_nc_reference<T>{}, std::decay_t<T> > get(lua_State* const L) noexcept { assert(lua_isstring(L, I)); return lua_tostring(L, I); } template <int I, typename T> inline std::enable_if_t< std::is_pointer<T>{} && !std::is_same<std::decay_t<T>, char const*>{}, std::decay_t<T> > get(lua_State* const L) noexcept { assert(lua_islightuserdata(L, I)); return static_cast<T>(lua_touserdata(L, I)); } template <int I, typename T> inline std::enable_if_t< is_nc_reference<T>{}, T > get(lua_State* const L) noexcept { assert(lua_islightuserdata(L, I)); return *static_cast<std::decay_t<T>*>(lua_touserdata(L, I)); } template <int I, typename T> inline std::enable_if_t< std::is_same<std::remove_const_t<T>, any>{}, T > get(lua_State* const) noexcept { return {}; } #ifndef LUALITE_NO_STD_CONTAINERS template <typename> struct is_std_pair : std::false_type { }; template <class T1, class T2> struct is_std_pair<std::pair<T1, T2> > : std::true_type { }; template <typename> struct is_std_array : std::false_type { }; template <typename T, std::size_t N> struct is_std_array<std::array<T, N> > : std::true_type { }; template <typename> struct is_std_deque : std::false_type { }; template <typename T, class Alloc> struct is_std_deque<std::deque<T, Alloc> > : std::true_type { }; template <typename> struct is_std_forward_list : std::false_type { }; template <typename T, class Alloc> struct is_std_forward_list<std::forward_list<T, Alloc> > : std::true_type { }; template <typename> struct is_std_list : std::false_type { }; template <typename T, class Alloc> struct is_std_list<std::list<T, Alloc> > : std::true_type { }; template <typename> struct is_std_map : std::false_type { }; template <class Key, class T, class Compare, class Alloc> struct is_std_map<std::map<Key, T, Compare, Alloc> > : std::true_type { }; template <typename> struct is_std_set : std::false_type { }; template <class Key, class Compare, class Alloc> struct is_std_set<std::set<Key, Compare, Alloc> > : std::true_type { }; template <typename> struct is_std_unordered_map : std::false_type { }; template <class Key, class T, class Hash, class P, class Alloc> struct is_std_unordered_map<std::unordered_map<Key, T, Hash, P, Alloc> > : std::true_type { }; template <typename> struct is_std_unordered_set : std::false_type { }; template <class Key, class Hash, class Equal, class Alloc> struct is_std_unordered_set<std::unordered_set<Key, Hash, Equal, Alloc> > : std::true_type { }; template <typename> struct is_std_tuple : std::false_type { }; template <class ...Types> struct is_std_tuple<std::tuple<Types...> > : std::true_type { }; template <typename> struct is_std_vector : std::false_type { }; template <typename T, class Alloc> struct is_std_vector<std::vector<T, Alloc> > : std::true_type { }; template <typename T> inline std::enable_if_t< std::is_same<std::decay_t<T>, std::string>{} && !is_nc_reference<T>{}, int > set(lua_State* const L, T&& s) noexcept { lua_pushlstring(L, s.c_str(), s.size()); return 1; } template <typename C> inline std::enable_if_t< is_std_pair<std::decay_t<C>>{} && !is_nc_reference<C>{}, int > set(lua_State* const L, C&& p) noexcept( noexcept(set(L, p.first), set(L, p.second)) ) { set(L, p.first); set(L, p.second); return 2; } template <typename ...Types, std::size_t ...I> inline void set_tuple_result(lua_State* const L, std::tuple<Types...> const& t, std::index_sequence<I...> const) noexcept( noexcept(swallow{(set(L, std::get<I>(t)), 0)...}) ) { swallow{(set(L, std::get<I>(t)), 0)...}; } template <typename C> inline std::enable_if_t< is_std_tuple<std::decay_t<C>>{} && !is_nc_reference<C>{}, int > set(lua_State* const L, C&& t) noexcept( noexcept( set_tuple_result(L, t, std::make_index_sequence<std::size_t(std::tuple_size<C>{})>() ) ) ) { using result_type = std::decay_t<C>; set_tuple_result(L, t, std::make_index_sequence<std::tuple_size<C>{}>() ); return std::tuple_size<result_type>{}; } template <typename C> inline std::enable_if_t< (is_std_array<std::decay_t<C>>{} || is_std_deque<std::decay_t<C>>{} || is_std_forward_list<std::decay_t<C>>{} || is_std_list<std::decay_t<C>>{} || is_std_vector<std::decay_t<C>>{} || is_std_set<std::decay_t<C>>{} || is_std_unordered_set<std::decay_t<C>>{}) && !is_nc_reference<C>{}, int > set(lua_State* const L, C&& c) { lua_createtable(L, c.size(), 0); int j{}; auto const cend(c.cend()); for (auto i(c.cbegin()); i != cend; ++i) { set(L, *i); lua_rawseti(L, -2, ++j); } return 1; } template <typename C> inline std::enable_if_t< (is_std_map<std::decay_t<C>>{} || is_std_unordered_map<std::decay_t<C>>{}) && !is_nc_reference<C>{}, int > set(lua_State* const L, C&& m) { lua_createtable(L, 0, m.size()); auto const cend(m.cend()); for (auto i(m.cbegin()); i != cend; ++i) { set(L, i->first); set(L, i->second); lua_rawset(L, -3); } return 1; } template <int I, class C> inline std::enable_if_t< std::is_same<std::decay_t<C>, std::string>{} && !is_nc_reference<C>{}, std::decay_t<C> > get(lua_State* const L) { assert(lua_isstring(L, I)); std::size_t len; auto const s(lua_tolstring(L, I, &len)); return {s, len}; } template<int I, class C> inline std::enable_if_t< is_std_pair<std::decay_t<C>>{} && !is_nc_reference<C>{}, std::decay_t<C> > get(lua_State* const L) { assert(lua_istable(L, I)); using result_type = std::decay_t<C>; lua_rawgeti(L, -1, 1); lua_rawgeti(L, -2, 2); result_type const result( get<-2, typename result_type::first_type>(L), get<-1, typename result_type::second_type>(L) ); lua_pop(L, 2); return result; } template <std::size_t O, class C, std::size_t ...I> inline C get_tuple_arg(lua_State* const L, std::index_sequence<I...> const) noexcept( noexcept(std::make_tuple(get<int(I - sizeof...(I)), std::tuple_element_t<I, C>>(L)...) ) ) { swallow{(lua_rawgeti(L, O, I + 1), 0)...}; C result(std::make_tuple(get<int(I - sizeof...(I)), std::tuple_element_t<I, C>>(L)...)); lua_pop(L, int(sizeof...(I))); return result; } template <int I, class C> inline std::enable_if_t< is_std_tuple<std::decay_t<C>>{} && !is_nc_reference<C>{}, std::decay_t<C> > get(lua_State* const L) noexcept( noexcept(get_tuple_arg<I, std::decay_t<C>>(L, std::make_index_sequence< std::size_t(std::tuple_size<std::decay_t<C>>{}) >() ) ) ) { assert(lua_istable(L, I)); using result_type = std::decay_t<C>; return get_tuple_arg<I, result_type>(L, std::make_index_sequence<std::tuple_size<result_type>{}>() ); } template<int I, class C> inline std::enable_if_t< is_std_array<std::decay_t<C>>{} && !is_nc_reference<C>{}, std::decay_t<C> > get(lua_State* const L) { assert(lua_istable(L, I)); using result_type = std::decay_t<C>; result_type result; auto const len(std::min(lua_rawlen(L, I), lua_Unsigned(result.size()))); for (decltype(lua_rawlen(L, I)) i{}; i != len; ++i) { lua_rawgeti(L, I, i + 1); result[i] = get<-1, typename result_type::value_type>(L); } lua_pop(L, len); return result; } template <int I, class C> inline std::enable_if_t< (is_std_deque<std::decay_t<C>>{} || is_std_forward_list<std::decay_t<C>>{} || is_std_list<std::decay_t<C>>{}) && !is_nc_reference<C>{}, std::decay_t<C> > get(lua_State* const L) { assert(lua_istable(L, I)); using result_type = std::decay_t<C>; result_type result; auto const len(lua_rawlen(L, I)); for (auto i(len); i; --i) { lua_rawgeti(L, I, i); result.emplace_front(get<-1, typename result_type::value_type>(L)); } lua_pop(L, len); return result; } template <int I, class C> inline std::enable_if_t< is_std_vector<std::decay_t<C>>{} && !is_nc_reference<C>{}, std::decay_t<C> > get(lua_State* const L) { assert(lua_istable(L, I)); using result_type = std::decay_t<C>; result_type result; auto const cend(lua_rawlen(L, I) + 1); result.reserve(cend - 1); for (decltype(lua_rawlen(L, I)) i(1); i != cend; ++i) { lua_rawgeti(L, I, i); result.emplace_back(get<-1, typename result_type::value_type>(L)); } lua_pop(L, cend - 1); return result; } template <int I, class C> inline std::enable_if_t< (is_std_map<std::decay_t<C>>{} || is_std_unordered_map<std::decay_t<C>>{}) && !is_nc_reference<C>{}, std::decay_t<C> > get(lua_State* const L) { assert(lua_istable(L, I)); using result_type = std::decay_t<C>; result_type result; lua_pushnil(L); while (lua_next(L, I)) { result.emplace(get<-2, typename result_type::key_type>(L), get<-1, typename result_type::mapped_type>(L) ); lua_pop(L, 1); } return result; } template <int I, class C> inline std::enable_if_t< (is_std_set<std::decay_t<C>>{} || is_std_unordered_set<std::decay_t<C>>{}) && !is_nc_reference<C>{}, std::decay_t<C> > get(lua_State* const L) { assert(lua_istable(L, I)); using result_type = std::decay_t<C>; result_type result; auto const end(lua_rawlen(L, I) + 1); for (decltype(lua_rawlen(L, I)) i(1); i != end; ++i) { lua_rawgeti(L, I, i); result.emplace(get<-1, typename result_type::value_type>(L)); } lua_pop(L, end - 1); return result; } #endif // LUALITE_NO_STD_CONTAINERS template <class C> int default_finalizer(lua_State* const L) noexcept(noexcept(std::declval<C>().~C())) { delete static_cast<C*>(lua_touserdata(L, lua_upvalueindex(1))); return {}; } template <std::size_t O, typename C, typename ...A, std::size_t ...I> inline std::enable_if_t<bool(!sizeof...(A)), C*> forward(lua_State* const, std::index_sequence<I...> const) noexcept( noexcept(C()) ) { return new C(); } template <std::size_t O, typename C, typename ...A, std::size_t ...I> inline std::enable_if_t<bool(sizeof...(A)), C*> forward(lua_State* const L, std::index_sequence<I...> const) noexcept( noexcept(C(get<I + O, A>(L)...)) ) { return new C(get<I + O, A>(L)...); } template <std::size_t O, class C, class ...A> int constructor_stub(lua_State* const L) noexcept(noexcept( forward<O, C, A...>(L, std::make_index_sequence<sizeof...(A)>())) ) { assert(sizeof...(A) == lua_gettop(L)); auto const instance(forward<O, C, A...>(L, std::make_index_sequence<sizeof...(A)>()) ); // table lua_createtable(L, 0, default_nrec); for (auto& mi: lualite::class_<C>::defs()) { assert(lua_istable(L, -1)); void* p(instance); for (auto const f: mi.first) { p = f(p); } lua_pushnil(L); lua_pushlightuserdata(L, p); lua_pushcclosure(L, mi.second.callback, 2); rawsetfield(L, -2, mi.second.name); } // metatable assert(lua_istable(L, -1)); lua_createtable(L, 0, 3); // gc assert(lua_istable(L, -1)); lua_pushlightuserdata(L, instance); lua_pushcclosure(L, default_finalizer<C>, 1); rawsetfield(L, -2, "__gc"); // getters assert(lua_istable(L, -1)); lua_pushnil(L); lua_pushlightuserdata(L, instance); lua_pushcclosure(L, getter<C>, 2); rawsetfield(L, -2, "__index"); // setters assert(lua_istable(L, -1)); lua_pushnil(L); lua_pushlightuserdata(L, instance); lua_pushcclosure(L, setter<C>, 2); rawsetfield(L, -2, "__newindex"); lua_setmetatable(L, -2); assert(lua_istable(L, -1)); return 1; } template <std::size_t O, typename R, typename ...A, std::size_t ...I> inline std::enable_if_t<bool(!sizeof...(A)), R> forward(lua_State* const, R (* const f)(A...), std::index_sequence<I...> const) noexcept(noexcept((*f)())) { return (*f)(); } template <std::size_t O, typename R, typename ...A, std::size_t ...I> inline std::enable_if_t<bool(sizeof...(A)), R> forward(lua_State* const L, R (* const f)(A...), std::index_sequence<I...> const) noexcept( noexcept((*f)(get<I + O, A>(L)...)) ) { return (*f)(get<I + O, A>(L)...); } template <typename FP, FP fp, std::size_t O, class R, class ...A> inline std::enable_if_t<std::is_void<R>{}, int> func_stub(lua_State* const L) noexcept( noexcept( forward<O, R, A...>(L, fp, std::make_index_sequence<sizeof...(A)>()) ) ) { assert(sizeof...(A) == lua_gettop(L)); forward<O, R, A...>(L, fp, std::make_index_sequence<sizeof...(A)>()); return {}; } template <typename FP, FP fp, std::size_t O, class R, class ...A> inline std::enable_if_t<!std::is_void<R>{}, int> func_stub(lua_State* const L) noexcept( noexcept( set(L, forward<O, R, A...>(L, fp, std::make_index_sequence<sizeof...(A)>())) ) ) { return set(L, forward<O, R, A...>(L, fp, std::make_index_sequence<sizeof...(A)>())); } template <typename FP, FP fp, class R> inline std::enable_if_t<!std::is_void<R>{}, int> vararg_func_stub(lua_State* const L) noexcept(noexcept(set(fp(L)))) { return set(fp(L)); } template <typename FP, FP fp, class R> inline std::enable_if_t<std::is_void<R>{}, int> vararg_func_stub(lua_State* const L) noexcept(noexcept(fp(L))) { fp(L); return {}; } template <std::size_t O, typename C, typename R, typename ...A, std::size_t ...I> inline std::enable_if_t<bool(!sizeof...(A)), R> forward(lua_State* const, C* const c, R (C::* const ptr_to_member)(A...) const, std::index_sequence<I...> const) noexcept( noexcept((c->*ptr_to_member)()) ) { return (c->*ptr_to_member)(); } template <std::size_t O, typename C, typename R, typename ...A, std::size_t ...I> inline std::enable_if_t<bool(!sizeof...(A)), R> forward(lua_State* const, C* const c, R (C::* const ptr_to_member)(A...), std::index_sequence<I...> const) noexcept( noexcept((c->*ptr_to_member)()) ) { return (c->*ptr_to_member)(); } template <std::size_t O, typename C, typename R, typename ...A, std::size_t ...I> inline std::enable_if_t<bool(sizeof...(A)), R> forward(lua_State* const L, C* const c, R (C::* const ptr_to_member)(A...) const, std::index_sequence<I...> const) noexcept( noexcept((c->*ptr_to_member)(get<I + O, A>(L)...)) ) { return (c->*ptr_to_member)(get<I + O, A>(L)...); } template <std::size_t O, typename C, typename R, typename ...A, std::size_t ...I> inline std::enable_if_t<bool(sizeof...(A)), R> forward(lua_State* const L, C* const c, R (C::* const ptr_to_member)(A...), std::index_sequence<I...> const) noexcept(noexcept((c->*ptr_to_member)(get<I + O, A>(L)...))) { return (c->*ptr_to_member)(get<I + O, A>(L)...); } template <typename FP, FP fp, std::size_t O, class C, class R, class ...A> inline std::enable_if_t<!std::is_void<R>{}, int> member_stub(lua_State* const L) noexcept( noexcept(set(L, forward<O, C, R, A...>(L, static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2))), fp, std::make_index_sequence<sizeof...(A)>())) ) ) { //std::cout << lua_gettop(L) << " " << sizeof...(A) + O - 1 << std::endl; assert(sizeof...(A) + O - 1 == lua_gettop(L)); return set(L, forward<O, C, R, A...>(L, static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2))), fp, std::make_index_sequence<sizeof...(A)>())); } template <typename FP, FP fp, std::size_t O, class C, class R, class ...A> inline std::enable_if_t<std::is_void<R>{}, int> member_stub(lua_State* const L) noexcept( noexcept(forward<O, C, R, A...>(L, static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2))), fp, std::make_index_sequence<sizeof...(A)>()) ) ) { assert(sizeof...(A) + O - 1 == lua_gettop(L)); forward<O, C, R, A...>(L, static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2))), fp, std::make_index_sequence<sizeof...(A)>()); return {}; } template <typename FP, FP fp, class C, class R> inline std::enable_if_t<!std::is_void<R>{}, int> vararg_member_stub(lua_State* const L) noexcept( noexcept(set(L, (static_cast<C*>( lua_touserdata(L, lua_upvalueindex(2)))->*fp)(L)) ) ) { return set(L, (static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2)))->*fp)(L) ); } template <typename FP, FP fp, class C, class R> inline std::enable_if_t<std::is_void<R>{}, int> vararg_member_stub(lua_State* const L) noexcept( noexcept( (static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2)))->*fp)(L) ) ) { (static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2)))->*fp)(L); return {}; } template <typename FP, FP fp, std::size_t O, class R, class ...A> constexpr inline lua_CFunction func_stub(R (*)(A...)) noexcept { return &func_stub<FP, fp, O, R, A...>; } template <typename FP, FP fp, std::size_t O, class R, class C, class ...A> constexpr inline lua_CFunction member_stub(R (C::*)(A...)) noexcept { return &member_stub<FP, fp, O, C, R, A...>; } template <typename FP, FP fp, std::size_t O, class R, class C, class ...A> constexpr inline lua_CFunction member_stub(R (C::*)(A...) const) noexcept { return &member_stub<FP, fp, O, C, R, A...>; } template <typename FP, FP fp, class R, class C> constexpr inline lua_CFunction vararg_member_stub(R (C::*)(lua_State*)) noexcept { return &vararg_member_stub<FP, fp, C, R>; } template <typename FP, FP fp, class R, class C> constexpr inline lua_CFunction vararg_member_stub(R (C::*)(lua_State*) const) noexcept { return &vararg_member_stub<FP, fp, C, R>; } template <typename R> constexpr inline enum property_type get_property_type() noexcept { if (std::is_same<std::decay_t<R>, bool>{}) { return BOOLEAN; } else if (std::is_integral<R>{}) { return INTEGER; } else if (std::is_floating_point<R>{}) { return NUMBER; } else if (std::is_same<R, std::string const&>{} || std::is_same<std::decay_t<R>, char const*>{}) { return STRING; } else { return OTHER; } } template <typename FP, FP fp, class R, class C, class ...A> constexpr inline auto get_property_type( R (C::* const)(A...)) noexcept { return get_property_type<R>(); } template <typename FP, FP fp, class R, class C, class ...A> constexpr inline auto get_property_type(R (C::* const)(A...) const) noexcept { return get_property_type<R>(); } template <typename ...A> inline void call(lua_State* const L, int const nresults, A&& ...args) noexcept(noexcept(swallow{(set(L, std::forward<A>(args)))...})) { int ac{}; swallow{ (ac += set(L, std::forward<A>(args)))... }; assert(ac >= int(sizeof...(A))); lua_call(L, ac, nresults); } class scope { public: scope(char const* const name) : name_(name) { } template <typename ...A> scope(char const* const name, A&&... args) : name_(name) { swallow((args.set_parent_scope(this), 0)...); } scope(scope const&) = delete; scope& operator=(scope const&) = delete; template <typename T> std::enable_if_t< std::is_same<std::decay_t<T>, bool>{}, scope& > constant(char const* const name, T const value) { struct constant_info_type const ci { BOOLEAN, {value} }; constants_.emplace_back(name, ci); return *this; } template <typename T> std::enable_if_t< std::is_floating_point<std::decay_t<T>>{}, scope& > constant(char const* const name, T const value) { struct constant_info_type ci; ci.type = NUMBER; ci.u.number = value; constants_.emplace_back(name, ci); return *this; } template <typename T> std::enable_if_t< std::is_integral<std::decay_t<T>>{} && !std::is_same<std::decay_t<T>, bool>{}, scope& > constant(char const* const name, T const value) { struct constant_info_type ci; ci.type = INTEGER; ci.u.integer = value; constants_.emplace_back(name, ci); return *this; } scope& constant(char const* const name, char const* const value) { struct constant_info_type ci; ci.type = STRING; ci.u.string = value; constants_.emplace_back(name, ci); return *this; } template <typename FP, FP fp> scope& def(char const* const name) { push_function<FP, fp>(name, fp); return *this; } scope& enum_(char const* const name, lua_Integer const value) { constant(name, value); return *this; } template <typename FP, FP fp> scope& vararg_def(char const* const name) { push_vararg_function<FP, fp>(name, fp); return *this; } protected: virtual void apply(lua_State* const L) { struct S { static void push_constant(lua_State* const L, decltype(constants_)::const_reference i) { switch (i.second.type) { default: assert(0); case BOOLEAN: lua_pushboolean(L, i.second.u.boolean); break; case INTEGER: lua_pushinteger(L, i.second.u.integer); break; case NUMBER: lua_pushnumber(L, i.second.u.number); break; case STRING: lua_pushstring(L, i.second.u.string); } } }; if (parent_scope_) { scope::get_scope(L); assert(lua_istable(L, -1)); for (auto& i: constants_) { assert(lua_istable(L, -1)); S::push_constant(L, i); rawsetfield(L, -2, i.first); } for (auto& i: functions_) { assert(lua_istable(L, -1)); lua_pushnil(L); lua_pushcclosure(L, i.callback, 1); rawsetfield(L, -2, i.name); } lua_pop(L, 1); } else { for (auto& i: constants_) { assert(lua_istable(L, -1)); S::push_constant(L, i); lua_setglobal(L, i.first); } for (auto& i: functions_) { lua_pushnil(L); lua_pushcclosure(L, i.callback, 1); lua_setglobal(L, i.name); } auto next(next_); while (next) { next->apply(L); next = next->next_; } } assert(!lua_gettop(L)); } void append_child_scope(scope* const instance) { if (next_) { auto next(next_); while (next->next_) { next = next->next_; } next->next_ = instance; } else { next_ = instance; } } void set_parent_scope(scope* const parent_scope) { parent_scope->append_child_scope(this); parent_scope_ = parent_scope; } void get_scope(lua_State* const L) { if (parent_scope_) { assert(name_); parent_scope_->get_scope(L); if (scope_create_) { scope_create_ = false; if (lua_gettop(L)) { assert(lua_istable(L, -1)); lua_createtable(L, 0, default_nrec); rawsetfield(L, -2, name_); } else { lua_createtable(L, 0, default_nrec); lua_setglobal(L, name_); } } // else do nothing if (lua_gettop(L) && lua_istable(L, -1)) { luaL_getsubtable(L, -1, name_); lua_remove(L, -2); } else { lua_getglobal(L, name_); } } else if (name_) { if (scope_create_) { scope_create_ = false; lua_createtable(L, 0, default_nrec); lua_setglobal(L, name_); } // else do nothing lua_getglobal(L, name_); } // else do nothing } protected: char const* const name_; scope* parent_scope_{}; std::vector<func_info_type> functions_; private: template <typename FP, FP fp, typename R, typename ...A> void push_function(char const* const name, R (* const)(A...)) { functions_.push_back({name, func_stub<FP, fp, 1, R, A...>}); } template <typename FP, FP fp, typename R> void push_vararg_function(char const* const name, R (* const)(lua_State*)) { functions_.push_back({name, vararg_func_stub<FP, fp, R>}); } private: friend class module; constants_type constants_; scope* next_{}; bool scope_create_{true}; }; class module : public scope { lua_State* const L_; public: template <typename ...A> module(lua_State* const L, A&&... args) : scope(nullptr), L_(L) { swallow((args.set_parent_scope(this), 0)...); scope::apply(L); } template <typename ...A> module(lua_State* const L, char const* const name, A&&... args) : scope(name), L_(L) { swallow((args.set_parent_scope(this), 0)...); scope::apply(L); } template <typename T> std::enable_if_t< std::is_same<std::decay_t<T>, bool>{}, module& > constant(char const* const name, T const value) { if (name_) { scope::get_scope(L_); assert(lua_istable(L_, -1)); lua_pushboolean(L_, value); rawsetfield(L_, -2, name); lua_pop(L_, 1); } else { lua_pushboolean(L_, value); lua_setglobal(L_, name); } return *this; } template <typename T> std::enable_if_t< std::is_floating_point<std::decay_t<T>>{}, module& > constant(char const* const name, T const value) { if (name_) { scope::get_scope(L_); assert(lua_istable(L_, -1)); lua_pushnumber(L_, value); rawsetfield(L_, -2, name); lua_pop(L_, 1); } else { lua_pushnumber(L_, value); lua_setglobal(L_, name); } return *this; } template <typename T> std::enable_if_t< std::is_integral<std::decay_t<T>>{} && !std::is_same<std::decay_t<T>, bool>{}, module& > constant(char const* const name, T const value) { if (name_) { scope::get_scope(L_); assert(lua_istable(L_, -1)); lua_pushinteger(L_, value); rawsetfield(L_, -2, name); lua_pop(L_, 1); } else { lua_pushinteger(L_, value); lua_setglobal(L_, name); } return *this; } module& constant(char const* const name, char const* const value) { if (name_) { scope::get_scope(L_); assert(lua_istable(L_, -1)); lua_pushstring(L_, value); rawsetfield(L_, -2, name); lua_pop(L_, 1); } else { lua_pushstring(L_, value); lua_setglobal(L_, name); } return *this; } template <typename FP, FP fp> module& def(char const* const name) { if (name_) { scope::get_scope(L_); assert(lua_istable(L_, -1)); push_function<FP, fp>(fp); rawsetfield(L_, -2, name); lua_pop(L_, 1); } else { push_function<FP, fp>(fp); lua_setglobal(L_, name); } return *this; } module& enum_(char const* const name, int const value) { return constant(name, lua_Number(value)); } template <typename FP, FP fp> module& vararg_def(char const* const name) { if (name_) { scope::get_scope(L_); assert(lua_istable(L_, -1)); push_vararg_function<FP, fp>(fp); rawsetfield(L_, -2, name); lua_pop(L_, 1); } else { push_vararg_function<FP, fp>(fp); lua_setglobal(L_, name); } return *this; } private: template <typename FP, FP fp, typename R, typename ...A> void push_function(R (* const)(A...)) { lua_pushnil(L_); lua_pushcclosure(L_, func_stub<FP, fp, 1, R, A...>, 1); } template <typename FP, FP fp, typename R> void push_vararg_function(R (* const)(lua_State*)) { lua_pushnil(L_); lua_pushcclosure(L_, vararg_func_stub<FP, fp, R>, 1); } }; using accessor_type = std::tuple< std::vector<void* (*)(void*) noexcept>, map_member_info_type, enum property_type >; using accessors_type = std::unordered_map<char const*, accessor_type, str_hash, str_eq >; using accessors_info_type = std::unordered_map<char const*, unsigned, str_hash, str_eq >; using defs_type = std::vector< std::pair< std::vector<void* (*)(void*) noexcept>, member_info_type > >; template <class C> class class_ : public scope { static char const* class_name_; static std::vector<bool(*)(char const*) noexcept> inherits_; static std::vector<func_info_type> constructors_; static defs_type defs_; static accessors_type getters_; static accessors_type setters_; public: class_(char const* const name) : scope(name) { class_name_ = name; } template <typename T> class_& constant(char const* const name, T&& value) { scope::constant(name, std::forward<T>(value)); return *this; } class_& constructor(char const* const name = "new") { return constructor<>(name); } template <class ...A> class_& constructor(char const* const name = "new") { constructors_.push_back({name, constructor_stub<1, C, A...>}); return *this; } template <class ...A> class_& inherits() { swallow{ (S<A>::copy_accessors(class_<A>::getters(), getters_), 0)... }; swallow{ (S<A>::copy_accessors(class_<A>::setters(), setters_), 0)... }; swallow{ (S<A>::copy_defs(class_<A>::defs(), defs_), 0)... }; assert(inherits_.empty()); inherits_.reserve(sizeof...(A)); swallow{ (inherits_.push_back(class_<A>::inherits), 0)... }; return *this; } static auto class_name() noexcept { return class_name_; } static auto const& defs() noexcept { return defs_; } static auto const& getters() noexcept { return getters_; } static auto const& setters() noexcept { return setters_; } auto getters_info() const { accessors_info_type r; for (auto& g: getters_) { r.emplace(g.first, std::get<2>(g.second)); } return r; } auto setters_info() const { accessors_info_type r; for (auto& s: setters_) { r.emplace(s.first, std::get<2>(s.second)); } return r; } static bool inherits(char const* const name) noexcept { assert(class_name_ && name); if (std::strcmp(name, class_name_)) { for (auto const f: inherits_) { if (f(name)) { return true; } // else do nothing } return false; } else { return true; } } template <typename FP, FP fp> std::enable_if_t< is_function_pointer<FP>{}, class_& > def(char const* const name) { scope::def<FP, fp>(name); return *this; } template <typename FP, FP fp> std::enable_if_t< !is_function_pointer<FP>{}, class_& > def(char const* const name) { defs_.push_back( { {}, member_info_type { name, member_stub<FP, fp, 2>(fp) } } ); return *this; } template <typename FP, FP fp> std::enable_if_t< !is_function_pointer<FP>{}, class_& > def_func(char const* const name) { defs_.push_back( { {}, member_info_type { name, member_stub<FP, fp, 1>(fp) } } ); return *this; } template <typename FP, FP fp> std::enable_if_t< is_function_pointer<FP>{}, class_& > def_func(char const* const name) { defs_.push_back( { {}, member_info_type { name, func_stub<FP, fp, 1>(fp) } } ); return *this; } auto& enum_(char const* const name, lua_Integer const value) { scope::constant(name, value); return *this; } template <class FP, FP fp> auto& property(char const* const name) { getters_.emplace(name, accessors_type::mapped_type { {}, member_stub<FP, fp, 3>(fp), get_property_type<FP, fp>(fp) } ); assert(std::get<1>(getters_[name])); return *this; } template <typename FPA, FPA fpa, typename FPB, FPB fpb> auto& property(char const* const name) { getters_.emplace(name, accessors_type::mapped_type { {}, member_stub<FPA, fpa, 3>(fpa), get_property_type<FPA, fpa>(fpa) } ); assert(std::get<1>(getters_[name])); setters_.emplace(name, accessors_type::mapped_type { {}, member_stub<FPB, fpb, 3>(fpb), get_property_type<FPA, fpa>(fpa) } ); assert(std::get<1>(setters_[name])); return *this; } template <typename FP, FP fp> std::enable_if_t< !is_function_pointer<FP>{}, class_& > vararg_def(char const* const name) { defs_.push_back( { {}, member_info_type { name, vararg_member_stub<FP, fp>(fp) } } ); return *this; } private: template <class A> struct S { static void copy_accessors(accessors_type const& src, accessors_type& dst) { for (auto& a: src) { auto& n(dst[a.first] = a.second); std::get<0>(n).emplace_back(convert<A>); std::get<0>(n).shrink_to_fit(); } } static void copy_defs(defs_type const& src, defs_type& dst) { dst.reserve(dst.size() + src.size()); for (auto& a: src) { dst.push_back(a); dst.back().first.emplace_back(convert<A>); dst.back().first.shrink_to_fit(); } } }; void apply(lua_State* const L) { assert(parent_scope_); scope::apply(L); scope::get_scope(L); assert(lua_istable(L, -1)); for (auto& i: constructors_) { assert(lua_istable(L, -1)); lua_pushcfunction(L, i.callback); rawsetfield(L, -2, i.name); } assert(inherits_.capacity() == inherits_.size()); constructors_.shrink_to_fit(); defs_.shrink_to_fit(); lua_pop(L, 1); assert(!lua_gettop(L)); } template <class A> static void* convert(void* const a) noexcept { return static_cast<A*>(static_cast<C*>(a)); } }; template <class C> char const* class_<C>::class_name_; template <class C> std::vector<bool(*)(char const*) noexcept> class_<C>::inherits_; template <class C> std::vector<func_info_type> class_<C>::constructors_; template <class C> defs_type class_<C>::defs_; template <class C> accessors_type class_<C>::getters_; template <class C> accessors_type class_<C>::setters_; } // lualite #endif // LUALITE_HPP
19.952663
86
0.620358
user1095108
0bc65c610251e169438e76ce0313901a45f79ad6
7,030
hpp
C++
include/utils/Utils.hpp
DarkWingMcQuack/GridGraphPathFinder
d8f9a237f17516141bf58c8c86d468f3559af5e3
[ "Apache-2.0" ]
null
null
null
include/utils/Utils.hpp
DarkWingMcQuack/GridGraphPathFinder
d8f9a237f17516141bf58c8c86d468f3559af5e3
[ "Apache-2.0" ]
null
null
null
include/utils/Utils.hpp
DarkWingMcQuack/GridGraphPathFinder
d8f9a237f17516141bf58c8c86d468f3559af5e3
[ "Apache-2.0" ]
null
null
null
#pragma once #include <algorithm> #include <fmt/core.h> #include <functional> #include <future> #include <iomanip> #include <sstream> #include <utility> #include <vector> namespace utils { template<class T> using Ref = std::reference_wrapper<T>; template<class T> using CRef = std::reference_wrapper<const T>; template<class T> using RefVec = std::vector<Ref<T>>; template<class T> using CRefVec = std::vector<CRef<T>>; template<class T> struct is_ref : std::false_type { }; template<class T> struct is_ref<Ref<T>> : std::true_type { }; template<class T> struct is_ref<CRef<T>> : std::true_type { }; template<class T> constexpr auto is_ref_v = is_ref<T>::value; template<class Head0, class Head1, class... Tail> constexpr auto min(Head0&& head0, Head1&& head1, Tail&&... tail) noexcept { if constexpr(sizeof...(tail) == 0) { return head0 < head1 ? head0 : head1; } else { return min( min(std::forward<Head0>(head0), std::forward<Head1>(head1)), std::forward<Tail>(tail)...); } } template<class Head0, class Head1, class... Tail> constexpr auto max(Head0&& head0, Head1&& head1, Tail&&... tail) noexcept { if constexpr(sizeof...(tail) == 0) { return head0 > head1 ? head0 : head1; } else { return max( max(std::forward<Head0>(head0), std::forward<Head1>(head1)), std::forward<Tail>(tail)...); } } template<class Head0, class Head1, class... Tail> constexpr auto concat(Head0&& head0, Head1&& head1, Tail&&... tail) noexcept { if constexpr(sizeof...(tail) == 0) { head0.insert(std::end(head0), std::begin(head1), std::end(head1)); return std::forward<Head0>(head0); } else { return concat( concat(std::forward<Head0>(head0), std::forward<Head1>(head1)), std::forward<Tail>(tail)...); } } template<class T> auto collectFutures(std::vector<std::future<T>>&& futures) noexcept -> std::vector<T> { std::vector<T> collected; collected.reserve(futures.size()); std::transform(std::make_move_iterator(std::begin(futures)), std::make_move_iterator(std::end(futures)), std::back_inserter(collected), [](auto future) { return future.get(); }); return collected; } template<class Head0, class Head1, class... Tail> auto await(std::future<Head0>&& head0, std::future<Head1>&& head1, std::future<Tail>&&... tail) noexcept -> std::tuple<Head0, Head1, Tail...> { return std::tuple{head0.get(), head1.get(), tail.get()...}; } template<class T, class... Tail> auto intersect(std::vector<T>&& head0, std::vector<T>&& head1, Tail&&... tail) noexcept -> std::vector<T> { if constexpr(sizeof...(tail) == 0) { std::vector<T> intersection; std::set_intersection(std::make_move_iterator(std::begin(head0)), std::make_move_iterator(std::end(head0)), std::make_move_iterator(std::begin(head1)), std::make_move_iterator(std::end(head1)), std::back_inserter(intersection)); return intersection; } else { return intersect( intersect(std::move(head0), std::move(head1)), std::forward<Tail>(tail)...); } } template<class T, class... Tail> auto intersect(const std::vector<T>& head0, const std::vector<T>& head1, Tail&&... tail) noexcept -> std::vector<T> { if constexpr(sizeof...(tail) == 0) { std::vector<T> intersection; std::set_intersection(std::begin(head0), std::end(head0), std::begin(head1), std::end(head1), std::back_inserter(intersection)); return intersection; } else { return intersect( intersect(head0, head1), std::forward<Tail>(tail)...); } } template<class T, class F, class... Tail> auto intersect(std::vector<T>&& head0, std::vector<T>&& head1, Tail&&... tail, F&& func) noexcept -> std::vector<T> { if constexpr(sizeof...(tail) == 0) { std::vector<T> intersection; std::set_intersection(std::make_move_iterator(std::begin(head0)), std::make_move_iterator(std::end(head0)), std::make_move_iterator(std::begin(head1)), std::make_move_iterator(std::end(head1)), std::back_inserter(intersection), std::forward<F>(func)); return intersection; } else { return intersect( intersect(std::move(head0), std::move(head1), std::forward<F>(func)), std::forward<Tail>(tail)..., std::forward<F>(func)); } } template<class T, class F, class... Tail> auto intersect(const std::vector<T>& head0, const std::vector<T>& head1, Tail&&... tail, F&& func) noexcept -> std::vector<T> { if constexpr(sizeof...(tail) == 0) { std::vector<T> intersection; std::set_intersection(std::begin(head0), std::end(head0), std::begin(head1), std::end(head1), std::back_inserter(intersection), std::forward<F>(func)); return intersection; } else { return intersect( intersect(head0, head1, std::forward<F>(func)), std::forward<Tail>(tail)..., std::forward<F>(func)); } } template<class Head0, class Head1, class... Tail> auto hashCombine(Head0&& head0, Head1&& head1, Tail&&... tail) { if constexpr(sizeof...(tail) == 0) { std::hash<std::remove_const_t<std::remove_reference_t<Head0>>> hasher0; std::hash<std::remove_const_t<std::remove_reference_t<Head1>>> hasher1; auto seed = hasher0(head0); return seed xor (hasher1(head1) + 0x9e3779b9 + (seed << 6) + (seed >> 2)); } else { return hashCombine( hashCombine(head0, head1), std::forward<Tail>(tail)...); } } inline auto unquote(const std::string& s) -> std::string { std::string result; std::istringstream ss(s); ss >> std::quoted(result); return result; } template<class... Ts> struct Overloaded : Ts... { using Ts::operator()...; }; template<class... Ts> Overloaded(Ts...) -> Overloaded<Ts...>; } // namespace utils
28.693878
82
0.526316
DarkWingMcQuack
0bc9d6fffbd6c918a0c680ee105052f90bcdf2bf
1,941
hpp
C++
application/timely-matter/src/views/BaseView.hpp
davidbeermann/timely-matter
fca86fb5b48766c5371677a90ac5149c1b071149
[ "MIT" ]
2
2016-09-03T17:49:30.000Z
2016-12-20T18:12:58.000Z
application/timely-matter/src/views/BaseView.hpp
davidbeermann/timely-matter
fca86fb5b48766c5371677a90ac5149c1b071149
[ "MIT" ]
null
null
null
application/timely-matter/src/views/BaseView.hpp
davidbeermann/timely-matter
fca86fb5b48766c5371677a90ac5149c1b071149
[ "MIT" ]
null
null
null
#pragma once #include "ofMain.h" #include "ofEvents.h" #include "AppModel.hpp" #include "KinectModel.hpp" #include "ProjectorModel.hpp" #include "ViewEvent.hpp" namespace timelymatter { // Base view class to be extended by concrete views managed by ViewManager class. // Implementation for NVI Non-Virtual Interface derived from here: // http://stackoverflow.com/questions/14323595/best-way-to-declare-an-interface-in-c11#answer-14324500 class BaseView { protected: AppModel& m_app_model; KinectModel& m_kinect_model; ProjectorModel& m_projector_model; ViewEvent& m_view_event; // Methods to be implemented by concrete view. virtual void m_onWindowResized(const int width, const int height) = 0; virtual void m_onSetup() = 0; virtual void m_onUpdate() = 0; virtual void m_onDraw() = 0; public: // Setup model references for all views derived from this class. BaseView() : m_app_model(AppModel::get()), m_kinect_model(KinectModel::get()), m_projector_model(ProjectorModel::get()), m_view_event(ViewEvent::get()) { ofAddListener(ofEvents().windowResized, this, &BaseView::onWindowResized); }; // always define virtual destructors for base classes // http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors#461224 virtual ~BaseView() { ofRemoveListener(ofEvents().windowResized, this, &BaseView::onWindowResized); }; // event listener methods void onWindowResized(ofResizeEventArgs& args) { m_onWindowResized(args.width, args.height); }; // Non-Virtual Interface methods void setup() { // call setup first... m_onSetup(); // ...before triggering a virtual window resize. m_onWindowResized(ofGetWindowWidth(), ofGetWindowHeight()); }; void update() { m_onUpdate(); }; void draw() { m_onDraw(); }; }; }
30.809524
102
0.679547
davidbeermann
0bca25337e84c7bd598a52dd189ecc5e486e43f0
24
cpp
C++
02-classes-constructors-destructors/2-makefile/Triangle.cpp
nofar88/cpp-5782
473c68627fc0908fdef8956caf1e1d2267c9417b
[ "MIT" ]
14
2021-01-30T16:36:18.000Z
2022-03-30T17:24:44.000Z
02-classes-constructors-destructors/2-makefile/Triangle.cpp
dimastar2310/cpp-5781
615ba07e0841522df74384f380172557f5e305a7
[ "MIT" ]
1
2022-03-02T20:55:14.000Z
2022-03-02T20:55:14.000Z
02-classes-constructors-destructors/2-makefile/Triangle.cpp
dimastar2310/cpp-5781
615ba07e0841522df74384f380172557f5e305a7
[ "MIT" ]
23
2020-03-12T13:21:29.000Z
2021-02-22T21:29:48.000Z
#include "Triangle.hpp"
12
23
0.75
nofar88
0bcb1bb4438a2047624f8ec1ed46047bd24dc449
14,628
cpp
C++
tiger_ci/erkale/eri_digest.cpp
EACcodes/TigerCI
ac1311ea5e2b829b5507171afdbdd6c64e12e6fd
[ "BSD-3-Clause" ]
3
2016-12-08T13:57:10.000Z
2019-01-17T17:05:46.000Z
tiger_ci/erkale/eri_digest.cpp
EACcodes/TigerCI
ac1311ea5e2b829b5507171afdbdd6c64e12e6fd
[ "BSD-3-Clause" ]
null
null
null
tiger_ci/erkale/eri_digest.cpp
EACcodes/TigerCI
ac1311ea5e2b829b5507171afdbdd6c64e12e6fd
[ "BSD-3-Clause" ]
2
2019-02-20T06:03:24.000Z
2020-06-09T09:00:49.000Z
/* * This source code is part of * * E R K A L E * - * DFT from Hel * * Written by Susi Lehtola, 2010-2015 * Copyright (c) 2010-2015, Susi Lehtola * * This program 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 2 * of the License, or (at your option) any later version. */ #include "eri_digest.h" #include "eriworker.h" IntegralDigestor::IntegralDigestor() { } IntegralDigestor::~IntegralDigestor() { } JDigestor::JDigestor(const arma::mat & P_) : P(P_) { J.zeros(P.n_rows,P.n_cols); } JDigestor::~JDigestor() { } void JDigestor::digest(const std::vector<eripair_t> & shpairs, size_t ip, size_t jp, const std::vector<double> & ints, size_t ioff) { // Shells in quartet are size_t is=shpairs[ip].is; size_t js=shpairs[ip].js; size_t ks=shpairs[jp].is; size_t ls=shpairs[jp].js; // Amount of functions on the first pair is size_t Ni=shpairs[ip].Ni; size_t Nj=shpairs[ip].Nj; // and on second pair is size_t Nk=shpairs[jp].Ni; size_t Nl=shpairs[jp].Nj; // First functions on the first pair is size_t i0=shpairs[ip].i0; size_t j0=shpairs[ip].j0; // Second pair is size_t k0=shpairs[jp].i0; size_t l0=shpairs[jp].j0; // J_ij = (ij|kl) P_kl { // Work matrix arma::mat Jij(Ni,Nj); Jij.zeros(); arma::mat Pkl=P.submat(k0,l0,k0+Nk-1,l0+Nl-1); // Degeneracy factor double fac=1.0; if(ks!=ls) fac=2.0; // Increment matrix for(size_t ii=0;ii<Ni;ii++) for(size_t jj=0;jj<Nj;jj++) { // Matrix element double el=0.0; for(size_t kk=0;kk<Nk;kk++) for(size_t ll=0;ll<Nl;ll++) el+=Pkl(kk,ll)*ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]; // Set the element Jij(ii,jj)+=fac*el; } // Store the matrix element J.submat(i0,j0,i0+Ni-1,j0+Nj-1)+=Jij; if(is!=js) J.submat(j0,i0,j0+Nj-1,i0+Ni-1)+=arma::trans(Jij); } // Permutation: J_kl = (ij|kl) P_ij if(ip!=jp) { // Work matrix arma::mat Jkl(Nk,Nl); Jkl.zeros(); arma::mat Pij=P.submat(i0,j0,i0+Ni-1,j0+Nj-1); // Degeneracy factor double fac=1.0; if(is!=js) fac=2.0; // Increment matrix for(size_t kk=0;kk<Nk;kk++) for(size_t ll=0;ll<Nl;ll++) { // Matrix element double el=0.0; for(size_t ii=0;ii<Ni;ii++) { for(size_t jj=0;jj<Nj;jj++) { el+=Pij(ii,jj)*ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]; } } // Set the element Jkl(kk,ll)+=fac*el; } // Store the matrix element J.submat(k0,l0,k0+Nk-1,l0+Nl-1)+=Jkl; if(ks!=ls) J.submat(l0,k0,l0+Nl-1,k0+Nk-1)+=arma::trans(Jkl); } } arma::mat JDigestor::get_J() const { return J; } KDigestor::KDigestor(const arma::mat & P_) : P(P_) { K.zeros(P.n_rows,P.n_cols); } KDigestor::~KDigestor() { } void KDigestor::digest(const std::vector<eripair_t> & shpairs, size_t ip, size_t jp, const std::vector<double> & ints, size_t ioff) { size_t is=shpairs[ip].is; size_t js=shpairs[ip].js; size_t ks=shpairs[jp].is; size_t ls=shpairs[jp].js; // Amount of functions on the first pair is size_t Ni=shpairs[ip].Ni; size_t Nj=shpairs[ip].Nj; // and on second pair is size_t Nk=shpairs[jp].Ni; size_t Nl=shpairs[jp].Nj; // First functions on the first pair is size_t i0=shpairs[ip].i0; size_t j0=shpairs[ip].j0; // Second pair is size_t k0=shpairs[jp].i0; size_t l0=shpairs[jp].j0; /* When all indices are different, the following integrals are equivalent: (ij|kl) (ij|lk) (ji|kl) (ji|lk) (kl|ij) (kl|ji) (lk|ij) (lk|ji) This translates to K(i,k) += (ij|kl) P(j,l) // always K(j,k) += (ij|kl) P(i,l) // if (is!=js) K(i,l) += (ij|kl) P(j,k) // if (ls!=ks) K(j,l) += (ij|kl) P(i,k) // if (is!=js) and (ls!=ks) and for ij != kl K(k,i) += (ij|kl) P(j,l) // always K(k,j) += (ij|kl) P(i,l) // if (is!=js) K(l,i) += (ij|kl) P(j,k) // if (ks!=ls) K(l,j) += (ij|kl) P(i,k) // if (is!=js) and (ks!=ls) However, the latter four permutations just make the exchange matrix symmetric. So the only thing we need to do is do the first four permutations, and at the end we sum up K_ij and K_ji for j>i and set K_ij and K_ji to this value. This makes things a *lot* easier. So: We just need to check if the shells are different, in which case K will get extra increments. */ // First, do the ik part: K(i,k) += (ij|kl) P(j,l) { arma::mat Kik(Ni,Nk); Kik.zeros(); arma::mat Pjl =P.submat(j0,l0,j0+Nj-1,l0+Nl-1); // Increment Kik for(size_t ii=0;ii<Ni;ii++) for(size_t kk=0;kk<Nk;kk++) for(size_t ll=0;ll<Nl;ll++) for(size_t jj=0;jj<Nj;jj++) Kik (ii,kk)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pjl (jj,ll); // Set elements K.submat(i0,k0,i0+Ni-1,k0+Nk-1)+=Kik; // Symmetrize if necessary if(ip!=jp) K.submat(k0,i0,k0+Nk-1,i0+Ni-1)+=arma::trans(Kik); } // Then, the second part: K(j,k) += (ij|kl) P(i,l) if(is!=js) { arma::mat Kjk(Nj,Nk); Kjk.zeros(); arma::mat Pil=P.submat(i0,l0,i0+Ni-1,l0+Nl-1); // Increment Kjk for(size_t jj=0;jj<Nj;jj++) for(size_t kk=0;kk<Nk;kk++) for(size_t ll=0;ll<Nl;ll++) for(size_t ii=0;ii<Ni;ii++) Kjk(jj,kk)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pil(ii,ll); // Set elements K.submat(j0,k0,j0+Nj-1,k0+Nk-1)+=Kjk; // Symmetrize if necessary (take care about possible overlap with next routine) if(ip!=jp) { K.submat(k0,j0,k0+Nk-1,j0+Nj-1)+=arma::trans(Kjk); } } // Third part: K(i,l) += (ij|kl) P(j,k) if(ks!=ls) { arma::mat Kil(Ni,Nl); Kil.zeros(); arma::mat Pjk=P.submat(j0,k0,j0+Nj-1,k0+Nk-1); // Increment Kil for(size_t ii=0;ii<Ni;ii++) for(size_t ll=0;ll<Nl;ll++) for(size_t jj=0;jj<Nj;jj++) for(size_t kk=0;kk<Nk;kk++) { Kil(ii,ll)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pjk(jj,kk); } // Set elements K.submat(i0,l0,i0+Ni-1,l0+Nl-1)+=Kil; // Symmetrize if necessary if(ip!=jp) K.submat(l0,i0,l0+Nl-1,i0+Ni-1)+=arma::trans(Kil); } // Last permutation: K(j,l) += (ij|kl) P(i,k) if(is!=js && ks!=ls) { arma::mat Kjl(Nj,Nl); Kjl.zeros(); arma::mat Pik=P.submat(i0,k0,i0+Ni-1,k0+Nk-1); // Increment Kjl for(size_t jj=0;jj<Nj;jj++) for(size_t ll=0;ll<Nl;ll++) for(size_t ii=0;ii<Ni;ii++) for(size_t kk=0;kk<Nk;kk++) { Kjl(jj,ll)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pik(ii,kk); } // Set elements K.submat(j0,l0,j0+Nj-1,l0+Nl-1)+=Kjl; // Symmetrize if necessary if (ip!=jp) K.submat(l0,j0,l0+Nl-1,j0+Nj-1)+=arma::trans(Kjl); } } arma::mat KDigestor::get_K() const { return K; } cxKDigestor::cxKDigestor(const arma::cx_mat & P_) : P(P_) { K.zeros(P.n_rows,P.n_cols); } cxKDigestor::~cxKDigestor() { } void cxKDigestor::digest(const std::vector<eripair_t> & shpairs, size_t ip, size_t jp, const std::vector<double> & ints, size_t ioff) { size_t is=shpairs[ip].is; size_t js=shpairs[ip].js; size_t ks=shpairs[jp].is; size_t ls=shpairs[jp].js; // Amount of functions on the first pair is size_t Ni=shpairs[ip].Ni; size_t Nj=shpairs[ip].Nj; // and on second pair is size_t Nk=shpairs[jp].Ni; size_t Nl=shpairs[jp].Nj; // First functions on the first pair is size_t i0=shpairs[ip].i0; size_t j0=shpairs[ip].j0; // Second pair is size_t k0=shpairs[jp].i0; size_t l0=shpairs[jp].j0; /* When all indices are different, the following integrals are equivalent: (ij|kl) (ij|lk) (ji|kl) (ji|lk) (kl|ij) (kl|ji) (lk|ij) (lk|ji) This translates to K(i,k) += (ij|kl) P(j,l) // always K(j,k) += (ij|kl) P(i,l) // if (is!=js) K(i,l) += (ij|kl) P(j,k) // if (ls!=ks) K(j,l) += (ij|kl) P(i,k) // if (is!=js) and (ls!=ks) and for ij != kl K(k,i) += (ij|kl) P(j,l) // always K(k,j) += (ij|kl) P(i,l) // if (is!=js) K(l,i) += (ij|kl) P(j,k) // if (ks!=ls) K(l,j) += (ij|kl) P(i,k) // if (is!=js) and (ks!=ls) However, the latter four permutations just make the exchange matrix symmetric. So the only thing we need to do is do the first four permutations, and at the end we sum up K_ij and K_ji for j>i and set K_ij and K_ji to this value. This makes things a *lot* easier. So: We just need to check if the shells are different, in which case K will get extra increments. */ // First, do the ik part: K(i,k) += (ij|kl) P(j,l) { arma::cx_mat Kik(Ni,Nk); Kik.zeros(); arma::cx_mat Pjl =P.submat(j0,l0,j0+Nj-1,l0+Nl-1); // Increment Kik for(size_t ii=0;ii<Ni;ii++) for(size_t kk=0;kk<Nk;kk++) for(size_t ll=0;ll<Nl;ll++) for(size_t jj=0;jj<Nj;jj++) Kik (ii,kk)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pjl (jj,ll); // Set elements K.submat(i0,k0,i0+Ni-1,k0+Nk-1)+=Kik; // Symmetrize if necessary if(ip!=jp) K.submat(k0,i0,k0+Nk-1,i0+Ni-1)+=arma::trans(Kik); } // Then, the second part: K(j,k) += (ij|kl) P(i,l) if(is!=js) { arma::cx_mat Kjk(Nj,Nk); Kjk.zeros(); arma::cx_mat Pil=P.submat(i0,l0,i0+Ni-1,l0+Nl-1); // Increment Kjk for(size_t jj=0;jj<Nj;jj++) for(size_t kk=0;kk<Nk;kk++) for(size_t ll=0;ll<Nl;ll++) for(size_t ii=0;ii<Ni;ii++) Kjk(jj,kk)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pil(ii,ll); // Set elements K.submat(j0,k0,j0+Nj-1,k0+Nk-1)+=Kjk; // Symmetrize if necessary (take care about possible overlap with next routine) if(ip!=jp) { K.submat(k0,j0,k0+Nk-1,j0+Nj-1)+=arma::trans(Kjk); } } // Third part: K(i,l) += (ij|kl) P(j,k) if(ks!=ls) { arma::cx_mat Kil(Ni,Nl); Kil.zeros(); arma::cx_mat Pjk=P.submat(j0,k0,j0+Nj-1,k0+Nk-1); // Increment Kil for(size_t ii=0;ii<Ni;ii++) for(size_t ll=0;ll<Nl;ll++) for(size_t jj=0;jj<Nj;jj++) for(size_t kk=0;kk<Nk;kk++) { Kil(ii,ll)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pjk(jj,kk); } // Set elements K.submat(i0,l0,i0+Ni-1,l0+Nl-1)+=Kil; // Symmetrize if necessary if(ip!=jp) K.submat(l0,i0,l0+Nl-1,i0+Ni-1)+=arma::trans(Kil); } // Last permutation: K(j,l) += (ij|kl) P(i,k) if(is!=js && ks!=ls) { arma::cx_mat Kjl(Nj,Nl); Kjl.zeros(); arma::cx_mat Pik=P.submat(i0,k0,i0+Ni-1,k0+Nk-1); // Increment Kjl for(size_t jj=0;jj<Nj;jj++) for(size_t ll=0;ll<Nl;ll++) for(size_t ii=0;ii<Ni;ii++) for(size_t kk=0;kk<Nk;kk++) { Kjl(jj,ll)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pik(ii,kk); } // Set elements K.submat(j0,l0,j0+Nj-1,l0+Nl-1)+=Kjl; // Symmetrize if necessary if (ip!=jp) K.submat(l0,j0,l0+Nl-1,j0+Nj-1)+=arma::trans(Kjl); } } arma::cx_mat cxKDigestor::get_K() const { return K; } ForceDigestor::ForceDigestor() { } ForceDigestor::~ForceDigestor() { } JFDigestor::JFDigestor(const arma::mat & P_) : P(P_) { } JFDigestor::~JFDigestor() { } void JFDigestor::digest(const std::vector<eripair_t> & shpairs, size_t ip, size_t jp, dERIWorker & deriw, arma::vec & f) { // Shells in question are size_t is=shpairs[ip].is; size_t js=shpairs[ip].js; size_t ks=shpairs[jp].is; size_t ls=shpairs[jp].js; // Amount of functions on the first pair is size_t Ni=shpairs[ip].Ni; size_t Nj=shpairs[ip].Nj; // and on second pair is size_t Nk=shpairs[jp].Ni; size_t Nl=shpairs[jp].Nj; // First functions on the first pair is size_t i0=shpairs[ip].i0; size_t j0=shpairs[ip].j0; // Second pair is size_t k0=shpairs[jp].i0; size_t l0=shpairs[jp].j0; // E_J = P_ij (ij|kl) P_kl. Work matrices arma::mat Pij=P.submat(i0,j0,i0+Ni-1,j0+Nj-1); arma::mat Pkl=P.submat(k0,l0,k0+Nk-1,l0+Nl-1); // Degeneracy factor double Jfac=-0.5; if(is!=js) Jfac*=2.0; if(ks!=ls) Jfac*=2.0; if(ip!=jp) Jfac*=2.0; // Increment the forces. for(int idx=0;idx<12;idx++) { // Get the integral derivatives const std::vector<double> *erip=deriw.getp(idx); // E_J = P_ij (ij|kl) P_kl double el=0.0; for(size_t ii=0;ii<Ni;ii++) for(size_t jj=0;jj<Nj;jj++) for(size_t kk=0;kk<Nk;kk++) for(size_t ll=0;ll<Nl;ll++) el+=Pij(ii,jj)*Pkl(kk,ll)*(*erip)[((ii*Nj+jj)*Nk+kk)*Nl+ll]; // Increment the element f(idx)+=Jfac*el; } } KFDigestor::KFDigestor(const arma::mat & P_, double kfrac_, bool restr) : P(P_), kfrac(kfrac_) { fac = restr ? 0.5 : 1.0; } KFDigestor::~KFDigestor() { } void KFDigestor::digest(const std::vector<eripair_t> & shpairs, size_t ip, size_t jp, dERIWorker & deriw, arma::vec & f) { // Shells on quartet are size_t is=shpairs[ip].is; size_t js=shpairs[ip].js; size_t ks=shpairs[jp].is; size_t ls=shpairs[jp].js; // Amount of functions on the first pair is size_t Ni=shpairs[ip].Ni; size_t Nj=shpairs[ip].Nj; // and on second pair is size_t Nk=shpairs[jp].Ni; size_t Nl=shpairs[jp].Nj; // First functions on the first pair is size_t i0=shpairs[ip].i0; size_t j0=shpairs[ip].j0; // Second pair is size_t k0=shpairs[jp].i0; size_t l0=shpairs[jp].j0; // E_K = P_ik (ij|kl) P_jl arma::mat Pik=P.submat(i0,k0,i0+Ni-1,k0+Nk-1); arma::mat Pjl=P.submat(j0,l0,j0+Nj-1,l0+Nl-1); // + P_jk (ij|kl) P_il arma::mat Pjk=P.submat(j0,k0,j0+Nj-1,k0+Nk-1); arma::mat Pil=P.submat(i0,l0,i0+Ni-1,l0+Nl-1); double K1fac, K2fac; if(is!=js && ks!=ls) { // Get both twice. K1fac=1.0; K2fac=1.0; } else if(is==js && ks==ls) { // Only get the first one, once. K1fac=0.5; K2fac=0.0; } else { // Get both once. K1fac=0.5; K2fac=0.5; } // Switch symmetry if(ip!=jp) { K1fac*=2.0; K2fac*=2.0; } // Restricted calculation? K1fac*=fac*kfrac; K2fac*=fac*kfrac; // Increment the forces. for(int idx=0;idx<12;idx++) { // Get the integral derivatives const std::vector<double> * erip=deriw.getp(idx); // E_K = P_ik (ij|kl) P_jl double el=0.0; // Increment matrix for(size_t ii=0;ii<Ni;ii++) for(size_t jj=0;jj<Nj;jj++) for(size_t kk=0;kk<Nk;kk++) for(size_t ll=0;ll<Nl;ll++) el+=Pik(ii,kk)*Pjl(jj,ll)*(*erip)[((ii*Nj+jj)*Nk+kk)*Nl+ll]; // Increment the element f(idx)+=K1fac*el; // Second contribution if(K2fac!=0.0) { el=0.0; // Increment matrix for(size_t ii=0;ii<Ni;ii++) for(size_t jj=0;jj<Nj;jj++) for(size_t kk=0;kk<Nk;kk++) for(size_t ll=0;ll<Nl;ll++) el+=Pjk(jj,kk)*Pil(ii,ll)*(*erip)[((ii*Nj+jj)*Nk+kk)*Nl+ll]; // Increment the element f(idx)+=K2fac*el; } } }
25.844523
135
0.588392
EACcodes
0bcccb877eee61c1da092529970437fd4bf0d898
5,080
cpp
C++
sources/source/tierlibs.cpp
vocweb/cso2-launcher
abc144acaa3dfb5b0c9acd61cd75970cac012617
[ "MIT" ]
55
2018-09-01T17:52:17.000Z
2019-09-23T10:30:49.000Z
sources/source/tierlibs.cpp
RedheatWei/cso2-launcher
4cebbb98d51d33bd24c9a86a1d3fc311686d5011
[ "MIT" ]
70
2018-08-22T05:53:34.000Z
2019-09-23T15:11:39.000Z
sources/source/tierlibs.cpp
RedheatWei/cso2-launcher
4cebbb98d51d33bd24c9a86a1d3fc311686d5011
[ "MIT" ]
39
2018-09-01T21:42:50.000Z
2019-09-23T18:38:07.000Z
#include "source/tierlibs.hpp" #include <stdexcept> #include "platform.hpp" #include <engine/cdll_int.hpp> #include <engine/cso2/icso2msgmanager.hpp> #include <filesystem/filesystem.hpp> #include <icvar.hpp> #include <ienginevgui.hpp> #include <inputsystem/iinputsystem.hpp> #include <materialsystem/imaterialsystem.hpp> #include <tier0/cso2/iloadingsplash.hpp> #include <tier0/cso2/iprecommandlineparser.hpp> #include <tier0/dbg.hpp> #include <tier0/icommandline.hpp> #include <tier0/platform.hpp> #include <vgui/ilocalize.hpp> template <class T> inline T* FactoryCast( CreateInterfaceFn f, const char* szName, int* retCode ) { return reinterpret_cast<T*>( f( szName, retCode ) ); } // // tier1 libraries // ICvar* g_pCVar = nullptr; void ConnectTier1Libraries( CreateInterfaceFn factory ) { g_pCVar = FactoryCast<ICvar>( factory, CVAR_INTERFACE_VERSION, NULL ); } // // tier2 libraries // IFileSystem* g_pFullFileSystem = nullptr; IMaterialSystem* g_pMaterialSystem = nullptr; IInputSystem* g_pInputSystem = nullptr; void ConnectTier2Libraries( CreateInterfaceFn factory ) { g_pFullFileSystem = FactoryCast<IFileSystem>( factory, FILESYSTEM_INTERFACE_VERSION, NULL ); g_pMaterialSystem = FactoryCast<IMaterialSystem>( factory, MATERIAL_SYSTEM_INTERFACE_VERSION, NULL ); g_pInputSystem = FactoryCast<IInputSystem>( factory, INPUTSYSTEM_INTERFACE_VERSION, NULL ); } // // tier3 libraries // vgui::ILocalize* g_pVGuiLocalize = nullptr; void ConnectTier3Libraries( CreateInterfaceFn factory ) { g_pVGuiLocalize = FactoryCast<vgui::ILocalize>( factory, VGUI_LOCALIZE_INTERFACE_VERSION, NULL ); } // // aditional libraries // IVEngineClient* g_pEngineClient = nullptr; ICSO2MsgHandlerEngine* g_pCSO2MsgHandler = nullptr; IEngineVGui* g_pEngineVGui = nullptr; void ConnectNonTierLibraries( CreateInterfaceFn factory ) { g_pEngineClient = FactoryCast<IVEngineClient>( factory, VENGINE_CLIENT_INTERFACE_VERSION, NULL ); g_pCSO2MsgHandler = FactoryCast<ICSO2MsgHandlerEngine>( factory, CSO2_MSGHANDLER_ENGINE_VERSION, NULL ); g_pEngineVGui = FactoryCast<IEngineVGui>( factory, VENGINE_VGUI_VERSION, NULL ); } void ConnectAllLibraries( CreateInterfaceFn factory ) { ConnectTier1Libraries( factory ); ConnectTier2Libraries( factory ); ConnectTier3Libraries( factory ); ConnectNonTierLibraries( factory ); } // // tier0 imports // void* GetTierZeroModule() { static void* zeroModuleBase = nullptr; if ( zeroModuleBase == nullptr ) { zeroModuleBase = Sys_LoadLibrary( "tier0.dll" ); if ( zeroModuleBase == nullptr ) { throw std::runtime_error( "Could not find/load tier0.dll.\n" "Make sure the launcher is in the correct directory." ); } } return zeroModuleBase; } template <typename FuncType> inline FuncType GetTierZeroExport( const char* exportName ) { auto res = reinterpret_cast<FuncType>( Sys_GetModuleExport( GetTierZeroModule(), exportName ) ); if ( res == nullptr ) { std::string errMsg = "Could not get tier0 export "; errMsg += exportName; throw std::runtime_error( errMsg ); } return res; } ICommandLine* CommandLine() { using fn_t = ICommandLine* (*)(); static fn_t pFunc = nullptr; if ( pFunc == nullptr ) { pFunc = GetTierZeroExport<fn_t>( "CommandLine_Tier0" ); } return pFunc(); } ICSO2LoadingSplash* GetCSO2LoadingSplash() { using fn_t = ICSO2LoadingSplash* (*)(); static fn_t pFunc = nullptr; if ( pFunc == nullptr ) { pFunc = GetTierZeroExport<fn_t>( "GetCSO2LoadingSplash" ); } return pFunc(); } void SpewOutputFunc( SpewOutputFunc_t func ) { using fn_t = void ( * )( SpewOutputFunc_t ); static fn_t pFunc = nullptr; if ( pFunc == nullptr ) { pFunc = GetTierZeroExport<fn_t>( "SpewOutputFunc" ); } pFunc( func ); } ICSO2PreCommandLineParser* GetCSO2PreCommandLineParser() { using fn_t = ICSO2PreCommandLineParser* (*)(); static fn_t pFunc = nullptr; if ( pFunc == nullptr ) { pFunc = GetTierZeroExport<fn_t>( "GetCSO2PreCommandLineParser" ); } return pFunc(); } const char* GetSpewOutputGroup() { using fn_t = const char* (*)(); static fn_t pFunc = nullptr; if ( pFunc == nullptr ) { pFunc = GetTierZeroExport<fn_t>( "GetSpewOutputGroup" ); } return pFunc(); } bool ShouldUseNewAssertDialog() { using fn_t = bool ( * )(); static fn_t pFunc = nullptr; if ( pFunc == nullptr ) { pFunc = GetTierZeroExport<fn_t>( "ShouldUseNewAssertDialog" ); } return pFunc(); } double Plat_FloatTime() { using fn_t = double ( * )(); static fn_t pFunc = nullptr; if ( pFunc == nullptr ) { pFunc = GetTierZeroExport<fn_t>( "Plat_FloatTime" ); } return pFunc(); } IEngineVGuiInternal* EngineVGui() { return static_cast<IEngineVGuiInternal*>( g_pEngineVGui ); }
22.280702
80
0.679528
vocweb
0bcd809ea0d4ed685272d2bd6d7080129cc2ea7d
91,177
cpp
C++
src/shell/shell.cpp
mediaexplorer74/dosbox-x
be9f94b740234f7813bf5a063a558cef9dc7f9a6
[ "MIT" ]
3
2022-02-20T11:06:29.000Z
2022-03-11T08:16:55.000Z
src/shell/shell.cpp
mediaexplorer74/dosbox-x
be9f94b740234f7813bf5a063a558cef9dc7f9a6
[ "MIT" ]
null
null
null
src/shell/shell.cpp
mediaexplorer74/dosbox-x
be9f94b740234f7813bf5a063a558cef9dc7f9a6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2002-2021 The DOSBox Team * * This program 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 2 of the License, or * (at your option) any later version. * * This program 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. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <assert.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <sys/stat.h> #include <gtest/gtest.h> #include "dosbox.h" #include "logging.h" #include "regs.h" #include "control.h" #include "shell.h" #include "menu.h" #include "cpu.h" #include "callback.h" #include "dos_inc.h" #include "support.h" #include "mapper.h" #include "render.h" #include "jfont.h" #include "../dos/drives.h" #include "../ints/int10.h" #include <unistd.h> #include <time.h> #include <string> #include <sstream> #include <vector> #if defined(WIN32) #include <windows.h> #else #include <dirent.h> #endif #include "build_timestamp.h" extern bool startcmd, startwait, startquiet, winautorun; extern bool halfwidthkana, force_conversion, showdbcs; extern bool dos_shell_running_program, mountwarning; extern bool addovl, addipx, addne2k, enableime, gbk; extern const char* RunningProgram; extern int enablelfn, msgcodepage; extern uint16_t countryNo; extern unsigned int dosbox_shell_env_size; bool outcon = true, usecon = true; bool shellrun = false, prepared = false; uint16_t shell_psp = 0; Bitu call_int2e = 0; std::string GetDOSBoxXPath(bool withexe=false); int Reflect_Menu(void); void SetIMPosition(void); void initRand(); void initcodepagefont(void); void runMount(const char *str); void ResolvePath(std::string& in); void DOS_SetCountry(uint16_t countryNo); void CALLBACK_DeAllocate(Bitu in), DOSBox_ConsolePauseWait(); void GFX_SetTitle(int32_t cycles, int frameskip, Bits timing, bool paused); bool isDBCSCP(), InitCodePage(), isKanji1(uint8_t chr), shiftjis_lead_byte(int c); Bitu call_shellstop = 0; /* Larger scope so shell_del autoexec can use it to * remove things from the environment */ DOS_Shell * first_shell = 0; static Bitu shellstop_handler(void) { return CBRET_STOP; } void SHELL_ProgramStart(Program * * make) { *make = new DOS_Shell; } //Repeat it with the correct type, could do it in the function below, but this way it should be //clear that if the above function is changed, this function might need a change as well. static void SHELL_ProgramStart_First_shell(DOS_Shell * * make) { *make = new DOS_Shell; } bool i4dos=false; char i4dos_data[CONFIG_SIZE] = { 0 }; char config_data[CONFIG_SIZE] = { 0 }; char autoexec_data[AUTOEXEC_SIZE] = { 0 }; static std::list<std::string> autoexec_strings; typedef std::list<std::string>::iterator auto_it; void VFILE_Remove(const char *name,const char *dir=""); void runRescan(const char *str), DOSBox_SetSysMenu(void); void toSetCodePage(DOS_Shell *shell, int newCP, int opt); #if defined(WIN32) void MountAllDrives(bool quiet) { char str[100]; uint16_t n = 0; uint32_t drives = GetLogicalDrives(); char name[4]="A:\\"; for (int i=0; i<25; i++) { if ((drives & (1<<i)) && !Drives[i]) { name[0]='A'+i; int type=GetDriveType(name); if (type!=DRIVE_NO_ROOT_DIR) { if (!quiet) { sprintf(str, "Mounting %c: => %s..\r\n", name[0], name); n = (uint16_t)strlen(str); DOS_WriteFile(STDOUT,(uint8_t *)str,&n); } char mountstring[DOS_PATHLENGTH+CROSS_LEN+20]; name[2]=' '; strcpy(mountstring,name); name[2]='\\'; strcat(mountstring,name); strcat(mountstring," -Q"); runMount(mountstring); if (!Drives[i] && !quiet) { sprintf(str, "Drive %c: failed to mount.\r\n",name[0]); n = (uint16_t)strlen(str); DOS_WriteFile(STDOUT,(uint8_t *)str,&n); } else if(mountwarning && !quiet && type==DRIVE_FIXED && (strcasecmp(name,"C:\\")==0)) { strcpy(str, MSG_Get("PROGRAM_MOUNT_WARNING_WIN")); if (strlen(str)>2&&str[strlen(str)-1]=='\n'&&str[strlen(str)-2]!='\r') { str[strlen(str)-1]=0; strcat(str, "\r\n"); } n = (uint16_t)strlen(str); DOS_WriteFile(STDOUT,(uint8_t *)str,&n); } } } } } #endif void AutoexecObject::Install(const std::string &in) { if(GCC_UNLIKELY(installed)) E_Exit("autoexec: already created %s",buf.c_str()); installed = true; buf = in; autoexec_strings.push_back(buf); this->CreateAutoexec(); //autoexec.bat is normally created AUTOEXEC_Init. //But if we are already running (first_shell) //we have to update the envirionment to display changes if(first_shell) { //create a copy as the string will be modified std::string::size_type n = buf.size(); char* buf2 = new char[n + 1]; safe_strncpy(buf2, buf.c_str(), n + 1); if((strncasecmp(buf2,"set ",4) == 0) && (strlen(buf2) > 4)){ char* after_set = buf2 + 4;//move to variable that is being set char* test2 = strpbrk(after_set,"="); if(!test2) {first_shell->SetEnv(after_set,"");return;} *test2++ = 0; //If the shell is running/exists update the environment first_shell->SetEnv(after_set,test2); } delete [] buf2; } } void AutoexecObject::InstallBefore(const std::string &in) { if(GCC_UNLIKELY(installed)) E_Exit("autoexec: already created %s",buf.c_str()); installed = true; buf = in; autoexec_strings.push_front(buf); this->CreateAutoexec(); } void AutoexecObject::CreateAutoexec(void) { /* Remove old autoexec.bat if the shell exists */ if(first_shell) VFILE_Remove("AUTOEXEC.BAT"); //Create a new autoexec.bat autoexec_data[0] = 0; size_t auto_len; for(auto_it it = autoexec_strings.begin(); it != autoexec_strings.end(); ++it) { std::string linecopy = *it; std::string::size_type offset = 0; //Lets have \r\n as line ends in autoexec.bat. while(offset < linecopy.length()) { std::string::size_type n = linecopy.find("\n",offset); if ( n == std::string::npos ) break; std::string::size_type rn = linecopy.find("\r\n",offset); if ( rn != std::string::npos && rn + 1 == n) {offset = n + 1; continue;} // \n found without matching \r linecopy.replace(n,1,"\r\n"); offset = n + 2; } auto_len = strlen(autoexec_data); if ((auto_len+linecopy.length() + 3) > AUTOEXEC_SIZE) { E_Exit("SYSTEM:Autoexec.bat file overflow"); } sprintf((autoexec_data + auto_len),"%s\r\n",linecopy.c_str()); } if (first_shell) VFILE_Register("AUTOEXEC.BAT",(uint8_t *)autoexec_data,(uint32_t)strlen(autoexec_data)); } void AutoexecObject::Uninstall() { if(!installed) return; // Remove the line from the autoexecbuffer and update environment for(auto_it it = autoexec_strings.begin(); it != autoexec_strings.end(); ) { if ((*it) == buf) { std::string::size_type n = buf.size(); char* buf2 = new char[n + 1]; safe_strncpy(buf2, buf.c_str(), n + 1); bool stringset = false; // If it's a environment variable remove it from there as well if ((strncasecmp(buf2,"set ",4) == 0) && (strlen(buf2) > 4)){ char* after_set = buf2 + 4;//move to variable that is being set char* test2 = strpbrk(after_set,"="); if (!test2) { delete [] buf2; continue; } *test2 = 0; stringset = true; //If the shell is running/exists update the environment if (first_shell) first_shell->SetEnv(after_set,""); } delete [] buf2; if (stringset && first_shell && first_shell->bf && first_shell->bf->filename.find("AUTOEXEC.BAT") != std::string::npos) { //Replace entry with spaces if it is a set and from autoexec.bat, as else the location counter will be off. *it = buf.assign(buf.size(),' '); ++it; } else { it = autoexec_strings.erase(it); } } else ++it; } installed=false; this->CreateAutoexec(); } AutoexecObject::~AutoexecObject(){ Uninstall(); } DOS_Shell::~DOS_Shell() { if (bf != NULL) delete bf; /* free batch file */ } DOS_Shell::DOS_Shell():Program(){ input_handle=STDIN; echo=true; exit=false; perm = false; bf=0; call=false; exec=false; lfnfor = uselfn; input_eof=false; completion_index = 0; } Bitu DOS_Shell::GetRedirection(char *s, char **ifn, char **ofn, char **toc,bool * append) { char * lr=s; char * lw=s; char ch; Bitu num=0; bool quote = false; bool lead1 = false, lead2 = false; char* t; int q; while ( (ch=*lr++) ) { if(quote && ch != '"') { /* don't parse redirection within quotes. Not perfect yet. Escaped quotes will mess the count up */ *lw++ = ch; continue; } if (lead1) { lead1=false; if (ch=='|') { *lw++=ch; continue; } } else if ((IS_PC98_ARCH && shiftjis_lead_byte(ch)) || (isDBCSCP() && !((dos.loaded_codepage == 936 || IS_PDOSV) && !gbk) && isKanji1(ch))) lead1 = true; switch (ch) { case '"': quote = !quote; break; case '>': *append = ((*lr) == '>'); if (*append) lr++; lr = ltrim(lr); if (*ofn) free(*ofn); *ofn = lr; q = 0; lead2 = false; while (*lr && (q/2*2!=q || *lr != ' ') && *lr != '<' && !(!lead2 && *lr == '|')) { if (lead2) lead2 = false; else if ((IS_PC98_ARCH && shiftjis_lead_byte(*lr&0xff)) || (isDBCSCP() && !((dos.loaded_codepage == 936 || IS_PDOSV) && !gbk) && isKanji1(*lr&0xff))) lead2 = true; if (*lr=='"') q++; lr++; } // if it ends on a : => remove it. if ((*ofn != lr) && (lr[-1] == ':')) lr[-1] = 0; t = (char*)malloc(lr-*ofn+1); safe_strncpy(t, *ofn, lr-*ofn+1); *ofn = t; continue; case '<': if (*ifn) free(*ifn); lr = ltrim(lr); *ifn = lr; q = 0; lead2 = false; while (*lr && (q/2*2!=q || *lr != ' ') && *lr != '>' && !(!lead2 && *lr == '|')) { if (lead2) lead2 = false; else if ((IS_PC98_ARCH && shiftjis_lead_byte(*lr&0xff)) || (isDBCSCP() && !((dos.loaded_codepage == 936 || IS_PDOSV) && !gbk) && isKanji1(*lr&0xff))) lead2 = true; if (*lr=='"') q++; lr++; } if ((*ifn != lr) && (lr[-1] == ':')) lr[-1] = 0; t = (char*)malloc(lr-*ifn+1); safe_strncpy(t, *ifn, lr-*ifn+1); *ifn = t; continue; case '|': num++; if (*toc) free(*toc); lr = ltrim(lr); *toc = lr; while (*lr) lr++; t = (char*)malloc(lr-*toc+1); safe_strncpy(t, *toc, lr-*toc+1); *toc = t; continue; } *lw++=ch; } *lw=0; return num; } void DOS_Shell::ParseLine(char * line) { LOG(LOG_EXEC,LOG_DEBUG)("Parsing command line: %s",line); /* Check for a leading @ */ if (line[0] == '@') line[0] = ' '; line = trim(line); /* Do redirection and pipe checks */ char * in = 0; char * out = 0; char * toc = 0; uint16_t dummy,dummy2; uint32_t bigdummy = 0; bool append; bool normalstdin = false; /* whether stdin/out are open on start. */ bool normalstdout = false; /* Bug: Assumed is they are "con" */ GetRedirection(line, &in, &out, &toc, &append); if (in || out || toc) { normalstdin = (psp->GetFileHandle(0) != 0xff); normalstdout = (psp->GetFileHandle(1) != 0xff); } if (in) { if(DOS_OpenFile(in,OPEN_READ,&dummy)) { //Test if file exists DOS_CloseFile(dummy); LOG_MSG("SHELL:Redirect input from %s",in); if(normalstdin) DOS_CloseFile(0); //Close stdin DOS_OpenFile(in,OPEN_READ,&dummy); //Open new stdin } else { WriteOut(!*in?"File open error\n":(dos.errorcode==DOSERR_ACCESS_DENIED?MSG_Get("SHELL_CMD_FILE_ACCESS_DENIED"):"File open error - %s\n"), in); in = 0; return; } } bool fail=false; char pipetmp[270]; uint16_t fattr; if (toc) { initRand(); std::string line; if (!GetEnvStr("TEMP",line)&&!GetEnvStr("TMP",line)) sprintf(pipetmp, "pipe%d.tmp", rand()%10000); else { std::string::size_type idx = line.find('='); std::string temp=line.substr(idx +1 , std::string::npos); if (DOS_GetFileAttr(temp.c_str(), &fattr) && fattr&DOS_ATTR_DIRECTORY) sprintf(pipetmp, "%s\\pipe%d.tmp", temp.c_str(), rand()%10000); else sprintf(pipetmp, "pipe%d.tmp", rand()%10000); } } if (out||toc) { if (out&&toc) WriteOut(!*out?"Duplicate redirection\n":"Duplicate redirection - %s\n", out); LOG_MSG("SHELL:Redirect output to %s",toc?pipetmp:out); if(normalstdout) DOS_CloseFile(1); if(!normalstdin && !in) DOS_OpenFile("con",OPEN_READWRITE,&dummy); bool status = true; /* Create if not exist. Open if exist. Both in read/write mode */ if(!toc&&append) { if (DOS_GetFileAttr(out, &fattr) && fattr&DOS_ATTR_READ_ONLY) { DOS_SetError(DOSERR_ACCESS_DENIED); status = false; } else if( (status = DOS_OpenFile(out,OPEN_READWRITE,&dummy)) ) { DOS_SeekFile(1,&bigdummy,DOS_SEEK_END); } else { status = DOS_CreateFile(out,DOS_ATTR_ARCHIVE,&dummy); //Create if not exists. } } else if (!toc&&DOS_GetFileAttr(out, &fattr) && fattr&DOS_ATTR_READ_ONLY) { DOS_SetError(DOSERR_ACCESS_DENIED); status = false; } else { if (toc&&DOS_FindFirst(pipetmp, ~DOS_ATTR_VOLUME)&&!DOS_UnlinkFile(pipetmp)) fail=true; status = DOS_OpenFileExtended(toc&&!fail?pipetmp:out,OPEN_READWRITE,DOS_ATTR_ARCHIVE,0x12,&dummy,&dummy2); if (toc&&(fail||!status)&&!strchr(pipetmp,'\\')&&(Drives[0]||Drives[2])) { int len = (int)strlen(pipetmp); if (len > 266) { len = 266; pipetmp[len] = 0; } for (int i = len; i >= 0; i--) pipetmp[i + 3] = pipetmp[i]; pipetmp[0] = Drives[2]?'c':'a'; pipetmp[1] = ':'; pipetmp[2] = '\\'; fail=false; if (DOS_FindFirst(pipetmp, ~DOS_ATTR_VOLUME) && !DOS_UnlinkFile(pipetmp)) fail=true; else status = DOS_OpenFileExtended(pipetmp, OPEN_READWRITE, DOS_ATTR_ARCHIVE, 0x12, &dummy, &dummy2); } } if(!status && normalstdout) { DOS_OpenFile("con", OPEN_READWRITE, &dummy); // Read only file, open con again if (!toc) { WriteOut(!*out?"File creation error\n":(dos.errorcode==DOSERR_ACCESS_DENIED?MSG_Get("SHELL_CMD_FILE_ACCESS_DENIED"):"File creation error - %s\n"), out); DOS_CloseFile(1); DOS_OpenFile("nul", OPEN_READWRITE, &dummy); } } if(!normalstdin && !in) DOS_CloseFile(0); } /* Run the actual command */ if (this == first_shell) dos_shell_running_program = true; #if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU Reflect_Menu(); #endif if (toc||(!toc&&((out&&DOS_FindDevice(out)!=DOS_FindDevice("con"))))) outcon=false; if (toc||(!toc&&((out&&DOS_FindDevice(out)!=DOS_FindDevice("con"))||(in&&DOS_FindDevice(in)!=DOS_FindDevice("con"))))) usecon=false; DoCommand(line); if (this == first_shell) dos_shell_running_program = false; #if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU Reflect_Menu(); #endif /* Restore handles */ if(in) { DOS_CloseFile(0); if(normalstdin) DOS_OpenFile("con",OPEN_READWRITE,&dummy); free(in); } if(out||toc) { DOS_CloseFile(1); if(!normalstdin) DOS_OpenFile("con",OPEN_READWRITE,&dummy); if(normalstdout) DOS_OpenFile("con",OPEN_READWRITE,&dummy); if(!normalstdin) DOS_CloseFile(0); if (out) free(out); } if (toc) { if (!fail&&DOS_OpenFile(pipetmp, OPEN_READ, &dummy)) // Test if file can be opened for reading { DOS_CloseFile(dummy); if (normalstdin) DOS_CloseFile(0); // Close stdin DOS_OpenFile(pipetmp, OPEN_READ, &dummy); // Open new stdin ParseLine(toc); DOS_CloseFile(0); if (normalstdin) DOS_OpenFile("con", OPEN_READWRITE, &dummy); } else WriteOut("\nFailed to create/open a temporary file for piping. Check the %%TEMP%% variable.\n"); free(toc); if (DOS_FindFirst(pipetmp, ~DOS_ATTR_VOLUME)) DOS_UnlinkFile(pipetmp); } outcon=usecon=true; } void DOS_Shell::RunInternal(void) { char input_line[CMD_MAXLINE] = {0}; while (bf) { if (bf->ReadLine(input_line)) { if (echo) { if (input_line[0] != '@') { ShowPrompt(); WriteOut_NoParsing(input_line); WriteOut_NoParsing("\n"); } } ParseLine(input_line); if (echo) WriteOut_NoParsing("\n"); } } } char *str_replace(char *orig, char *rep, char *with); std::string GetPlatform(bool save); bool ANSI_SYS_installed(); const char *ParseMsg(const char *msg) { char str[13]; strncpy(str, UPDATED_STR, 12); str[12]=0; if (machine != MCH_PC98) { if (!ANSI_SYS_installed() || J3_IsJapanese()) { msg = str_replace(str_replace((char *)msg, (char*)"\033[0m", (char*)""), (char*)"\033[1m", (char*)""); for (int i=1; i<8; i++) { sprintf(str, "\033[3%dm", i); msg = str_replace((char *)msg, str, (char*)""); sprintf(str, "\033[4%d;1m", i); msg = str_replace((char *)msg, str, (char*)""); } } Section_prop *section = static_cast<Section_prop *>(control->GetSection("dosbox")); std::string theme = section->Get_string("bannercolortheme"); if (theme == "black") msg = str_replace((char *)msg, (char*)"\033[44;1m", (char*)"\033[40;1m"); else if (theme == "red") msg = str_replace(str_replace((char *)msg, (char*)"\033[31m", (char*)"\033[34m"), (char*)"\033[44;1m", (char*)"\033[41;1m"); else if (theme == "green") msg = str_replace(str_replace(str_replace((char *)msg, (char*)"\033[36m", (char*)"\033[34m"), (char*)"\033[32m", (char*)"\033[36m"), (char*)"\033[44;1m", (char*)"\033[42;1m"); else if (theme == "yellow") msg = str_replace(str_replace((char *)msg, (char*)"\033[31m", (char*)"\033[34m"), (char*)"\033[44;1m", (char*)"\033[43;1m"); else if (theme == "blue") msg = str_replace((char *)msg, (char*)"\033[44;1m", (char*)"\033[44;1m"); else if (theme == "magenta") msg = str_replace(str_replace((char *)msg, (char*)"\033[31m", (char*)"\033[34m"), (char*)"\033[44;1m", (char*)"\033[45;1m"); else if (theme == "cyan") msg = str_replace(str_replace((char *)msg, (char*)"\033[36m", (char*)"\033[34m"), (char*)"\033[44;1m", (char*)"\033[46;1m"); else if (theme == "white") msg = str_replace(str_replace((char *)msg, (char*)"\033[36m", (char*)"\033[34m"), (char*)"\033[44;1m", (char*)"\033[47;1m"); } if (machine == MCH_PC98) return msg; else { if (real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS)>80) msg = str_replace(str_replace(str_replace((char *)msg, (char*)"\xBA\033[0m", (char*)"\xBA\033[0m\n"), (char*)"\xBB\033[0m", (char*)"\xBB\033[0m\n"), (char*)"\xBC\033[0m", (char*)"\xBC\033[0m\n"); bool uselowbox = false; force_conversion = true; int cp=dos.loaded_codepage; if ((showdbcs #if defined(USE_TTF) || ttf.inUse #endif ) #if defined(USE_TTF) && halfwidthkana #endif && InitCodePage() && dos.loaded_codepage==932) uselowbox = true; force_conversion = false; dos.loaded_codepage=cp; if (uselowbox || IS_JEGA_ARCH || IS_JDOSV) { std::string m=msg; if (strstr(msg, "\xCD\xCD\xCD\xCD") != NULL) { if (IS_JEGA_ARCH) { msg = str_replace((char *)msg, (char*)"\xC9", (char *)std::string(1, 0x15).c_str()); msg = str_replace((char *)msg, (char*)"\xBB", (char *)std::string(1, 0x16).c_str()); msg = str_replace((char *)msg, (char*)"\xC8", (char *)std::string(1, 0x18).c_str()); msg = str_replace((char *)msg, (char*)"\xBC", (char *)std::string(1, 0x17).c_str()); msg = str_replace((char *)msg, (char*)"\xCD", (char *)std::string(1, 0x13).c_str()); } else { msg = str_replace((char *)msg, (char*)"\xC9", (char *)std::string(1, 1).c_str()); msg = str_replace((char *)msg, (char*)"\xBB", (char *)std::string(1, 2).c_str()); msg = str_replace((char *)msg, (char*)"\xC8", (char *)std::string(1, 3).c_str()); msg = str_replace((char *)msg, (char*)"\xBC", (char *)std::string(1, 4).c_str()); msg = str_replace((char *)msg, (char*)"\xCD", (char *)std::string(1, 6).c_str()); } } else { if (IS_JEGA_ARCH) { msg = str_replace((char *)msg, (char*)"\xBA ", (char *)(std::string(1, 0x14)+" ").c_str()); msg = str_replace((char *)msg, (char*)" \xBA", (char *)(" "+std::string(1, 0x14)).c_str()); } else { msg = str_replace((char *)msg, (char*)"\xBA ", (char *)(std::string(1, 5)+" ").c_str()); msg = str_replace((char *)msg, (char*)" \xBA", (char *)(" "+std::string(1, 5)).c_str()); } } } return msg; } } static char const * const path_string="PATH=Z:\\;Z:\\SYSTEM;Z:\\BIN;Z:\\DOS;Z:\\4DOS;Z:\\DEBUG;Z:\\TEXTUTIL"; static char const * const comspec_string="COMSPEC=Z:\\COMMAND.COM"; static char const * const prompt_string="PROMPT=$P$G"; static char const * const full_name="Z:\\COMMAND.COM"; static char const * const init_line="/INIT AUTOEXEC.BAT"; extern uint8_t ZDRIVE_NUM; char *str_replace(char *orig, char *rep, char *with); void GetExpandedPath(std::string &path) { std::string udrive = std::string(1,ZDRIVE_NUM+'A'), ldrive = std::string(1,ZDRIVE_NUM+'a'); char pathstr[100]; strcpy(pathstr, path_string+5); if (path==udrive+":\\"||path==ldrive+":\\") path=ZDRIVE_NUM==25?pathstr:str_replace(pathstr, (char*)"Z:\\", (char *)(udrive+":\\").c_str()); else if (path.size()>3&&(path.substr(0, 4)==udrive+":\\;"||path.substr(0, 4)==ldrive+":\\;")&&path.substr(4).find(udrive+":\\")==std::string::npos&&path.substr(4).find(ldrive+":\\")==std::string::npos) path=std::string(ZDRIVE_NUM==25?pathstr:str_replace(pathstr, (char*)"Z:\\", (char *)(udrive+":\\").c_str()))+path.substr(3); else if (path.size()>3) { size_t pos = path.find(";"+udrive+":\\"); if (pos == std::string::npos) pos = path.find(";"+ldrive+":\\"); if (pos != std::string::npos && (!path.substr(pos+4).size() || (path[pos+4]==';'&&path.substr(pos+4).find(udrive+":\\")==std::string::npos&&path.substr(pos+4).find(ldrive+":\\")==std::string::npos))) path=path.substr(0, pos+1)+std::string(ZDRIVE_NUM==25?pathstr:str_replace(pathstr, (char*)"Z:\\", (char *)(udrive+":\\").c_str()))+path.substr(pos+4); } } void DOS_Shell::Prepare(void) { if (this == first_shell) { Section_prop *section = static_cast<Section_prop *>(control->GetSection("dosbox")); if (section->Get_bool("startbanner")&&!control->opt_fastlaunch) { /* Start a normal shell and check for a first command init */ std::string verstr = "v"+std::string(VERSION)+", "+GetPlatform(false); if (machine == MCH_PC98) { WriteOut(ParseMsg("\x86\x52\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x56\n")); WriteOut(ParseMsg((std::string("\x86\x46 \033[32m")+(MSG_Get("SHELL_STARTUP_TITLE")+std::string(" ")).substr(0,30)+std::string(" \033[33m%*s\033[37m \x86\x46\n")).c_str()),34,verstr.c_str()); WriteOut(ParseMsg("\x86\x46 \x86\x46\n")); WriteOut(ParseMsg((std::string("\x86\x46 ")+MSG_Get("SHELL_STARTUP_HEAD1_PC98")+std::string(" \x86\x46\n")).c_str())); WriteOut(ParseMsg("\x86\x46 \x86\x46\n")); WriteOut(ParseMsg((std::string("\x86\x46 ")+str_replace((char *)MSG_Get("SHELL_STARTUP_TEXT1_PC98"), (char*)"\n", (char*)" \x86\x46\n\x86\x46 ")+std::string(" \x86\x46\n")).c_str())); WriteOut(ParseMsg((std::string("\x86\x46 ")+MSG_Get("SHELL_STARTUP_EXAMPLE_PC98")+std::string(" \x86\x46\n")).c_str())); WriteOut(ParseMsg("\x86\x46 \x86\x46\n")); WriteOut(ParseMsg((std::string("\x86\x46 ")+str_replace((char *)MSG_Get("SHELL_STARTUP_TEXT2_PC98"), (char*)"\n", (char*)" \x86\x46\n\x86\x46 ")+std::string(" \x86\x46\n")).c_str())); WriteOut(ParseMsg("\x86\x46 \x86\x46\n")); WriteOut(ParseMsg((std::string("\x86\x46 ")+str_replace((char *)MSG_Get("SHELL_STARTUP_INFO_PC98"), (char*)"\n", (char*)" \x86\x46\n\x86\x46 ")+std::string(" \x86\x46\n")).c_str())); WriteOut(ParseMsg("\x86\x46 \x86\x46\n")); WriteOut(ParseMsg((std::string("\x86\x46 ")+str_replace((char *)MSG_Get("SHELL_STARTUP_TEXT3_PC98"), (char*)"\n", (char*)" \x86\x46\n\x86\x46 ")+std::string(" \x86\x46\n")).c_str())); WriteOut(ParseMsg("\x86\x5A\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x5E\033[0m\n")); WriteOut(ParseMsg((std::string("\033[1m\033[32m")+MSG_Get("SHELL_STARTUP_LAST")+"\033[0m\n").c_str())); } else { WriteOut(ParseMsg("\033[44;1m\xC9\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBB\033[0m")); WriteOut(ParseMsg((std::string("\033[44;1m\xBA \033[32m")+(MSG_Get("SHELL_STARTUP_TITLE")+std::string(" ")).substr(0,30)+std::string(" \033[33m%*s\033[37m \xBA\033[0m")).c_str()),45,verstr.c_str()); WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m")); WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+MSG_Get("SHELL_STARTUP_HEAD1")+std::string(" \xBA\033[0m")).c_str())); WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m")); WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+str_replace((char *)MSG_Get("SHELL_STARTUP_TEXT1"), (char*)"\n", (char*)" \xBA\033[0m\033[44;1m\xBA ")+std::string(" \xBA\033[0m")).c_str())); if (IS_VGA_ARCH) WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+MSG_Get("SHELL_STARTUP_EXAMPLE")+std::string(" \xBA\033[0m")).c_str())); WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m")); WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+MSG_Get("SHELL_STARTUP_HEAD2")+std::string(" \xBA\033[0m")).c_str())); WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m")); WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+str_replace((char *)MSG_Get("SHELL_STARTUP_TEXT2"), (char*)"\n", (char*)" \xBA\033[0m\033[44;1m\xBA ")+std::string(" \xBA\033[0m")).c_str())); WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m")); if (IS_DOSV) { WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+str_replace((char *)MSG_Get("SHELL_STARTUP_DOSV"), (char*)"\n", (char*)" \xBA\033[0m\033[44;1m\xBA ")+std::string(" \xBA\033[0m")).c_str())); WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m")); } else if (machine == MCH_CGA || machine == MCH_PCJR || machine == MCH_AMSTRAD) { WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+str_replace((char *)MSG_Get(mono_cga?"SHELL_STARTUP_CGA_MONO":"SHELL_STARTUP_CGA"), (char*)"\n", (char*)" \xBA\033[0m\033[44;1m\xBA ")+std::string(" \xBA\033[0m")).c_str())); WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m")); } else if (machine == MCH_HERC || machine == MCH_MDA) { WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+str_replace((char *)MSG_Get("SHELL_STARTUP_HERC"), (char*)"\n", (char*)" \xBA\033[0m\033[44;1m\xBA ")+std::string(" \xBA\033[0m")).c_str())); WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m")); } WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+MSG_Get("SHELL_STARTUP_HEAD3")+std::string(" \xBA\033[0m")).c_str())); WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m")); WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+str_replace((char *)MSG_Get("SHELL_STARTUP_TEXT3"), (char*)"\n", (char*)" \xBA\033[0m\033[44;1m\xBA ")+std::string(" \xBA\033[0m")).c_str())); WriteOut(ParseMsg("\033[44;1m\xC8\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBC\033[0m")); WriteOut(ParseMsg((std::string("\033[32m")+(MSG_Get("SHELL_STARTUP_LAST")+std::string(" ")).substr(0,79)+std::string("\033[0m\n")).c_str())); } } else if (CurMode->type==M_TEXT || IS_PC98_ARCH) WriteOut("\033[2J"); if (!countryNo) { #if defined(WIN32) char buffer[128]; #endif if (IS_PC98_ARCH || IS_JEGA_ARCH) countryNo = 81; else if (IS_DOSV) countryNo = IS_PDOSV?86:(IS_TDOSV?886:(IS_KDOSV?82:81)); #if defined(WIN32) else if (GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ICOUNTRY, buffer, 128)) { countryNo = uint16_t(atoi(buffer)); DOS_SetCountry(countryNo); } #endif else countryNo = 1; } section = static_cast<Section_prop *>(control->GetSection("dos")); bool zdirpath = section->Get_bool("drive z expand path"); strcpy(config_data, ""); section = static_cast<Section_prop *>(control->GetSection("config")); if ((section!=NULL&&!control->opt_noconfig)||control->opt_langcp) { char *countrystr = (char *)section->Get_string("country"), *r=strchr(countrystr, ','); int country = 0; if ((r==NULL || !*(r+1)) && !control->opt_langcp) country = atoi(trim(countrystr)); else { if (r!=NULL) *r=0; country = atoi(trim(countrystr)); int newCP = r==NULL||IS_PC98_ARCH||IS_JEGA_ARCH||IS_DOSV?dos.loaded_codepage:atoi(trim(r+1)); if (control->opt_langcp && msgcodepage>0 && isSupportedCP(msgcodepage) && msgcodepage != newCP) newCP = msgcodepage; if (r!=NULL) *r=','; if (!IS_PC98_ARCH&&!IS_JEGA_ARCH) { #if defined(USE_TTF) if (ttf.inUse) { if (newCP) toSetCodePage(this, newCP, control->opt_fastlaunch?1:0); else if (r!=NULL) WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), trim(r+1)); } else #endif if (!newCP && IS_DOSV) { if (IS_JDOSV) newCP=932; else if (IS_PDOSV) newCP=936; else if (IS_KDOSV) newCP=949; else if (IS_TDOSV) newCP=950; } if (newCP==932||newCP==936||newCP==949||newCP==950||newCP==951) { dos.loaded_codepage=newCP; SetupDBCSTable(); runRescan("-A -Q"); DOSBox_SetSysMenu(); } } } if (country>0&&!control->opt_noconfig) { countryNo = country; DOS_SetCountry(countryNo); } const char * extra = section->data.c_str(); if (extra&&!control->opt_securemode&&!control->SecureMode()&&!control->opt_noconfig) { std::string vstr; std::istringstream in(extra); char linestr[CROSS_LEN+1], cmdstr[CROSS_LEN], valstr[CROSS_LEN], tmpstr[CROSS_LEN]; char *cmd=cmdstr, *val=valstr, *tmp=tmpstr, *p; if (in) for (std::string line; std::getline(in, line); ) { if (line.length()>CROSS_LEN) { strncpy(linestr, line.c_str(), CROSS_LEN); linestr[CROSS_LEN]=0; } else strcpy(linestr, line.c_str()); p=strchr(linestr, '='); if (p!=NULL) { *p=0; strcpy(cmd, linestr); strcpy(val, p+1); cmd=trim(cmd); val=trim(val); if (strlen(config_data)+strlen(cmd)+strlen(val)+3<CONFIG_SIZE) { strcat(config_data, cmd); strcat(config_data, "="); strcat(config_data, val); strcat(config_data, "\r\n"); } if (!strncasecmp(cmd, "set ", 4)) { vstr=std::string(val); ResolvePath(vstr); if (zdirpath && !strcmp(cmd, "set path")) GetExpandedPath(vstr); DoCommand((char *)(std::string(cmd)+"="+vstr).c_str()); } else if (!strcasecmp(cmd, "install")||!strcasecmp(cmd, "installhigh")||!strcasecmp(cmd, "device")||!strcasecmp(cmd, "devicehigh")) { vstr=std::string(val); ResolvePath(vstr); strcpy(tmp, vstr.c_str()); char *name=StripArg(tmp); if (!*name) continue; if (!DOS_FileExists(name)&&!DOS_FileExists((std::string("Z:\\SYSTEM\\")+name).c_str())&&!DOS_FileExists((std::string("Z:\\BIN\\")+name).c_str())&&!DOS_FileExists((std::string("Z:\\DOS\\")+name).c_str())&&!DOS_FileExists((std::string("Z:\\4DOS\\")+name).c_str())&&!DOS_FileExists((std::string("Z:\\DEBUG\\")+name).c_str())&&!DOS_FileExists((std::string("Z:\\TEXTUTIL\\")+name).c_str())) { WriteOut(MSG_Get("SHELL_MISSING_FILE"), name); continue; } if (!strcasecmp(cmd, "install")) DoCommand((char *)vstr.c_str()); else if (!strcasecmp(cmd, "installhigh")) DoCommand((char *)("lh "+vstr).c_str()); else if (!strcasecmp(cmd, "device")) DoCommand((char *)("device "+vstr).c_str()); else if (!strcasecmp(cmd, "devicehigh")) DoCommand((char *)("lh device "+vstr).c_str()); } } else if (!strncasecmp(line.c_str(), "rem ", 4)) { strcat(config_data, line.c_str()); strcat(config_data, "\r\n"); } } } } std::string line; GetEnvStr("PATH",line); if (!strlen(config_data)) { strcat(config_data, "rem="); strcat(config_data, section->Get_string("rem")); strcat(config_data, "\r\n"); } VFILE_Register("CONFIG.SYS",(uint8_t *)config_data,(uint32_t)strlen(config_data)); #if defined(WIN32) if (!control->opt_securemode&&!control->SecureMode()) { const Section_prop* sec = static_cast<Section_prop*>(control->GetSection("dos")); const char *automountstr = sec->Get_string("automountall"); if (strcmp(automountstr, "0") && strcmp(automountstr, "false")) MountAllDrives(!strcmp(automountstr, "quiet")||control->opt_fastlaunch); } #endif strcpy(i4dos_data, ""); section = static_cast<Section_prop *>(control->GetSection("4dos")); if (section!=NULL) { const char * extra = section->data.c_str(); if (extra) { std::istringstream in(extra); if (in) for (std::string line; std::getline(in, line); ) { if (strncasecmp(line.c_str(), "rem=", 4)&&strncasecmp(line.c_str(), "rem ", 4)) { strcat(i4dos_data, line.c_str()); strcat(i4dos_data, "\r\n"); } } } } VFILE_Register("4DOS.INI",(uint8_t *)i4dos_data,(uint32_t)strlen(i4dos_data), "/4DOS/"); int cp=dos.loaded_codepage; if (!dos.loaded_codepage) InitCodePage(); initcodepagefont(); dos.loaded_codepage=cp; } #if (defined(WIN32) && !defined(HX_DOS) || defined(LINUX) && C_X11) && (defined(C_SDL2) || defined(SDL_DOSBOX_X_SPECIAL)) if (enableime) SetIMPosition(); #endif } void DOS_Shell::Run(void) { shellrun=true; char input_line[CMD_MAXLINE] = {0}; std::string line; bool optP=cmd->FindStringRemain("/P",line), optC=cmd->FindStringRemainBegin("/C",line), optK=false; if (!optC) optK=cmd->FindStringRemainBegin("/K",line); if (optP) perm=true; if (optC||optK) { input_line[CMD_MAXLINE-1u] = 0; strncpy(input_line,line.c_str(),CMD_MAXLINE-1u); char* sep = strpbrk(input_line,"\r\n"); //GTA installer if (sep) *sep = 0; DOS_Shell temp; temp.echo = echo; temp.exec=true; temp.ParseLine(input_line); //for *.exe *.com |*.bat creates the bf needed by runinternal; temp.RunInternal(); // exits when no bf is found. temp.exec=false; if (!optK||(!perm&&temp.exit)) { shellrun=false; return; } } else if (cmd->FindStringRemain("/?",line)) { WriteOut(MSG_Get("SHELL_CMD_COMMAND_HELP")); shellrun=false; return; } bool optInit=cmd->FindString("/INIT",line,true); if (this != first_shell && !optInit) WriteOut(optK?"\n":"DOSBox-X command shell [Version %s %s]\nCopyright DOSBox-X Team. All rights reserved.\n\n",VERSION,SDL_STRING); if(optInit) { input_line[CMD_MAXLINE - 1u] = 0; strncpy(input_line, line.c_str(), CMD_MAXLINE - 1u); line.erase(); ParseLine(input_line); } if (!exit) { RunningProgram = "COMMAND"; GFX_SetTitle(-1,-1,-1,false); } do { /* Get command once a line */ if (bf) { if (bf->ReadLine(input_line)) { if (echo) { if (input_line[0]!='@') { ShowPrompt(); WriteOut_NoParsing(input_line); WriteOut_NoParsing("\n"); } } } else input_line[0]='\0'; } else { if (optInit && control->opt_exit) break; if (echo) ShowPrompt(); InputCommand(input_line); if (echo && !input_eof) WriteOut("\n"); /* Bugfix: CTTY NUL will return immediately, the shell input will return * immediately, and if we don't consume CPU cycles to compensate, * will leave DOSBox-X running in an endless loop, hung. */ if (input_eof) CALLBACK_Idle(); } /* do it */ if(strlen(input_line)!=0) { ParseLine(input_line); if (echo && !bf) WriteOut_NoParsing("\n"); } } while (perm||!exit); shellrun=false; } void DOS_Shell::SyntaxError(void) { WriteOut(MSG_Get("SHELL_SYNTAXERROR")); } bool filename_not_8x3(const char *n), isDBCSCP(), isKanji1(uint8_t chr), shiftjis_lead_byte(int c); class AUTOEXEC:public Module_base { private: AutoexecObject autoexec[17]; AutoexecObject autoexec_echo; AutoexecObject autoexec_auto_bat; public: void RunAdditional() { force_conversion = true; int cp=dos.loaded_codepage; InitCodePage(); force_conversion = false; int ind=0; /* The user may have given .BAT files to run on the command line */ if (!control->auto_bat_additional.empty()) { std::string cmd = "@echo off\n"; for (unsigned int i=0;i<control->auto_bat_additional.size();i++) { if (!control->opt_prerun) cmd += "\n"; if (!strncmp(control->auto_bat_additional[i].c_str(), "@mount c: ", 10)) { cmd += control->auto_bat_additional[i]+"\n"; cmd += "@config -get lastmount>nul\n"; cmd += "@if not '%CONFIG%'=='' %CONFIG%"; } else { std::string batname; //LOG_MSG("auto_bat_additional %s\n", control->auto_bat_additional[i].c_str()); std::replace(control->auto_bat_additional[i].begin(),control->auto_bat_additional[i].end(),'/','\\'); size_t pos = std::string::npos; bool lead = false; for (unsigned int j=0; j<control->auto_bat_additional[i].size(); j++) { if (lead) lead = false; else if ((IS_PC98_ARCH && shiftjis_lead_byte(control->auto_bat_additional[i][j])) || (isDBCSCP() && isKanji1(control->auto_bat_additional[i][j]))) lead = true; else if (control->auto_bat_additional[i][j]=='\\') pos = j; } if(pos == std::string::npos) { //Only a filename, mount current directory batname = control->auto_bat_additional[i]; cmd += "@mount c: . -nl -q\n"; } else { //Parse the path of .BAT file std::string batpath = control->auto_bat_additional[i].substr(0,pos+1); if (batpath==".\\") batpath="."; else if (batpath=="..\\") batpath=".."; batname = control->auto_bat_additional[i].substr(pos+1); cmd += "@mount c: \"" + batpath + "\" -nl -q\n"; } std::string opt = control->opt_o.size() > ind && control->opt_o[ind].size() ? " "+control->opt_o[ind] : ""; ind++; bool templfn=!uselfn&&filename_not_8x3(batname.c_str())&&(enablelfn==-1||enablelfn==-2); cmd += "@config -get lastmount>nul\n"; cmd += "@set LASTMOUNT=%CONFIG%\n"; cmd += "@if not '%LASTMOUNT%'=='' %LASTMOUNT%\n"; cmd += "@cd \\\n"; if (templfn) cmd += "@config -set lfn=true\n"; #if defined(WIN32) && !defined(HX_DOS) if (!winautorun) cmd += "@config -set startcmd=true\n"; #endif cmd += "@CALL \""; cmd += batname; cmd += "\"" + opt + "\n"; if (templfn) cmd += "@config -set lfn=" + std::string(enablelfn==-1?"auto":"autostart") + "\n"; #if defined(WIN32) && !defined(HX_DOS) if (!winautorun) cmd += "@config -set startcmd=false\n"; #endif cmd += "@if not '%LASTMOUNT%'=='' mount %LASTMOUNT% -q -u\n"; cmd += "@set LASTMOUNT="; } if (control->opt_prerun) cmd += "\n"; } autoexec_auto_bat.Install(cmd); } dos.loaded_codepage = cp; } AUTOEXEC(Section* configuration):Module_base(configuration) { /* Register a virtual AUTOEXEC.BAT file */ const Section_line * section=static_cast<Section_line *>(configuration); /* Check -securemode switch to disable mount/imgmount/boot after running autoexec.bat */ bool secure = control->opt_securemode; if (control->opt_prerun) RunAdditional(); /* add stuff from the configfile unless -noautexec or -securemode is specified. */ const char * extra = section->data.c_str(); if (extra && !secure && !control->opt_noautoexec) { /* detect if "echo off" is the first line */ size_t firstline_length = strcspn(extra,"\r\n"); bool echo_off = !strncasecmp(extra,"echo off",8); if (echo_off && firstline_length == 8) extra += 8; else { echo_off = !strncasecmp(extra,"@echo off",9); if (echo_off && firstline_length == 9) extra += 9; else echo_off = false; } /* if "echo off" move it to the front of autoexec.bat */ if (echo_off) { autoexec_echo.InstallBefore("@echo off"); if (*extra == '\r') extra++; //It can point to \0 if (*extra == '\n') extra++; //same } /* Install the stuff from the configfile if anything left after moving echo off */ if (*extra) autoexec[0].Install(std::string(extra)); } /* Check to see for extra command line options to be added (before the command specified on commandline) */ /* Maximum of extra commands: 10 */ Bitu i = 1; for (auto it=control->opt_c.begin();i <= 11 && it!=control->opt_c.end();it++) /* -c switches */ autoexec[i++].Install(*it); /* Check for the -exit switch which causes dosbox to when the command on the commandline has finished */ bool addexit = control->opt_exit; if (!control->opt_prerun) RunAdditional(); #if 0/*FIXME: This is ugly. I don't care to follow through on this nonsense for now. When needed, port to new command line switching. */ /* Check for first command being a directory or file */ char buffer[CROSS_LEN+1]; char orig[CROSS_LEN+1]; char cross_filesplit[2] = {CROSS_FILESPLIT , 0}; Bitu dummy = 1; bool command_found = false; while (control->cmdline->FindCommand(dummy++,line) && !command_found) { struct stat test; if (line.length() > CROSS_LEN) continue; strcpy(buffer,line.c_str()); if (stat(buffer,&test)) { if (getcwd(buffer,CROSS_LEN) == NULL) continue; if (strlen(buffer) + line.length() + 1 > CROSS_LEN) continue; strcat(buffer,cross_filesplit); strcat(buffer,line.c_str()); if (stat(buffer,&test)) continue; } if (test.st_mode & S_IFDIR) { autoexec[12].Install(std::string("MOUNT C \"") + buffer + "\""); autoexec[13].Install("C:"); if(secure) autoexec[14].Install("z:\\system\\config.com -securemode"); command_found = true; } else { char* name = strrchr(buffer,CROSS_FILESPLIT); if (!name) { //Only a filename line = buffer; if (getcwd(buffer,CROSS_LEN) == NULL) continue; if (strlen(buffer) + line.length() + 1 > CROSS_LEN) continue; strcat(buffer,cross_filesplit); strcat(buffer,line.c_str()); if(stat(buffer,&test)) continue; name = strrchr(buffer,CROSS_FILESPLIT); if(!name) continue; } *name++ = 0; if (access(buffer,F_OK)) continue; autoexec[12].Install(std::string("MOUNT C \"") + buffer + "\""); autoexec[13].Install("C:"); /* Save the non-modified filename (so boot and imgmount can use it (long filenames, case sensivitive)) */ strcpy(orig,name); upcase(name); if(strstr(name,".BAT") != 0) { if(secure) autoexec[14].Install("z:\\system\\config.com -securemode"); /* BATch files are called else exit will not work */ autoexec[15].Install(std::string("CALL ") + name); if(addexit) autoexec[16].Install("exit"); } else if((strstr(name,".IMG") != 0) || (strstr(name,".IMA") !=0 )) { //No secure mode here as boot is destructive and enabling securemode disables boot /* Boot image files */ autoexec[15].Install(std::string("BOOT ") + orig); } else if((strstr(name,".ISO") != 0) || (strstr(name,".CUE") !=0 )) { /* imgmount CD image files */ /* securemode gets a different number from the previous branches! */ autoexec[14].Install(std::string("IMGMOUNT D \"") + orig + std::string("\" -t iso")); //autoexec[16].Install("D:"); if(secure) autoexec[15].Install("z:\\system\\config.com -securemode"); /* Makes no sense to exit here */ } else { if(secure) autoexec[14].Install("z:\\system\\config.com -securemode"); autoexec[15].Install(name); if(addexit) autoexec[16].Install("exit"); } command_found = true; } } /* Combining -securemode, noautoexec and no parameters leaves you with a lovely Z:\. */ if ( !command_found ) { if ( secure ) autoexec[12].Install("z:\\system\\config.com -securemode"); } #else if (secure) autoexec[i++].Install("z:\\system\\config.com -securemode"); #endif if (addexit) autoexec[i++].Install("exit"); assert(i <= 17); /* FIXME: autoexec[] should not be fixed size */ VFILE_Register("AUTOEXEC.BAT",(uint8_t *)autoexec_data,(uint32_t)strlen(autoexec_data)); } }; static AUTOEXEC* test = NULL; static void AUTOEXEC_ShutDown(Section * sec) { (void)sec;//UNUSED if (test != NULL) { delete test; test = NULL; } if (first_shell != NULL) { delete first_shell; first_shell = 0;//Make clear that it shouldn't be used anymore } if (call_shellstop != 0) { CALLBACK_DeAllocate(call_shellstop); call_shellstop = 0; } } void AUTOEXEC_Startup(Section *sec) { (void)sec;//UNUSED if (test == NULL) { LOG(LOG_MISC,LOG_DEBUG)("Allocating AUTOEXEC.BAT emulation"); test = new AUTOEXEC(control->GetSection("autoexec")); } } void AUTOEXEC_Init() { LOG(LOG_MISC,LOG_DEBUG)("Initializing AUTOEXEC.BAT emulation"); AddExitFunction(AddExitFunctionFuncPair(AUTOEXEC_ShutDown)); AddVMEventFunction(VM_EVENT_RESET,AddVMEventFunctionFuncPair(AUTOEXEC_ShutDown)); AddVMEventFunction(VM_EVENT_DOS_EXIT_BEGIN,AddVMEventFunctionFuncPair(AUTOEXEC_ShutDown)); AddVMEventFunction(VM_EVENT_DOS_EXIT_REBOOT_BEGIN,AddVMEventFunctionFuncPair(AUTOEXEC_ShutDown)); AddVMEventFunction(VM_EVENT_DOS_SURPRISE_REBOOT,AddVMEventFunctionFuncPair(AUTOEXEC_ShutDown)); } static Bitu INT2E_Handler(void) { /* Save return address and current process */ RealPt save_ret=real_readd(SegValue(ss),reg_sp); uint16_t save_psp=dos.psp(); /* Set first shell as process and copy command */ dos.psp(shell_psp);//DOS_FIRST_SHELL); DOS_PSP psp(shell_psp);//DOS_FIRST_SHELL); psp.SetCommandTail(RealMakeSeg(ds,reg_si)); SegSet16(ss,RealSeg(psp.GetStack())); reg_sp=2046; /* Read and fix up command string */ CommandTail tail; MEM_BlockRead(PhysMake(dos.psp(),CTBUF+1),&tail,CTBUF+1); if (tail.count<CTBUF) tail.buffer[tail.count]=0; else tail.buffer[CTBUF-1]=0; char* crlf=strpbrk(tail.buffer,"\r\n"); if (crlf) *crlf=0; /* Execute command */ if (strlen(tail.buffer)) { DOS_Shell temp; temp.ParseLine(tail.buffer); temp.RunInternal(); } /* Restore process and "return" to caller */ dos.psp(save_psp); SegSet16(cs,RealSeg(save_ret)); reg_ip=RealOff(save_ret); reg_ax=0; return CBRET_NONE; } /* TODO: Why is all this DOS kernel and VFILE registration here in SHELL_Init()? * That's like claiming that DOS memory and device initialization happens from COMMAND.COM! * We need to move the DOS kernel initialization into another function, and the VFILE * registration to another function, and then message initialization to another function, * and then those functions need to be called before SHELL_Init() -J.C. */ void SHELL_Init() { LOG(LOG_MISC,LOG_DEBUG)("Initializing DOS shell"); /* Add messages */ MSG_Add("SHELL_CMD_TREE_ERROR", "No subdirectories exist\n"); MSG_Add("SHELL_CMD_VOL_TREE", "Directory PATH listing for Volume %s\n"); MSG_Add("SHELL_CMD_VOL_DRIVE","\n Volume in drive %c "); MSG_Add("SHELL_CMD_VOL_SERIAL"," Volume Serial Number is "); MSG_Add("SHELL_CMD_VOL_SERIAL_NOLABEL","has no label\n"); MSG_Add("SHELL_CMD_VOL_SERIAL_LABEL","is %s\n"); MSG_Add("SHELL_ILLEGAL_PATH","Path not found\n"); MSG_Add("SHELL_ILLEGAL_DRIVE","Invalid drive specification\n"); MSG_Add("SHELL_CMD_HELP","If you want a list of all supported internal commands type \033[33;1mHELP /ALL\033[0m.\nYou can also find external commands on the Z: drive as programs.\nA short list of the most often used commands:\n"); MSG_Add("SHELL_CMD_HELP_END1","External commands such as \033[33;1mMOUNT\033[0m and \033[33;1mIMGMOUNT\033[0m can be found on the Z: drive.\n"); MSG_Add("SHELL_CMD_HELP_END2","Type \033[33;1mHELP command\033[0m or \033[33;1mcommand /?\033[0m for help information for the specified command.\n"); MSG_Add("SHELL_CMD_ECHO_ON","ECHO is on.\n"); MSG_Add("SHELL_CMD_ECHO_OFF","ECHO is off.\n"); MSG_Add("SHELL_ILLEGAL_SWITCH","Invalid switch - %s\n"); MSG_Add("SHELL_INVALID_PARAMETER","Invalid parameter - %s\n"); MSG_Add("SHELL_MISSING_PARAMETER","Required parameter missing.\n"); MSG_Add("SHELL_MISSING_FILE","The following file is missing or corrupted: %s\n"); MSG_Add("SHELL_CMD_CHDIR_ERROR","Invalid directory - %s\n"); MSG_Add("SHELL_CMD_CHDIR_HINT","Hint: To change to different drive type \033[31m%c:\033[0m\n"); MSG_Add("SHELL_CMD_CHDIR_HINT_2","directoryname contains unquoted spaces.\nTry \033[31mcd %s\033[0m or properly quote them with quotation marks.\n"); MSG_Add("SHELL_CMD_CHDIR_HINT_3","You are still on drive Z:, and the specified directory cannot be found.\nFor accessing a mounted drive, change to the drive with a syntax like \033[31mC:\033[0m.\n"); MSG_Add("SHELL_CMD_DATE_HELP","Displays or changes the internal date.\n"); MSG_Add("SHELL_CMD_DATE_ERROR","The specified date is not correct.\n"); MSG_Add("SHELL_CMD_DATE_DAYS","3SunMonTueWedThuFriSat"); // "2SoMoDiMiDoFrSa" MSG_Add("SHELL_CMD_DATE_NOW","Current date: "); MSG_Add("SHELL_CMD_DATE_SETHLP","Type 'date %s' to change.\n"); MSG_Add("SHELL_CMD_DATE_HELP_LONG","DATE [[/T] [/H] [/S] | date]\n"\ " date: New date to set\n"\ " /S: Permanently use host time and date as DOS time\n"\ " /F: Switch back to DOSBox-X internal time (opposite of /S)\n"\ " /T: Only display date\n"\ " /H: Synchronize with host\n"); MSG_Add("SHELL_CMD_TIME_HELP","Displays or changes the internal time.\n"); MSG_Add("SHELL_CMD_TIME_ERROR","The specified time is not correct.\n"); MSG_Add("SHELL_CMD_TIME_NOW","Current time: "); MSG_Add("SHELL_CMD_TIME_SETHLP","Type 'time %s' to change.\n"); MSG_Add("SHELL_CMD_TIME_HELP_LONG","TIME [[/T] [/H] | time]\n"\ " time: New time to set\n"\ " /T: Display simple time\n"\ " /H: Synchronize with host\n"); MSG_Add("SHELL_CMD_MKDIR_EXIST","Directory already exists - %s\n"); MSG_Add("SHELL_CMD_MKDIR_ERROR","Unable to create directory - %s\n"); MSG_Add("SHELL_CMD_RMDIR_ERROR","Invalid path, not directory, or directory not empty - %s\n"); MSG_Add("SHELL_CMD_RENAME_ERROR","Unable to rename - %s\n"); MSG_Add("SHELL_CMD_ATTRIB_GET_ERROR","Unable to get attributes: %s\n"); MSG_Add("SHELL_CMD_ATTRIB_SET_ERROR","Unable to set attributes: %s\n"); MSG_Add("SHELL_CMD_DEL_ERROR","Unable to delete - %s\n"); MSG_Add("SHELL_CMD_DEL_SURE","All files in directory will be deleted!\nAre you sure [Y/N]?"); MSG_Add("SHELL_SYNTAXERROR","Syntax error\n"); MSG_Add("SHELL_CMD_SET_NOT_SET","Environment variable %s not defined.\n"); MSG_Add("SHELL_CMD_SET_OUT_OF_SPACE","Not enough environment space left.\n"); MSG_Add("SHELL_CMD_IF_EXIST_MISSING_FILENAME","IF EXIST: Missing filename.\n"); MSG_Add("SHELL_CMD_IF_ERRORLEVEL_MISSING_NUMBER","IF ERRORLEVEL: Missing number.\n"); MSG_Add("SHELL_CMD_IF_ERRORLEVEL_INVALID_NUMBER","IF ERRORLEVEL: Invalid number.\n"); MSG_Add("SHELL_CMD_GOTO_MISSING_LABEL","No label supplied to GOTO command.\n"); MSG_Add("SHELL_CMD_GOTO_LABEL_NOT_FOUND","GOTO: Label %s not found.\n"); MSG_Add("SHELL_CMD_FILE_ACCESS_DENIED","Access denied - %s\n"); MSG_Add("SHELL_CMD_FILE_NOT_FOUND","File not found - %s\n"); MSG_Add("SHELL_CMD_FILE_EXISTS","File %s already exists.\n"); MSG_Add("SHELL_CMD_DIR_INTRO"," Directory of %s\n\n"); MSG_Add("SHELL_CMD_DIR_BYTES_USED","%5d File(s) %17s Bytes\n"); MSG_Add("SHELL_CMD_DIR_BYTES_FREE","%5d Dir(s) %17s Bytes free\n"); MSG_Add("SHELL_CMD_DIR_FILES_LISTED","Total files listed:\n"); MSG_Add("SHELL_EXECUTE_DRIVE_NOT_FOUND","Drive %c does not exist!\nYou must \033[31mmount\033[0m it first. Type \033[1;33mintro\033[0m or \033[1;33mintro mount\033[0m for more information.\n"); MSG_Add("SHELL_EXECUTE_DRIVE_ACCESS_CDROM","Do you want to give DOSBox-X access to your real CD-ROM drive %c [Y/N]?"); MSG_Add("SHELL_EXECUTE_DRIVE_ACCESS_FLOPPY","Do you want to give DOSBox-X access to your real floppy drive %c [Y/N]?"); MSG_Add("SHELL_EXECUTE_DRIVE_ACCESS_REMOVABLE","Do you want to give DOSBox-X access to your real removable drive %c [Y/N]?"); MSG_Add("SHELL_EXECUTE_DRIVE_ACCESS_NETWORK","Do you want to give DOSBox-X access to your real network drive %c [Y/N]?"); MSG_Add("SHELL_EXECUTE_DRIVE_ACCESS_FIXED","Do you really want to give DOSBox-X access to your real hard drive %c [Y/N]?"); MSG_Add("SHELL_EXECUTE_ILLEGAL_COMMAND","Bad command or filename - \"%s\"\n"); MSG_Add("SHELL_CMD_PAUSE","Press any key to continue . . .\n"); MSG_Add("SHELL_CMD_PAUSE_HELP","Waits for one keystroke to continue.\n"); MSG_Add("SHELL_CMD_PAUSE_HELP_LONG","PAUSE\n"); MSG_Add("SHELL_CMD_COPY_FAILURE","Copy failure - %s\n"); MSG_Add("SHELL_CMD_COPY_SUCCESS"," %d File(s) copied.\n"); MSG_Add("SHELL_CMD_COPY_CONFIRM","Overwrite %s (Yes/No/All)?"); MSG_Add("SHELL_CMD_COPY_NOSPACE","Insufficient disk space - %s\n"); MSG_Add("SHELL_CMD_COPY_ERROR","Copy error - %s\n"); MSG_Add("SHELL_CMD_SUBST_DRIVE_LIST","The currently mounted local drives are:\n"); MSG_Add("SHELL_CMD_SUBST_NO_REMOVE","Unable to remove, drive not in use.\n"); MSG_Add("SHELL_CMD_SUBST_IN_USE","Target drive is already in use.\n"); MSG_Add("SHELL_CMD_SUBST_NOT_LOCAL","It is only possible to use SUBST on local drives.\n"); MSG_Add("SHELL_CMD_SUBST_INVALID_PATH","The specified drive or path is invalid.\n"); MSG_Add("SHELL_CMD_SUBST_FAILURE","SUBST: There is an error in your command line.\n"); MSG_Add("SHELL_CMD_VTEXT_ON","DOS/V V-text is currently enabled.\n"); MSG_Add("SHELL_CMD_VTEXT_OFF","DOS/V V-text is currently disabled.\n"); std::string mapper_keybind = mapper_event_keybind_string("host"); if (mapper_keybind.empty()) mapper_keybind = "unbound"; /* Capitalize the binding */ if (mapper_keybind.size() > 0) mapper_keybind[0] = toupper(mapper_keybind[0]); std::string default_host = #if defined(WIN32) && !defined(HX_DOS) "F11" #else "F12" #endif ; /* Punctuation is important too. */ //mapper_keybind += "."; /* NTS: MSG_Add() takes the string as const char * but it does make a copy of the string when entering into the message map, * so there is no problem here of causing use-after-free crashes when we exit. */ std::string host_key_help; // SHELL_STARTUP_BEGIN2 if (machine == MCH_PC98) { // "\x86\x46 To activate the keymapper \033[31mhost+M\033[37m. Host key is F12. \x86\x46\n" } else { // "\xBA To activate the keymapper \033[31mhost+M\033[37m. Host key is F12. \xBA\n" } MSG_Add("SHELL_STARTUP_TITLE", "Welcome to DOSBox-X !"); MSG_Add("SHELL_STARTUP_HEAD1_PC98", "\033[36mGetting Started with DOSBox-X:\033[37m "); MSG_Add("SHELL_STARTUP_TEXT1_PC98", "Type \033[32mHELP\033[37m for shell commands, and \033[32mINTRO\033[37m for a short introduction. \nYou could also complete various tasks through the \033[33mdrop-down menus\033[37m."); MSG_Add("SHELL_STARTUP_EXAMPLE_PC98", "\033[32mExample\033[37m: Try select \033[33mTrueType font\033[37m or \033[33mOpenGL perfect\033[37m output option."); MSG_Add("SHELL_STARTUP_TEXT2_PC98", (std::string("To launch the \033[33mConfiguration Tool\033[37m, use \033[31mhost+C\033[37m. Host key is \033[32m") + (mapper_keybind + "\033[37m. ").substr(0,13) + std::string("\nTo activate the \033[33mMapper Editor\033[37m for key assignments, use \033[31mhost+M\033[37m. \nTo switch between windowed and full-screen mode, use \033[31mhost+F\033[37m. \nTo adjust the emulated CPU speed, use \033[31mhost+Plus\033[37m and \033[31mhost+Minus\033[37m. ")).c_str()); MSG_Add("SHELL_STARTUP_INFO_PC98","\033[36mDOSBox-X is now running in \033[32mJapanese NEC PC-98\033[36m emulation mode.\033[37m "); MSG_Add("SHELL_STARTUP_TEXT3_PC98", "\033[32mDOSBox-X project \033[33mhttps://dosbox-x.com/ \033[36mComplete DOS emulations\033[37m\n\033[32mDOSBox-X guide \033[33mhttps://dosbox-x.com/wiki\033[37m \033[36mDOS, Windows 3.x and 9x\033[37m\n\033[32mDOSBox-X support \033[33mhttps://github.com/joncampbell123/dosbox-x/issues\033[37m"); MSG_Add("SHELL_STARTUP_HEAD1", "\033[36mGetting started with DOSBox-X: \033[37m"); MSG_Add("SHELL_STARTUP_TEXT1", "Type \033[32mHELP\033[37m to see the list of shell commands, \033[32mINTRO\033[37m for a brief introduction.\nYou can also complete various tasks in DOSBox-X through the \033[33mdrop-down menus\033[37m."); MSG_Add("SHELL_STARTUP_EXAMPLE", "\033[32mExample\033[37m: Try select the \033[33mTrueType font\033[37m or \033[33mOpenGL pixel-perfect\033[37m output option."); MSG_Add("SHELL_STARTUP_HEAD2", "\033[36mUseful default shortcuts: \033[37m"); MSG_Add("SHELL_STARTUP_TEXT2", (std::string("- switch between windowed and full-screen mode with key combination \033[31m")+(default_host+" \033[37m+ \033[31mF\033[37m ").substr(0,23)+std::string("\033[37m\n") + std::string("- launch \033[33mConfiguration Tool\033[37m using \033[31m")+(default_host+" \033[37m+ \033[31mC\033[37m ").substr(0,22)+std::string("\033[37m, and \033[33mMapper Editor\033[37m using \033[31m")+(default_host+" \033[37m+ \033[31mM\033[37m ").substr(0,24)+std::string("\033[37m\n") + std::string("- increase or decrease the emulation speed with \033[31m")+(default_host+" \033[37m+ \033[31mPlus\033[37m ").substr(0,25)+std::string("\033[37m or \033[31m") + (default_host+" \033[37m+ \033[31mMinus\033[37m ").substr(0,29)+std::string("\033[37m")).c_str()); MSG_Add("SHELL_STARTUP_DOSV","\033[32mDOS/V mode\033[37m is now active. Try also \033[32mTTF CJK mode\033[37m for a general DOS emulation."); MSG_Add("SHELL_STARTUP_CGA", "Composite CGA mode is supported. Use \033[31mCtrl+F8\033[37m to set composite output ON/OFF.\nUse \033[31mCtrl+Shift+[F7/F8]\033[37m to change hue; \033[31mCtrl+F7\033[37m selects early/late CGA model. "); MSG_Add("SHELL_STARTUP_CGA_MONO","Use \033[31mCtrl+F7\033[37m to cycle through green, amber, and white monochrome color, \nand \033[31mCtrl+F8\033[37m to change contrast/brightness settings. "); MSG_Add("SHELL_STARTUP_HERC","Use \033[31mCtrl+F7\033[37m to cycle through white, amber, and green monochrome color. \nUse \033[31mCtrl+F8\033[37m to toggle horizontal blending (only in graphics mode). "); MSG_Add("SHELL_STARTUP_HEAD3", "\033[36mDOSBox-X project on the web: \033[37m"); MSG_Add("SHELL_STARTUP_TEXT3", "\033[32mHomepage of project\033[37m: \033[33mhttps://dosbox-x.com/ \033[36mComplete DOS emulations\033[37m\n\033[32mUser guides on Wiki\033[37m: \033[33mhttps://dosbox-x.com/wiki\033[32m \033[36mDOS, Windows 3.x and 9x\033[37m\n\033[32mIssue or suggestion\033[37m: \033[33mhttps://github.com/joncampbell123/dosbox-x/issues \033[37m"); MSG_Add("SHELL_STARTUP_LAST", "HAVE FUN WITH DOSBox-X !"); MSG_Add("SHELL_CMD_BREAK_HELP","Sets or clears extended CTRL+C checking.\n"); MSG_Add("SHELL_CMD_BREAK_HELP_LONG","BREAK [ON | OFF]\n\nType BREAK without a parameter to display the current BREAK setting.\n"); MSG_Add("SHELL_CMD_CHDIR_HELP","Displays or changes the current directory.\n"); MSG_Add("SHELL_CMD_CHDIR_HELP_LONG","CHDIR [drive:][path]\n" "CHDIR [..]\n" "CD [drive:][path]\n" "CD [..]\n\n" " .. Specifies that you want to change to the parent directory.\n\n" "Type CD drive: to display the current directory in the specified drive.\n" "Type CD without parameters to display the current drive and directory.\n"); MSG_Add("SHELL_CMD_CLS_HELP","Clears screen.\n"); MSG_Add("SHELL_CMD_CLS_HELP_LONG","CLS\n"); MSG_Add("SHELL_CMD_DIR_HELP","Displays a list of files and subdirectories in a directory.\n"); MSG_Add("SHELL_CMD_DIR_HELP_LONG","DIR [drive:][path][filename] [/[W|B]] [/S] [/P] [/A[D|H|S|R|A]] [/O[N|E|G|S|D]]\n\n" " [drive:][path][filename]\n" " Specifies drive, directory, and/or files to list.\n" " /W Uses wide list format.\n" " /B Uses bare format (no heading information or summary).\n" " /S Displays files in specified directory and all subdirectories.\n" " /P Pauses after each screenful of information.\n" " /A Displays files with specified attributes.\n" " attributes D Directories R Read-only files\n" " H Hidden files A Files ready for archiving\n" " S System files - Prefix meaning not\n" " /O List by files in sorted order.\n" " sortorder N By name (alphabetic) S By size (smallest first)\n" " E By extension (alphabetic) D By date & time (earliest first)\n" " G Group directories first - Prefix to reverse order\n\n" "Switches may be preset in the DIRCMD environment variable. Override\n" "preset switches by prefixing any switch with - (hyphen)--for example, /-W.\n" ); MSG_Add("SHELL_CMD_ECHO_HELP","Displays messages, or turns command-echoing on or off.\n"); MSG_Add("SHELL_CMD_ECHO_HELP_LONG"," ECHO [ON | OFF]\n ECHO [message]\n\nType ECHO without parameters to display the current echo setting.\n"); MSG_Add("SHELL_CMD_EXIT_HELP","Exits from the command shell.\n"); MSG_Add("SHELL_CMD_EXIT_HELP_LONG","EXIT\n"); MSG_Add("SHELL_CMD_HELP_HELP","Shows DOSBox-X command help.\n"); MSG_Add("SHELL_CMD_HELP_HELP_LONG","HELP [/A or /ALL]\nHELP [command]\n\n" " /A or /ALL Lists all supported internal commands.\n" " [command] Shows help for the specified command.\n\n" "\033[0mE.g., \033[37;1mHELP COPY\033[0m or \033[37;1mCOPY /?\033[0m shows help information for COPY command.\n\n" "Note: External commands like \033[33;1mMOUNT\033[0m and \033[33;1mIMGMOUNT\033[0m are not listed by HELP [/A].\n" " These commands can be found on the Z: drive as programs (e.g. MOUNT.COM).\n" " Type \033[33;1mcommand /?\033[0m or \033[33;1mHELP command\033[0m for help information for that command.\n"); MSG_Add("SHELL_CMD_LS_HELP","Lists directory contents.\n"); MSG_Add("SHELL_CMD_LS_HELP_LONG","LS [drive:][path][filename] [/A] [/L] [/P] [/Z]\n\n" " /A Lists hidden and system files also.\n" " /L Lists names one per line.\n" " /P Pauses after each screenful of information.\n" " /Z Displays short names even if LFN support is available.\n"); MSG_Add("SHELL_CMD_MKDIR_HELP","Creates a directory.\n"); MSG_Add("SHELL_CMD_MKDIR_HELP_LONG","MKDIR [drive:][path]\n" "MD [drive:][path]\n"); MSG_Add("SHELL_CMD_RMDIR_HELP","Removes a directory.\n"); MSG_Add("SHELL_CMD_RMDIR_HELP_LONG","RMDIR [drive:][path]\n" "RD [drive:][path]\n"); MSG_Add("SHELL_CMD_SET_HELP","Displays or changes environment variables.\n"); MSG_Add("SHELL_CMD_SET_HELP_LONG","SET [variable=[string]]\n\n" " variable Specifies the environment-variable name.\n" " string Specifies a series of characters to assign to the variable.\n\n" "* If no string is specified, the variable is removed from the environment.\n\n" "Type SET without parameters to display the current environment variables.\n"); MSG_Add("SHELL_CMD_IF_HELP","Performs conditional processing in batch programs.\n"); MSG_Add("SHELL_CMD_IF_HELP_LONG","IF [NOT] ERRORLEVEL number command\n" "IF [NOT] string1==string2 command\n" "IF [NOT] EXIST filename command\n\n" " NOT Specifies that DOS should carry out\n" " the command only if the condition is false.\n\n" " ERRORLEVEL number Specifies a true condition if the last program run\n" " returned an exit code equal to or greater than the number\n" " specified.\n\n" " string1==string2 Specifies a true condition if the specified text strings\n" " match.\n\n" " EXIST filename Specifies a true condition if the specified filename\n" " exists.\n\n" " command Specifies the command to carry out if the condition is\n" " met. Command can be followed by ELSE command which\n" " will execute the command after the ELSE keyword if the\n" " specified condition is FALSE\n"); MSG_Add("SHELL_CMD_GOTO_HELP","Jumps to a labeled line in a batch program.\n"); MSG_Add("SHELL_CMD_GOTO_HELP_LONG","GOTO label\n\n" " label Specifies a text string used in the batch program as a label.\n\n" "You type a label on a line by itself, beginning with a colon.\n"); MSG_Add("SHELL_CMD_HISTORY_HELP","Displays or clears the command history list.\n"); MSG_Add("SHELL_CMD_HISTORY_HELP_LONG","HISTORY [/C]\n\n /C Clears the command history list.\n"); MSG_Add("SHELL_CMD_SHIFT_HELP","Changes the position of replaceable parameters in a batch file.\n"); MSG_Add("SHELL_CMD_SHIFT_HELP_LONG","SHIFT\n"); MSG_Add("SHELL_CMD_FOR_HELP","Runs a specified command for each file in a set of files.\n"); MSG_Add("SHELL_CMD_FOR_HELP_LONG","FOR %%variable IN (set) DO command [command-parameters]\n\n %%variable Specifies a replaceable parameter.\n (set) Specifies a set of one or more files. Wildcards may be used.\n command Specifies the command to carry out for each file.\n command-parameters\n Specifies parameters or switches for the specified command.\n\nTo use the command in a batch program, specify %%%%variable instead of %%variable.\n"); MSG_Add("SHELL_CMD_LFNFOR_HELP","Enables or disables long filenames when processing FOR wildcards.\n"); MSG_Add("SHELL_CMD_LFNFOR_HELP_LONG","LFNFOR [ON | OFF]\n\nType LFNFOR without a parameter to display the current LFNFOR setting.\n\nThis command is only useful if LFN support is currently enabled.\n"); MSG_Add("SHELL_CMD_TYPE_HELP","Displays the contents of a text file.\n"); MSG_Add("SHELL_CMD_TYPE_HELP_LONG","TYPE [drive:][path][filename]\n"); MSG_Add("SHELL_CMD_REM_HELP","Adds comments in a batch file.\n"); MSG_Add("SHELL_CMD_REM_HELP_LONG","REM [comment]\n"); MSG_Add("SHELL_CMD_RENAME_HELP","Renames a file/directory or files.\n"); MSG_Add("SHELL_CMD_RENAME_HELP_LONG","RENAME [drive:][path][directoryname1 | filename1] [directoryname2 | filename2]\n" "REN [drive:][path][directoryname1 | filename1] [directoryname2 | filename2]\n\n" "Note that you can not specify a new drive or path for your destination.\n\n" "Wildcards (* and ?) are supported for files. For example, the following command\n" "renames all text files: \033[37;1mREN *.TXT *.BAK\033[0m\n"); MSG_Add("SHELL_CMD_DELETE_HELP","Removes one or more files.\n"); MSG_Add("SHELL_CMD_DELETE_HELP_LONG","DEL [/P] [/F] [/Q] names\n" "ERASE [/P] [/F] [/Q] names\n\n" " names Specifies a list of one or more files or directories.\n" " Wildcards may be used to delete multiple files. If a\n" " directory is specified, all files within the directory\n" " will be deleted.\n" " /P Prompts for confirmation before deleting one or more files.\n" " /F Force deleting of read-only files.\n" " /Q Quiet mode, do not ask if ok to delete on global wildcard.\n"); MSG_Add("SHELL_CMD_COPY_HELP","Copies one or more files.\n"); MSG_Add("SHELL_CMD_COPY_HELP_LONG","COPY [/Y | /-Y] source [+source [+ ...]] [destination]\n\n" " source Specifies the file or files to be copied.\n" " destination Specifies the directory and/or filename for the new file(s).\n" " /Y Suppresses prompting to confirm you want to overwrite an\n" " existing destination file.\n" " /-Y Causes prompting to confirm you want to overwrite an\n" " existing destination file.\n\n" "The switch /Y may be preset in the COPYCMD environment variable.\n" "This may be overridden with /-Y on the command line.\n\n" "To append files, specify a single file for destination, but multiple files\n" "for source (using wildcards or file1+file2+file3 format).\n"); MSG_Add("SHELL_CMD_CALL_HELP","Starts a batch file from within another batch file.\n"); MSG_Add("SHELL_CMD_CALL_HELP_LONG","CALL [drive:][path]filename [batch-parameters]\n\n" "batch-parameters Specifies any command-line information required by\n" " the batch program.\n"); MSG_Add("SHELL_CMD_SUBST_HELP","Assigns an internal directory to a drive.\n"); MSG_Add("SHELL_CMD_SUBST_HELP_LONG","SUBST [drive1: [drive2:]path]\nSUBST drive1: /D\n\n" " drive1: Specifies a drive to which you want to assign a path.\n" " [drive2:]path Specifies a mounted local drive and path you want to assign to.\n" " /D Deletes a mounted or substituted drive.\n\n" "Type SUBST with no parameters to display a list of mounted local drives.\n"); MSG_Add("SHELL_CMD_LOADHIGH_HELP","Loads a program into upper memory (requires XMS and UMB memory).\n"); MSG_Add("SHELL_CMD_LOADHIGH_HELP_LONG","LH [drive:][path]filename [parameters]\n" "LOADHIGH [drive:][path]filename [parameters]\n"); MSG_Add("SHELL_CMD_CHOICE_HELP","Waits for a keypress and sets ERRORLEVEL.\n"); MSG_Add("SHELL_CMD_CHOICE_HELP_LONG","CHOICE [/C:choices] [/N] [/S] text\n" " /C[:]choices - Specifies allowable keys. Default is: yn.\n" " /N - Do not display the choices at end of prompt.\n" " /S - Enables case-sensitive choices to be selected.\n" " text - The text to display as a prompt.\n"); MSG_Add("SHELL_CMD_ATTRIB_HELP","Displays or changes file attributes.\n"); MSG_Add("SHELL_CMD_ATTRIB_HELP_LONG","ATTRIB [+R | -R] [+A | -A] [+S | -S] [+H | -H] [drive:][path][filename] [/S]\n\n" " + Sets an attribute.\n" " - Clears an attribute.\n" " R Read-only file attribute.\n" " A Archive file attribute.\n" " S System file attribute.\n" " H Hidden file attribute.\n" " [drive:][path][filename]\n" " Specifies file(s) or directory for ATTRIB to process.\n" " /S Processes files in all directories in the specified path.\n"); MSG_Add("SHELL_CMD_PATH_HELP","Displays or sets a search path for executable files.\n"); MSG_Add("SHELL_CMD_PATH_HELP_LONG","PATH [[drive:]path[;...][;%PATH%]\n" "PATH ;\n\n" "Type PATH ; to clear all search path settings.\n" "Type PATH without parameters to display the current path.\n"); MSG_Add("SHELL_CMD_PUSHD_HELP","Stores the current directory for use by the POPD command, then\nchanges to the specified directory.\n"); MSG_Add("SHELL_CMD_PUSHD_HELP_LONG","PUSHD [path]\n\n" "path Specifies the directory to make the current directory.\n\n" "Type PUSHD with no parameters to display currently stored directories.\n"); MSG_Add("SHELL_CMD_POPD_HELP","Changes to the directory stored by the PUSHD command.\n"); MSG_Add("SHELL_CMD_POPD_HELP_LONG","POPD\n"); MSG_Add("SHELL_CMD_VERIFY_HELP","Controls whether to verify files are written correctly to a disk.\n"); MSG_Add("SHELL_CMD_VERIFY_HELP_LONG","VERIFY [ON | OFF]\n\nType VERIFY without a parameter to display the current VERIFY setting.\n"); MSG_Add("SHELL_CMD_VER_HELP","Displays or sets DOSBox-X's reported DOS version.\n"); MSG_Add("SHELL_CMD_VER_HELP_LONG","VER [/R]\n" "VER [SET] number or VER SET [major minor]\n\n" " /R Display DOSBox-X's Git commit version and build date.\n" " [SET] number Set the specified number as the reported DOS version.\n" " SET [major minor] Set the reported DOS version in major and minor format.\n\n" " \033[0mE.g., \033[37;1mVER 6.0\033[0m or \033[37;1mVER 7.1\033[0m sets the DOS version to 6.0 and 7.1, respectively.\n" " On the other hand, \033[37;1mVER SET 7 1\033[0m sets the DOS version to 7.01 instead of 7.1.\n\n" "Type VER without parameters to display DOSBox-X and the reported DOS version.\n"); MSG_Add("SHELL_CMD_VER_VER","DOSBox-X version %s (%s). Reported DOS version %d.%02d.\n"); MSG_Add("SHELL_CMD_VER_INVALID","The specified DOS version is not correct.\n"); MSG_Add("SHELL_CMD_VOL_HELP","Displays the disk volume label and serial number, if they exist.\n"); MSG_Add("SHELL_CMD_VOL_HELP_LONG","VOL [drive]\n"); MSG_Add("SHELL_CMD_PROMPT_HELP","Changes the command prompt.\n"); MSG_Add("SHELL_CMD_PROMPT_HELP_LONG","PROMPT [text]\n" " text Specifies a new command prompt.\n\n" "Prompt can be made up of normal characters and the following special codes:\n" " $A & (Ampersand)\n" " $B | (pipe)\n" " $C ( (Left parenthesis)\n" " $D Current date\n" " $E Escape code (ASCII code 27)\n" " $F ) (Right parenthesis)\n" " $G > (greater-than sign)\n" " $H Backspace (erases previous character)\n" " $L < (less-than sign)\n" " $N Current drive\n" " $P Current drive and path\n" " $Q = (equal sign)\n" " $S (space)\n" " $T Current time\n" " $V DOS version number\n" " $_ Carriage return and linefeed\n" " $$ $ (dollar sign)\n"); MSG_Add("SHELL_CMD_ALIAS_HELP", "Defines or displays aliases.\n"); MSG_Add("SHELL_CMD_ALIAS_HELP_LONG", "ALIAS [name[=value] ... ]\n\nType ALIAS without parameters to display the list of aliases in the form:\n`ALIAS NAME = VALUE'\n"); MSG_Add("SHELL_CMD_ASSOC_HELP", "Displays or changes file extension associations.\n"); MSG_Add("SHELL_CMD_ASSOC_HELP_LONG", "ASSOC [.ext[=command] ... ]\n\nType ASSOC without parameters to display the current file associations.\nFile extensions must start with a dot (.); wildcards (* and ?) are allowed.\n"); MSG_Add("SHELL_CMD_CHCP_HELP", "Displays or changes the current DOS code page.\n"); MSG_Add("SHELL_CMD_CHCP_HELP_LONG", "CHCP [nnn [file]]\n\n nnn Specifies a code page number.\n file Specifies a code page file.\n\nSupported code pages for changing in the TrueType font output:\n\n437,737,775,808,850,852,853,855,857,858,860-866,869,872,874,3021\n\nWindows code pages: 1250,1251,1252,1253,1254,1255,1256,1257,1258\n\nAlso double-byte code pages including 932, 936, 949, and 950.\n\nCustomized code pages are supported by providing code page files.\n"); MSG_Add("SHELL_CMD_CHCP_ACTIVE", "Active code page: %d\n"); MSG_Add("SHELL_CMD_CHCP_MISSING", "ASCII characters not defined in TTF font: %d\n"); MSG_Add("SHELL_CMD_CHCP_INVALID", "Invalid code page number - %s\n"); MSG_Add("SHELL_CMD_COUNTRY_HELP", "Displays or changes the current country.\n"); MSG_Add("SHELL_CMD_COUNTRY_HELP_LONG", "COUNTRY [nnn] \n\n nnn Specifies a country code.\n\nCountry-specific information such as date and time formats will be affected.\n"); MSG_Add("SHELL_CMD_CTTY_HELP","Changes the terminal device used to control the system.\n"); MSG_Add("SHELL_CMD_CTTY_HELP_LONG","CTTY device\n device The terminal device to use, such as CON.\n"); MSG_Add("SHELL_CMD_MORE_HELP","Displays output one screen at a time.\n"); MSG_Add("SHELL_CMD_MORE_HELP_LONG","MORE [drive:][path][filename]\nMORE < [drive:][path]filename\ncommand-name | MORE [drive:][path][filename]\n"); MSG_Add("SHELL_CMD_TRUENAME_HELP","Finds the fully-expanded name for a file.\n"); MSG_Add("SHELL_CMD_TRUENAME_HELP_LONG","TRUENAME [/H] file\n"); MSG_Add("SHELL_CMD_DXCAPTURE_HELP","Runs program with video or audio capture.\n"); MSG_Add("SHELL_CMD_DXCAPTURE_HELP_LONG","DX-CAPTURE [/V|/-V] [/A|/-A] [/M|/-M] [command] [options]\n\nIt will start video or audio capture, run program, and then automatically stop capture when the program exits.\n"); #if C_DEBUG MSG_Add("SHELL_CMD_DEBUGBOX_HELP","Runs program and breaks into debugger at entry point.\n"); MSG_Add("SHELL_CMD_DEBUGBOX_HELP_LONG","DEBUGBOX [command] [options]\n\nType DEBUGBOX without a parameter to start the debugger.\n"); #endif MSG_Add("SHELL_CMD_COMMAND_HELP","Starts the DOSBox-X command shell.\n\nThe following options are accepted:\n\n /C Executes the specified command and returns.\n /K Executes the specified command and continues running.\n /P Loads a permanent copy of the command shell.\n /INIT Initializes the command shell.\n"); /* Regular startup */ call_shellstop=CALLBACK_Allocate(); /* Setup the startup CS:IP to kill the last running machine when exited */ RealPt newcsip=CALLBACK_RealPointer(call_shellstop); SegSet16(cs,RealSeg(newcsip)); reg_ip=RealOff(newcsip); CALLBACK_Setup(call_shellstop,shellstop_handler,CB_IRET,"shell stop"); /* NTS: Some DOS programs behave badly if run from a command interpreter * who's PSP segment is too low in memory and does not appear in * the MCB chain (SimCity 2000). So allocate shell memory normally * as any DOS application would do. * * That includes allocating COMMAND.COM stack NORMALLY (not up in * the UMB as DOSBox SVN would do) */ /* Now call up the shell for the first time */ uint16_t psp_seg;//=DOS_FIRST_SHELL; uint16_t env_seg;//=DOS_FIRST_SHELL+19; //DOS_GetMemory(1+(4096/16))+1; uint16_t stack_seg;//=DOS_GetMemory(2048/16,"COMMAND.COM stack"); uint16_t tmp,total_sz; // decide shell env size if (dosbox_shell_env_size == 0) dosbox_shell_env_size = (0x158u - (0x118u + 19u)) << 4u; /* equivalent to mainline DOSBox */ else dosbox_shell_env_size = (dosbox_shell_env_size+15u)&(~15u); /* round up to paragraph */ LOG_MSG("COMMAND.COM env size: %u bytes",dosbox_shell_env_size); // According to some sources, 0x0008 is a special PSP segment value used by DOS before the first // program is used. We need the current PSP segment to be nonzero so that DOS_AllocateMemory() // can properly allocate memory. dos.psp(8); auto savedMemAllocStrategy = DOS_GetMemAllocStrategy(); auto shellHigh = std::string(static_cast<Section_prop*>(control->GetSection("dos"))->Get_string("shellhigh")); if (shellHigh=="true" || shellHigh=="1" || (shellHigh=="auto" && dos.version.major >= 7)) { DOS_SetMemAllocStrategy(savedMemAllocStrategy | 0x80); } // COMMAND.COM environment block tmp = dosbox_shell_env_size>>4; if (!DOS_AllocateMemory(&env_seg,&tmp)) E_Exit("COMMAND.COM failed to allocate environment block segment"); LOG_MSG("COMMAND.COM environment block: 0x%04x sz=0x%04x",env_seg,tmp); // COMMAND.COM main binary (including PSP and stack) tmp = 0x1A + (2048/16); total_sz = tmp; if (!DOS_AllocateMemory(&psp_seg,&tmp)) E_Exit("COMMAND.COM failed to allocate main body + PSP segment"); LOG_MSG("COMMAND.COM main body (PSP): 0x%04x sz=0x%04x",psp_seg,tmp); DOS_SetMemAllocStrategy(savedMemAllocStrategy); // now COMMAND.COM has a main body and PSP segment, reflect it dos.psp(psp_seg); shell_psp = psp_seg; { DOS_MCB mcb((uint16_t)(env_seg-1)); mcb.SetPSPSeg(psp_seg); mcb.SetFileName("COMMAND"); } { DOS_MCB mcb((uint16_t)(psp_seg-1)); mcb.SetPSPSeg(psp_seg); mcb.SetFileName("COMMAND"); } // set the stack at 0x1A stack_seg = psp_seg + 0x1A; LOG_MSG("COMMAND.COM stack: 0x%04x",stack_seg); // set the stack pointer SegSet16(ss,stack_seg); reg_sp=2046; /* Set up int 24 and psp (Telarium games) */ real_writeb(psp_seg+16+1,0,0xea); /* far jmp */ real_writed(psp_seg+16+1,1,real_readd(0,0x24*4)); real_writed(0,0x24*4,((uint32_t)psp_seg<<16) | ((16+1)<<4)); /* Set up int 23 to "int 20" in the psp. Fixes what.exe */ real_writed(0,0x23*4,((uint32_t)psp_seg<<16)); /* Set up int 2e handler */ if (call_int2e == 0) call_int2e = CALLBACK_Allocate(); // RealPt addr_int2e=RealMake(psp_seg+16+1,8); // NTS: It's apparently common practice to enumerate MCBs by reading the segment value of INT 2Eh and then // scanning forward from there. The assumption seems to be that COMMAND.COM writes INT 2Eh there using // it's PSP segment and an offset like that of a COM executable even though COMMAND.COM is often an EXE file. RealPt addr_int2e=RealMake(psp_seg,8+((16+1)*16)); CALLBACK_Setup(call_int2e,&INT2E_Handler,CB_IRET_STI,Real2Phys(addr_int2e),"Shell Int 2e"); RealSetVec(0x2e,addr_int2e); /* Setup environment */ PhysPt env_write=PhysMake(env_seg,0); MEM_BlockWrite(env_write,path_string,(Bitu)(strlen(path_string)+1)); env_write += (PhysPt)(strlen(path_string)+1); MEM_BlockWrite(env_write,comspec_string,(Bitu)(strlen(comspec_string)+1)); env_write += (PhysPt)(strlen(comspec_string)+1); MEM_BlockWrite(env_write,prompt_string,(Bitu)(strlen(prompt_string)+1)); env_write +=(PhysPt)(strlen(prompt_string)+1); mem_writeb(env_write++,0); mem_writew(env_write,1); env_write+=2; MEM_BlockWrite(env_write,full_name,(Bitu)(strlen(full_name)+1)); // extern bool Mouse_Vertical; extern bool Mouse_Drv; Mouse_Drv = true; DOS_PSP psp(psp_seg); psp.MakeNew(0); dos.psp(psp_seg); /* The start of the filetable in the psp must look like this: * 01 01 01 00 02 * In order to achieve this: First open 2 files. Close the first and * duplicate the second (so the entries get 01) */ uint16_t dummy=0; DOS_OpenFile("CON",OPEN_READWRITE,&dummy); /* STDIN */ DOS_OpenFile("CON",OPEN_READWRITE,&dummy); /* STDOUT */ DOS_CloseFile(0); /* Close STDIN */ DOS_ForceDuplicateEntry(1,0); /* "new" STDIN */ DOS_ForceDuplicateEntry(1,2); /* STDERR */ DOS_OpenFile("CON",OPEN_READWRITE,&dummy); /* STDAUX */ if (!DOS_OpenFile("PRN",OPEN_READWRITE,&dummy)) DOS_OpenFile("CON",OPEN_READWRITE,&dummy); /* STDPRN */ psp.SetSize(psp_seg + total_sz); psp.SetStack(((unsigned int)stack_seg << 16u) + (unsigned int)reg_sp); /* Create appearance of handle inheritance by first shell */ for (uint16_t i=0;i<5;i++) { uint8_t handle=psp.GetFileHandle(i); if (Files[handle]) Files[handle]->AddRef(); } psp.SetParent(psp_seg); /* Set the environment */ psp.SetEnvironment(env_seg); /* Set the command line for the shell start up */ CommandTail tail; tail.count=(uint8_t)strlen(init_line); memset(&tail.buffer, 0, CTBUF); strncpy(tail.buffer,init_line,CTBUF); MEM_BlockWrite(PhysMake(psp_seg,CTBUF+1),&tail,CTBUF+1); /* Setup internal DOS Variables */ dos.dta(RealMake(psp_seg,CTBUF+1)); dos.psp(psp_seg); } /* Pfff... starting and running the shell from a configuration section INIT * What the hell were you guys thinking? --J.C. */ void SHELL_Run() { dos_shell_running_program = false; #if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU Reflect_Menu(); #endif LOG(LOG_MISC,LOG_DEBUG)("Running DOS shell now"); if (first_shell != NULL) E_Exit("Attempt to start shell when shell already running"); Section_prop *section = static_cast<Section_prop *>(control->GetSection("config")); bool altshell=false; char namestr[CROSS_LEN], tmpstr[CROSS_LEN], *name=namestr, *tmp=tmpstr; SHELL_ProgramStart_First_shell(&first_shell); first_shell->Prepare(); prepared = true; if (section!=NULL&&!control->opt_noconfig&&!control->opt_securemode&&!control->SecureMode()) { char *shell = (char *)section->Get_string("shell"); if (strlen(shell)) { tmp=trim(shell); name=StripArg(tmp); upcase(name); if (*name&&(DOS_FileExists(name)||DOS_FileExists((std::string("Z:\\SYSTEM\\")+name).c_str())||DOS_FileExists((std::string("Z:\\BIN\\")+name).c_str())||DOS_FileExists((std::string("Z:\\DOS\\")+name).c_str())||DOS_FileExists((std::string("Z:\\4DOS\\")+name).c_str())||DOS_FileExists((std::string("Z:\\DEBUG\\")+name).c_str())||DOS_FileExists((std::string("Z:\\TEXTUTIL\\")+name).c_str()))) { strreplace(name,'/','\\'); altshell=true; } else if (*name) first_shell->WriteOut(MSG_Get("SHELL_MISSING_FILE"), name); } } #if C_DEBUG if (control->opt_test) { RUN_ALL_TESTS(); #if defined(WIN32) DOSBox_ConsolePauseWait(); #endif return; } #endif i4dos=false; if (altshell) { if (strstr(name, "4DOS.COM")) i4dos=true; first_shell->SetEnv("COMSPEC",name); if (!strlen(tmp)) { char *p=strrchr(name, '\\'); if (!strcasecmp(p==NULL?name:p+1, "COMMAND.COM") || !strcasecmp(name, "Z:COMMAND.COM")) {strcpy(tmpstr, init_line);tmp=tmpstr;} else if (!strcasecmp(p==NULL?name:p+1, "4DOS.COM") || !strcasecmp(name, "Z:4DOS.COM")) {strcpy(tmpstr, "AUTOEXEC.BAT");tmp=tmpstr;} } first_shell->Execute(name, tmp); return; } try { first_shell->Run(); delete first_shell; first_shell = 0;//Make clear that it shouldn't be used anymore prepared = false; dos_shell_running_program = false; #if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU Reflect_Menu(); #endif } catch (...) { delete first_shell; first_shell = 0;//Make clear that it shouldn't be used anymore prepared = false; dos_shell_running_program = false; #if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU Reflect_Menu(); #endif throw; } }
49.796286
536
0.625914
mediaexplorer74
0bd39c5cf06f01ba1df7246af22c7859405ea451
45
cc
C++
lib/colour/Colour.cc
westrik/millipede
b2049b9333c1888e75fb8688a24be35f5724ac4d
[ "MIT" ]
1
2020-11-12T08:26:55.000Z
2020-11-12T08:26:55.000Z
lib/colour/Colour.cc
westrik/millipede
b2049b9333c1888e75fb8688a24be35f5724ac4d
[ "MIT" ]
null
null
null
lib/colour/Colour.cc
westrik/millipede
b2049b9333c1888e75fb8688a24be35f5724ac4d
[ "MIT" ]
null
null
null
#include "Colour.h" namespace Millipede { }
9
21
0.711111
westrik
0bdc848c91d9cb7b9c11d16e5b89a35082e46987
29,229
cpp
C++
TransShiftMex/lpc_formant.cpp
084/audapter_mex
d01df787e860062fd3360e533f3ecd5104d034a9
[ "Apache-2.0" ]
7
2015-10-26T19:44:08.000Z
2021-03-24T02:19:41.000Z
TransShiftMex/lpc_formant.cpp
084/audapter_mex
d01df787e860062fd3360e533f3ecd5104d034a9
[ "Apache-2.0" ]
5
2016-07-13T15:23:52.000Z
2021-07-08T18:13:46.000Z
TransShiftMex/lpc_formant.cpp
084/audapter_mex
d01df787e860062fd3360e533f3ecd5104d034a9
[ "Apache-2.0" ]
13
2018-06-26T01:09:16.000Z
2021-09-03T12:06:20.000Z
/* lpc_formant.cpp Linear prediction and formant tracking Shanqing Cai 12/2013 */ #include <algorithm> #include <cmath> #include <vector> #include "mex.h" #include "lpc_formant.h" #include "DSPF.h" /* Utility inline functions */ inline dtype mul_sign(const dtype &a, const dtype &b) { return (b >= 0.0 ? fabs(a) : -fabs(a)); } inline int imax(const int &k, const int &j) { return (k <= j ? j : k); } SmoothPitchTracker::SmoothPitchTracker(const int sr, const int window) : sr(sr), window(window), frameCounter(0) { memory = new dtype[window]; reset(); } SmoothPitchTracker::~SmoothPitchTracker() { if (memory) { delete[] memory; } } void SmoothPitchTracker::reset() { for (int i = 0; i < window; ++i) { memory[i] = -1.0; } frameCounter = 0; } dtype SmoothPitchTracker::track( std::vector<std::pair<int, dtype>>& indexAndMags) { // Perform partial sort to get the top-3 cepstral points std::vector<std::pair<int, dtype>>::iterator candBegin = indexAndMags.begin(); const size_t len = indexAndMags.size(); std::vector<std::pair<int, dtype>>::iterator candMiddle = (len >= numCandidates) ? candBegin + numCandidates : indexAndMags.end(); std::partial_sort( candBegin, candMiddle, indexAndMags.end(), [](std::pair<int, dtype> a, std::pair<int, dtype> b) { return a.second > b.second; // Sort in descending order. }); return sr / trackPitchValues(candBegin, candMiddle); } int SmoothPitchTracker::trackPitchValues( std::vector<std::pair<int, dtype>>::iterator candBegin, std::vector<std::pair<int, dtype>>::iterator candEnd) { dtype memoryMean = 0.0; bool anyMemory = false; for (int i = 0; i < window; ++i) { if (memory[i] > 0.0) { anyMemory = true; memoryMean += memory[i]; } } memoryMean /= static_cast<dtype>(window); int winner = (*candBegin).first; if (frameCounter > ignoreFirstFrames && anyMemory) { dtype minCost = std::numeric_limits<dtype>::infinity(); int bestIndex = -1; auto iter = candBegin; while (iter < candEnd) { const dtype dist = abs((*iter).first - memoryMean); if (dist < minCost) { // Find the closest to memoryMean. minCost = dist; bestIndex = iter - candBegin; } iter++; } winner = (*(candBegin + bestIndex)).first; } // Refresh memory. for (int i = 1; i < window; ++i) { memory[i - 1] = memory[i]; } memory[window - 1] = winner; frameCounter++; return winner; } /* Constructor Input arguments: t_nLPC: LPC order t_sr: sampling rate of the input signal (Hz) t_bufferSize: input buffer size (# of samples) t_nFFT: FFT length (must be power of 2) t_cepsWinWidth: cepstral liftering window width (dimensionless) t_nTracks: Number of formants to be tracked t_aFact: alpha parameter in the DP formant tracking algorithm (Xia and Espy-Wilson, 2000) t_bFact: beta t_gFact: gamma t_fn1: prior value of F1 (Hz) t_fn2: prior value of F2 (Hz) If cepsWinWidth is <= 0, cepstral liftering will be disabled. */ LPFormantTracker::LPFormantTracker(const int t_nLPC, const int t_sr, const int t_bufferSize, const int t_nFFT, const int t_cepsWinWidth, const int t_nTracks, const dtype t_aFact, const dtype t_bFact, const dtype t_gFact, const dtype t_fn1, const dtype t_fn2, const bool t_bMWA, const int t_avgLen, const CepstralPitchTrackerConfig& pitchTrackerConfig) : nLPC(t_nLPC), sr(t_sr), bufferSize(t_bufferSize), nFFT(t_nFFT), cepsWinWidth(t_cepsWinWidth), nTracks(t_nTracks), aFact(t_aFact), bFact(t_bFact), gFact(t_gFact), fn1(t_fn1), fn2(t_fn2), bMWA(t_bMWA), avgLen(t_avgLen), bTrackPitch(pitchTrackerConfig.activated), pitchLowerBoundHz(pitchTrackerConfig.pitchLowerBoundHz), pitchUpperBoundHz(pitchTrackerConfig.pitchUpperBoundHz), smoothPitchTracker(t_sr, pitchTrackerConfig.smoothPitchTrackerMemoryWindow) { /* Input sanity checks */ if ((nLPC <= 0) || (bufferSize <= 0) || (nFFT <= 0) || (nTracks <= 0)) { throw initializationError(); } if (nLPC > maxNLPC) { throw nLPCTooLargeError(); } bCepsLift = (cepsWinWidth > 0); winFunc = new dtype[bufferSize]; /* Initialize window */ genHanningWindow(); nLPC_SQR = nLPC * nLPC; Acompanion = new dtype[nLPC_SQR]; AHess = new dtype[nLPC_SQR]; temp_frame = new dtype[bufferSize + nLPC + 2]; // +2 for playing it safe! TODO: improve R = new dtype[nLPC * 2]; // *2 for playing it safe! TODO: improve /* Initalize FFT working date fields */ ftBuf1 = new dtype[nFFT * 2]; ftBuf2 = new dtype[nFFT * 2]; fftc = new dtype[nFFT * 2]; gen_w_r2(fftc, nFFT); /* Intermediate data fields */ lpcAi = new dtype[maxNLPC + 1]; realRoots = new dtype[maxNLPC]; imagRoots = new dtype[maxNLPC]; cumMat = new dtype[maxFmtTrackJump * maxNTracks]; costMat = new dtype[maxFmtTrackJump * maxNTracks]; nCands = 6; /* number of possible formant candiates (should be > ntracks but < p.nLPC/2!!!! (choose carefully : not fool-proof) TODO: Implement automatic checks */ weiMatPhi = new dtype[nTracks * maxAvgLen]; weiMatBw = new dtype[nTracks * maxAvgLen]; weiVec = new dtype[maxAvgLen]; sumWeiPhi = new dtype[nTracks]; sumWeiBw = new dtype[nTracks]; trackFF = 0.95; radius_us = new dtype[maxNLPC]; /* TODO: Tighten the size */ phi_us = new dtype[maxNLPC]; bandwidth_us = new dtype[maxNLPC]; //phi_s = new dtype[maxNLPC]; /* Call reset */ reset(); } /* Destructor */ LPFormantTracker::~LPFormantTracker() { if (winFunc) { delete[] winFunc; } if (Acompanion) { delete[] Acompanion; } if (AHess) { delete[] AHess; } if (temp_frame) { delete[] temp_frame; } if (R) { delete[] R; } if (ftBuf1) { delete[] ftBuf1; } if (ftBuf2) { delete[] ftBuf2; } if (fftc) { delete[] fftc; } if (lpcAi) { delete[] lpcAi; } if (realRoots) { delete[] realRoots; } if (imagRoots) { delete[] imagRoots; } if (cumMat) { delete[] cumMat; } if (costMat) { delete[] costMat; } if (weiMatPhi) { delete[] weiMatPhi; } if (weiMatBw) { delete[] weiMatBw; } if (weiVec) { delete[] weiVec; } if (sumWeiPhi) { delete[] sumWeiPhi; } if (sumWeiBw) { delete[] sumWeiBw; } if (radius_us) { delete[] radius_us; } if (phi_us) { delete[] phi_us; } if (bandwidth_us) { delete[] bandwidth_us; } } /* Reset after a supra-threshold interval */ void LPFormantTracker::postSupraThreshReset() { for (int i = 0; i < maxNLPC; ++i) { realRoots[i] = 0.0; imagRoots[i] = 0.0; } for(int j0 = 0; j0 < nTracks; ++j0) { sumWeiPhi[j0] = 0.0; sumWeiBw[j0] = 0.0; for(int i0 = 0; i0 < maxAvgLen; ++i0) { weiMatPhi[j0 + nTracks * i0] = 0.0; weiMatBw[j0 + nTracks * i0] = 0.0; } } for(int i0 = 0; i0 < maxAvgLen; ++i0) weiVec[i0]=0.0; //weiVec[mwaCircCtr] = 0.0; sumWei = 0.0; mwaCtr = 0; mwaCircCtr = 0; latestPitchHz = 0.0; } /* Resetting */ void LPFormantTracker::reset() { for (int i = 0; i < nFFT * 2; ++i) { ftBuf1[i] = 0.0; ftBuf2[i] = 0.0; } for (int i = 0; i < nLPC_SQR; ++i) { Acompanion[i] = 0.0; AHess[i] = 0.0; } for (int i = nLPC - 2; i >= 0; --i) { Acompanion[(nLPC + 1) * i + 1] = 1.0; AHess[(nLPC + 1) * i + 1] = 1.0; } for(int j0 = 0; j0 < nTracks; ++j0) { sumWeiPhi[j0] = 0.0; sumWeiBw[j0] = 0.0; for(int i0 = 0; i0 < maxAvgLen; ++i0) { weiMatPhi[j0 + nTracks * i0] = 0.0; weiMatBw[j0 + nTracks * i0] = 0.0; } } for (int i0 = 0; i0 < maxAvgLen; ++i0) { weiVec[i0] = 0.0; } sumWei = 0.0; postSupraThreshReset(); smoothPitchTracker.reset(); } /* Levinson recursion for linear prediction (LP) */ void LPFormantTracker::levinson(dtype * R, dtype * aa, const int size) { dtype ki, t; dtype E = R[0]; int i0, j0; if (R[0] == 0.0) { for(i0=1; i0<size; i0++) aa[i0] = 0.0; aa[0] = 1; return; } for(i0=1; i0<size; i0++) { ki = R[i0]; // Update reflection coefficient: for (j0=1; j0<i0; j0++) ki += aa[j0] * R[i0-j0]; ki /= -E; E *= (1 - ki*ki); // Update polynomial: for (j0 = 1; j0 <= RSL(i0 - 1, 1); j0++) { t = aa[j0]; aa[j0] += ki * aa[i0 - j0]; aa[i0 - j0] += ki * t; } if (i0%2 == 0) aa[RSL(i0, 1)] *= 1+ki; // Record reflection coefficient aa[i0] = ki; } // end of for loop aa[0] = 1.0; } /* The following takes in a polynomial stored in *c, and yields the roots of this polynomial (*wr stores the real comp, and *wi stores the imag comp) It forms a companion matrix, then uses the hqr algorithm VV 19 June 2003 Input arguments: c: coefficients of the polynomial wr: real parts of the roots (output) wi: imaginary parts of the roots (output) */ int LPFormantTracker::hqr_roots(dtype * c, dtype * wr, dtype * wi) { #ifndef aMat #define aMat(k, j) AHess[((j) - 1) * nLPC + (k) - 1] #endif int nn, m, l, k, j, i, its, mmin, nLPC_SQR = nLPC * nLPC; /* dtype AHess[maxNLPC_squared]; */ dtype z, y, x, w, v, u, t, s, r, q, p, anorm = 0.0F; /* generate companion matrix, starting off with an intialized version */ DSPF_dp_blk_move(Acompanion, AHess, nLPC_SQR); for (i = 0; i < nLPC; i++) AHess[nLPC * i] = -c[i + 1]; /* end of companion matrix generation */ /* the following performs the hqr algoritm */ /* NOTE: This was taken from Numerical Recipes in C, with modification Specifically, the wr and wi arrays were assumed to number from 1..n in the book. I modified calls to these arrays so that they number 0..n-1 Additionally, n (the order of the polynomial) is hardset to be 8 VV 19 June 2003 */ for (i = 1; i < nLPC + 1; i++) for (j = imax(i - 1, 1); j < nLPC + 1; j++) anorm += fabs(aMat(i, j)); /*anorm += fabs(AHess[(j - 1) * nLPC + i - 1]);*/ nn = nLPC; t = 0.0; while (nn >= 1) { its=0; do { for (l = nn; l >= 2; l--) { s = fabs(aMat(l - 1, l - 1)) + fabs(aMat(l, l)); /*s = fabs(AHess[(l - 2) * nLPC + l - 2]) + fabs(AHess[(l - 1) * nLPC + l - 1]);*/ if (s == 0.0) { s = anorm; } if (static_cast<dtype>(fabs(aMat(l, l - 1)) + s) == s) { /*if ((dtype) (fabs(AHess[(l - 2) * nLPC + l - 1]) + s) == s)*/ break; } } x=aMat(nn, nn); /*x = AHess[(nn - 1) * nLPC + nn - 1];*/ if (l == nn) { wr[(-1) + nn] = x + t; wi[(-1) + nn--] = 0.0; } else { y = aMat(nn - 1 ,nn - 1); /*y = AHess[(nn - 2) * nLPC + nn - 2];*/ w = aMat(nn, nn - 1) * aMat(nn - 1, nn); /*w = AHess[(nn - 2) * nLPC + nn - 1] * AHess[(nn - 2) * nLPC + nn - 1];*/ if (l == (nn-1)) { p = 0.5 * (y - x); q = p * p + w; z=sqrt(fabs(q)); x += t; if (q >= 0.0) { z = p + mul_sign(z, p); wr[(-1) + nn - 1] = wr[(-1) + nn] = x + z; if (z) wr[(-1) + nn] = x - w / z; wi[(-1) + nn - 1] = wi[(-1) + nn] = 0.0; } else { wr[(-1) + nn - 1] = wr[(-1) + nn] = x + p; wi[(-1) + nn - 1] = -(wi[(-1) + nn] = z); } nn -= 2; } else { if (its == 10 || its == 20) { t += x; for (i = 1; i <= nn; i++) aMat(i, i) -= x; /*AHess[(i - 1) * nLPC + i - 1] -= x;*/ s = fabs(aMat(nn, nn - 1)) + fabs(aMat(nn - 1, nn - 2)); /*s = fabs(AHess[(nn - 2) * nLPC + nn - 1]) + fabs(AHess[(nn - 3) * nLPC + nn - 2]);*/ y = x = 0.75 * s; w = -0.4375 * s * s; } ++its; for (m = nn - 2; m >= l; m--) { z = aMat(m, m); /*z = AHess[(m - 1) * nLPC + m - 1];*/ r = x - z; s = y - z; p = (r * s - w) / aMat(m + 1, m) + aMat(m, m + 1); /*p = (r * s - w) / AHess[(m - 1) * nLPC + m] + AHess[m * nLPC + m - 1];*/ q = aMat(m + 1, m + 1) - z - r - s; /*q = AHess[m * nLPC + m] - z - r - s;*/ r = aMat(m + 2, m + 1); /*r = AHess[m * nLPC + m + 1];*/ s = fabs(p) + fabs(q) + fabs(r); p /= s; q /= s; r /= s; if (m == l) break; u = fabs(aMat(m, m - 1)) * (fabs(q) + fabs(r)); /*u = fabs(AHess[(m - 2) * nLPC + m - 1]) * (fabs(q) + fabs(r));*/ v = fabs(p) * (fabs(aMat(m - 1, m - 1)) + fabs(z) + fabs(aMat(m + 1, m + 1))); /*v = fabs(p) * (fabs(AHess[(m - 2) * nLPC + m - 2]) + fabs(z) + fabs(AHess[m * nLPC + m]));*/ if (static_cast<dtype>(u + v) == v) { break; } } for (i = m + 2; i <= nn; i++) { aMat(i, i - 2) = 0.0F; //AHess[(i - 3) * nLPC + i - 1] = 0.0F; if (i != (m + 2)) aMat(i, i - 3) = 0.0F; /*AHess[(i - 4) * nLPC + i - 1] = 0.0F;*/ } for (k = m; k <= nn - 1; k++) { if (k != m) { p = aMat(k, k - 1); /*p = AHess[(k - 2) * nLPC + k - 1];*/ q = aMat(k + 1,k - 1); /*p = AHess[(k - 2) * nLPC + k];*/ r = 0.0F; if (k != (nn - 1)) r = aMat(k + 2, k - 1); /*r = AHess[(k - 2) * nLPC + k + 1];*/ if ((x = fabs(p) + fabs(q) + fabs(r)) != 0.0) { p /= x; q /= x; r /= x; } } if ((s = mul_sign(sqrt(p * p + q * q + r * r), p)) != 0.0) { if (k == m) { if (l != m) aMat(k,k-1) = -aMat(k,k-1); /*AHess[(k - 2) * nLPC + k - 1] *= -1.0;*/ } else aMat(k, k - 1) = -s * x; /*AHess[(k - 2) * nLPC + k - 1] = -s * x;*/ p += s; x=p/s; y=q/s; z=r/s; q /= p; r /= p; for (j=k;j<=nn;j++) { p=aMat(k,j)+q*aMat(k+1,j); /*p = AHess[(j - 1) * nLPC + k - 1] + q * AHess[(j - 1) * nLPC + k];*/ if (k != (nn-1)) { p += r * aMat(k + 2, j); /*p += r * AHess[(j - 1) * nLPC + k + 1];*/ aMat(k + 2, j) -= p * z; /* AHess[(j - 1) * nLPC + k + 1] -= p * z;*/ } aMat(k+1,j) -= p*y; /*AHess[(j - 1) * nLPC + k] -= p * y;*/ aMat(k,j) -= p*x; /*AHess[(j - 1) * nLPC + k - 1] -= p * x;*/ } mmin = nn<k+3 ? nn : k+3; for (i=l;i<=mmin;i++) { p = x * aMat(i, k) + y * aMat(i, k + 1); /*p = x * AHess[(k - 1) * nLPC + i - 1] + y * AHess[k * nLPC + i - 1];*/ if (k != (nn-1)) { p += z*aMat(i,k+2); /*p += z * AHess[(k + 1) * nLPC + i - 1];*/ aMat(i,k+2) -= p*r; /*AHess[(k + 1) * nLPC + i - 1] -= p * r;*/ } aMat(i,k+1) -= p*q; /*AHess[k * nLPC + i - 1] -= p * q;*/ aMat(i,k) -= p; /*AHess[(k - 1) * nLPC + i - 1] -= p;*/ } } } } } } while (l < nn - 1); } if (nn == 0) return 1; else return 0; } /* Autocorrelation-based LPC analysis Performs the LPC analysis on a given frame... returns the lpc coefficients Input arguments xx: input buffer pointer aa: LPC coefficients pointer (output) size: size of the input buffer (xx) nlpc: LPC order, i.e., number of LPC coefficients SC (2008/05/06): Incoroporating cepstral lifting */ void LPFormantTracker::getAi(dtype* xx, dtype* aa) { int i0; //dtype temp_frame[maxBufLen + maxNLPC]; // Utility buffer for various filtering operations //dtype R[maxNLPC]; // lpc fit Autocorrelation estimate int nlpcplus1 = nLPC + 1; for(i0 = 0; i0 < nlpcplus1; i0++) temp_frame[i0] = 0; // Window input //SC vecmu1: vector multiply //SC hwin: a Hanning window DSPF_dp_vecmul(xx, winFunc, &temp_frame[nlpcplus1], bufferSize); // Apply a Hanning window // TODO: Check temp_frame size //////////////////////////////////////////////////// //SC(2008/05/07) ----- Cepstral lifting ----- if (bCepsLift){ for (i0 = 0; i0 < nFFT; i0++){ if (i0 < bufferSize){ ftBuf1[i0 * 2] = temp_frame[nlpcplus1 + i0]; ftBuf1[i0 * 2 + 1] = 0; } else { ftBuf1[i0 * 2] = 0; ftBuf1[i0 * 2 + 1] = 0; } } DSPF_dp_cfftr2(nFFT, ftBuf1, fftc, 1); bit_rev(ftBuf1, nFFT); // Now ftBuf1 is X for (i0 = 0; i0 < nFFT; i0++){ if (i0 <= nFFT / 2){ ftBuf2[i0 * 2] = log(sqrt(ftBuf1[i0 * 2] * ftBuf1[i0 * 2] + ftBuf1[i0 * 2 + 1] * ftBuf1[i0 * 2 + 1])); // Optimize ftBuf2[i0 * 2 + 1] = 0; } else{ ftBuf2[i0 * 2] = ftBuf2[(nFFT - i0) * 2]; ftBuf2[i0 * 2 + 1] = 0; } } DSPF_dp_icfftr2(nFFT, ftBuf2, fftc, 1); bit_rev(ftBuf2, nFFT); // Now ftBuf2 is Xceps: the cepstrum const int minCepstralIndex = bTrackPitch ? static_cast<int>(sr / pitchUpperBoundHz) : -1; const int maxCepstralIndex = bTrackPitch ? static_cast<int>(sr / pitchLowerBoundHz) : -1; for (i0 = 0; i0 < nFFT; i0++){ if (i0 < cepsWinWidth || i0 > nFFT - cepsWinWidth){ // Adjust! ftBuf1[i0 * 2] = ftBuf2[i0 * 2] / nFFT; // Normlize the result of the previous IFFT ftBuf1[i0 * 2 + 1] = 0; } else { ftBuf1[i0 * 2] = 0; ftBuf1[i0 * 2 + 1] = 0; } } if (bTrackPitch) { std::vector<std::pair<int, dtype>> indexMags; for (int i = minCepstralIndex; i < maxCepstralIndex; ++i) { indexMags.push_back(std::make_pair( i, ftBuf2[i * 2] * ftBuf2[i * 2] + ftBuf2[i * 2 + 1] * ftBuf2[i * 2 + 1])); } latestPitchHz = smoothPitchTracker.track(indexMags); } // Now ftBuf1 is Xcepw: the windowed cepstrum DSPF_dp_cfftr2(nFFT,ftBuf1,fftc,1); bit_rev(ftBuf1,nFFT); for (i0=0;i0<nFFT;i0++){ if (i0<=nFFT/2){ ftBuf2[i0*2]=exp(ftBuf1[i0*2]); ftBuf2[i0*2+1]=0; } else{ ftBuf2[i0*2]=ftBuf2[(nFFT-i0)*2]; ftBuf2[i0*2+1]=0; } } DSPF_dp_icfftr2(nFFT,ftBuf2,fftc,1); // Need normalization bit_rev(ftBuf2,nFFT); for (i0 = 0; i0 < bufferSize / 2; i0++){ temp_frame[nlpcplus1 + bufferSize / 2 + i0] = ftBuf2[i0 * 2] / nFFT; } for (i0 = 1; i0 < bufferSize / 2; i0++){ temp_frame[nlpcplus1 + bufferSize / 2 - i0] = ftBuf2[i0 * 2] / nFFT; } temp_frame[nlpcplus1] = 0.0; } //~SC(2008/05/07) ----- Cepstral lifting ----- /////////////////////////////////////////////////////////// // Find autocorrelation values DSPF_dp_autocor(R, temp_frame, bufferSize, nlpcplus1); //SC Get LPC coefficients by autocorrelation // Get unbiased autocorrelation for(i0 = 0; i0 < nlpcplus1; i0++) R[i0] /= bufferSize; // levinson recursion levinson(R, aa, nlpcplus1); } /* Get the angle (Phi) and magnitude (Bw) of the roots Input argments: wr: real part of roots wi: imag part of roots radius: root radii (output) phi: root angle (output) bandwidth: root bandwidth (output) */ void LPFormantTracker::getRPhiBw(dtype * wr, dtype * wi, dtype * radius, dtype * phi, dtype * bandwidth) { /* The following sorts the roots in wr and wi. It is adapted from a matlab script that Reiner wrote */ /*const int maxNLPC = 64;*/ //if (nLPC > maxNLPC) // mexErrMsgTxt("getRPhiBw: nLPC too large"); dtype arc[maxNLPC], arc2[maxNLPC], wr2[maxNLPC], wi2[maxNLPC]; dtype wreal, wimag, warc, wmag, mag[maxNLPC], mag2[maxNLPC]; int numroots, i0, j0, nmark; /* calculate angles for all defined roots */ numroots = 0; for (i0=0; i0 < nLPC; i0++) { arc[i0] = atan2(wi[i0],wr[i0]); mag[i0] = sqrt(wi[i0]*wi[i0] + wr[i0]*wr[i0]); if ( /*(arc[i0] > F1_min) && */ (wi[i0]>0) /*&& (mag[i0] > 0.9) && (mag[i0] < 1.0) */ ) /* only store positive arc root of conjugate pairs */ { mag2[numroots] = mag[i0]; arc2[numroots] = arc[i0]; wr2[numroots] = wr[i0]; wi2[numroots++] = wi[i0]; } } /* sort according to arc using a stupid sort algorithm. */ for (i0=0; i0<numroots; i0++) /* look for minimal first */ { nmark = i0; for (j0=i0+1; j0<numroots; j0++) /* find smallest arc (frequency) */ if (arc2[j0] < arc2[nmark]) nmark = j0; if (nmark != i0) /* switch places if smaller arc */ { wreal = wr2[i0]; wimag = wi2[i0]; warc = arc2[i0]; wmag = mag2[i0]; wr2[i0] = wr2[nmark]; wi2[i0] = wi2[nmark]; arc2[i0] = arc2[nmark]; mag2[i0] = mag2[nmark]; wr2[nmark] = wreal; wi2[nmark] = wimag; arc2[nmark] = warc; mag2[nmark] = wmag; } } for (i0=0; i0<numroots; i0++) { radius[i0]=mag2[i0]; bandwidth[i0] = -log(mag2[i0]) * dtype(sr) / M_PI; phi[i0]=arc2[i0]; } } /* Dynamic programming based formant tracking (Xia and Espy-Wilson, 2000, ICSLP) Input: r_ptr: array of amplitudes of the roots phi_ptr: array of phase angles of the roots In-place operations are done on r_ptr and phi_ptr. */ void LPFormantTracker::trackPhi(dtype *r_ptr, dtype *phi_ptr) { //dtype cumMat[maxFmtTrackJump][maxNTracks];// cumulative cost matrix //dtype costMat[maxFmtTrackJump][maxNTracks];// local cost Mat // just for debugging const dtype fmts_min[maxNTracks] = {0, 350, 1200, 2000, 3000}; // defines minimal value for each formant const dtype fmts_max[maxNTracks] = {1500, 3500, 4500, 5000, 7000};// defines maximal value for each formant dtype fn[maxNTracks] = {500, 1500, 2500, 3500, 4500};// neutral formant values (start formants : here vowel [a]) static dtype last_f[maxNTracks]={500,1500,2500,3500,4500};// last moving average estimated formants int f_list[maxNTracks] = {0, 0, 0, 0, 0}; const int tri[maxNTracks] = {0, 1, 2, 3, 4}; dtype this_fmt, this_bw, this_cost, this_cum_cost, low_cost, min_cost, inf_cost=10000000; bool in_range = false; int k = 0, i0 = 0, j0; int bound, indx = 0, new_indx; k = 0; i0 = 0; j0 = 0; fn[0] = fn1; fn[1] = fn2; // loop builds the cumulative cost Matrix cumMat // each column represents the cumulative cost for each node which will be the cost entry value for the next column for (k = 0; k < nTracks; k++) { low_cost=inf_cost; for(i0=k;i0<(nCands-nTracks+k+2);i0++) { //cumMat[i0-k][k]=inf_cost; this_cum_cost=inf_cost; this_fmt=phi_ptr[i0]*sr/(2*M_PI); this_bw=-log(r_ptr[i0])*sr/M_PI; if((this_fmt>fmts_min[k]) && (this_fmt<fmts_max[k]))// check if actual formant is in range { in_range=true; this_cost=aFact*this_bw+bFact*fabs(this_fmt-fn[k])+gFact*fabs(this_fmt-last_f[k]);//calc local cost costMat[(i0 - k) + k * maxFmtTrackJump]=this_cost; if (k==0)// build first column: cumulative cost = local cost this_cum_cost=this_cost; else// build all other columns: cumulative cost(this column) = cumulative cost(previous column)+local cost this_cum_cost = cumMat[(i0 - k) + (k - 1) * maxFmtTrackJump] + this_cost; if (this_cum_cost<low_cost) low_cost=this_cum_cost;// low_cost is the lowest cumulative cost of all elements in this column until element [i0] (included) // therefore, for each column :i0=0 low_cost=cumulative cost // :i0=n low_cost=min(cumulative_cost(from 0 to [n])) } if (k<nTracks-1)// for all columns except last cumMat[(i0 - k) + k * maxFmtTrackJump] = low_cost;//ATTENTION: represents the minimal cost that serves as entry cost for the next node (same row element, but next column) else// last column cumMat[(i0 - k) + k * maxFmtTrackJump] = this_cum_cost;//shows the overall accumulated cost... from here will start the viterbi traceback } } bound=nCands-nTracks+2;// VERY IMPORTANT!!! because values of cumMat beyond this point are not referenced !! indx=0; // viterbi traceback updates index vector f_list // ATTENTION!!! f_list is not the definitive index vector.. has to be diagonalised for(k=0;k<nTracks;k++) { min_cost=inf_cost; for(i0=0;i0<bound;i0++) { if(cumMat[i0 + (nTracks - k - 1) * maxFmtTrackJump] < min_cost) { min_cost=cumMat[i0 + (nTracks - k - 1) * maxFmtTrackJump]; indx=i0; } } if(indx==0) break; else { bound=indx+1; f_list[nTracks-k-1]=indx; } } // update r, phi and last_f for(k=0;k<nTracks;k++) { new_indx = f_list[k]+k;// rediagonalize index vector r_ptr[k] = r_ptr[new_indx]; phi_ptr[k] = phi_ptr[new_indx]; last_f[k] = (1 - trackFF) * phi_ptr[k] * sr / (2 * M_PI) + trackFF * last_f[k]; } } /* Computational efficient weithed moving average Input arguments: phi_ptr: unaveraged phi bw_ptr: unaveraged bw wmaPhi_ptr: moving-averaged phi Return value: */ int LPFormantTracker::mwa(dtype * phi_ptr, dtype * bw_ptr, dtype * wmaPhi_ptr) { int circ_indx_sub = 0; circ_indx_sub = (mwaCtr++ - avgLen) % maxAvgLen; // points to the data to withdraw from sum if (circ_indx_sub < 0) circ_indx_sub += maxAvgLen; sumWei += weiVec[mwaCircCtr] - weiVec[circ_indx_sub]; // update weighting sum for (int i0 = 0; i0 < nTracks; ++i0) { weiMatPhi[i0 + nTracks * mwaCircCtr] = weiVec[mwaCircCtr] * phi_ptr[i0]; weiMatBw[i0 + nTracks * mwaCircCtr] = weiVec[mwaCircCtr] * bw_ptr[i0]; sumWeiPhi[i0] += weiMatPhi[i0 + nTracks * mwaCircCtr] - weiMatPhi[i0 + nTracks * circ_indx_sub]; sumWeiBw[i0] += weiMatBw[i0 + nTracks * mwaCircCtr] - weiMatBw[i0 + nTracks * circ_indx_sub]; if (sumWei > 0.0000001) { wmaPhi_ptr[i0] = sumWeiPhi[i0] / sumWei; } else { mwaCircCtr = mwaCtr % maxAvgLen; return 1; } } mwaCircCtr = mwaCtr % maxAvgLen; return 0; } /* Public interface: process incoming frame Input arguments: xx: input signal frame (assume length == bufferSize) st_rms: short-time RMS intensity, used by the moving weighted average algorithm if bMWA == true TODO: radius, phi, bandwidth fmts: (output) formant frequencies */ void LPFormantTracker::procFrame(dtype * xx, dtype st_rms, dtype * radius, dtype * phi, dtype * bandwidth, dtype * fmts) { //Marked for (int i0 = 0; i0 < nLPC + 1; i0++) { //SC Initialize the order LPC coefficients lpcAi[i0] = 0.0; // TODO: Incorporate into fmtTracker } getAi(xx, lpcAi); int quit_hqr = hqr_roots(lpcAi, realRoots, imagRoots); /*getRPhiBw(realRoots, imagRoots, radius, phi, bandwidth);*/ getRPhiBw(realRoots, imagRoots, radius, phi_us, bandwidth); /*trackPhi(radius, phi);*/ trackPhi(radius, phi_us); /* Moving window average (MWA) (Optional, but highly recommended) */ weiVec[mwaCircCtr] = st_rms; if (bMWA) { mwa(phi_us, bandwidth, phi); } else { /* Copy from phi_us to phi */ for (int i = 0; i < nTracks; ++i) { phi[i] = phi_us[i]; } } for (int i = 0; i < nTracks; ++i) { //Marked fmts[i] = phi[i] * sr / (2 * M_PI); } } /* Setters and getters (inline) */ void LPFormantTracker::setBCepsLift(const bool t_bCepsLift) { bCepsLift = t_bCepsLift; } void LPFormantTracker::setNLPC(const int t_nLPC) { nLPC = t_nLPC; } void LPFormantTracker::setBufferSize(const int t_bufferSize) { bufferSize = t_bufferSize; } void LPFormantTracker::setNFFT(const int t_nFFT) { nFFT = t_nFFT; /* TODO: re-initiliaze windows */ } void LPFormantTracker::setCepsWinWidth(const int t_cepsWinWidth) { cepsWinWidth = t_cepsWinWidth; /* TODO: re-initialize FFT data */ } void LPFormantTracker::genHanningWindow() { for(int i0 = 0; i0 < bufferSize; i0++){ /* Total length: p.anaLen */ winFunc[i0] = 0.5*cos(dtype(2 * M_PI * (i0 + 1)) / dtype(bufferSize + 1)); //Marked winFunc[i0] = 0.5 - winFunc[i0]; //Marked winFunc[bufferSize - i0 - 1] = winFunc[i0]; } } const int LPFormantTracker::getNLPC() const { return nLPC; } const dtype LPFormantTracker::getLatestPitchHz() const { return latestPitchHz; }
28.543945
175
0.533203
084
0bdcba48167abd60cf2d47c88ae6aa54b2fb565c
22,443
hpp
C++
lib/mtl4/boost/numeric/mtl/interface/umfpack_solve.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
2
2018-07-04T16:44:04.000Z
2021-01-03T07:26:27.000Z
lib/mtl4/boost/numeric/mtl/interface/umfpack_solve.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
lib/mtl4/boost/numeric/mtl/interface/umfpack_solve.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
// Software License for MTL // // Copyright (c) 2007 The Trustees of Indiana University. // 2008 Dresden University of Technology and the Trustees of Indiana University. // 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com. // All rights reserved. // Authors: Peter Gottschling and Andrew Lumsdaine // // This file is part of the Matrix Template Library // // See also license.mtl.txt in the distribution. #ifndef MTL_MATRIX_UMFPACK_SOLVE_INCLUDE #define MTL_MATRIX_UMFPACK_SOLVE_INCLUDE #ifdef MTL_HAS_UMFPACK #include <iostream> #include <cassert> #include <algorithm> #include <boost/mpl/bool.hpp> #include <boost/numeric/mtl/matrix/compressed2D.hpp> #include <boost/numeric/mtl/matrix/parameter.hpp> #include <boost/numeric/mtl/concept/collection.hpp> #include <boost/numeric/mtl/utility/exception.hpp> #include <boost/numeric/mtl/utility/make_copy_or_reference.hpp> #include <boost/numeric/mtl/operation/merge_complex_vector.hpp> #include <boost/numeric/mtl/operation/split_complex_vector.hpp> #include <boost/numeric/mtl/interface/vpt.hpp> extern "C" { # include <umfpack.h> } namespace mtl { namespace matrix { /// Namespace for Umfpack solver namespace umfpack { // conversion for value_type needed if not double or complex<double> (where possible) template <typename Value> struct value {}; template<> struct value<long double> { typedef double type; }; template<> struct value<double> { typedef double type; }; template<> struct value<float> { typedef double type; }; template<> struct value<std::complex<long double> > { typedef std::complex<double> type; }; template<> struct value<std::complex<double> > { typedef std::complex<double> type; }; template<> struct value<std::complex<float> > { typedef std::complex<double> type; }; template <typename Value> struct use_long { static const bool value= sizeof(Value) > sizeof(int); }; template <bool Larger> struct index_aux { typedef int type; }; #if defined(UF_long) template<> struct index_aux<true> { typedef UF_long type; }; #elif defined(SuiteSparse_long) template<> struct index_aux<true> { typedef SuiteSparse_long type; }; #else template<> struct index_aux<true> { typedef long type; }; #endif template <typename Value> struct index : index_aux<use_long<Value>::value> {}; template <typename Matrix, typename Value, typename Orientation> struct matrix_copy {}; // If arbitrary compressed matrix -> copy template <typename Value, typename Parameters, typename Orientation> struct matrix_copy<compressed2D<Value, Parameters>, Value, Orientation> { typedef typename value<Value>::type value_type; typedef compressed2D<value_type, parameters<col_major> > matrix_type; typedef compressed2D<Value, Parameters> in_matrix_type; matrix_copy(const in_matrix_type& A) : matrix(A) {} matrix_type matrix; }; struct error : public domain_error { error(const char *s, int code) : domain_error(s), code(code) {} int code; }; inline void check(int res, const char* s) { MTL_THROW_IF(res != UMFPACK_OK, error(s, res)); } /// Class for repeated Umfpack solutions /** Keeps symbolic and numeric preprocessing. Numeric part can be updated. Only defined for compressed2D<double> and compressed2D<complex<double> >. **/ template <typename T> class solver { public: /// Constructor referring to matrix \p A (not changed) and optionally Umfpack's strategy and alloc_init (look for the specializations) // \ref solver<compressed2D<double, Parameters> > and \ref solver<compressed2D<std::complex<double>, Parameters> >) explicit solver(const T& /*A*/) {} /// Update numeric part, for matrices that kept the sparsity and changed the values void update_numeric() {} /// Update symbolic and numeric part void update() {} /// Solve system A*x == b with matrix passed in constructor /** Please note that the order of b and x is different than in solve() !!! **/ template <typename VectorX, typename VectorB> int operator()(VectorX& /*x*/, const VectorB& /*b*/) const {return 0;} /// Solve system A*x == b with matrix passed in constructor /** Please note that the order of b and x is different than in operator() !!! **/ template <typename VectorB, typename VectorX> int operator()(const VectorB& /*b*/, VectorX& /*x*/) const {return 0;} }; /// Speciatization of solver for \ref matrix::compressed2D with double values template <typename Parameters> class solver<compressed2D<double, Parameters> > { typedef double value_type; typedef compressed2D<value_type, Parameters> matrix_type; typedef typename matrix_type::size_type size_type; typedef typename index<size_type>::type index_type; static const bool copy_indices= sizeof(index_type) != sizeof(size_type), long_indices= use_long<size_type>::value; typedef boost::mpl::bool_<long_indices> blong; typedef boost::mpl::true_ true_; typedef boost::mpl::false_ false_; // typedef parameters<col_major> Parameters; void assign_pointers() { if (copy_indices) { if (Apc == 0) Apc= new index_type[n + 1]; if (my_nnz != A.nnz() && Aic) { delete[] Aic; Aic= 0; } if (Aic == 0) Aic= new index_type[A.nnz()]; std::copy(A.address_major(), A.address_major() + n + 1, Apc); std::copy(A.address_minor(), A.address_minor() + A.nnz(), Aic); Ap= Apc; Ai= Aic; } else { Ap= reinterpret_cast<const index_type*>(A.address_major()); Ai= reinterpret_cast<const index_type*>(A.address_minor()); } Ax= A.address_data(); } void init_aux(true_) { check(umfpack_dl_symbolic(n, n, Ap, Ai, Ax, &Symbolic, Control, Info), "Error in dl_symbolic"); check(umfpack_dl_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info), "Error in dl_numeric"); } void init_aux(false_) { check(umfpack_di_symbolic(n, n, Ap, Ai, Ax, &Symbolic, Control, Info), "Error in di_symbolic"); #if 0 std::cout << "=== INFO of umfpack_*_symbolic ===\n"; std::cout << " UMFPACK_STATUS: " << (Info[UMFPACK_STATUS] == UMFPACK_OK ? "OK" : "ERROR") << "\n"; std::cout << " UMFPACK_NROW: " << Info[UMFPACK_NROW] << "\n"; std::cout << " UMFPACK_NCOL: " << Info[UMFPACK_NCOL] << "\n"; std::cout << " UMFPACK_NZ: " << Info[UMFPACK_NZ] << "\n"; std::cout << " UMFPACK_SIZE_OF_UNIT: " << Info[UMFPACK_SIZE_OF_UNIT] << "\n"; std::cout << " UMFPACK_NDENSE_ROW: " << Info[UMFPACK_NDENSE_ROW] << "\n"; std::cout << " UMFPACK_NEMPTY_ROW: " << Info[UMFPACK_NEMPTY_ROW] << "\n"; std::cout << " UMFPACK_NDENSE_COL: " << Info[UMFPACK_NDENSE_COL] << "\n"; std::cout << " UMFPACK_NEMPTY_COL: " << Info[UMFPACK_NEMPTY_COL] << "\n"; std::cout << " UMFPACK_SYMBOLIC_DEFRAG: " << Info[UMFPACK_SYMBOLIC_DEFRAG] << "\n"; std::cout << " UMFPACK_SYMBOLIC_PEAK_MEMORY: " << Info[UMFPACK_SYMBOLIC_PEAK_MEMORY] << "\n"; std::cout << " UMFPACK_SYMBOLIC_SIZE: " << Info[UMFPACK_SYMBOLIC_SIZE] << "\n"; std::cout << " UMFPACK_VARIABLE_PEAK_ESTIMATE: " << Info[UMFPACK_VARIABLE_PEAK_ESTIMATE] << "\n"; std::cout << " UMFPACK_NUMERIC_SIZE_ESTIMATE: " << Info[UMFPACK_NUMERIC_SIZE_ESTIMATE] << "\n"; std::cout << " UMFPACK_PEAK_MEMORY_ESTIMATE: " << Info[UMFPACK_PEAK_MEMORY_ESTIMATE] << "\n"; std::cout << " UMFPACK_FLOPS_ESTIMATE: " << Info[UMFPACK_FLOPS_ESTIMATE] << "\n"; std::cout << " UMFPACK_LNZ_ESTIMATE: " << Info[UMFPACK_LNZ_ESTIMATE] << "\n"; std::cout << " UMFPACK_UNZ_ESTIMATE: " << Info[UMFPACK_UNZ_ESTIMATE] << "\n"; std::cout << " UMFPACK_MAX_FRONT_SIZE_ESTIMATE: " << Info[UMFPACK_MAX_FRONT_SIZE_ESTIMATE] << "\n"; std::cout << " UMFPACK_SYMBOLIC_TIME: " << Info[UMFPACK_SYMBOLIC_TIME] << "\n"; std::cout << " UMFPACK_SYMBOLIC_WALLTIME: " << Info[UMFPACK_SYMBOLIC_WALLTIME] << "\n"; if (Info[UMFPACK_STRATEGY_USED] == UMFPACK_STRATEGY_SYMMETRIC) std::cout << " UMFPACK_STRATEGY_USED: SYMMETRIC\n"; else { if(Info[UMFPACK_STRATEGY_USED] == UMFPACK_STRATEGY_UNSYMMETRIC) std::cout << " UMFPACK_STRATEGY_USED: UNSYMMETRIC\n"; else { if (Info[UMFPACK_STRATEGY_USED] == UMFPACK_STRATEGY_2BY2) std::cout << " UMFPACK_STRATEGY_USED: 2BY2\n"; else std::cout << " UMFPACK_STRATEGY_USED: UNKOWN STRATEGY " << Info[UMFPACK_STRATEGY_USED] << "\n"; } } std::cout << " UMFPACK_ORDERING_USED: " << Info[UMFPACK_ORDERING_USED] << "\n"; std::cout << " UMFPACK_QFIXED: " << Info[UMFPACK_QFIXED] << "\n"; std::cout << " UMFPACK_DIAG_PREFERRED: " << Info[UMFPACK_DIAG_PREFERRED] << "\n"; std::cout << " UMFPACK_ROW_SINGLETONS: " << Info[UMFPACK_ROW_SINGLETONS] << "\n"; std::cout << " UMFPACK_COL_SINGLETONS: " << Info[UMFPACK_COL_SINGLETONS] << "\n"; std::cout << " UMFPACK_PATTERN_SYMMETRY: " << Info[UMFPACK_PATTERN_SYMMETRY] << "\n"; std::cout << " UMFPACK_NZ_A_PLUS_AT: " << Info[UMFPACK_NZ_A_PLUS_AT] << "\n"; std::cout << " UMFPACK_NZDIAG: " << Info[UMFPACK_NZDIAG] << "\n"; std::cout << " UMFPACK_N2: " << Info[UMFPACK_N2] << "\n"; std::cout << " UMFPACK_S_SYMMETRIC: " << Info[UMFPACK_S_SYMMETRIC] << "\n"; std::cout << " UMFPACK_MAX_FRONT_NROWS_ESTIMATE: " << Info[UMFPACK_MAX_FRONT_NROWS_ESTIMATE] << "\n"; std::cout << " UMFPACK_MAX_FRONT_NCOLS_ESTIMATE: " << Info[UMFPACK_MAX_FRONT_NCOLS_ESTIMATE] << "\n"; std::cout << " UMFPACK_SYMMETRIC_LUNZ: " << Info[UMFPACK_SYMMETRIC_LUNZ] << "\n"; std::cout << " UMFPACK_SYMMETRIC_FLOPS: " << Info[UMFPACK_SYMMETRIC_FLOPS] << "\n"; std::cout << " UMFPACK_SYMMETRIC_NDENSE: " << Info[UMFPACK_SYMMETRIC_NDENSE] << "\n"; std::cout << " UMFPACK_SYMMETRIC_DMAX: " << Info[UMFPACK_SYMMETRIC_DMAX] << "\n"; #endif check(umfpack_di_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info), "Error in di_numeric"); #if 0 std::cout << "=== INFO of umfpack_*_numeric ===\n"; std::cout << " UMFPACK_STATUS: " << (Info[UMFPACK_STATUS] == UMFPACK_OK ? "OK" : "ERROR") << "\n"; std::cout << " UMFPACK_VARIABLE_PEAK: " << Info[UMFPACK_VARIABLE_PEAK] << "\n"; std::cout << " UMFPACK_PEAK_MEMORY: " << Info[UMFPACK_PEAK_MEMORY] << "\n"; std::cout << " UMFPACK_FLOPS: " << Info[UMFPACK_FLOPS] << "\n"; std::cout << " UMFPACK_LNZ: " << Info[UMFPACK_LNZ] << "\n"; std::cout << " UMFPACK_UNZ: " << Info[UMFPACK_UNZ] << "\n"; std::cout << " UMFPACK_NUMERIC_DEFRAG: " << Info[UMFPACK_NUMERIC_DEFRAG] << "\n"; std::cout << " UMFPACK_NUMERIC_REALLOC: " << Info[UMFPACK_NUMERIC_REALLOC] << "\n"; std::cout << " UMFPACK_NUMERIC_COSTLY_REALLOC: " << Info[UMFPACK_NUMERIC_COSTLY_REALLOC] << "\n"; std::cout << " UMFPACK_COMPRESSED_PATTERN: " << Info[UMFPACK_COMPRESSED_PATTERN] << "\n"; std::cout << " UMFPACK_LU_ENTRIES: " << Info[UMFPACK_LU_ENTRIES] << "\n"; std::cout << " UMFPACK_NUMERIC_TIME: " << Info[UMFPACK_NUMERIC_TIME] << "\n"; std::cout << " UMFPACK_RCOND: " << Info[UMFPACK_RCOND] << "\n"; std::cout << " UMFPACK_UDIAG_NZ: " << Info[UMFPACK_UDIAG_NZ] << "\n"; std::cout << " UMFPACK_UMIN: " << Info[UMFPACK_UMIN] << "\n"; std::cout << " UMFPACK_UMAX: " << Info[UMFPACK_UMAX] << "\n"; std::cout << " UMFPACK_MAX_FRONT_NROWS: " << Info[UMFPACK_MAX_FRONT_NROWS] << "\n"; std::cout << " UMFPACK_MAX_FRONT_NCOLS: " << Info[UMFPACK_MAX_FRONT_NCOLS] << "\n"; std::cout << " UMFPACK_ALL_LNZ: " << Info[UMFPACK_ALL_LNZ] << "\n"; std::cout << " UMFPACK_ALL_UNZ: " << Info[UMFPACK_ALL_UNZ] << "\n"; #endif } void init() { MTL_THROW_IF(num_rows(A) != num_cols(A), matrix_not_square()); n= num_rows(A); assign_pointers(); init_aux(blong()); } public: /// Constructor referring to matrix \p A (not changed) and optionally Umfpack's strategy and alloc_init solver(const matrix_type& A, int strategy = UMFPACK_STRATEGY_AUTO, double alloc_init = 0.7) : A(A), Apc(0), Aic(0), my_nnz(0), Symbolic(0), Numeric(0) { vampir_trace<5060> trace; // Use default setings. if (long_indices) umfpack_dl_defaults(Control); else umfpack_di_defaults(Control); Control[UMFPACK_STRATEGY] = strategy; Control[UMFPACK_ALLOC_INIT] = alloc_init; init(); } ~solver() { vampir_trace<5061> trace; if (long_indices) { umfpack_dl_free_numeric(&Numeric); umfpack_dl_free_symbolic(&Symbolic); } else { umfpack_di_free_numeric(&Numeric); umfpack_di_free_symbolic(&Symbolic); } if (Apc) delete[] Apc; if (Aic) delete[] Aic; } void update_numeric_aux(true_) { umfpack_dl_free_numeric(&Numeric); check(umfpack_dl_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info), "Error in dl_numeric"); } void update_numeric_aux(false_) { umfpack_di_free_numeric(&Numeric); check(umfpack_di_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info), "Error in di_numeric"); } /// Update numeric part, for matrices that kept the sparsity and changed the values void update_numeric() { assign_pointers(); update_numeric_aux(blong()); } /// Update symbolic and numeric part void update() { if (long_indices) { umfpack_dl_free_numeric(&Numeric); umfpack_dl_free_symbolic(&Symbolic); } else { umfpack_di_free_numeric(&Numeric); umfpack_di_free_symbolic(&Symbolic); } init(); } template <typename VectorX, typename VectorB> void solve_aux(int sys, VectorX& xx, const VectorB& bb, true_) { check(umfpack_dl_solve(sys, Ap, Ai, Ax, &xx.value[0], &bb.value[0], Numeric, Control, Info), "Error in dl_solve"); } template <typename VectorX, typename VectorB> void solve_aux(int sys, VectorX& xx, const VectorB& bb, false_) { check(umfpack_di_solve(sys, Ap, Ai, Ax, &xx.value[0], &bb.value[0], Numeric, Control, Info), "Error in di_solve"); } /// Solve double system template <typename VectorX, typename VectorB> int operator()(VectorX& x, const VectorB& b) { vampir_trace<5062> trace; MTL_THROW_IF(num_rows(A) != size(x) || num_rows(A) != size(b), incompatible_size()); make_in_out_copy_or_reference<dense_vector<value_type>, VectorX> xx(x); make_in_copy_or_reference<dense_vector<value_type>, VectorB> bb(b); int sys= mtl::traits::is_row_major<Parameters>::value ? UMFPACK_At : UMFPACK_A; solve_aux(sys, xx, bb, blong()); return UMFPACK_OK; } /// Solve double system template <typename VectorB, typename VectorX> int solve(const VectorB& b, VectorX& x) const { // return (*this)(x, b); return const_cast<solver&>(*this)(x, b); // evil hack because Umfpack has no const } private: const matrix_type& A; int n; const index_type *Ap, *Ai; index_type *Apc, *Aic; size_type my_nnz; const double *Ax; double Control[UMFPACK_CONTROL], Info[UMFPACK_INFO]; void *Symbolic, *Numeric; }; /// Speciatization of solver for \ref matrix::compressed2D with double values template <typename Parameters> class solver<compressed2D<std::complex<double>, Parameters> > { typedef std::complex<double> value_type; typedef compressed2D<value_type, Parameters> matrix_type; typedef typename matrix_type::size_type size_type; typedef typename index<size_type>::type index_type; static const bool copy_indices= sizeof(index_type) != sizeof(size_type), long_indices= use_long<size_type>::value; typedef boost::mpl::bool_<long_indices> blong; typedef boost::mpl::true_ true_; typedef boost::mpl::false_ false_; void assign_pointers() { if (copy_indices) { if (Apc == 0) Apc= new index_type[n + 1]; if (Aic == 0) Aic= new index_type[A.nnz()]; std::copy(A.address_major(), A.address_major() + n + 1, Apc); std::copy(A.address_minor(), A.address_minor() + A.nnz(), Aic); Ap= Apc; Ai= Aic; } else { Ap= reinterpret_cast<const index_type*>(A.address_major()); Ai= reinterpret_cast<const index_type*>(A.address_minor()); } split_complex_vector(A.data, Ax, Az); } void init_aux(true_) { check(umfpack_zl_symbolic(n, n, Ap, Ai, &Ax[0], &Az[0], &Symbolic, Control, Info), "Error in zl_symbolic"); check(umfpack_zl_numeric(Ap, Ai, &Ax[0], &Az[0], Symbolic, &Numeric, Control, Info), "Error in zl_numeric"); } void init_aux(false_) { check(umfpack_zi_symbolic(n, n, Ap, Ai, &Ax[0], &Az[0], &Symbolic, Control, Info), "Error in zi_symbolic"); check(umfpack_zi_numeric(Ap, Ai, &Ax[0], &Az[0], Symbolic, &Numeric, Control, Info), "Error in zi_numeric"); } void initialize() { MTL_THROW_IF(num_rows(A) != num_cols(A), matrix_not_square()); n= num_rows(A); assign_pointers(); init_aux(blong()); } public: /// Constructor referring to matrix \p A (not changed) and optionally Umfpack's strategy and alloc_init (look for the specializations) explicit solver(const compressed2D<value_type, Parameters>& A, int strategy = UMFPACK_STRATEGY_AUTO, double alloc_init = 0.7) : A(A), Apc(0), Aic(0) { vampir_trace<5060> trace; // Use default setings. if (long_indices) umfpack_zl_defaults(Control); else umfpack_zi_defaults(Control); // umfpack_zi_defaults(Control); Control[UMFPACK_STRATEGY] = strategy; Control[UMFPACK_ALLOC_INIT] = alloc_init; initialize(); } ~solver() { vampir_trace<5061> trace; if (long_indices) { umfpack_zl_free_numeric(&Numeric); umfpack_zl_free_symbolic(&Symbolic); } else { umfpack_zi_free_numeric(&Numeric); umfpack_zi_free_symbolic(&Symbolic); } if (Apc) delete[] Apc; if (Aic) delete[] Aic; } void update_numeric_aux(true_) { umfpack_zl_free_numeric(&Numeric); check(umfpack_zl_numeric(Ap, Ai, &Ax[0], &Az[0], Symbolic, &Numeric, Control, Info), "Error in dl_numeric D"); } void update_numeric_aux(false_) { umfpack_zi_free_numeric(&Numeric); check(umfpack_zi_numeric(Ap, Ai, &Ax[0], &Az[0], Symbolic, &Numeric, Control, Info), "Error in di_numeric"); } /// Update numeric part, for matrices that kept the sparsity and changed the values void update_numeric() { assign_pointers(); update_numeric_aux(blong()); } /// Update symbolic and numeric part void update() { Ax.change_dim(0); Az.change_dim(0); if (long_indices) { umfpack_zl_free_numeric(&Numeric); umfpack_zl_free_symbolic(&Symbolic); } else { umfpack_zi_free_numeric(&Numeric); umfpack_zi_free_symbolic(&Symbolic); } initialize(); } template <typename VectorX, typename VectorB> void solve_aux(int sys, VectorX& Xx, VectorX& Xz, const VectorB& Bx, const VectorB& Bz, true_) { check(umfpack_zl_solve(sys, Ap, Ai, &Ax[0], &Az[0], &Xx[0], &Xz[0], &Bx[0], &Bz[0], Numeric, Control, Info), "Error in zi_solve"); } template <typename VectorX, typename VectorB> void solve_aux(int sys, VectorX& Xx, VectorX& Xz, const VectorB& Bx, const VectorB& Bz, false_) { check(umfpack_zi_solve(sys, Ap, Ai, &Ax[0], &Az[0], &Xx[0], &Xz[0], &Bx[0], &Bz[0], Numeric, Control, Info), "Error in zi_solve"); } /// Solve complex system template <typename VectorX, typename VectorB> int operator()(VectorX& x, const VectorB& b) { vampir_trace<5062> trace; MTL_THROW_IF(num_rows(A) != size(x) || num_rows(A) != size(b), incompatible_size()); dense_vector<double> Xx(size(x)), Xz(size(x)), Bx, Bz; split_complex_vector(b, Bx, Bz); int sys= mtl::traits::is_row_major<Parameters>::value ? UMFPACK_Aat : UMFPACK_A; solve_aux(sys, Xx, Xz, Bx, Bz, blong()); merge_complex_vector(Xx, Xz, x); return UMFPACK_OK; } /// Solve complex system template <typename VectorB, typename VectorX> int solve(const VectorB& b, VectorX& x) { return (*this)(x, b); } private: const matrix_type& A; int n; const index_type *Ap, *Ai; index_type *Apc, *Aic; dense_vector<double> Ax, Az; double Control[UMFPACK_CONTROL], Info[UMFPACK_INFO]; void *Symbolic, *Numeric; }; template <typename Value, typename Parameters> class solver<compressed2D<Value, Parameters> > : matrix_copy<compressed2D<Value, Parameters>, Value, typename Parameters::orientation>, public solver<typename matrix_copy<compressed2D<Value, Parameters>, Value, typename Parameters::orientation>::matrix_type > { typedef matrix_copy<compressed2D<Value, Parameters>, Value, typename Parameters::orientation> copy_type; typedef solver<typename matrix_copy<compressed2D<Value, Parameters>, Value, typename Parameters::orientation>::matrix_type > solver_type; public: explicit solver(const compressed2D<Value, Parameters>& A) : copy_type(A), solver_type(copy_type::matrix), A(A) {} void update() { copy_type::matrix= A; solver_type::update(); } void update_numeric() { copy_type::matrix= A; solver_type::update_numeric(); } private: const compressed2D<Value, Parameters>& A; }; } // umfpack /// Solve A*x == b with umfpack /** Only available when compiled with enabled macro MTL_HAS_UMFPACK. Uses classes umfpack::solver internally. If you want more control on single operations or to keep umfpack's internal factorization, use this class. **/ template <typename Value, typename Parameters, typename VectorX, typename VectorB> int umfpack_solve(const compressed2D<Value, Parameters>& A, VectorX& x, const VectorB& b) { umfpack::solver<compressed2D<Value, Parameters> > solver(A); return solver(x, b); } }} // namespace mtl::matrix #endif #endif // MTL_MATRIX_UMFPACK_SOLVE_INCLUDE
39.512324
142
0.648666
spraetor
0bdd832726dc6ddca7ecb83a5d60cac34c516680
1,161
cpp
C++
misc/test/mmaptest.cpp
warsier/nstore
0959cba2c68cddab490fd9ded3a92a6baa0cd6fa
[ "BSD-3-Clause" ]
23
2016-10-07T11:13:45.000Z
2022-01-18T06:51:04.000Z
misc/test/mmaptest.cpp
warsier/nstore
0959cba2c68cddab490fd9ded3a92a6baa0cd6fa
[ "BSD-3-Clause" ]
null
null
null
misc/test/mmaptest.cpp
warsier/nstore
0959cba2c68cddab490fd9ded3a92a6baa0cd6fa
[ "BSD-3-Clause" ]
9
2017-07-23T03:39:50.000Z
2022-03-30T11:46:17.000Z
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <errno.h> int main(int argc, char *argv[]) { int fd, offset; char *data; struct stat sbuf; if (argc != 1) { fprintf(stderr, "usage: mmapdemo \n"); exit(1); } fd = open("log", O_RDWR | O_CREAT); if (fd < 0) { perror("open"); exit(1); } size_t len = 8UL * 1024; if (posix_fallocate(fd, 0, len) < 0) { perror("open"); exit(1); } if (stat("log", &sbuf) == -1) { perror("stat"); exit(1); } printf("size : %lu\n", sbuf.st_size); printf("fd : %d\n", fd); caddr_t location = (caddr_t) 0x010000000; if ((data = (char*) mmap(location, sbuf.st_size, PROT_WRITE, MAP_SHARED, fd, 0)) == (caddr_t) (-1)) { perror("mmap"); exit(1); } printf("data : %s %p\n", data, data); char cmd[512]; sprintf(cmd, "cat /proc/%d/maps", getpid()); system(cmd); data[2] = 'x'; char* ptr = (char*) (location + 2); printf("data : %p %c \n", ptr, (*ptr)); msync(data, sbuf.st_size, MS_SYNC); return 0; }
17.861538
78
0.540913
warsier
0be0b0f10e7706f7566e7ada6953dab84a2fee9e
1,676
cpp
C++
Engine/nvImage/src/nvImageHdr.cpp
ansel86castro/Igneel
7a1e6c81e18326aff78be97cc4321f3a610481ff
[ "Apache-2.0" ]
8
2017-03-08T20:20:13.000Z
2021-12-12T20:20:07.000Z
Engine/nvImage/src/nvImageHdr.cpp
ansel86castro/Igneel
7a1e6c81e18326aff78be97cc4321f3a610481ff
[ "Apache-2.0" ]
null
null
null
Engine/nvImage/src/nvImageHdr.cpp
ansel86castro/Igneel
7a1e6c81e18326aff78be97cc4321f3a610481ff
[ "Apache-2.0" ]
4
2018-09-28T15:45:08.000Z
2021-03-22T17:15:46.000Z
// // nvImageHdr.cpp - Image support class // // The nvImage class implements an interface for a multipurpose image // object. This class is useful for loading and formating images // for use as textures. The class supports dds, png, and hdr formats. // // This file implements the HDR specific functionality. // // Author: Evan Hart // Email: [email protected] // // Copyright (c) NVIDIA Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////// #include "rgbe.h" #include "nvImage.h" using std::vector; namespace nv { // // readHdr // // Image loader function for hdr files. //////////////////////////////////////////////////////////// bool Image::readHdr( const char *file, Image& i) { int width, height; FILE *fp = fopen(file, "rb"); if (!fp) { return false; } rgbe_header_info header; if (RGBE_ReadHeader( fp, &width, &height, &header)) { fclose(fp); return false; } GLubyte *data = (GLubyte*)new float[width*height*3]; if (!data) { fclose(fp); return false; } if (RGBE_ReadPixels_RLE( fp, (float*)data, width, height)) { delete []data; fclose(fp); return false; } //set all the parameters i._width = width; i._height = height; i._depth = 0; i._levelCount = 1; i._type = GL_FLOAT; i._format = GL_RGB; i._internalFormat = GL_RGB32F_ARB; i._faces = 0; i._elementSize = 12; i._data.push_back( data); //hdr images come in upside down i.flipSurface( data, i._width, i._height, i._depth); fclose(fp); return true; } };
21.766234
80
0.563842
ansel86castro
0be1223ac789454d04643ea4363650c9fd64c2d2
4,467
cpp
C++
tf2_src/hammer/MapDiffDlg.cpp
IamIndeedGamingAsHardAsICan03489/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
src/hammer/MapDiffDlg.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
null
null
null
src/hammer/MapDiffDlg.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // MapDiffDlg.cpp : implementation file // #include "stdafx.h" #include "GlobalFunctions.h" #include "History.h" #include "MainFrm.h" #include "MapDiffDlg.h" #include "MapDoc.h" #include "MapEntity.h" #include "MapSolid.h" #include "MapView2D.h" #include "MapWorld.h" #include "ObjectProperties.h" // For ObjectProperties::RefreshData #include "Options.h" #include "ToolManager.h" #include "VisGroup.h" #include "hammer.h" #include "MapOverlay.h" #include "GameConfig.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> #include ".\mapdiffdlg.h" CMapDiffDlg *s_pDlg = NULL; CMapDoc *s_pCurrentMap = NULL; // MapDiffDlg dialog CMapDiffDlg::CMapDiffDlg(CWnd* pParent ) : CDialog(CMapDiffDlg::IDD, pParent) { m_bCheckSimilar = true; } void CMapDiffDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Check(pDX, IDC_SIMILARCHECK, m_bCheckSimilar); DDX_Control(pDX, IDC_MAPNAME, m_mapName); } BEGIN_MESSAGE_MAP(CMapDiffDlg, CDialog) ON_BN_CLICKED(IDC_SIMILARCHECK, OnBnClickedSimilarcheck) ON_BN_CLICKED(IDC_MAPBROWSE, OnBnClickedMapbrowse) ON_BN_CLICKED(IDOK, OnBnClickedOk) ON_BN_CLICKED(IDCANCEL, OnBnClickedCancel) ON_WM_DESTROY() END_MESSAGE_MAP() void CMapDiffDlg::MapDiff(CWnd *pwndParent, CMapDoc *pCurrentMapDoc) { if (!s_pDlg) { s_pDlg = new CMapDiffDlg; s_pDlg->Create(IDD, pwndParent); s_pDlg->ShowWindow(SW_SHOW); s_pCurrentMap = pCurrentMapDoc; } } // MapDiffDlg message handlers void CMapDiffDlg::OnBnClickedSimilarcheck() { // TODO: Add your control notification handler code here m_bCheckSimilar = !m_bCheckSimilar; } void CMapDiffDlg::OnBnClickedMapbrowse() { CString m_pszFilename; // TODO: Add your control notification handler code here static char szInitialDir[MAX_PATH] = ""; if (szInitialDir[0] == '\0') { strcpy(szInitialDir, g_pGameConfig->szMapDir); } // TODO: need to prevent (or handle) opening VMF files when using old map file formats CFileDialog dlg(TRUE, NULL, NULL, OFN_LONGNAMES | OFN_HIDEREADONLY | OFN_NOCHANGEDIR, "Valve Map Files (*.vmf)|*.vmf|Valve Map Files Autosaves (*.vmf_autosave)|*.vmf_autosave|Worldcraft RMFs (*.rmf)|*.rmf|Worldcraft Maps (*.map)|*.map||"); dlg.m_ofn.lpstrInitialDir = szInitialDir; int iRvl = dlg.DoModal(); if (iRvl == IDCANCEL) { return; } // // Get the directory they browsed to for next time. // m_pszFilename = dlg.GetPathName(); m_mapName.SetWindowText( m_pszFilename ); } void CMapDiffDlg::OnBnClickedOk() { // TODO: Add your control notification handler code here OnOK(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMapDiffDlg::OnOK() { CString strFilename; m_mapName.GetWindowText( strFilename ); CHammer *pApp = (CHammer*) AfxGetApp(); CMapDoc *pDoc = (CMapDoc*) pApp->pMapDocTemplate->OpenDocumentFile( strFilename ); CUtlVector <int> IDList; const CMapObjectList *pChildren = pDoc->GetMapWorld()->GetChildren(); FOR_EACH_OBJ( *pChildren, pos ) { int nID = pChildren->Element(pos)->GetID(); IDList.AddToTail( nID ); } pDoc->OnCloseDocument(); CVisGroup *resultsVisGroup = NULL; pChildren = s_pCurrentMap->GetMapWorld()->GetChildren(); int nTotalSimilarities = 0; if ( m_bCheckSimilar ) { FOR_EACH_OBJ( *pChildren, pos ) { CMapClass *pChild = pChildren->Element(pos) ; int ID = pChild->GetID(); if ( IDList.Find( ID ) != -1 ) { if ( resultsVisGroup == NULL ) { resultsVisGroup = s_pCurrentMap->VisGroups_AddGroup( "Similar" ); nTotalSimilarities++; } pChild->AddVisGroup( resultsVisGroup ); } } } if ( nTotalSimilarities > 0 ) { GetMainWnd()->MessageBox( "Similarities were found and placed into the \"Similar\" visgroup.", "Map Similarities Found", MB_OK | MB_ICONEXCLAMATION); } s_pCurrentMap->VisGroups_UpdateAll(); DestroyWindow(); } //----------------------------------------------------------------------------- // Purpose: Called when our window is being destroyed. //----------------------------------------------------------------------------- void CMapDiffDlg::OnDestroy() { delete this; s_pDlg = NULL; s_pCurrentMap = NULL; } void CMapDiffDlg::OnBnClickedCancel() { // TODO: Add your control notification handler code here DestroyWindow(); }
25.820809
240
0.670025
IamIndeedGamingAsHardAsICan03489
0be12afc1cd459e68d697162fd7960a35b011dd9
1,155
cpp
C++
Data_Structures/Linked_list/insert_circularLL.cpp
SouvikSSG/C-Programming
e5ae8b4b0ab0ca39532ed4d25e1d997b793f669c
[ "Apache-2.0" ]
null
null
null
Data_Structures/Linked_list/insert_circularLL.cpp
SouvikSSG/C-Programming
e5ae8b4b0ab0ca39532ed4d25e1d997b793f669c
[ "Apache-2.0" ]
null
null
null
Data_Structures/Linked_list/insert_circularLL.cpp
SouvikSSG/C-Programming
e5ae8b4b0ab0ca39532ed4d25e1d997b793f669c
[ "Apache-2.0" ]
null
null
null
#include "headers/create_circular_LLcpp.h" #include <iostream> node *linkedList::InsertCLL(struct node *ptr) { int x, index; std::cout << "Enter an index and data to insert respectively: "; std::cin >> index >> x; if (index < 0 || index > CountCLL(ptr)) { std::cout << "Invalid index. Unable to insert.\n"; return ptr; // function just do nothing under this condition } node *t = new node(x); if (index == 0) { while (ptr->next != first) { ptr = ptr->next; } ptr->next = t; t->next = first; first = t; } else { for (int i = 0; i < index - 1; i++) { ptr = ptr->next; } t->next = ptr->next; ptr->next = t; } return first; } int main() { linkedList C_LL1, C_LL2; int A[] = {2, 5, 9, 4, 10, 7}; int B[] = {7, 0, 3, 2}; int num1 = sizeof(A) / sizeof(A[0]); int num2 = sizeof(B) / sizeof(B[0]); node *LL1 = C_LL1.CreateCLL(A, num1); node *LL2 = C_LL2.CreateCLL(B, num2); LL1 = C_LL1.InsertCLL(LL1); LL2 = C_LL2.InsertCLL(LL2); C_LL1.DisplayCLL(LL1); std::cout << std::endl; C_LL2.DisplayCLL(LL2); return 0; }
24.574468
67
0.547186
SouvikSSG
0be3898d6529a68c3dd1a023bf1f2809a12160f3
6,246
cpp
C++
Lux/MainPage.cpp
axodox/Lux
00e8da582233ab4ecf22d773e647c9bd84eb7b32
[ "MIT" ]
9
2020-11-30T01:13:25.000Z
2022-03-14T15:17:44.000Z
Lux/MainPage.cpp
axodox/Lux
00e8da582233ab4ecf22d773e647c9bd84eb7b32
[ "MIT" ]
1
2020-11-30T15:45:27.000Z
2021-02-17T22:11:14.000Z
Lux/MainPage.cpp
axodox/Lux
00e8da582233ab4ecf22d773e647c9bd84eb7b32
[ "MIT" ]
1
2021-02-15T22:17:37.000Z
2021-02-15T22:17:37.000Z
#include "pch.h" #include "MainPage.h" #include "MainPage.g.cpp" #include "DeviceSettings.h" #include "DependencyConfiguration.h" #include "ThreadName.h" using namespace ::Lux; using namespace ::Lux::Events; using namespace ::Lux::Observable; using namespace ::Lux::Graphics; using namespace ::Lux::Configuration; using namespace ::Lux::Threading; using namespace winrt; using namespace Windows::Foundation; using namespace Windows::ApplicationModel::Core; using namespace Windows::UI; using namespace Windows::UI::Core; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::ViewManagement; using namespace Windows::Storage; using namespace Windows::Storage::Pickers; using namespace Windows::Data::Json; namespace winrt::Lux::implementation { MainPage::MainPage() : _client(DependencyConfiguration::Instance().resolve<observable_client<LightConfiguration>>()) { InitializeComponent(); InitializeView(); _client->is_connected_changed(no_revoke, member_func(this, &MainPage::OnClientConnectedChanged)); _client->full_data_reset(no_revoke, member_func(this, &MainPage::OnFullDataReset)); _client->root()->property_changed(no_revoke, member_func(this, &MainPage::OnSettingChanged)); _client->open(); } bool MainPage::IsConnected() { return _client->is_connected(); } hstring MainPage::ConnectionState() { if (_client->is_connected()) { return _client->root()->IsConnected ? L"Connected" : L"Disconnected"; } else { return L"Idle"; } } void MainPage::InitializeView() { set_thread_name(L"* UI thread"); auto currentView = ApplicationView::GetForCurrentView(); currentView.PreferredLaunchViewSize({ 1024, 512 }); currentView.PreferredLaunchWindowingMode(ApplicationViewWindowingMode::PreferredLaunchViewSize); const auto& coreTitleBar = CoreApplication::GetCurrentView().TitleBar(); coreTitleBar.ExtendViewIntoTitleBar(true); _titleBarLayoutMetricsChangedRevoker = coreTitleBar.LayoutMetricsChanged(auto_revoke, [this](const CoreApplicationViewTitleBar& sender, const IInspectable&) { UpdateTitleBarLayout(sender); }); UpdateTitleBarLayout(coreTitleBar); Window::Current().SetTitleBar(AppTitleBar()); const auto& viewTitleBar = ApplicationView::GetForCurrentView().TitleBar(); viewTitleBar.ButtonBackgroundColor(Colors::Transparent()); viewTitleBar.ButtonForegroundColor(Colors::White()); viewTitleBar.ButtonInactiveBackgroundColor(Colors::Transparent()); viewTitleBar.ButtonInactiveForegroundColor(Colors::White()); } void MainPage::UpdateTitleBarLayout(const CoreApplicationViewTitleBar& titleBar) { AppTitleBar().Height(titleBar.Height()); TitleBarLeftPaddingColumn().Width({ titleBar.SystemOverlayLeftInset() }); TitleBarRightPaddingColumn().Width({ titleBar.SystemOverlayRightInset() }); } void MainPage::OnClientConnectedChanged(observable_client<LightConfiguration>* /*sender*/) { Dispatcher().RunAsync({}, [&] { _propertyChanged(*this, PropertyChangedEventArgs(L"IsConnected")); _propertyChanged(*this, PropertyChangedEventArgs(L"ConnectionState")); }).get(); } void MainPage::OnFullDataReset(::Lux::Observable::observable_client<::Lux::Configuration::LightConfiguration>* /*sender*/) { Dispatcher().RunAsync({}, [&] { _propertyChanged(*this, PropertyChangedEventArgs(L"")); }); } void MainPage::OnSettingChanged(observable_object<LightConfigurationProperty>* object, LightConfigurationProperty propertyKey) { switch (propertyKey) { case LightConfigurationProperty::IsConnected: _propertyChanged(*this, PropertyChangedEventArgs(L"ConnectionState")); break; case LightConfigurationProperty::Brightness: _propertyChanged(*this, PropertyChangedEventArgs(L"Brightness")); break; } } fire_and_forget MainPage::ConfigureDevice() { FileOpenPicker picker{}; picker.ViewMode(PickerViewMode::List); picker.SuggestedStartLocation(PickerLocationId::DocumentsLibrary); picker.FileTypeFilter().Append(L".json"); picker.CommitButtonText(L"Open configuration"); picker.SettingsIdentifier(L"device_configuration"); auto file = co_await picker.PickSingleFileAsync(); if (!file) co_return; ContentDialog messageDialog{}; messageDialog.Title(box_value(L"Lux configuration importer")); messageDialog.CloseButtonText(L"OK"); try { auto text = co_await FileIO::ReadTextAsync(file); auto json = JsonValue::Parse(text); DeviceSettings settings{ json }; auto ledCount = settings.Layout.LedCount(); if (ledCount > 0u) { _client->root()->Device.value(std::move(settings)); messageDialog.Content(box_value(L"Successfully loaded configuration from " + file.Path() + L".")); } else { messageDialog.Content(box_value(L"The configuration at path " + file.Path() + L" contains no LEDs.")); } } catch (const hresult_error& e) { messageDialog.Content(box_value(L"Failed to load configuration " + file.Path() + L". Reason: " + e.message())); } catch (...) { messageDialog.Content(box_value(L"Failed to load configuration " + file.Path() + L". Unknown error.")); } if (messageDialog) { co_await messageDialog.ShowAsync(); } } uint8_t MainPage::Brightness() { return _client->root()->Brightness; } void MainPage::Brightness(uint8_t value) { if (_client->root()->Brightness == value) return; _client->root()->Brightness = value; } winrt::event_token MainPage::PropertyChanged(PropertyChangedEventHandler const& value) { return _propertyChanged.add(value); } void MainPage::PropertyChanged(event_token const& token) { _propertyChanged.remove(token); } bool MainPage::IsShowingSettings() { return _isShowingSettings; } void MainPage::IsShowingSettings(bool value) { _isShowingSettings = value; _propertyChanged(*this, PropertyChangedEventArgs(L"IsShowingSettings")); } }
31.074627
162
0.715818
axodox
0be8ac1c160e42e43740fcffc6bac14b3c4cc920
130
cpp
C++
src/drivers/uavcan/uavcan_servers.cpp
Diksha-agg/Firmware_val
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
[ "BSD-3-Clause" ]
null
null
null
src/drivers/uavcan/uavcan_servers.cpp
Diksha-agg/Firmware_val
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
[ "BSD-3-Clause" ]
null
null
null
src/drivers/uavcan/uavcan_servers.cpp
Diksha-agg/Firmware_val
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
[ "BSD-3-Clause" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:e684b09136ca6c7639d0daeee71deb8ac30ebb9f0a33ca01c127846e8fce807a size 38788
32.5
75
0.884615
Diksha-agg
0be8ba93767d692410957a05128a899a7f442745
5,102
hpp
C++
include/net.hpp
EntireTwix/Ruminate
0f40bd78d9cec4c0b52b480495699a0cece11a54
[ "MIT" ]
12
2020-10-30T20:57:55.000Z
2021-05-06T22:10:45.000Z
include/net.hpp
EntireTwix/Ruminate
0f40bd78d9cec4c0b52b480495699a0cece11a54
[ "MIT" ]
2
2020-12-04T04:12:52.000Z
2021-03-13T08:28:53.000Z
include/net.hpp
EntireTwix/Ruminate
0f40bd78d9cec4c0b52b480495699a0cece11a54
[ "MIT" ]
3
2020-11-04T23:17:47.000Z
2020-12-04T23:36:47.000Z
#pragma once #include <string> #include <numeric> #include "layers.hpp" namespace rum { template <Matrix M> class NeuralNetwork { private: Layer<M> **layers = nullptr; const uint_fast8_t sz; public: NeuralNetwork() noexcept = delete; template <typename... Params> NeuralNetwork(Params *&&...args) : sz(sizeof...(args)) { layers = new Layer<M> *[sz] { args... }; } /** * @brief * Forward Propogates the given Input matrix across the network * then returns a vector of matrices containing each step * (THREAD SAFE) * * @param input * @return std::vector<Mat<T>> of steps */ std::vector<M> ForwardProp(const M &input) const { std::vector<M> res(sz); res[0] = layers[0]->ForwardProp(input); if constexpr (LOG_LAYERS_FLAG) { std::cout << res[0] << '\n'; //debugging } for (size_t i = 1; i < res.size(); ++i) { res[i] = layers[i]->ForwardProp(res[i - 1]); //result 1 = 1th layer propogated with 0th result if constexpr (LOG_LAYERS_FLAG) { std::cout << res[i] << '\n'; //debugging } } return res; } /** * @brief Backpropogates the cost of a given ForwardProp() staMing from the last layer * to the first layer of the network. Each layer may modify the cost and is given the context * of the forwardprops result, current layers state, and current cost. * (THREAD SAFE) * * @param forwardRes, the result of a forward prop * @param cost_prime, the error of the last anwser, caclulated with CostPrime() * @param lr, the learning rate of the network, you could say how sensitive it is to change * @return std::vector<M> of corrections to be applied with Learn() */ std::vector<M> BackwordProp(const std::vector<M> &forwardRes, M &&cost_prime, const float lr) const { std::vector<M> res(sz); M cost = std::move(cost_prime *= lr); //not optimal //std::cout << "\nBackProp:\n" << cost << '\n'; for (uint8_t i = sz - 1; i > 0; --i) { res[i] = layers[i]->BackwardProp(cost, forwardRes, layers, i); if (LOG_LAYERS_FLAG) { std::cout << "{\nCorrection:\n" << res[i] << "\nOriginal:\n" << layers[i]->inside() << "}\n\n"; } } return res; } /** * @brief calls each layers * Learn() function passing the corresponding correction as an arg, * applying the corrections. * (NOT THREAD SAFE) * * @param backRes, backpropogation correction results to be applied */ void Learn(const std::vector<M> &backRes) { for (uint_fast8_t i = 0; i < sz; ++i) { layers[i]->Learn(backRes[i]); } } /** * @brief a janky solution to problem of saving networks, when called this function * will return a string that if copied and pasted would be the constructor for the layer * it corresponds to. * Ex Output: (2,1,0.999917,0.999930) * Ex Paste: new Weight(2,1,0.999917,0.999930); * (TO BE REFRACTORED LATER) * * @return std::string, each save is on a newline */ std::string Save() const noexcept { std::string res; for (uint8_t i = 1; i < sz; ++i) //skipping input layer { res += layers[i]->inside().Save() + '\n'; } return res; } /** * @brief returns the cost of the 0.5(guess - anwser)^2 * * @param guess * @param anwser * @return matrix of cost */ static M Cost(const M &guess, const M &anwser) { M res(guess.SizeX(), guess.SizeY()); for (size_t i = 0; i < guess.SizeX() * guess.SizeY(); ++i) //kinda bad to keep calling Area() { res.FastAt(i) = 0.5 * ((guess.FastAt(i) - anwser.FastAt(i)) * (guess.FastAt(i) - anwser.FastAt(i))); } return res; } /** * @brief passed to BackProp() to calculate raw cost of guess-anwser * * @param guess * @param anwser * @return matrix of cost */ static M CostPrime(const M &guess, const M &anwser) noexcept { return guess - anwser; } ~NeuralNetwork() { for (size_t i = 0; i < sz; ++i) { delete layers[i]; } delete[] layers; } }; }; // namespace rum
32.705128
116
0.48138
EntireTwix
0bf11cafdf2894d63ea8a59ff15ff677da72ebb5
2,498
hh
C++
extern/glow-extras/viewer/glow-extras/viewer/aabb.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/glow-extras/viewer/glow-extras/viewer/aabb.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
extern/glow-extras/viewer/glow-extras/viewer/aabb.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
#pragma once #include <initializer_list> #include <sstream> #include <string> #include <typed-geometry/tg-std.hh> #include <glow/common/log.hh> namespace glow { namespace viewer { struct aabb { // member public: tg::pos3 min = tg::pos3(std::numeric_limits<tg::f32>::max()); tg::pos3 max = tg::pos3(std::numeric_limits<tg::f32>::lowest()); // properties public: constexpr tg::vec3 size() const; constexpr tg::pos3 center() const; constexpr float radius() const; ///< Radius of the bounding sphere (positioned at the center) constexpr float volume() const; constexpr bool isEmpty() const; ///< NOT the same as zero volume! 2D aabb is not empty. // mutating methods public: /// includes a given point constexpr void add(tg::pos3 const& p); /// includes a given aabb constexpr void add(aabb const& rhs); // non-mutating public: /// calculates a transformed aabb constexpr aabb transformed(tg::mat4 const& transform) const; // ctor public: aabb() = default; constexpr aabb(tg::pos3 min, tg::pos3 max) : min(min), max(max) {} static aabb empty() { return aabb(); } }; // ======== IMPLEMENTATION ======== constexpr inline tg::vec3 aabb::size() const { return max - min; } constexpr inline tg::pos3 aabb::center() const { return tg::centroid_of(tg::aabb3(min, max)); } constexpr inline float aabb::radius() const { return tg::length(size()) * .5f; } constexpr inline float aabb::volume() const { if (isEmpty()) return 0; auto s = size(); return s.x * s.y * s.z; } constexpr inline bool aabb::isEmpty() const { return max.x < min.x || max.y < min.y || max.z < min.z; } constexpr inline void aabb::add(const tg::pos3& p) { min = tg::min(min, p); max = tg::max(max, p); } constexpr inline void aabb::add(const aabb& rhs) { if (!rhs.isEmpty()) { add(rhs.min); add(rhs.max); } } constexpr inline aabb aabb::transformed(const tg::mat4& transform) const { aabb r; for (auto dz : {0.f, 1.f}) for (auto dy : {0.f, 1.f}) for (auto dx : {0.f, 1.f}) { auto p = tg::comp3(min) + tg::comp3(max - min) * tg::comp3(dx, dy, dz); r.add(tg::pos3(transform * tg::vec4(p.comp0, p.comp1, p.comp2, 1.0f))); } return r; } inline std::string to_string(aabb const& aabb) { std::stringstream ss; ss << "aabb[" << aabb.min << ", " << aabb.max << "]"; return ss.str(); } } }
23.790476
103
0.598078
rovedit
0bf3433c99a4ac6c853be5e75731b108d0b19952
576
cpp
C++
code/framework/src/instigation.cpp
Feupos/utfprct-tex
8ed2994fd907e3bef93d5f734d58731cd0ef64e2
[ "LPPL-1.3c" ]
null
null
null
code/framework/src/instigation.cpp
Feupos/utfprct-tex
8ed2994fd907e3bef93d5f734d58731cd0ef64e2
[ "LPPL-1.3c" ]
null
null
null
code/framework/src/instigation.cpp
Feupos/utfprct-tex
8ed2994fd907e3bef93d5f734d58731cd0ef64e2
[ "LPPL-1.3c" ]
null
null
null
#include "libnop/instigation.h" #include <execution> namespace NOP { void Instigation::AddMethod(Method method) { methods_.insert(methods_.end(), std::move(method)); } void Instigation::Instigate() { LOG(this, "Instigated"); for (const auto& method : methods_) { method(); } } void ParallelInstigation::Instigate() { LOG(this, "Instigated"); std::for_each(std::execution::par_unseq, methods_.begin(), methods_.end(), [](auto& method) { method(); }); } } // namespace NOP
19.862069
63
0.578125
Feupos
0bf7071a706170648877edd995042c748041738e
4,029
hpp
C++
src/common/utilities/initializehelper.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
3
2020-03-05T06:36:51.000Z
2020-06-20T03:25:02.000Z
src/common/utilities/initializehelper.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
13
2020-03-11T17:43:42.000Z
2020-12-11T03:36:05.000Z
src/common/utilities/initializehelper.hpp
squeevee/Addle
20ec4335669fbd88d36742f586899d8416920959
[ "MIT" ]
1
2020-09-28T06:53:46.000Z
2020-09-28T06:53:46.000Z
/** * Addle source code * @file * @copyright Copyright 2020 Eleanor Hawk * @copyright Modification and distribution permitted under the terms of the * MIT License. See "LICENSE" for full details. */ #ifndef INITIALIZEHELPER_HPP #define INITIALIZEHELPER_HPP #include <QObject> #include <typeinfo> #include <type_traits> #include <cstdint> // for INT_MAX #include "utilities/errors.hpp" #include "../exceptions/initializeexceptions.hpp" // TODO: It might be better for this class to do *nothing* in release builds. // depends on whether we want objects to be uninitialized on purpose and use // exceptions to test for this state. // If uninitialized objects aren't supported then we will want to switch these // from named runtime errors to generic logic errors /** * A helper class for objects that expect initialization. Tracks whether the * owner class is initialized and performs assertions as called upon. */ namespace Addle { class InitializeHelper { public: InitializeHelper() : _isInitialized(false), _depth(0) { } inline bool isInitialized() { return _isInitialized; } // The `checkpoint` argument permits classes to selectively make some // resources accessible before initialization is complete. This can be useful // for example when a class creates an owned object during initialization // that itself needs information from its owner (saving the trouble of // `initialize` functions with long and esoteric argument lists) // // This could lead to fiddly behavioral gotchas not explicit to an interface // but when you pick at the edge cases, that seems hard to avoid, and this // is probably one of the more graceful solutions. inline void check(int checkpoint = INT_MAX) const { //potential threading hazard // meh if (_depth > 0 && checkpoint > _checkpoint) ADDLE_THROW(InvalidInitializeException( InvalidInitializeException::Why::improper_order )); if (!_isInitialized && checkpoint > _checkpoint) ADDLE_THROW(NotInitializedException()); } // Checkpoint values are arbitrary and internal to a class (and its // descendants if any) inline void setCheckpoint(int checkpoint) { _checkpoint = checkpoint; } // will anyone ever use this function for any reason? inline void assertNotInitialized() { if (_isInitialized) ADDLE_THROW(AlreadyInitializedException()); } //Call at the beginning of the initialize function block, before calling //any parent class's initialize function. inline void initializeBegin() { assertNotInitialized(); _depth++; } //Call at the end of the initialize function block, after calling any //parent class's initialize function. inline void initializeEnd() { _depth--; if (_depth == 0) _isInitialized = true; else if (_depth < 0) ADDLE_THROW(InvalidInitializeException(InvalidInitializeException::Why::improper_order)); } private: bool _isInitialized; int _depth; int _checkpoint = -1; }; class Initializer { public: Initializer(InitializeHelper& helper) : _helper(helper) { _helper.initializeBegin(); } Initializer(const Initializer&) = delete; ~Initializer() { _helper.initializeEnd(); } private: InitializeHelper& _helper; }; #ifdef ADDLE_DEBUG #define _ASSERT_INIT(x) \ try { x.check(); } catch(InitializeException& ex) { ADDLE_THROW(ex); } #define _ASSERT_INIT_CHECKPOINT(x, y) \ try { x.check(y); } catch(InitializeException& ex) { ADDLE_THROW(ex); } #else #define _ASSERT_INIT(x) x.check(); #define _ASSERT_INIT_CHECKPOINT(x, y) x.check(y); #endif //ADDLE_DEBUG #define ASSERT_INIT() _ASSERT_INIT(_initHelper) #define ASSERT_INIT_CHECKPOINT(checkpoint) _ASSERT_INIT_CHECKPOINT(_initHelper, checkpoint) } // namespace Addle #endif // INITIALIZEHELPER_HPP
27.979167
101
0.692728
squeevee
0bf9b05fedd901d57b0f3f13aa31c8552de5856f
667
hh
C++
Rowset.hh
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
1
2017-09-14T13:31:16.000Z
2017-09-14T13:31:16.000Z
Rowset.hh
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
null
null
null
Rowset.hh
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
5
2015-04-11T02:59:06.000Z
2021-03-03T19:45:39.000Z
// // Copyright 2009-2016 M. Shulhan ([email protected]). All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef _LIBVOS_ROWSET_HH #define _LIBVOS_ROWSET_HH 1 #include "List.hh" namespace vos { // // class Rowset define a list of row. // Each row may contain different number of record. // class Rowset : public List { public: Rowset(); virtual ~Rowset(); const char* chars(); // `__cname` contain canonical name of this object. static const char* __cname; private: Rowset(const Rowset&); void operator=(const Rowset&); }; } // namespace vos #endif // vi: ts=8 sw=8 tw=78:
18.527778
73
0.701649
shuLhan
0bfa1c6a82258463a0c97b516169b5b236b054c8
1,296
hpp
C++
modules/math/source/blub/math/ray.hpp
qwertzui11/voxelTerrain
05038fb261893dd044ae82fab96b7708ea5ed623
[ "MIT" ]
96
2015-02-02T20:01:24.000Z
2021-11-14T20:33:29.000Z
modules/math/source/blub/math/ray.hpp
qwertzui11/voxelTerrain
05038fb261893dd044ae82fab96b7708ea5ed623
[ "MIT" ]
12
2016-06-04T15:45:30.000Z
2020-02-04T11:10:51.000Z
modules/math/source/blub/math/ray.hpp
qwertzui11/voxelTerrain
05038fb261893dd044ae82fab96b7708ea5ed623
[ "MIT" ]
19
2015-09-22T01:21:45.000Z
2020-09-30T09:52:27.000Z
#ifndef LINE_HPP #define LINE_HPP #include "blub/math/vector3.hpp" namespace Ogre { class Ray; } namespace blub { class ray { public: #ifndef BLUB_NO_OGRE3D ray(const Ogre::Ray &vec); operator Ogre::Ray() const; #endif ray():mOrigin(vector3::ZERO), mDirection(vector3::UNIT_Z) {} ray(const vector3& origin, const vector3& direction) :mOrigin(origin), mDirection(direction) {} /** Sets the origin of the ray. */ void setOrigin(const vector3& origin) {mOrigin = origin;} /** Gets the origin of the ray. */ const vector3& getOrigin(void) const {return mOrigin;} /** Sets the direction of the ray. */ void setDirection(const vector3& dir) {mDirection = dir;} /** Gets the direction of the ray. */ const vector3& getDirection(void) const {return mDirection;} /** Gets the position of a point t units along the ray. */ vector3 getPoint(real t) const { return vector3(mOrigin + (mDirection * t)); } /** Gets the position of a point t units along the ray. */ vector3 operator*(real t) const { return getPoint(t); } bool intersects (const plane &pl, vector3 *point = nullptr, real *tOut = nullptr) const; protected: vector3 mOrigin; vector3 mDirection; }; } #endif // LINE_HPP
21.966102
92
0.652778
qwertzui11
0bfcfa7e7e86b593c2ef6719b0fa63bed6de57b9
2,550
hpp
C++
include/boost/spirit/fusion/sequence/detail/trsfrm_view_begin_end_trts.hpp
dstrigl/mcotf
92a9caf6173b1241a2f9ed45cd379469762b7178
[ "BSL-1.0" ]
93
2015-11-20T04:13:36.000Z
2022-03-24T00:03:08.000Z
include/boost/spirit/fusion/sequence/detail/trsfrm_view_begin_end_trts.hpp
dstrigl/mcotf
92a9caf6173b1241a2f9ed45cd379469762b7178
[ "BSL-1.0" ]
206
2015-11-09T00:27:15.000Z
2021-12-04T19:05:18.000Z
include/boost/spirit/fusion/sequence/detail/trsfrm_view_begin_end_trts.hpp
dstrigl/mcotf
92a9caf6173b1241a2f9ed45cd379469762b7178
[ "BSL-1.0" ]
117
2015-11-08T02:43:46.000Z
2022-02-12T06:29:00.000Z
/*============================================================================= Copyright (c) 2003 Joel de Guzman Use, modification and distribution is subject to 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) ==============================================================================*/ #if !defined(FUSION_SEQUENCE_DETAIL_TRANSFORM_VIEW_BEGIN_END_TRAITS_HPP) #define FUSION_SEQUENCE_DETAIL_TRANSFORM_VIEW_BEGIN_END_TRAITS_HPP #include <boost/spirit/fusion/detail/config.hpp> namespace boost { namespace fusion { struct transform_view_tag; template <typename Sequence, typename F> struct transform_view; template <typename First, typename F> struct transform_view_iterator; namespace meta { template <typename Tag> struct begin_impl; template <> struct begin_impl<transform_view_tag> { template <typename Sequence> struct apply { typedef typename Sequence::first_type first_type; typedef typename Sequence::transform_type transform_type; typedef transform_view_iterator<first_type, transform_type> type; static type call(Sequence& s) { return type(s.first, s.f); } }; }; template <typename Tag> struct end_impl; template <> struct end_impl<transform_view_tag> { template <typename Sequence> struct apply { typedef typename Sequence::last_type last_type; typedef typename Sequence::transform_type transform_type; typedef transform_view_iterator<last_type, transform_type> type; static type call(Sequence& s) { return type(s.last, s.f); } }; }; } }} namespace boost { namespace mpl { template <typename Tag> struct begin_impl; template <typename Tag> struct end_impl; template <> struct begin_impl<fusion::transform_view_tag> : fusion::meta::begin_impl<fusion::transform_view_tag> {}; template <> struct end_impl<fusion::transform_view_tag> : fusion::meta::end_impl<fusion::transform_view_tag> {}; }} #endif
28.651685
82
0.548235
dstrigl
0bff6c1add4ac634e906b20584fb1b78a1b1776c
32,043
cpp
C++
rssavers-0.2/src/Flux/Flux.cpp
NickPepper/MacScreensavers
088625b06b123adcb61c7e9e1adc4415dda66a59
[ "MIT" ]
3
2017-08-13T14:47:57.000Z
2020-03-02T06:48:29.000Z
rssavers-0.2/src/Flux/Flux.cpp
NickPepper/MacScreensavers
088625b06b123adcb61c7e9e1adc4415dda66a59
[ "MIT" ]
1
2018-09-19T14:14:54.000Z
2018-09-26T22:35:03.000Z
rssavers-0.2/src/Flux/Flux.cpp
NickPepper/MacScreensavers
088625b06b123adcb61c7e9e1adc4415dda66a59
[ "MIT" ]
1
2018-09-19T14:13:55.000Z
2018-09-19T14:13:55.000Z
/* * Copyright (C) 1999-2010 Terence M. Welsh * * This file is part of Flux. * * Flux 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 2 of the License, * or (at your option) any later version. * * Flux 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. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Flux screen saver #ifdef WIN32 #include <windows.h> #include <rsWin32Saver/rsWin32Saver.h> #include <regstr.h> #include <commctrl.h> #include <time.h> #include <resource.h> #endif #ifdef RS_XSCREENSAVER #include <rsXScreenSaver/rsXScreenSaver.h> #endif #include <stdio.h> #include <rsText/rsText.h> #include <math.h> #include <GL/gl.h> #include <GL/glu.h> #include <Rgbhsl/Rgbhsl.h> #define NUMCONSTS 8 #define PIx2 6.28318530718f #define DEG2RAD 0.0174532925f #define LIGHTSIZE 64 class flux; class particle; // Global variables #ifdef WIN32 LPCTSTR registryPath = ("Software\\Really Slick\\Flux"); HGLRC hglrc; HDC hdc; #endif int readyToDraw = 0; unsigned int tex; flux *fluxes; float lumdiff; int whichparticle; float cosCameraAngle, sinCameraAngle; unsigned char lightTexture[LIGHTSIZE][LIGHTSIZE]; float aspectRatio; float frameTime = 0.0f; float orbitiness = 0.0f; float prevOrbitiness = 0.0f; // text output rsText* textwriter; // Parameters edited in the dialog box int dFluxes; int dParticles; int dTrail; int dGeometry; int dSize; int dComplexity; int dRandomize; int dExpansion; int dRotation; int dWind; int dInstability; int dBlur; #ifdef RS_XSCREENSAVER #define DEFAULTS1 1 #define DEFAULTS2 2 #define DEFAULTS3 3 #define DEFAULTS4 4 #define DEFAULTS5 5 #define DEFAULTS6 6 #endif // Useful random number macros // Don't forget to initialize with srand() inline int rsRandi(int x){ return rand() % x; } inline float rsRandf(float x){ return x * (float(rand()) / float(RAND_MAX)); } // This class is poorly named. It's actually a whole trail of particles. class particle{ public: float **vertices; int counter; float offset[3]; particle(); ~particle(); void update(float *c); }; particle::particle(){ int i; // Offsets are somewhat like default positions for the head of each // particle trail. Offsets spread out the particle trails and keep // them from all overlapping. offset[0] = cosf(PIx2 * float(whichparticle) / float(dParticles)); offset[1] = float(whichparticle) / float(dParticles) - 0.5f; offset[2] = sinf(PIx2 * float(whichparticle) / float(dParticles)); whichparticle++; // Initialize memory and set initial positions out of view of the camera vertices = new float*[dTrail]; for(i=0; i<dTrail; i++){ vertices[i] = new float[5]; // 0,1,2 = position, 3 = hue, 4 = saturation vertices[i][0] = 0.0f; vertices[i][1] = 3.0f; vertices[i][2] = 0.0f; vertices[i][3] = 0.0f; vertices[i][4] = 0.0f; } counter = 0; } particle::~particle(){ for(int i=0; i<dTrail; i++) delete[] vertices[i]; delete[] vertices; } void particle::update(float *c){ int i, p, growth; float rgb[3]; float cx, cy, cz; // Containment variables float luminosity; static float expander = 1.0f + 0.0005f * float(dExpansion); static float blower = 0.001f * float(dWind); static float otherxyz[3]; float depth; // Record old position int oldc = counter; counter ++; if(counter >= dTrail) counter = 0; // Here's the iterative math for calculating new vertex positions // first calculate limiting terms which keep vertices from constantly // flying off to infinity cx = vertices[oldc][0] * (1.0f - 1.0f / (vertices[oldc][0] * vertices[oldc][0] + 1.0f)); cy = vertices[oldc][1] * (1.0f - 1.0f / (vertices[oldc][1] * vertices[oldc][1] + 1.0f)); cz = vertices[oldc][2] * (1.0f - 1.0f / (vertices[oldc][2] * vertices[oldc][2] + 1.0f)); // then calculate new positions vertices[counter][0] = vertices[oldc][0] + c[6] * offset[0] - cx + c[2] * vertices[oldc][1] + c[5] * vertices[oldc][2]; vertices[counter][1] = vertices[oldc][1] + c[6] * offset[1] - cy + c[1] * vertices[oldc][2] + c[4] * vertices[oldc][0]; vertices[counter][2] = vertices[oldc][2] + c[6] * offset[2] - cz + c[0] * vertices[oldc][0] + c[3] * vertices[oldc][1]; // calculate "orbitiness" of particles const float xdiff(vertices[counter][0] - vertices[oldc][0]); const float ydiff(vertices[counter][1] - vertices[oldc][1]); const float zdiff(vertices[counter][2] - vertices[oldc][2]); const float distsq(vertices[counter][0] * vertices[counter][0] + vertices[counter][1] * vertices[counter][1] + vertices[counter][2] * vertices[counter][2]); const float oldDistsq(vertices[oldc][0] * vertices[oldc][0] + vertices[oldc][1] * vertices[oldc][1] + vertices[oldc][2] * vertices[oldc][2]); orbitiness += (xdiff * xdiff + ydiff * ydiff + zdiff * zdiff) / (2.0f - fabs(distsq - oldDistsq)); // Pick a hue vertices[counter][3] = cx * cx + cy * cy + cz * cz; if(vertices[counter][3] > 1.0f) vertices[counter][3] = 1.0f; vertices[counter][3] += c[7]; // Limit the hue (0 - 1) if(vertices[counter][3] > 1.0f) vertices[counter][3] -= 1.0f; if(vertices[counter][3] < 0.0f) vertices[counter][3] += 1.0f; // Pick a saturation vertices[counter][4] = c[0] + vertices[counter][3]; // Limit the saturation (0 - 1) if(vertices[counter][4] < 0.0f) vertices[counter][4] = -vertices[counter][4]; vertices[counter][4] -= float(int(vertices[counter][4])); vertices[counter][4] = 1.0f - (vertices[counter][4] * vertices[counter][4]); // Bring particles back if they escape if(!counter){ if(vertices[counter][0] * vertices[counter][0] + vertices[counter][1] * vertices[counter][1] + vertices[counter][2] * vertices[counter][2] > 100000000.0f){ vertices[counter][0] = rsRandf(2.0f) - 1.0f; vertices[counter][1] = rsRandf(2.0f) - 1.0f; vertices[counter][2] = rsRandf(2.0f) - 1.0f; } } // Draw every vertex in particle trail p = counter; growth = 0; luminosity = lumdiff; for(i=0; i<dTrail; i++){ p ++; if(p >= dTrail) p = 0; growth++; if(vertices[p][0] * vertices[p][0] + vertices[p][1] * vertices[p][1] + vertices[p][2] * vertices[p][2] < 40000.0f){ // assign color to particle hsl2rgb(vertices[p][3], vertices[p][4], luminosity, rgb[0], rgb[1], rgb[2]); glColor3fv(rgb); glPushMatrix(); switch(dGeometry){ case 0: // Points depth = cosCameraAngle * vertices[p][2] - sinCameraAngle * vertices[p][0]; glTranslatef(cosCameraAngle * vertices[p][0] + sinCameraAngle * vertices[p][2], vertices[p][1], depth); switch(dTrail - growth){ case 0: glPointSize(float(dSize * (depth + 200.0f) * 0.001036f)); break; case 1: glPointSize(float(dSize * (depth + 200.0f) * 0.002f)); break; case 2: glPointSize(float(dSize * (depth + 200.0f) * 0.002828f)); break; case 3: glPointSize(float(dSize * (depth + 200.0f) * 0.003464f)); break; case 4: glPointSize(float(dSize * (depth + 200.0f) * 0.003864f)); break; default: glPointSize(float(dSize * (depth + 200.0f) * 0.004f)); } glBegin(GL_POINTS); glVertex3f(0.0f,0.0f,0.0f); glEnd(); break; case 1: // Spheres glTranslatef(vertices[p][0], vertices[p][1], vertices[p][2]); switch(dTrail - growth){ case 0: glScalef(0.259f, 0.259f, 0.259f); break; case 1: glScalef(0.5f, 0.5f, 0.5f); break; case 2: glScalef(0.707f, 0.707f, 0.707f); break; case 3: glScalef(0.866f, 0.866f, 0.866f); break; case 4: glScalef(0.966f, 0.966f, 0.966f); } glCallList(1); break; case 2: // Lights depth = cosCameraAngle * vertices[p][2] - sinCameraAngle * vertices[p][0]; glTranslatef(cosCameraAngle * vertices[p][0] + sinCameraAngle * vertices[p][2], vertices[p][1], depth); switch(dTrail - growth){ case 0: glScalef(0.259f, 0.259f, 0.259f); break; case 1: glScalef(0.5f, 0.5f, 0.5f); break; case 2: glScalef(0.707f, 0.707f, 0.707f); break; case 3: glScalef(0.866f, 0.866f, 0.866f); break; case 4: glScalef(0.966f, 0.966f, 0.966f); } glCallList(1); } glPopMatrix(); } vertices[p][0] *= expander; vertices[p][1] *= expander; vertices[p][2] *= expander; vertices[p][2] += blower; luminosity += lumdiff; } } // This class is a set of particle trails and constants that enter // into their equations of motion. class flux{ public: particle *particles; int randomize; float c[NUMCONSTS]; // constants float cv[NUMCONSTS]; // constants' change velocities flux(); ~flux(); void update(); }; flux::flux(){ int i; whichparticle = 0; particles = new particle[dParticles]; randomize = 1; for(i=0; i<NUMCONSTS; i++){ c[i] = rsRandf(2.0f) - 1.0f; cv[i] = rsRandf(0.000005f * float(dInstability) * float(dInstability)) + 0.000001f * float(dInstability) * float(dInstability); } } flux::~flux(){ delete[] particles; } void flux::update(){ int i; // randomize constants if(dRandomize){ randomize --; if(randomize <= 0){ for(i=0; i<NUMCONSTS; i++) c[i] = rsRandf(2.0f) - 1.0f; int temp = 101 - dRandomize; temp = temp * temp; randomize = temp + rsRandi(temp); } } // update constants for(i=0; i<NUMCONSTS; i++){ c[i] += cv[i]; if(c[i] >= 1.0f){ c[i] = 1.0f; cv[i] = -cv[i]; } if(c[i] <= -1.0f){ c[i] = -1.0f; cv[i] = -cv[i]; } } prevOrbitiness = orbitiness; orbitiness = 0.0f; // update all particles in this flux field for(i=0; i<dParticles; i++) particles[i].update(c); /* if(orbitiness < prevOrbitiness){ i = rsRandi(NUMCONSTS - 1); cv[i] = -cv[i]; }*/ } void draw(){ int i; // clear the screen if(dBlur){ // partially glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0.0, 1.0, 0.0, 1.0, 1.0, -1.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); glColor4f(0.0f, 0.0f, 0.0f, 0.5f - (float(sqrtf(sqrtf(float(dBlur)))) * 0.15495f)); glBegin(GL_TRIANGLE_STRIP); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f); glVertex3f(0.0f, 1.0f, 0.0f); glVertex3f(1.0f, 1.0f, 0.0f); glEnd(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } else // completely glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -2.5); // Rotate camera static float cameraAngle = 0.0f; cameraAngle += 0.01f * float(dRotation); if(cameraAngle >= 360.0f) cameraAngle -= 360.0f; if(dGeometry == 1) // Only rotate for spheres glRotatef(cameraAngle, 0.0f, 1.0f, 0.0f); else{ cosCameraAngle = cosf(cameraAngle * DEG2RAD); sinCameraAngle = sinf(cameraAngle * DEG2RAD); } // set up state for rendering particles switch(dGeometry){ case 0: // Blending for points glBlendFunc(GL_SRC_ALPHA, GL_ONE); glEnable(GL_BLEND); glEnable(GL_POINT_SMOOTH); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); break; case 1: // No blending for spheres, but we need z-buffering glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); glClear(GL_DEPTH_BUFFER_BIT); break; case 2: // Blending for lights glBlendFunc(GL_ONE, GL_ONE); glEnable(GL_BLEND); glBindTexture(GL_TEXTURE_2D, tex); glEnable(GL_TEXTURE_2D); } // Update particles glMatrixMode(GL_MODELVIEW); for(i=0; i<dFluxes; i++) fluxes[i].update(); // print text static float totalTime = 0.0f; totalTime += frameTime; static std::string str; static int frames = 0; ++frames; if(frames == 20){ str = "FPS = " + to_string(20.0f / totalTime); totalTime = 0.0f; frames = 0; } if(kStatistics){ glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0.0f, 50.0f * aspectRatio, 0.0f, 50.0f, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTranslatef(1.0f, 48.0f, 0.0f); glColor3f(1.0f, 0.6f, 0.0f); textwriter->draw(str); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } #ifdef WIN32 wglSwapLayerBuffers(hdc, WGL_SWAP_MAIN_PLANE); #endif #ifdef RS_XSCREENSAVER glXSwapBuffers(xdisplay, xwindow); #endif } void idleProc(){ // update time static rsTimer timer; frameTime = timer.tick(); if(readyToDraw && !isSuspended && !checkingPassword) draw(); } void setDefaults(int which){ switch(which){ case DEFAULTS1: // Regular dFluxes = 1; dParticles = 20; dTrail = 40; dGeometry = 2; dSize = 15; dComplexity = 3; dRandomize = 0; dExpansion = 40; dRotation = 30; dWind = 20; dInstability = 20; dBlur = 0; dFrameRateLimit = 60; break; case DEFAULTS2: // Hypnotic dFluxes = 2; dParticles = 10; dTrail = 40; dGeometry = 2; dSize = 15; dRandomize = 80; dExpansion = 20; dRotation = 0; dWind = 40; dInstability = 10; dBlur = 30; dFrameRateLimit = 60; break; case DEFAULTS3: // Insane dFluxes = 4; dParticles = 30; dTrail = 8; dGeometry = 2; dSize = 25; dRandomize = 0; dExpansion = 80; dRotation = 60; dWind = 40; dInstability = 100; dBlur = 10; dFrameRateLimit = 60; break; case DEFAULTS4: // Sparklers dFluxes = 3; dParticles = 20; dTrail = 6; dGeometry = 1; dSize = 20; dComplexity = 3; dRandomize = 85; dExpansion = 60; dRotation = 30; dWind = 20; dInstability = 30; dBlur = 0; dFrameRateLimit = 60; break; case DEFAULTS5: // Paradigm dFluxes = 1; dParticles = 40; dTrail = 40; dGeometry = 2; dSize = 5; dRandomize = 90; dExpansion = 30; dRotation = 20; dWind = 10; dInstability = 5; dBlur = 10; dFrameRateLimit = 60; break; case DEFAULTS6: // Galactic dFluxes = 3; dParticles = 2; dTrail = 1500; dGeometry = 2; dSize = 10; dRandomize = 0; dExpansion = 5; dRotation = 25; dWind = 0; dInstability = 5; dBlur = 0; dFrameRateLimit = 60; } } #ifdef RS_XSCREENSAVER void handleCommandLine(int argc, char* argv[]){ int defaults = DEFAULTS1; setDefaults(defaults); getArgumentsValue(argc, argv, std::string("-default"), defaults, DEFAULTS1, DEFAULTS6); setDefaults(defaults); getArgumentsValue(argc, argv, std::string("-fluxes"), dFluxes, 1, 100); getArgumentsValue(argc, argv, std::string("-particles"), dParticles, 1, 1000); getArgumentsValue(argc, argv, std::string("-trail"), dTrail, 3, 10000); getArgumentsValue(argc, argv, std::string("-geometry"), dGeometry, 0, 2); getArgumentsValue(argc, argv, std::string("-size"), dSize, 1, 100); getArgumentsValue(argc, argv, std::string("-complexity"), dComplexity, 1, 10); getArgumentsValue(argc, argv, std::string("-randomize"), dRandomize, 0, 100); getArgumentsValue(argc, argv, std::string("-expansion"), dExpansion, 0, 100); getArgumentsValue(argc, argv, std::string("-rotation"), dRotation, 1, 100); getArgumentsValue(argc, argv, std::string("-wind"), dWind, 1, 10); getArgumentsValue(argc, argv, std::string("-instability"), dInstability, 1, 100); getArgumentsValue(argc, argv, std::string("-blur"), dBlur, 0, 100); } void reshape(int width, int height){ glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); aspectRatio = float(width) / float(height); gluPerspective(100.0, aspectRatio, 0.01, 200.0); glMatrixMode(GL_MODELVIEW); } #endif #ifdef WIN32 void initSaver(HWND hwnd){ RECT rect; // Window initialization hdc = GetDC(hwnd); setBestPixelFormat(hdc); hglrc = wglCreateContext(hdc); GetClientRect(hwnd, &rect); wglMakeCurrent(hdc, hglrc); glViewport(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); aspectRatio = float(rect.right) / float(rect.bottom); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(100.0, aspectRatio, 0.01, 200.0); #endif #ifdef RS_XSCREENSAVER void initSaver(){ #endif int i, j; float x, y, temp; srand((unsigned)time(NULL)); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if(dGeometry == 0){ glEnable(GL_POINT_SMOOTH); //glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); } glFrontFace(GL_CCW); glEnable(GL_CULL_FACE); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(dGeometry == 1){ // Spheres and their lighting glNewList(1, GL_COMPILE); GLUquadricObj *qobj = gluNewQuadric(); gluSphere(qobj, 0.005f * float(dSize), dComplexity + 2, dComplexity + 1); gluDeleteQuadric(qobj); glEndList(); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); float ambient[4] = {0.0f, 0.0f, 0.0f, 0.0f}; float diffuse[4] = {1.0f, 1.0f, 1.0f, 0.0f}; float specular[4] = {1.0f, 1.0f, 1.0f, 0.0f}; float position[4] = {500.0f, 500.0f, 500.0f, 0.0f}; glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, specular); glLightfv(GL_LIGHT0, GL_POSITION, position); glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); } if(dGeometry == 2){ // Init lights for(i=0; i<LIGHTSIZE; i++){ for(j=0; j<LIGHTSIZE; j++){ x = float(i - LIGHTSIZE / 2) / float(LIGHTSIZE / 2); y = float(j - LIGHTSIZE / 2) / float(LIGHTSIZE / 2); temp = 1.0f - float(sqrt((x * x) + (y * y))); if(temp > 1.0f) temp = 1.0f; if(temp < 0.0f) temp = 0.0f; lightTexture[i][j] = static_cast<unsigned char>(255.0f * temp * temp); } } glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, 1, LIGHTSIZE, LIGHTSIZE, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, lightTexture); temp = float(dSize) * 0.005f; glNewList(1, GL_COMPILE); glBegin(GL_TRIANGLES); glTexCoord2f(0.0f, 0.0f); glVertex3f(-temp, -temp, 0.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(temp, -temp, 0.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(temp, temp, 0.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-temp, -temp, 0.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(temp, temp, 0.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-temp, temp, 0.0f); glEnd(); glEndList(); } // Initialize luminosity difference lumdiff = 1.0f / float(dTrail); // Initialize flux fields fluxes = new flux[dFluxes]; // Initialize text textwriter = new rsText; readyToDraw = 1; } #ifdef RS_XSCREENSAVER void cleanUp(){ // Free memory delete[] fluxes; } #endif #ifdef WIN32 void cleanUp(HWND hwnd){ // Free memory delete[] fluxes; // Kill device context ReleaseDC(hwnd, hdc); wglMakeCurrent(NULL, NULL); wglDeleteContext(hglrc); } // Initialize all user-defined stuff void readRegistry(){ LONG result; HKEY skey; DWORD valtype, valsize, val; setDefaults(DEFAULTS1); result = RegOpenKeyEx(HKEY_CURRENT_USER, registryPath, 0, KEY_READ, &skey); if(result != ERROR_SUCCESS) return; valsize=sizeof(val); result = RegQueryValueEx(skey, "Fluxes", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dFluxes = val; result = RegQueryValueEx(skey, "Particles", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dParticles = val; result = RegQueryValueEx(skey, "Trail", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dTrail = val; result = RegQueryValueEx(skey, "Geometry", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dGeometry = val; result = RegQueryValueEx(skey, "Size", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dSize = val; result = RegQueryValueEx(skey, "Complexity", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dComplexity = val; result = RegQueryValueEx(skey, "Randomize", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dRandomize = val; result = RegQueryValueEx(skey, "Expansion", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dExpansion = val; result = RegQueryValueEx(skey, "Rotation", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dRotation = val; result = RegQueryValueEx(skey, "Wind", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dWind = val; result = RegQueryValueEx(skey, "Instability", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dInstability = val; result = RegQueryValueEx(skey, "Blur", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dBlur = val; result = RegQueryValueEx(skey, "FrameRateLimit", 0, &valtype, (LPBYTE)&val, &valsize); if(result == ERROR_SUCCESS) dFrameRateLimit = val; RegCloseKey(skey); } // Save all user-defined stuff void writeRegistry(){ LONG result; HKEY skey; DWORD val, disp; result = RegCreateKeyEx(HKEY_CURRENT_USER, registryPath, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &skey, &disp); if(result != ERROR_SUCCESS) return; val = dFluxes; RegSetValueEx(skey, "Fluxes", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); val = dParticles; RegSetValueEx(skey, "Particles", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); val = dTrail; RegSetValueEx(skey, "Trail", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); val = dGeometry; RegSetValueEx(skey, "Geometry", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); val = dSize; RegSetValueEx(skey, "Size", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); val = dComplexity; RegSetValueEx(skey, "Complexity", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); val = dRandomize; RegSetValueEx(skey, "Randomize", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); val = dExpansion; RegSetValueEx(skey, "Expansion", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); val = dRotation; RegSetValueEx(skey, "Rotation", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); val = dWind; RegSetValueEx(skey, "Wind", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); val = dInstability; RegSetValueEx(skey, "Instability", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); val = dBlur; RegSetValueEx(skey, "Blur", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); val = dFrameRateLimit; RegSetValueEx(skey, "FrameRateLimit", 0, REG_DWORD, (CONST BYTE*)&val, sizeof(val)); RegCloseKey(skey); } BOOL CALLBACK aboutProc(HWND hdlg, UINT msg, WPARAM wpm, LPARAM lpm){ switch(msg){ case WM_CTLCOLORSTATIC: if(HWND(lpm) == GetDlgItem(hdlg, WEBPAGE)){ SetTextColor(HDC(wpm), RGB(0,0,255)); SetBkColor(HDC(wpm), COLORREF(GetSysColor(COLOR_3DFACE))); return int(GetSysColorBrush(COLOR_3DFACE)); } break; case WM_COMMAND: switch(LOWORD(wpm)){ case IDOK: case IDCANCEL: EndDialog(hdlg, LOWORD(wpm)); break; case WEBPAGE: ShellExecute(NULL, "open", "http://www.reallyslick.com/", NULL, NULL, SW_SHOWNORMAL); } } return false; } void initControls(HWND hdlg){ char cval[16]; SendDlgItemMessage(hdlg, FLUXES, UDM_SETRANGE, 0, LPARAM(MAKELONG(DWORD(100), DWORD(1)))); SendDlgItemMessage(hdlg, FLUXES, UDM_SETPOS, 0, LPARAM(dFluxes)); SendDlgItemMessage(hdlg, PARTICLES, UDM_SETRANGE, 0, LPARAM(MAKELONG(DWORD(1000), DWORD(1)))); SendDlgItemMessage(hdlg, PARTICLES, UDM_SETPOS, 0, LPARAM(dParticles)); SendDlgItemMessage(hdlg, TRAIL, UDM_SETRANGE, 0, LPARAM(MAKELONG(DWORD(10000), DWORD(3)))); SendDlgItemMessage(hdlg, TRAIL, UDM_SETPOS, 0, LPARAM(dTrail)); SendDlgItemMessage(hdlg, GEOMETRY, CB_DELETESTRING, WPARAM(2), 0); SendDlgItemMessage(hdlg, GEOMETRY, CB_DELETESTRING, WPARAM(1), 0); SendDlgItemMessage(hdlg, GEOMETRY, CB_DELETESTRING, WPARAM(0), 0); SendDlgItemMessage(hdlg, GEOMETRY, CB_ADDSTRING, 0, LPARAM("Points")); SendDlgItemMessage(hdlg, GEOMETRY, CB_ADDSTRING, 0, LPARAM("Spheres")); SendDlgItemMessage(hdlg, GEOMETRY, CB_ADDSTRING, 0, LPARAM("Lights")); SendDlgItemMessage(hdlg, GEOMETRY, CB_SETCURSEL, WPARAM(dGeometry), 0); SendDlgItemMessage(hdlg, SIZE, TBM_SETRANGE, 0, LPARAM(MAKELONG(DWORD(1), DWORD(100)))); SendDlgItemMessage(hdlg, SIZE, TBM_SETPOS, 1, LPARAM(dSize)); SendDlgItemMessage(hdlg, SIZE, TBM_SETLINESIZE, 0, LPARAM(1)); SendDlgItemMessage(hdlg, SIZE, TBM_SETPAGESIZE, 0, LPARAM(5)); sprintf(cval, "%d", dSize); SendDlgItemMessage(hdlg, SIZETEXT, WM_SETTEXT, 0, LPARAM(cval)); SendDlgItemMessage(hdlg, COMPLEXITY, TBM_SETRANGE, 0, LPARAM(MAKELONG(DWORD(1), DWORD(10)))); SendDlgItemMessage(hdlg, COMPLEXITY, TBM_SETPOS, 1, LPARAM(dComplexity)); SendDlgItemMessage(hdlg, COMPLEXITY, TBM_SETLINESIZE, 0, LPARAM(1)); SendDlgItemMessage(hdlg, COMPLEXITY, TBM_SETPAGESIZE, 0, LPARAM(2)); if(dGeometry == 1) EnableWindow(GetDlgItem(hdlg, COMPLEXITY), TRUE); else EnableWindow(GetDlgItem(hdlg, COMPLEXITY), FALSE); sprintf(cval, "%d", dComplexity); SendDlgItemMessage(hdlg, COMPLEXITYTEXT, WM_SETTEXT, 0, LPARAM(cval)); SendDlgItemMessage(hdlg, RANDOMIZE, TBM_SETRANGE, 0, LPARAM(MAKELONG(DWORD(0), DWORD(100)))); SendDlgItemMessage(hdlg, RANDOMIZE, TBM_SETPOS, 1, LPARAM(dRandomize)); SendDlgItemMessage(hdlg, RANDOMIZE, TBM_SETLINESIZE, 0, LPARAM(1)); SendDlgItemMessage(hdlg, RANDOMIZE, TBM_SETPAGESIZE, 0, LPARAM(5)); sprintf(cval, "%d", dRandomize); SendDlgItemMessage(hdlg, RANDOMIZETEXT, WM_SETTEXT, 0, LPARAM(cval)); SendDlgItemMessage(hdlg, EXPANSION, TBM_SETRANGE, 0, LPARAM(MAKELONG(DWORD(0), DWORD(100)))); SendDlgItemMessage(hdlg, EXPANSION, TBM_SETPOS, 1, LPARAM(dExpansion)); SendDlgItemMessage(hdlg, EXPANSION, TBM_SETLINESIZE, 0, LPARAM(1)); SendDlgItemMessage(hdlg, EXPANSION, TBM_SETPAGESIZE, 0, LPARAM(5)); sprintf(cval, "%d", dExpansion); SendDlgItemMessage(hdlg, EXPANSIONTEXT, WM_SETTEXT, 0, LPARAM(cval)); SendDlgItemMessage(hdlg, ROTATION, TBM_SETRANGE, 0, LPARAM(MAKELONG(DWORD(0), DWORD(100)))); SendDlgItemMessage(hdlg, ROTATION, TBM_SETPOS, 1, LPARAM(dRotation)); SendDlgItemMessage(hdlg, ROTATION, TBM_SETLINESIZE, 0, LPARAM(1)); SendDlgItemMessage(hdlg, ROTATION, TBM_SETPAGESIZE, 0, LPARAM(5)); sprintf(cval, "%d", dRotation); SendDlgItemMessage(hdlg, ROTATIONTEXT, WM_SETTEXT, 0, LPARAM(cval)); SendDlgItemMessage(hdlg, WIND, TBM_SETRANGE, 0, LPARAM(MAKELONG(DWORD(0), DWORD(100)))); SendDlgItemMessage(hdlg, WIND, TBM_SETPOS, 1, LPARAM(dWind)); SendDlgItemMessage(hdlg, WIND, TBM_SETLINESIZE, 0, LPARAM(1)); SendDlgItemMessage(hdlg, WIND, TBM_SETPAGESIZE, 0, LPARAM(5)); sprintf(cval, "%d", dWind); SendDlgItemMessage(hdlg, WINDTEXT, WM_SETTEXT, 0, LPARAM(cval)); SendDlgItemMessage(hdlg, INSTABILITY, TBM_SETRANGE, 0, LPARAM(MAKELONG(DWORD(1), DWORD(100)))); SendDlgItemMessage(hdlg, INSTABILITY, TBM_SETPOS, 1, LPARAM(dInstability)); SendDlgItemMessage(hdlg, INSTABILITY, TBM_SETLINESIZE, 0, LPARAM(1)); SendDlgItemMessage(hdlg, INSTABILITY, TBM_SETPAGESIZE, 0, LPARAM(5)); sprintf(cval, "%d", dInstability); SendDlgItemMessage(hdlg, INSTABILITYTEXT, WM_SETTEXT, 0, LPARAM(cval)); SendDlgItemMessage(hdlg, BLUR, TBM_SETRANGE, 0, LPARAM(MAKELONG(DWORD(0), DWORD(100)))); SendDlgItemMessage(hdlg, BLUR, TBM_SETPOS, 1, LPARAM(dBlur)); SendDlgItemMessage(hdlg, BLUR, TBM_SETLINESIZE, 0, LPARAM(1)); SendDlgItemMessage(hdlg, BLUR, TBM_SETPAGESIZE, 0, LPARAM(5)); sprintf(cval, "%d", dBlur); SendDlgItemMessage(hdlg, BLURTEXT, WM_SETTEXT, 0, LPARAM(cval)); initFrameRateLimitSlider(hdlg, FRAMERATELIMIT, FRAMERATELIMITTEXT); } BOOL screenSaverConfigureDialog(HWND hdlg, UINT msg, WPARAM wpm, LPARAM lpm){ int ival; char cval[16]; switch(msg){ case WM_INITDIALOG: InitCommonControls(); readRegistry(); initControls(hdlg); return TRUE; case WM_COMMAND: switch(LOWORD(wpm)){ case IDOK: dFluxes = SendDlgItemMessage(hdlg, FLUXES, UDM_GETPOS, 0, 0); dParticles = SendDlgItemMessage(hdlg, PARTICLES, UDM_GETPOS, 0, 0); dTrail = SendDlgItemMessage(hdlg, TRAIL, UDM_GETPOS, 0, 0); dGeometry = SendDlgItemMessage(hdlg, GEOMETRY, CB_GETCURSEL, 0, 0); dSize = SendDlgItemMessage(hdlg, SIZE, TBM_GETPOS, 0, 0); dComplexity = SendDlgItemMessage(hdlg, COMPLEXITY, TBM_GETPOS, 0, 0); dRandomize = SendDlgItemMessage(hdlg, RANDOMIZE, TBM_GETPOS, 0, 0); dExpansion = SendDlgItemMessage(hdlg, EXPANSION, TBM_GETPOS, 0, 0); dRotation = SendDlgItemMessage(hdlg, ROTATION, TBM_GETPOS, 0, 0); dWind = SendDlgItemMessage(hdlg, WIND, TBM_GETPOS, 0, 0); dInstability = SendDlgItemMessage(hdlg, INSTABILITY, TBM_GETPOS, 0, 0); dBlur = SendDlgItemMessage(hdlg, BLUR, TBM_GETPOS, 0, 0); dFrameRateLimit = SendDlgItemMessage(hdlg, FRAMERATELIMIT, TBM_GETPOS, 0, 0); writeRegistry(); // Fall through case IDCANCEL: EndDialog(hdlg, LOWORD(wpm)); break; case DEFAULTS1: setDefaults(DEFAULTS1); initControls(hdlg); break; case DEFAULTS2: setDefaults(DEFAULTS2); initControls(hdlg); break; case DEFAULTS3: setDefaults(DEFAULTS3); initControls(hdlg); break; case DEFAULTS4: setDefaults(DEFAULTS4); initControls(hdlg); break; case DEFAULTS5: setDefaults(DEFAULTS5); initControls(hdlg); break; case DEFAULTS6: setDefaults(DEFAULTS6); initControls(hdlg); break; case ABOUT: DialogBox(mainInstance, MAKEINTRESOURCE(DLG_ABOUT), hdlg, DLGPROC(aboutProc)); break; case GEOMETRY: if(SendDlgItemMessage(hdlg, GEOMETRY, CB_GETCURSEL, 0, 0) == 1) EnableWindow(GetDlgItem(hdlg, COMPLEXITY), TRUE); else EnableWindow(GetDlgItem(hdlg, COMPLEXITY), FALSE); } return TRUE; case WM_HSCROLL: if(HWND(lpm) == GetDlgItem(hdlg, SIZE)){ ival = SendDlgItemMessage(hdlg, SIZE, TBM_GETPOS, 0, 0); sprintf(cval, "%d", ival); SendDlgItemMessage(hdlg, SIZETEXT, WM_SETTEXT, 0, LPARAM(cval)); } if(HWND(lpm) == GetDlgItem(hdlg, COMPLEXITY)){ ival = SendDlgItemMessage(hdlg, COMPLEXITY, TBM_GETPOS, 0, 0); sprintf(cval, "%d", ival); SendDlgItemMessage(hdlg, COMPLEXITYTEXT, WM_SETTEXT, 0, LPARAM(cval)); } if(HWND(lpm) == GetDlgItem(hdlg, RANDOMIZE)){ ival = SendDlgItemMessage(hdlg, RANDOMIZE, TBM_GETPOS, 0, 0); sprintf(cval, "%d", ival); SendDlgItemMessage(hdlg, RANDOMIZETEXT, WM_SETTEXT, 0, LPARAM(cval)); } if(HWND(lpm) == GetDlgItem(hdlg, EXPANSION)){ ival = SendDlgItemMessage(hdlg, EXPANSION, TBM_GETPOS, 0, 0); sprintf(cval, "%d", ival); SendDlgItemMessage(hdlg, EXPANSIONTEXT, WM_SETTEXT, 0, LPARAM(cval)); } if(HWND(lpm) == GetDlgItem(hdlg, ROTATION)){ ival = SendDlgItemMessage(hdlg, ROTATION, TBM_GETPOS, 0, 0); sprintf(cval, "%d", ival); SendDlgItemMessage(hdlg, ROTATIONTEXT, WM_SETTEXT, 0, LPARAM(cval)); } if(HWND(lpm) == GetDlgItem(hdlg, WIND)){ ival = SendDlgItemMessage(hdlg, WIND, TBM_GETPOS, 0, 0); sprintf(cval, "%d", ival); SendDlgItemMessage(hdlg, WINDTEXT, WM_SETTEXT, 0, LPARAM(cval)); } if(HWND(lpm) == GetDlgItem(hdlg, INSTABILITY)){ ival = SendDlgItemMessage(hdlg, INSTABILITY, TBM_GETPOS, 0, 0); sprintf(cval, "%d", ival); SendDlgItemMessage(hdlg, INSTABILITYTEXT, WM_SETTEXT, 0, LPARAM(cval)); } if(HWND(lpm) == GetDlgItem(hdlg, BLUR)){ ival = SendDlgItemMessage(hdlg, BLUR, TBM_GETPOS, 0, 0); sprintf(cval, "%d", ival); SendDlgItemMessage(hdlg, BLURTEXT, WM_SETTEXT, 0, LPARAM(cval)); } if(HWND(lpm) == GetDlgItem(hdlg, FRAMERATELIMIT)) updateFrameRateLimitSlider(hdlg, FRAMERATELIMIT, FRAMERATELIMITTEXT); return TRUE; } return FALSE; } LRESULT screenSaverProc(HWND hwnd, UINT msg, WPARAM wpm, LPARAM lpm){ switch(msg){ case WM_CREATE: readRegistry(); initSaver(hwnd); break; case WM_DESTROY: readyToDraw = 0; cleanUp(hwnd); break; } return defScreenSaverProc(hwnd, msg, wpm, lpm); } #endif // WIN32
28.971971
123
0.681334
NickPepper
0400720c40240e32520f31fa769cd744bb446c1b
2,812
cpp
C++
src/ngraph/pass/dump_sorted.cpp
magrawal128/ngraph
ca911487d1eadfe6ec66dbe3da6f05cee3645b24
[ "Apache-2.0" ]
1
2020-04-28T22:50:33.000Z
2020-04-28T22:50:33.000Z
src/ngraph/pass/dump_sorted.cpp
biswajitcsecu/ngraph
d6bff37d7968922ef81f3bed63379e849fcf3b45
[ "Apache-2.0" ]
1
2019-02-20T20:56:47.000Z
2019-02-22T20:10:28.000Z
src/ngraph/pass/dump_sorted.cpp
biswajitcsecu/ngraph
d6bff37d7968922ef81f3bed63379e849fcf3b45
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // 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 <fstream> #include "ngraph/descriptor/input.hpp" #include "ngraph/descriptor/output.hpp" #include "ngraph/pass/dump_sorted.hpp" #include "ngraph/util.hpp" using namespace std; using namespace ngraph; pass::DumpSorted::DumpSorted(const string& output_file) : m_output_file{output_file} { } bool pass::DumpSorted::run_on_module(vector<shared_ptr<Function>>& functions) { ofstream out{m_output_file}; if (out) { for (shared_ptr<Function> f : functions) { out << "=====================================================================\n"; out << f->get_name() << " start\n"; out << "=====================================================================\n"; for (const shared_ptr<Node>& node : f->get_ordered_ops()) { out << node->get_name() << "("; vector<string> inputs; for (auto& input : node->inputs()) { inputs.push_back(input.get_tensor().get_name()); } out << join(inputs); out << ") -> "; vector<string> outputs; for (auto& output : node->outputs()) { outputs.push_back(output.get_tensor().get_name()); } out << join(outputs); out << "\n"; for (const descriptor::Tensor* tensor : node->liveness_new_list) { out << " N " << tensor->get_name() << "\n"; } for (const descriptor::Tensor* tensor : node->liveness_free_list) { out << " F " << tensor->get_name() << "\n"; } } out << "=====================================================================\n"; out << f->get_name() << " end\n"; out << "=====================================================================\n"; } } return false; }
36.051282
93
0.448791
magrawal128
0402ae3480bcdf1e980db3b3f22209d578338540
384
cpp
C++
AnimationProgramming/src/AnimationProgramming.cpp
Hukunaa/Animation_Programming
b48834a70e79d2bf5a2761c03af042ba0e76ff11
[ "MIT" ]
null
null
null
AnimationProgramming/src/AnimationProgramming.cpp
Hukunaa/Animation_Programming
b48834a70e79d2bf5a2761c03af042ba0e76ff11
[ "MIT" ]
null
null
null
AnimationProgramming/src/AnimationProgramming.cpp
Hukunaa/Animation_Programming
b48834a70e79d2bf5a2761c03af042ba0e76ff11
[ "MIT" ]
null
null
null
// AnimationProgramming.cpp : Defines the entry point for the console application. // #include <iostream> #include "stdafx.h" #include "Engine.h" #include "Simulation.h" #include <Animation.h> int main() { Animation anim; //IF IT CRASHES HERE, RESTART THE PROGRAM Run(&anim, 1400, 800); //IF IT CRASHES HERE, RESTART THE PROGRAM system("PAUSE"); return 0; }
17.454545
82
0.679688
Hukunaa
040adf94d9f986bd60daf16db9f697e06a8efdb6
3,498
cpp
C++
src/EncSim.cpp
luni64/EncSim
0be09144e6f968d65c2a361578fa0819f5bf7bcf
[ "MIT" ]
9
2017-06-12T02:59:45.000Z
2022-03-16T22:27:14.000Z
src/EncSim.cpp
luni64/EncSim
0be09144e6f968d65c2a361578fa0819f5bf7bcf
[ "MIT" ]
3
2019-07-10T10:30:28.000Z
2020-10-06T19:02:14.000Z
src/EncSim.cpp
luni64/EncSim
0be09144e6f968d65c2a361578fa0819f5bf7bcf
[ "MIT" ]
3
2018-07-23T00:36:28.000Z
2021-12-04T16:35:52.000Z
#include "EncSim.h" EncSim::EncSim(unsigned pinA, unsigned pinB, unsigned pinZ) { this->A = pinA; this->B = pinB; this->Z = pinZ; } EncSim& EncSim::begin(/*unsigned pinA, unsigned pinB, int pinZ*/) { phaseA.begin(A); phaseB.begin(B); if (Z < UINT32_MAX) { pinMode(Z, OUTPUT); digitalWriteFast(Z, LOW); } // defaults setFrequency(100); // Quadrature signal with setPhase(90); // 50Hz and 90° phase setTotalBounceDuration(0); // 5ms bouncing setBounceDurationMax(300); // bounce peaks between setBounceDurationMin(30); // 30 and 300µs setPeriod(100); // index pulse every 100 steps current = 0; // reset counter return *this; } void EncSim::moveAbsAsync(int _target) { if (_target == current) return; target = _target; direction = (target >= current) ? 1 : -1; if (!running) mainTimer.begin([this] {pitISR(); }, T[current & 1]); running = true; } // start relative move and return immediately void EncSim::moveRelAsync(int delta) { moveAbsAsync(current + delta); } // move to absolute position (blocking) void EncSim::moveAbs(int target) { moveAbsAsync(target); while (isRunning()) { delay(10); } } // move to relative position (blocking) void EncSim::moveRel(int delta) { moveAbs(current + delta); } // stop movement void EncSim::stop() { mainTimer.end(); running = false; } bool EncSim::isRunning() { return running; } EncSim& EncSim::setFrequency(float f_Hz) { frequency = f_Hz; return setCountRate(frequency, phase); } EncSim& EncSim::setPeriod(unsigned p) { period = p; return *this; } EncSim& EncSim::setPhase(float deg) { phase = deg; return setCountRate(frequency, phase); } EncSim& EncSim::setCountRate(float f_Hz, float phase_deg) { constexpr float minPhase = 5.f; // deg constexpr float maxPhase = 90.f; // deg constexpr float minFreq = 0.2f; // Hz constexpr float maxFreq = 2E6f; // Hz float freq = std::max(minFreq, std::min(maxFreq, f_Hz)); float halfPeriod = 1'000'000 / freq; //µs float phase = max(minPhase, min(maxPhase, phase_deg)); T[0] = halfPeriod * (phase / 90.0); T[1] = 2.0f * halfPeriod - T[0]; frequency = 2'000'000 / (T[0] + T[1]); //Serial.printf("%5f %5f %5f %5f \n", halfPeriod, T[0], T[1], frequency); return *this; } EncSim& EncSim::setTotalBounceDuration(unsigned microseconds) { phaseA.totalBounceTime = microseconds; phaseB.totalBounceTime = microseconds; return *this; } EncSim& EncSim::setBounceDurationMin(unsigned microseconds) { phaseA.minBounceTime = microseconds; phaseB.minBounceTime = microseconds; return *this; } EncSim& EncSim::setBounceDurationMax(unsigned microseconds) { phaseA.maxBounceTime = microseconds; phaseB.maxBounceTime = microseconds; return *this; } EncSim& EncSim::setContinousMode(bool contMode) { continousMode = contMode; return *this; } void EncSim::printSettings(Stream& s) { float phase = 180.0 * T[0] / (T[1] + T[0]); s.printf(" freq: %.0f Hz\n", frequency); s.printf(" phase: %.0f\u00B0\n", phase); s.printf(" period: %d steps\n", period); s.printf(" btot: %d \u00B5s\n", phaseA.totalBounceTime); s.printf(" bmin: %d \u00B5s\n", phaseA.minBounceTime); s.printf(" bmax: %d \u00B5s\n", phaseA.maxBounceTime); s.println(); }
22.423077
77
0.628645
luni64
040ba8b0ae87e46c9614648c4ce38b4ba7b8cf47
2,382
cpp
C++
Dsa self paced course Track/stack/MaxOfMinOfEveryWindowSize.cpp
sagar-maheshwari653/HactoberFest21
76797aba35b7b168688f2702b52defbff4014da8
[ "Unlicense" ]
1
2021-11-21T03:37:18.000Z
2021-11-21T03:37:18.000Z
Dsa self paced course Track/stack/MaxOfMinOfEveryWindowSize.cpp
sonishsinghal/HactoberFest21
c4ca69f2f8198585db9914e8b113290dad07a188
[ "Unlicense" ]
1
2021-10-06T04:41:55.000Z
2021-10-06T04:41:55.000Z
Dsa self paced course Track/stack/MaxOfMinOfEveryWindowSize.cpp
sonishsinghal/HactoberFest21
c4ca69f2f8198585db9914e8b113290dad07a188
[ "Unlicense" ]
1
2021-10-08T12:31:04.000Z
2021-10-08T12:31:04.000Z
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: //Function to find maximum of minimums of every window size. vector<int> maxOfMin(int arr[], int n) { // Your code here stack<int> st; unordered_map<int, int> mp; int i = 0; while (i < n) { if (st.empty() || arr[st.top()] <= arr[i]) st.push(i++); else { int x = st.top(), a; st.pop(); if (!st.empty()) a = i - st.top() - 1; else a = i; cout << "([" << arr[x] << "," << x << "]," << a << ") "; // if (mp.find(a) != mp.end()) // { // auto j = mp.find(a); // if (arr[(*j).second] < arr[x]) // (*j).second = x; // } // else // mp.insert({a, x}); } } // for (auto i = mp.begin(); i != mp.end(); i++) // { // cout << (*i).first << " " << (*i).second << endl; // } // cout << endl; while (!st.empty()) { int x = st.top(); st.pop(); int a; if (!st.empty()) a = n - st.top() - 1; else a = n; cout << "([" << arr[x] << "," << x << "]," << a << ") "; // if (mp.find(a) != mp.end()) // { // auto j = mp.find(a); // if (arr[(*j).second] < arr[x]) // (*j).second = x; // } // else // mp.insert({a, x}); } // for (auto i = mp.begin(); i != mp.end(); i++) // { // cout << (*i).first << " " << (*i).second << endl; // } vector<int> v; return v; } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; Solution ob; vector<int> res = ob.maxOfMin(a, n); for (int i : res) cout << i << " "; cout << endl; } return 0; } // } Driver Code Ends
25.340426
72
0.309824
sagar-maheshwari653
0412411b700494122657cab69ac31fdcd1c9e267
565
cpp
C++
Codeforces/41A - Translation.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/41A - Translation.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/41A - Translation.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; bool is_reversed(const string &, const string &); int main() { string ber_lang, bir_lang; cin >> ber_lang >> bir_lang; if (is_reversed(ber_lang, bir_lang)) cout << "YES" << endl; else cout << "NO" << endl; } bool is_reversed(const string &s1, const string &s2) { if (s1.length() != s2.length()) return false; int j = s1.length() - 1; for (char ch: s1) { if (ch != s2.at(j)) return false; j--; } return true; }
18.833333
54
0.546903
naimulcsx
04145c55e15e83f7eb1d57c758ceaf00a4525c21
801
hpp
C++
SDK/ARKSurvivalEvolved_PrimalItem_GenericMisc_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_PrimalItem_GenericMisc_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_PrimalItem_GenericMisc_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItem_GenericMisc_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass PrimalItem_GenericMisc.PrimalItem_GenericMisc_C // 0x0000 (0x0AE0 - 0x0AE0) class UPrimalItem_GenericMisc_C : public UPrimalItem_Base_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass PrimalItem_GenericMisc.PrimalItem_GenericMisc_C"); return ptr; } void ExecuteUbergraph_PrimalItem_GenericMisc(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
20.538462
114
0.639201
2bite
0423a73330544570ec92984d9801ff01826c27cd
10,825
cpp
C++
Libraries/libcar/Sources/Reader.cpp
djgalloway/xcbuild
936df10e59e5f5d531efca8bd48e445d88e78e0c
[ "BSD-2-Clause-NetBSD" ]
9
2018-04-30T23:18:27.000Z
2021-06-20T15:13:38.000Z
Libraries/libcar/Sources/Reader.cpp
djgalloway/xcbuild
936df10e59e5f5d531efca8bd48e445d88e78e0c
[ "BSD-2-Clause-NetBSD" ]
null
null
null
Libraries/libcar/Sources/Reader.cpp
djgalloway/xcbuild
936df10e59e5f5d531efca8bd48e445d88e78e0c
[ "BSD-2-Clause-NetBSD" ]
4
2018-10-10T19:44:17.000Z
2020-01-12T11:56:31.000Z
/** Copyright (c) 2015-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. */ #include <car/Reader.h> #include <car/Facet.h> #include <car/Rendition.h> #include <car/car_format.h> #include <limits> #include <random> #include <cassert> #include <cstring> using car::Reader; using car::AttributeList; using car::Facet; using car::Rendition; Reader:: Reader(unique_ptr_bom bom) : _bom(std::move(bom)), _keyfmt(ext::nullopt), _facetValues({ }), _renditionValues({ }) { } struct _car_iterator_ctx { Reader const *reader; void *iterator; }; static void _car_tree_iterator(Reader const *reader, const char *tree_variable, bom_tree_iterator tree_iterator, void *iterator) { assert(reader != NULL); assert(iterator != NULL); struct bom_tree_context *tree = bom_tree_alloc_load(reader->bom(), tree_variable); if (tree == NULL) { return; } struct _car_iterator_ctx iterator_ctx = { reader, iterator }; bom_tree_iterate(tree, tree_iterator, &iterator_ctx); bom_tree_free(tree); } void Reader:: facetIterate(std::function<void(Facet const &)> const &iterator) const { for (const auto &item : _facetValues) { Facet facet = Facet::Load(item.first, (struct car_facet_value *)item.second); iterator(facet); } } static void _car_facet_fast_iterator(struct bom_tree_context *tree, void *key, size_t key_len, void *value, size_t value_len, void *ctx) { struct _car_iterator_ctx *iterator_ctx = (struct _car_iterator_ctx *)ctx; (*reinterpret_cast<std::function<void(void *key, size_t key_len, void *value, size_t value_len)> const *>(iterator_ctx->iterator))(key, key_len, value, value_len); } void Reader:: facetFastIterate(std::function<void(void *key, size_t key_len, void *value, size_t value_len)> const &iterator) const { _car_tree_iterator(this, car_facet_keys_variable, _car_facet_fast_iterator, const_cast<void *>(reinterpret_cast<void const *>(&iterator))); } void Reader:: renditionIterate(std::function<void(Rendition const &)> const &iterator) const { auto keyfmt = *_keyfmt; for (const auto &it : _renditionValues) { KeyValuePair kv = (KeyValuePair)it.second; car_rendition_key *rendition_key = (car_rendition_key *)kv.key; struct car_rendition_value *rendition_value = (struct car_rendition_value *)kv.value; AttributeList attributes = AttributeList::Load(keyfmt->num_identifiers, keyfmt->identifier_list, rendition_key); Rendition rendition = Rendition::Load(attributes, rendition_value); iterator(rendition); } } static void _car_rendition_fast_iterator(struct bom_tree_context *tree, void *key, size_t key_len, void *value, size_t value_len, void *ctx) { struct _car_iterator_ctx *iterator_ctx = (struct _car_iterator_ctx *)ctx; (*reinterpret_cast<std::function<void(void *key, size_t key_len, void *value, size_t value_len)> const *>(iterator_ctx->iterator))(key, key_len, value, value_len); } void Reader:: renditionFastIterate(std::function<void(void *key, size_t key_len, void *value, size_t value_len)> const &iterator) const { _car_tree_iterator(this, car_renditions_variable, _car_rendition_fast_iterator, const_cast<void *>(reinterpret_cast<void const *>(&iterator))); } void Reader:: dump() const { int header_index = bom_variable_get(_bom.get(), car_header_variable); struct car_header *header = (struct car_header *)bom_index_get(_bom.get(), header_index, NULL); printf("Magic: %.4s\n", header->magic); printf("UI version: %x\n", header->ui_version); printf("Storage version: %x\n", header->storage_version); printf("Storage Timestamp: %x\n", header->storage_timestamp); printf("Rendition Count: %x\n", header->rendition_count); printf("Creator: %s\n", header->file_creator); printf("Other Creator: %s\n", header->other_creator); printf("UUID: %02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n", header->uuid[0], header->uuid[1], header->uuid[2], header->uuid[3], header->uuid[4], header->uuid[5], header->uuid[6], header->uuid[7], header->uuid[8], header->uuid[9], header->uuid[10], header->uuid[11], header->uuid[12], header->uuid[13], header->uuid[14], header->uuid[15]); printf("Associated Checksum: %x\n", header->associated_checksum); printf("Schema Version: %x\n", header->schema_version); printf("Color space ID: %x\n", header->color_space_id); printf("Key Semantics: %x\n", header->key_semantics); printf("\n"); int extended_metadata_index = bom_variable_get(_bom.get(), car_extended_metadata_variable); if (extended_metadata_index != -1) { struct car_extended_metadata *extended = (struct car_extended_metadata *)bom_index_get(_bom.get(), extended_metadata_index, NULL); printf("Extended metadata: %s\n", extended->contents); printf("\n"); } int key_format_index = bom_variable_get(_bom.get(), car_key_format_variable); struct car_key_format *keyfmt = (struct car_key_format *)bom_index_get(_bom.get(), key_format_index, NULL); printf("Key Format: %.4s\n", keyfmt->magic); printf("Identifier Count: %d\n", keyfmt->num_identifiers); for (uint32_t i = 0; i < keyfmt->num_identifiers; i++) { uint32_t identifier = keyfmt->identifier_list[i]; if (identifier < sizeof(car_attribute_identifier_names) / sizeof(*car_attribute_identifier_names)) { printf("Identifier: %s (%d)\n", car_attribute_identifier_names[identifier] ? car_attribute_identifier_names[identifier] : "(unknown)", identifier); } else { printf("Identifier: (unknown) (%d)\n", identifier); } } printf("\n"); auto part_element_iterator = [](struct bom_tree_context *tree, void *key, size_t key_len, void *value, size_t value_len, void *ctx) { struct car_part_element_key *part_element_key = (struct car_part_element_key *)key; printf("%s ID: %x\n", (char const *)ctx, part_element_key->part_element_id); struct car_part_element_value *part_element_value = (struct car_part_element_value *)value; printf("Unknown 1: %x\n", part_element_value->unknown1); printf("Unknown 2: %x\n", part_element_value->unknown2); printf("Name: %.*s\n", (int)(value_len - sizeof(struct car_part_element_value)), part_element_value->name); printf("\n"); }; struct bom_tree_context *part = bom_tree_alloc_load(_bom.get(), car_part_info_variable); if (part != NULL) { bom_tree_iterate(part, part_element_iterator, (void *)"Part"); bom_tree_free(part); } struct bom_tree_context *element = bom_tree_alloc_load(_bom.get(), car_element_info_variable); if (element != NULL) { bom_tree_iterate(element, part_element_iterator, (void *)"Element"); bom_tree_free(element); } } ext::optional<Reader> Reader:: Load(unique_ptr_bom bom) { int header_index = bom_variable_get(bom.get(), car_header_variable); size_t header_len; struct car_header *header = (struct car_header *)bom_index_get(bom.get(), header_index, &header_len); if (header_len < sizeof(struct car_header) || strncmp(header->magic, "RATC", 4) || header->storage_version < 8) { return ext::nullopt; } auto reader = Reader(std::move(bom)); /* * Iterate through the facets as fast as possible just save the name and value pointer for lookups later. */ reader.facetFastIterate([&reader](void *key, size_t key_len, void *value, size_t value_len) { auto name = std::string(static_cast<char *>(key), key_len); reader._facetValues.insert({ name, value }); }); /* Load the key format from the BOM. */ int key_format_index = bom_variable_get(reader.bom(), car_key_format_variable); struct car_key_format *keyfmt = (struct car_key_format *)bom_index_get(reader.bom(), key_format_index, NULL); if (!keyfmt) { return ext::nullopt; } reader._keyfmt = ext::optional<struct car_key_format*>(keyfmt); /* * The index into the attribute list for the identifer for the matching facet. * The attribute list is a list of uint16_t in the key portion of the entry for the rendition. */ size_t identifier_index = 0; /* Scan the key format for the facet identifier index. */ for (size_t i = 0; i < keyfmt->num_identifiers; i++) { if (keyfmt->identifier_list[i] == car_attribute_identifier_identifier) { identifier_index = i; break; } } /* Iterate through the renditions as fast as possible. Save the key and value pointers, indexed by the Facet identifier. */ reader.renditionFastIterate([identifier_index,&reader](void *key, size_t key_len, void *value, size_t value_len) { KeyValuePair kv; kv.key = key; kv.key_len = key_len; kv.value = value; kv.value_len = value_len; car_rendition_key *rendition_key = (car_rendition_key *)key; reader._renditionValues.insert({ rendition_key[identifier_index], kv }); }); return std::move(reader); } ext::optional<Facet> Reader::lookupFacet(std::string name) const { ext::optional<Facet> result; auto lookup = _facetValues.find(name); if (lookup == _facetValues.end()) { return result; } struct car_facet_value *facet_value = (struct car_facet_value *)lookup->second; AttributeList attributes = AttributeList::Load(facet_value->attributes_count, facet_value->attributes); result = Facet::Create(name, attributes); return result; } std::vector<Rendition> Reader:: lookupRenditions(Facet const &facet) const { std::vector<Rendition> result; ext::optional<uint16_t> facet_identifier = facet.attributes().get(car_attribute_identifier_identifier); if (!facet_identifier) { return result; } if (!_keyfmt) { // Expected to be ready return result; } auto keyfmt = *_keyfmt; auto lookupRendition = _renditionValues.equal_range(*facet_identifier); for (auto it = lookupRendition.first; it != lookupRendition.second; ++it) { KeyValuePair value = (KeyValuePair)it->second; car_rendition_key *rendition_key = (car_rendition_key *)value.key; struct car_rendition_value *rendition_value = (struct car_rendition_value *)value.value; AttributeList attributes = AttributeList::Load(keyfmt->num_identifiers, keyfmt->identifier_list, rendition_key); Rendition rendition = Rendition::Load(attributes, rendition_value); result.push_back(rendition); } return result; }
39.363636
369
0.697182
djgalloway
04241dc9f917c856adeb302e90df8f5a1d0498d7
5,634
hpp
C++
include/desalt/match/match.hpp
dechimal/desalt
29f2bbe9e41850ddd4ebff39958747e504e3a6a3
[ "WTFPL" ]
10
2015-03-05T08:28:29.000Z
2020-10-21T09:52:52.000Z
include/desalt/match/match.hpp
dechimal/desalt
29f2bbe9e41850ddd4ebff39958747e504e3a6a3
[ "WTFPL" ]
null
null
null
include/desalt/match/match.hpp
dechimal/desalt
29f2bbe9e41850ddd4ebff39958747e504e3a6a3
[ "WTFPL" ]
null
null
null
#ifndef DESALT_MATCH_MATCH_HPP_INCLUDED_ #define DESALT_MATCH_MATCH_HPP_INCLUDED_ #include <type_traits> #include <utility> #include <tuple> #include <desalt/match/fwd.hpp> #include <desalt/match/pattern_types.hpp> namespace desalt::match { namespace detail { namespace here = detail; // definitions // match_result template<typename T, typename Patterns, std::size_t ...Is> struct match_result<T, Patterns, std::index_sequence<Is...>> { explicit operator bool() const { return (here::test(val, std::get<Is>(patterns)) && ...); } auto operator*() { return std::tuple_cat(here::get(std::forward<T>(val), std::get<Is>(patterns))...); } T val; Patterns patterns; }; // match template<typename T, typename ...Patterns> auto match(T && v, Patterns && ...patterns) { using type = match_result< T, std::tuple<std::decay_t<Patterns>...>, std::index_sequence_for<Patterns...> >; return type { std::forward<T>(v), std::tuple{std::forward<Patterns>(patterns)...}, }; } // test template<typename T, typename Pattern> auto test(T const & v, Pattern const & pattern) { if constexpr (kind<Pattern, structured_pattern_tag>) { return here::test_structured_pattern(v, pattern, std::make_index_sequence<pattern.size>{}); } else if constexpr (kind<Pattern, value_pattern_tag>) { return here::test(v, pattern.pattern) && here::get_field(v, pattern.pattern) == pattern.val; } else if constexpr (kind<Pattern, tag_pattern_tag>) { return traits::pattern<std::decay_t<T>>::template test<typename std::remove_cv_t<std::remove_reference_t<Pattern>>::tag>(v); } else if constexpr (kind<Pattern, index_pattern_tag>) { return traits::pattern<std::decay_t<T>>::template test<pattern.index>(v); } else if constexpr (kind<Pattern, key_pattern_tag>) { return traits::pattern<std::decay_t<T>>::test(pattern.key, v); } else if constexpr (kind<Pattern, bound_pattern_tag, unbound_pattern_tag>) { return here::test(v, pattern.pattern); } else { static_assert(!std::is_same_v<Pattern, Pattern>); } } template<typename T, typename Structured, std::size_t ...Is> auto test_structured_pattern(T const & v, Structured const & pattern, std::index_sequence<Is...>) { if (here::test(v, pattern.pattern)) { auto const & w = here::get_field(v, pattern.pattern); return (... && here::test(w, std::get<Is>(pattern.patterns))); } else { return false; } } // get template<int HasBinding, typename T, typename Pattern> auto get(T && v, Pattern const & pattern) { constexpr bool has_binding = (HasBinding == -1 ? here::has_binding<Pattern>() >= 0 : (bool)HasBinding); if constexpr (kind<Pattern, structured_pattern_tag>) { return here::get_structured_pattern<has_binding>(std::forward<T>(v), pattern, std::make_index_sequence<pattern.size>{}); } else if constexpr (kind<Pattern, bound_pattern_tag, unbound_pattern_tag, value_pattern_tag>) { return here::get<has_binding>(std::forward<T>(v), pattern.pattern); } else if constexpr (kind<Pattern, tag_pattern_tag, index_pattern_tag, key_pattern_tag>) { if constexpr (has_binding) { return std::forward_as_tuple(get_field(std::forward<T>(v), pattern)); } else { return std::tuple<>{}; } } else { static_assert(!sizeof(Pattern)); } } template<bool HasBinding, typename T, typename Structured, std::size_t ...Is> auto get_structured_pattern(T && v, Structured const & pattern, std::index_sequence<Is...>) { auto && field = here::get_field(std::forward<T>(v), pattern.pattern); using field_type = decltype(field); auto bindings = std::tuple_cat(here::get(std::forward<field_type>(field), std::get<Is>(pattern.patterns))...); if constexpr (HasBinding) { return std::tuple_cat(std::forward_as_tuple(std::forward<field_type>(field)), std::move(bindings)); } else { return bindings; } } // get_field template<typename T, typename Pattern> decltype(auto) get_field(T && v, Pattern const & pattern) { if constexpr (kind<Pattern, tag_pattern_tag>) { return traits::pattern<std::decay_t<T>>::template get<typename std::remove_cv_t<std::remove_reference_t<Pattern>>::tag>(std::forward<T>(v)); } else if constexpr (kind<Pattern, index_pattern_tag>) { return traits::pattern<std::decay_t<T>>::template get<pattern.index>(std::forward<T>(v)); } else if constexpr (kind<Pattern, key_pattern_tag>) { return traits::pattern<std::decay_t<T>>::get(pattern.key, std::forward<T>(v)); } else if constexpr (kind<Pattern, bound_pattern_tag, unbound_pattern_tag, structured_pattern_tag, value_pattern_tag>) { return here::get_field(std::forward<T>(v), pattern.pattern); } else { static_assert(!sizeof(Pattern)); } } // has_binding template<typename Pattern> constexpr int has_binding() { if constexpr (kind<Pattern, bound_pattern_tag>) { return 1; } else if constexpr (kind<Pattern, unbound_pattern_tag>) { return -1; } else if constexpr (kind<Pattern, tag_pattern_tag, index_pattern_tag, key_pattern_tag>) { return 0; } else if constexpr (kind<Pattern, structured_pattern_tag, value_pattern_tag>) { return here::has_binding<typename std::remove_cv_t<std::remove_reference_t<Pattern>>::base_pattern>() > 0 ? 1 : -1; } else { static_assert(!sizeof(Pattern)); } } // at template<typename Key> key_pattern<Key> at(Key && key) { return {std::forward<Key>(key)}; } } } #endif
39.398601
148
0.671282
dechimal
042479c1f005ce0fbd2892bfe2ae3b487bdfff71
8,486
hxx
C++
src/tools.hxx
gregorweiss/Clustering
484eceff161adf972b068b02550d492af33535d5
[ "BSD-2-Clause" ]
9
2019-09-30T15:52:05.000Z
2022-01-23T07:18:49.000Z
src/tools.hxx
gregorweiss/Clustering
484eceff161adf972b068b02550d492af33535d5
[ "BSD-2-Clause" ]
5
2019-05-16T11:13:20.000Z
2021-03-11T17:22:23.000Z
src/tools.hxx
gregorweiss/Clustering
484eceff161adf972b068b02550d492af33535d5
[ "BSD-2-Clause" ]
3
2019-11-21T12:15:03.000Z
2021-04-19T10:45:20.000Z
/* Copyright (c) 2015-2019, Florian Sittel (www.lettis.net) and Daniel Nagel 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. 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 HOLDER 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 "tools.hpp" #include "logger.hpp" #include <iostream> #include <fstream> #include <sstream> #include <iterator> #include <map> #include <algorithm> namespace Clustering { namespace Tools { template <typename NUM> std::tuple<NUM*, std::size_t, std::size_t> read_coords(std::string filename, std::vector<std::size_t> usecols) { std::size_t n_rows=0; std::size_t n_cols=0; std::size_t n_cols_used=0; std::ifstream ifs(filename); Clustering::logger(std::cout) << "~~~ reading coordinates" << std::endl; if (ifs.fail()) { std::cerr << "error: cannot open file '" << filename << "'" << std::endl; exit(EXIT_FAILURE); } Clustering::logger(std::cout) << " from file: " << filename << std::endl; { // determine n_cols std::string linebuf; while (linebuf.empty() && ifs.good()) { std::getline(ifs, linebuf); } std::stringstream ss(linebuf); n_cols = std::distance(std::istream_iterator<std::string>(ss), std::istream_iterator<std::string>()); // go back to beginning to read complete file ifs.seekg(0); // determine n_rows while (ifs.good()) { std::getline(ifs, linebuf); if ( ! linebuf.empty()) { ++n_rows; } } // go back again ifs.clear(); ifs.seekg(0, std::ios::beg); } Clustering::logger(std::cout) << " with dimensions: " << n_rows << "x" << n_cols << "\n" << std::endl; std::map<std::size_t, bool> col_used; if (usecols.size() == 0) { // use all columns n_cols_used = n_cols; for (std::size_t i=0; i < n_cols; ++i) { col_used[i] = true; } } else { // use only defined columns n_cols_used = usecols.size(); for (std::size_t i=0; i < n_cols; ++i) { col_used[i] = false; } for (std::size_t i: usecols) { col_used[i] = true; } } // allocate memory // DC_MEM_ALIGNMENT is defined during cmake and // set depending on usage of SSE2, SSE4_1, AVX or Xeon Phi NUM* coords = (NUM*) _mm_malloc(sizeof(NUM)*n_rows*n_cols_used, DC_MEM_ALIGNMENT); ASSUME_ALIGNED(coords); // read data for (std::size_t cur_row = 0; cur_row < n_rows; ++cur_row) { std::size_t cur_col = 0; for (std::size_t i=0; i < n_cols; ++i) { NUM buf; ifs >> buf; if (col_used[i]) { coords[cur_row*n_cols_used + cur_col] = buf; ++cur_col; } } } return std::make_tuple(coords, n_rows, n_cols_used); } template <typename NUM> void free_coords(NUM* coords) { _mm_free(coords); } template <typename NUM> std::vector<NUM> dim1_sorted_coords(const NUM* coords , std::size_t n_rows , std::size_t n_cols) { std::vector<NUM> sorted_coords(n_rows*n_cols); if (n_cols == 1) { // directly sort on data if just one column for (std::size_t i=0; i < n_rows; ++i) { sorted_coords[i] = coords[i]; } std::sort(sorted_coords.begin(), sorted_coords.end()); } else { std::vector<std::vector<NUM>> c_tmp(n_rows , std::vector<float>(n_cols)); for (std::size_t i=0; i < n_rows; ++i) { for (std::size_t j=0; j < n_cols; ++j) { c_tmp[i][j] = coords[i*n_cols+j]; } } // sort on first index std::sort(c_tmp.begin() , c_tmp.end() , [] (const std::vector<NUM>& lhs , const std::vector<NUM>& rhs) { return lhs[0] < rhs[0]; }); // feed sorted data into 1D-array for (std::size_t i=0; i < n_rows; ++i) { for (std::size_t j=0; j < n_cols; ++j) { sorted_coords[i*n_cols+j] = c_tmp[i][j]; } } } return sorted_coords; } template <typename NUM> std::vector<NUM> boxlimits(const std::vector<NUM>& xs , std::size_t boxsize , std::size_t n_rows , std::size_t n_cols) { //std::size_t n_xs = xs.size() / n_dim; std::size_t n_boxes = n_rows / boxsize; if (n_boxes * boxsize < n_rows) { ++n_boxes; } std::vector<NUM> boxlimits(n_boxes); for (std::size_t i=0; i < n_boxes; ++i) { // split into boxes on 1st dimension // (i.e. col-index == 0) boxlimits[i] = xs[i*boxsize*n_cols]; } return boxlimits; } template <typename NUM> std::pair<std::size_t, std::size_t> min_max_box(const std::vector<NUM>& limits , NUM val , NUM radius) { std::size_t n_boxes = limits.size(); if (n_boxes == 0) { return {0,0}; } else { std::size_t i_min = n_boxes - 1; std::size_t i_max = 0; NUM lbound = val - radius; NUM ubound = val + radius; for (std::size_t i=1; i < n_boxes; ++i) { if (lbound < limits[i]) { i_min = i-1; break; } } for (std::size_t i=n_boxes; 0 < i; --i) { if (limits[i-1] < ubound) { i_max = i-1; break; } } return {i_min, i_max}; } } template <typename KEY, typename VAL> void write_map(std::string filename, std::map<KEY, VAL> mapping, std::string header_comment, bool val_then_key) { std::ofstream ofs(filename); if (ofs.fail()) { std::cerr << "error: cannot open file '" << filename << "' for writing." << std::endl; exit(EXIT_FAILURE); } ofs << header_comment; if (val_then_key) { for (auto key_val: mapping) { ofs << key_val.second << " " << key_val.first << "\n"; } } else { for (auto key_val: mapping) { ofs << key_val.first << " " << key_val.second << "\n"; } } } template <typename NUM> std::vector<NUM> read_single_column(std::string filename) { std::vector<NUM> dat; std::ifstream ifs(filename); if (ifs.fail()) { std::cerr << "error: cannot open file '" << filename << "'" << std::endl; exit(EXIT_FAILURE); } else { while (!ifs.eof() && !ifs.bad()) { NUM buf; ifs >> buf; if ( ! ifs.fail()) { dat.push_back(buf); } else { // if conversion error, skip (comment) line ifs.clear(); ifs.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } } if (dat.empty()) { std::cerr << "error: opened empty file '" << filename << "'" << std::endl; exit(EXIT_FAILURE); } return dat; } template <typename NUM> void write_single_column(std::string filename, std::vector<NUM> dat, std::string header_comment, bool with_scientific_format) { std::ofstream ofs(filename); if (ofs.fail()) { std::cerr << "error: cannot open file '" << filename << "' for writing." << std::endl; exit(EXIT_FAILURE); } ofs << header_comment; if (with_scientific_format) { ofs << std::scientific; } for (NUM i: dat) { ofs << i << "\n"; } } template <typename NUM> NUM string_to_num(const std::string &s) { std::stringstream ss(s); NUM buf; ss >> buf; return buf; } template <typename T> std::vector<T> unique_elements(std::vector<T> xs) { std::sort(xs.begin() , xs.end()); auto last = std::unique(xs.begin() , xs.end()); xs.erase(last , xs.end()); return xs; } } // end namespace Tools } // end namespace Clustering
28.381271
92
0.604054
gregorweiss
0424d8175e3de82ef5e0f2616e4b6aff37349ed5
3,969
cpp
C++
src/Protocols/TelnetProtocol.cpp
kangwenhang/WindTerm
24c96a6aa611675aeb5decf7f673318c0b626399
[ "Apache-2.0" ]
4,267
2019-10-12T03:52:44.000Z
2022-03-31T14:55:28.000Z
src/Protocols/TelnetProtocol.cpp
kangwenhang/WindTerm
24c96a6aa611675aeb5decf7f673318c0b626399
[ "Apache-2.0" ]
537
2020-01-24T09:34:07.000Z
2022-03-31T23:59:11.000Z
src/Protocols/TelnetProtocol.cpp
kangwenhang/WindTerm
24c96a6aa611675aeb5decf7f673318c0b626399
[ "Apache-2.0" ]
337
2019-10-17T00:11:40.000Z
2022-03-31T11:16:56.000Z
/* * Copyright 2020, WindTerm. * * 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 "TelnetProtocol.h" #include <iomanip> #include <mutex> #include <sstream> const char *arrTelnetCmds[] = { "XEOF", "SUSP", "ABORT", "EOR", "SE", "NOP", "DM", "BREAK", "IP", "AO", "AYT", "EC", "EL", "GA", "SB", "WILL", "WONT", "DO", "DONT", "IAC" }; const char *arrTelnetOpts[] = { "BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD", "NAME", "STATUS", "TIMING MARK", "RCTE", "NAOL", "NAOP", "NAOCRD", "NAOHTS", "NAOHTD", "NAOFFD", "NAOVTS", "NAOVTD", "NAOLFD", "EXTEND ASCII", "LOGOUT", "BYTE MACRO", "DATA ENTRY TERMINAL", "SUPDUP", "SUPDUP OUTPUT", "SEND LOCATION", "TERMINAL TYPE", "END OF RECORD", "TACACS UID", "OUTPUT MARKING", "TTYLOC", "3270 REGIME", "X.3 PAD", "NAWS", "TSPEED", "LFLOW", "LINEMODE", "XDISPLOC", "OLD ENVIRON", "AUTHENTICATION", "ENCRYPT", "NEW ENVIRON", "TN3270E", "XAUTH", "CHARSET", "RSP", "COM PORT CONTROL", "SUPPRESS LOCAL ECHO", "START TLS", "KERMIT", "SEND-URL", "FORWARD_X", }; std::string TelnetProtocol::GetCommandName(uchar chTelnetCmd) { if (chTelnetCmd >= TELCMD_XEOF && chTelnetCmd <= TELCMD_IAC) return arrTelnetCmds[chTelnetCmd - TELCMD_XEOF]; std::ostringstream oss; oss << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int)chTelnetCmd << "(Unknown Telnet Command)"; return oss.str(); } std::string TelnetProtocol::GetOptionName(uchar chTelnetOption) { if (chTelnetOption >= TELOPT_BINARY && chTelnetOption <= TELOPT_FORWARD_X) { return arrTelnetOpts[chTelnetOption - TELOPT_BINARY];} else if (chTelnetOption == TELOPT_MCCP1) { return "MUD COMPRESSION PROTOCOL (V1)"; } else if (chTelnetOption == TELOPT_MCCP2) { return "MUD COMPRESSION PROTOCOL (V2)"; } else if (chTelnetOption == TELOPT_MSP) { return "MUD SOUND PROTOCOL"; } else if (chTelnetOption == TELOPT_MXP) { return "MUD EXTENSION PROTOCOL";} else if (chTelnetOption == TELOPT_PRAGMA_LOGON) { return "TELOPT PRAGMA LOGON"; } else if (chTelnetOption == TELOPT_SSPI_LOGON) { return "TELOPT SSPI LOGON"; } else if (chTelnetOption == TELOPT_PRAGMA_HEARTBEAT) { return "TELOPT PRAGMA HEARTBEAT"; } else if (chTelnetOption == TELOPT_EXOPL) { return "EXTENDED OPTIONS LIST"; } std::ostringstream oss; oss << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int)chTelnetOption << "(Unknown Telnet Option)"; return oss.str(); } TelnetOptionVector &TelnetProtocol::GetOptionVector() { static TelnetOptionVector m_vTelnetOption; static std::once_flag flag; std::call_once(flag, [&]() { m_vTelnetOption.clear(); m_vTelnetOption.resize(TELOPT_INDEX_MAX); m_vTelnetOption[TELOPT_INDEX_NAWS].Init(TELOPT_NAWS, TELNET_CLIENT, TELOPT_STATE_INACTIVE_REQUESTED); m_vTelnetOption[TELOPT_INDEX_TTYPE].Init(TELOPT_TTYPE, TELNET_CLIENT, TELOPT_STATE_INACTIVE_REQUESTED); m_vTelnetOption[TELOPT_INDEX_ECHO].Init(TELOPT_ECHO, TELNET_SERVER, TELOPT_STATE_INACTIVE_REQUESTED); m_vTelnetOption[TELOPT_INDEX_SERVER_SGA].Init(TELOPT_SGA, TELNET_SERVER, TELOPT_STATE_INACTIVE_REQUESTED); m_vTelnetOption[TELOPT_INDEX_CLIENT_SGA].Init(TELOPT_SGA, TELNET_CLIENT, TELOPT_STATE_INACTIVE_REQUESTED); m_vTelnetOption[TELOPT_INDEX_SERVER_BIN].Init(TELOPT_BINARY, TELNET_SERVER, TELOPT_STATE_INACTIVE); m_vTelnetOption[TELOPT_INDEX_CLIENT_BIN].Init(TELOPT_BINARY, TELNET_CLIENT, TELOPT_STATE_INACTIVE); }); return m_vTelnetOption; } TelnetProtocol::TelnetProtocol() { m_name = "Telnet"; }
42.223404
133
0.719577
kangwenhang
0426086813c9126af5c4efd16ce569a2bf832915
631
cpp
C++
Sem1/WDI/zielu c++/3.1.cpp
YuunOoO/Code
5e01c53ab54b4cd8e1694e5f343b012797805688
[ "MIT" ]
1
2021-06-03T14:54:30.000Z
2021-06-03T14:54:30.000Z
Sem1/WDI/zielu c++/3.1.cpp
YuunOoO/Code
5e01c53ab54b4cd8e1694e5f343b012797805688
[ "MIT" ]
null
null
null
Sem1/WDI/zielu c++/3.1.cpp
YuunOoO/Code
5e01c53ab54b4cd8e1694e5f343b012797805688
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int liczba; cout << " Program podzielnosci liczby przez 3 / 2" cout << "Podaj liczbe: " << endl; cin>>liczba; if(liczba==0) return 0; if(liczba%3==0) { if(liczba%2==0) { cout<<"jest podzielna przez 3 i 2 , (6)"<<endl; return 0; } cout<<"jest podzielna przez 3 , (3)"<<endl; return 0; } if(liczba%2==0) { cout<<"Jest podzielna przez 2 , (2)"<<endl; return 0; } cout<<"nie jest podzielna ani przez 3 ani przez 2 , (1)"<<endl; return 0; }
20.354839
68
0.499208
YuunOoO
0426e00f10765435e5fb86761a155a32c495fdff
427
cc
C++
tests/mul.spec.cc
ganler/CUWRAP
c7abc3b546739e143163ce4d386f497adca1cb1b
[ "MIT" ]
4
2020-02-08T13:02:19.000Z
2020-02-10T17:59:02.000Z
tests/mul.spec.cc
ganler/CUWRAP
c7abc3b546739e143163ce4d386f497adca1cb1b
[ "MIT" ]
null
null
null
tests/mul.spec.cc
ganler/CUWRAP
c7abc3b546739e143163ce4d386f497adca1cb1b
[ "MIT" ]
null
null
null
#include "test.hpp" #include <cuwrap/kernels/mul.hpp> TEST(Test, MulTwoVectors) { constexpr std::size_t N = 1 << 20; int *a = new int[N](), *b = new int[N](), *r = new int[N](); for (int i = 0; i < N; i++) { a[i] = 2.0f; b[i] = 2.0f; } cuwrap::mul(N, a, b, r); for (int i = 0; i < N; i++) ASSERT_EQ(r[i], 4); delete[] a; delete[] b; delete[] r; }
17.791667
38
0.440281
ganler
54b8897e799a6bcc77211f35ad16ec6affc4b71f
6,258
cpp
C++
src/app/screens/main/help_screen.cpp
nabijaczleweli/controller-display
d7abaa206a0f2bfdbae92a6b8258a6d1a965b6fb
[ "MIT" ]
null
null
null
src/app/screens/main/help_screen.cpp
nabijaczleweli/controller-display
d7abaa206a0f2bfdbae92a6b8258a6d1a965b6fb
[ "MIT" ]
null
null
null
src/app/screens/main/help_screen.cpp
nabijaczleweli/controller-display
d7abaa206a0f2bfdbae92a6b8258a6d1a965b6fb
[ "MIT" ]
null
null
null
// The MIT License (MIT) // Copyright (c) 2017 nabijaczleweli // 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 "help_screen.hpp" #include "../../../data/container.hpp" #include "../../../util/fmt.hpp" #include "../../../util/url.hpp" #include "../../../util/utf.hpp" #include "../../application.hpp" #include "assets.hpp" #include "main_app_screen.hpp" #include <algorithm> #include <cmath> #include <fmt/format.h> #include <tinyfiledialogs.h> using namespace fmt::literals; static const sf::Color unclicked_link_colour(0x04, 0x49, 0xe7); void help_screen::setup() { screen::setup(); auto help_txt = from_utf8(fmt::format( assets::text_help_txt_s, "controller_display_version"_a = CONTROLLER_DISPLAY_VERSION, // "cereal_version"_a = CEREAL_VERSION, // "css_color_parser_js_version"_a = CSS_COLOR_PARSER_JS_VERSION, // "fmt_version"_a = format_version{(FMT_VERSION - (FMT_VERSION % 10000)) / 10000, ((FMT_VERSION - (FMT_VERSION % 100)) / 100) % 100, FMT_VERSION % 100}, // "optional_lite_version"_a = optional_lite_VERSION, // "SFML_version"_a = format_version{SFML_VERSION_MAJOR, SFML_VERSION_MINOR, SFML_VERSION_PATCH}, // "tinyfiledialogs_version"_a = tinyfd_version, // "variant_lite_version"_a = VARIANT_LITE_VERSION, // "whereami_cpp_version"_a = WHEREAMI_CPP_VERSION, // "yaml_cpp_version"_a = YAML_CPP_VERSION)); help_text.setString(help_txt); const auto char_height = help_text.getCharacterSize(); sf::RectangleShape shape; shape.setFillColor(unclicked_link_colour); { const auto first_char_pos = sf::Vector2i(help_text.findCharacterPos(0)); const sf::IntRect rect(first_char_pos, {static_cast<int>(help_text.findCharacterPos(help_txt.find(' ')).x - first_char_pos.x), static_cast<int>(char_height)}); auto link_shape = shape; link_shape.setSize(sf::Vector2f(rect.width, rect.height * 1.2)); link_shape.setPosition(rect.left, rect.top); links.emplace_back(rect, link_shape, "https://github.com/nabijaczleweli/controller-display"); } for(auto pfx : {"http://", "https://"}) for(auto pfx_idx = help_txt.find(pfx); pfx_idx != sf::String::InvalidPos; pfx_idx = help_txt.find(pfx, pfx_idx + 1)) { const auto end_idx = help_txt.find('\n', pfx_idx); const auto pfx_pos = sf::Vector2i(help_text.findCharacterPos(pfx_idx)); sf::IntRect rect(sf::Vector2i(help_text.findCharacterPos(pfx_idx)), {static_cast<int>(help_text.findCharacterPos(end_idx).x - pfx_pos.x), static_cast<int>(char_height)}); auto link_shape = shape; link_shape.setSize(sf::Vector2f(rect.width, rect.height * 1.2)); link_shape.setPosition(rect.left, rect.top); links.emplace_back(rect, link_shape, std::string(help_txt.begin() + pfx_idx, help_txt.begin() + end_idx)); } auto && help_text_bounds = help_text.getGlobalBounds(); app.resize({static_cast<unsigned int>(std::ceil(help_text_bounds.width)), static_cast<unsigned int>(std::ceil(help_text_bounds.height))}); } int help_screen::loop() { return 0; } int help_screen::draw() { app.window.draw(help_text); for(auto && link : links) app.window.draw(std::get<sf::RectangleShape>(link), sf::BlendMultiply); return 0; } int help_screen::handle_event(const sf::Event & event) { if(const auto i = screen::handle_event(event)) return i; if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) app.schedule_screen<main_app_screen>(std::move(saved_layout)); else if(event.type == sf::Event::MouseMoved) { if(std::any_of(links.begin(), links.end(), [&](auto && link) { return std::get<sf::RectangleShape>(link).getGlobalBounds().contains(event.mouseMove.x, event.mouseMove.y); })) app.set_cursor(cursor::type::hand); else app.set_cursor(cursor::type::normal); } else if(event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left) for(auto && link : links) if(std::get<sf::IntRect>(link).contains(event.mouseButton.x, event.mouseButton.y)) launch_browser(std::get<std::string>(link).c_str()); return 0; } help_screen::help_screen(application & theapp, nonstd::optional<sf::String> slayout) : screen(theapp), saved_layout(slayout), help_text("", font_default, 15) { help_text.setFillColor({0xE5, 0xE5, 0xE5}); help_text.setOutlineThickness(1); help_text.setOutlineColor({0x1A, 0x1A, 0x1A}); } help_screen::~help_screen() { app.set_cursor(cursor::type::normal); }
46.355556
159
0.63247
nabijaczleweli
54c07a948d06dc9fa8852f3ebe2aff390dcee4d8
16,475
cpp
C++
coast/modules/Oracle/OracleConnection.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/Oracle/OracleConnection.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/Oracle/OracleConnection.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2009, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "OracleConnection.h" #include "OracleStatement.h" #include "OracleException.h" #include "AnyIterators.h" #include "Threads.h" #include <string.h> // for strlen namespace { Anything fDescriptionCache( Anything::ArrayMarker(), coast::storage::Global() ); ROAnything fDescriptionCacheRO( fDescriptionCache ); RWLock fDescriptionLock( "OracleDescriptorLock", coast::storage::Global() ); } OracleConnection::OracleConnection( OracleEnvironment &rEnv ) : fStatus( eUnitialized ), fOracleEnv( rEnv ), fErrhp(), fSrvhp(), fSvchp(), fUsrhp() { StartTrace(OracleConnection.OracleConnection); // --- if ( AllocateHandle( fErrhp ) /* alloc error handle */ && AllocateHandle( fSvchp ) /* alloc service context handle */ && AllocateHandle( fSrvhp ) /* alloc server connection handle */ && AllocateHandle( fUsrhp ) /* alloc user session handle */ ) { fStatus = eHandlesAllocated; } } bool OracleConnection::Open( String const &strServer, String const &strUsername, String const &strPassword ) { StartTrace(OracleConnection.Open); if ( fStatus < eHandlesAllocated ) { SYSERROR("Allocation of OCI handles failed, can not connect to server [" << strServer << "] with user [" << strUsername << "]!"); return false; } if ( fStatus > eHandlesAllocated ) { SYSERROR("tried to open already opened connection to server [" << strServer << "] and user [" << strUsername << "]!"); return false; } text const *server( reinterpret_cast<const text *> ( (const char *) strServer ) ); text const *username( reinterpret_cast<const text *> ( (const char *) strUsername ) ); text const *password( reinterpret_cast<const text *> ( (const char *) strPassword ) ); String strErr( 128L ); // --- attach server if ( checkError( OCIServerAttach( fSrvhp.getHandle(), fErrhp.getHandle(), server, strlen( (const char *) server ), (ub4) OCI_DEFAULT ), strErr ) ) { SystemLog::Error( String( "FAILED: OCIServerAttach() to server [" ) << strServer << "] failed (" << strErr << ")" ); return false; } fStatus = eServerAttached; // --- set attribute server context in the service context if ( checkError( OCIAttrSet( fSvchp.getHandle(), (ub4) OCI_HTYPE_SVCCTX, fSrvhp.getHandle(), (ub4) 0, (ub4) OCI_ATTR_SERVER, fErrhp.getHandle() ), strErr ) ) { SystemLog::Error( String( "FAILED: OCIAttrSet(): setting attribute <server> into the service context failed (" ) << strErr << ")" ); return false; } // --- set attributes in the authentication handle if ( checkError( OCIAttrSet( fUsrhp.getHandle(), (ub4) OCI_HTYPE_SESSION, (dvoid *) username, (ub4) strlen( (const char *) username ), (ub4) OCI_ATTR_USERNAME, fErrhp.getHandle() ), strErr ) ) { SystemLog::Error( String( "FAILED: OCIAttrSet(): setting attribute <username> in the authentication handle failed (" ) << strErr << ")" ); return false; } if ( checkError( OCIAttrSet( fUsrhp.getHandle(), (ub4) OCI_HTYPE_SESSION, (dvoid *) password, (ub4) strlen( (const char *) password ), (ub4) OCI_ATTR_PASSWORD, fErrhp.getHandle() ), strErr ) ) { SystemLog::Error( String( "FAILED: OCIAttrSet(): setting attribute <password> in the authentication handle failed (" ) << strErr << ")" ); return false; } if ( checkError( OCISessionBegin( fSvchp.getHandle(), fErrhp.getHandle(), fUsrhp.getHandle(), OCI_CRED_RDBMS, (ub4) OCI_DEFAULT ), strErr ) ) { SystemLog::Error( String( "FAILED: OCISessionBegin() with user [" ) << strUsername << "] failed (" << strErr << ")" ); return false; } Trace( "connected to oracle as " << strUsername ) // --- Set the authentication handle into the Service handle if ( checkError( OCIAttrSet( fSvchp.getHandle(), (ub4) OCI_HTYPE_SVCCTX, fUsrhp.getHandle(), (ub4) 0, OCI_ATTR_SESSION, fErrhp.getHandle() ), strErr ) ) { SystemLog::Error( String( "FAILED: OCIAttrSet(): setting attribute <session> into the service context failed (" ) << strErr << ")" ); return false; } fStatus = eSessionValid; return true; } OracleConnection::~OracleConnection() { StartTrace(OracleConnection.~OracleConnection); Close(); fSrvhp.reset(); fSvchp.reset(); fErrhp.reset(); fUsrhp.reset(); fStatus = eUnitialized; } void OracleConnection::Close() { StartTrace(OracleConnection.Close); if ( fStatus == eSessionValid ) { if ( OCISessionEnd( fSvchp.getHandle(), fErrhp.getHandle(), fUsrhp.getHandle(), 0 ) ) { SystemLog::Error( "FAILED: OCISessionEnd() on svchp failed" ); } } if ( fStatus >= eServerAttached ) { if ( OCIServerDetach( fSrvhp.getHandle(), fErrhp.getHandle(), OCI_DEFAULT ) ) { SystemLog::Error( "FAILED: OCIServerDetach() on srvhp failed" ); } } fStatus = eHandlesAllocated; } bool OracleConnection::checkError( sword status ) { bool bRet( true ); if ( status == OCI_SUCCESS || status == OCI_NO_DATA ) { bRet = false; } StatTrace(OracleConnection.checkError, "status: " << (long) status << " retcode: " << (bRet ? "true" : "false"), coast::storage::Current()); return bRet; } bool OracleConnection::checkError( sword status, String &message ) { bool bError( checkError( status ) ); if ( bError ) { message = errorMessage( status ); StatTrace(OracleConnection.checkError, "status: " << (long) status << " message [" << message << "]", coast::storage::Current()); } return bError; } String OracleConnection::errorMessage( sword status ) { // error handling: checks 'status' for errors // in case of an error an error message is generated text errbuf[512]; sb4 errcode; String error( 128L ); switch ( status ) { case OCI_NO_DATA: case OCI_SUCCESS: // no error return error; break; case OCI_SUCCESS_WITH_INFO: error << "Error - OCI_SUCCESS_WITH_INFO"; break; case OCI_NEED_DATA: error << "Error - OCI_NEED_DATA"; break; case OCI_ERROR: if ( fErrhp.getHandle() ) OCIErrorGet( (dvoid *) fErrhp.getHandle(), 1, NULL, &errcode, errbuf, (ub4) sizeof ( errbuf ), OCI_HTYPE_ERROR ); error << "Error - " << (char *) errbuf; break; case OCI_INVALID_HANDLE: error << "Error - OCI_INVALID_HANDLE"; break; case OCI_STILL_EXECUTING: error << "Error - OCI_STILL_EXECUTE"; break; case OCI_CONTINUE: error << "Error - OCI_CONTINUE"; break; default: break; } return error; } OracleStatementPtr OracleConnection::createStatement( String strStatement, long lPrefetchRows, OracleConnection::ObjectType aObjType, String strReturnName ) { StartTrace1(OracleConnection.createStatement, "sp name [" << strStatement << "]"); ROAnything desc; if ( aObjType == OracleConnection::TYPE_UNK ) { try { aObjType = GetSPDescription( strStatement, desc ); strStatement = ConstructSPStr( strStatement, aObjType == OracleConnection::TYPE_FUNC, desc, strReturnName ); Trace(String("prepared stored ") << ( (aObjType == OracleConnection::TYPE_FUNC) ? "function: " : "procedure: ") << strStatement); } catch ( OracleException &ex ) { Trace("caught exception but throwing again..."); throw ex; } } OracleStatementPtr pStmt( new (coast::storage::Current()) OracleStatement( this, strStatement ) ); if ( pStmt.get() ) { pStmt->setPrefetchRows( lPrefetchRows ); if ( pStmt->Prepare() && pStmt->getStatementType() == OracleStatement::STMT_BEGIN ) { pStmt->setSPDescription( desc, strReturnName ); } } return pStmt; } bool checkGetCacheEntry(ROAnything &roaCache, OracleConnection::ObjectType &aObjType, const String &command, ROAnything &desc ) { StartTrace(OracleConnection.checkGetCacheEntry); ROAnything roaCacheEntry; if ( roaCache.LookupPath( roaCacheEntry, command ) ) { desc = roaCacheEntry["description"]; aObjType = (OracleConnection::ObjectType) roaCacheEntry["type"].AsLong( (long) OracleConnection::TYPE_UNK ); TraceAny(roaCacheEntry, "entry [" << command << "] found in cache"); return true; } return false; } OracleConnection::ObjectType OracleConnection::GetSPDescription( const String &command, ROAnything &desc ) { StartTrace(OracleConnection.GetSPDescription); ObjectType aObjType( TYPE_UNK ); { LockUnlockEntry aLockEntry( fDescriptionLock, RWLock::eReading ); if ( checkGetCacheEntry(fDescriptionCacheRO, aObjType, command, desc) ) { return aObjType; } } { LockUnlockEntry aLockEntry( fDescriptionLock, RWLock::eWriting ); // check if someone was faster and already stored the description if ( checkGetCacheEntry(fDescriptionCacheRO, aObjType, command, desc) ) { return aObjType; } Anything anyDesc( fDescriptionCache.GetAllocator() ); Anything anyType( fDescriptionCache.GetAllocator() ); aObjType = ReadSPDescriptionFromDB( command, anyDesc ); anyType = (long) aObjType; SlotPutter::Operate(anyDesc, fDescriptionCache, String(command).Append('.').Append("description")); SlotPutter::Operate(anyType, fDescriptionCache, String(command).Append('.').Append("type")); TraceAny(anyDesc, "new entry [" << command << "] stored in cache"); if ( checkGetCacheEntry(fDescriptionCacheRO, aObjType, command, desc) ) { return aObjType; } } return aObjType; } OracleConnection::ObjectType OracleConnection::DescribeObjectByName(const String &command, DscHandleType &aDschp, OCIParam *&parmh) { StartTrace(OracleConnection.DescribeObjectByName); text const *objptr = reinterpret_cast<const text *> ( (const char *) command ); String strErr( "DescribeObjectByName: " ); sword attrStat = OCIDescribeAny( SvcHandle(), ErrorHandle(), (dvoid *) objptr, (ub4) strlen( (char *) objptr ), OCI_OTYPE_NAME, 0, OCI_PTYPE_UNK, aDschp.getHandle() ); Trace("status after DESCRIBEANY::OCI_PTYPE_UNK: " << (long)attrStat) if ( checkError( attrStat, strErr ) ) { strErr << "{" << command << " is neither a stored procedure nor a function}"; throw OracleException( *this, strErr ); } Trace("get the parameter handle") attrStat = OCIAttrGet( aDschp.getHandle(), OCI_HTYPE_DESCRIBE, (dvoid *) &parmh, 0, OCI_ATTR_PARAM, ErrorHandle() ); Trace("status after OCI_HTYPE_DESCRIBE::OCI_ATTR_PARAM: " << (long)attrStat); if ( checkError( attrStat ) ) { throw OracleException( *this, attrStat ); } ObjectType aStmtType( TYPE_UNK ); ub1 ubFuncType( 0 ); attrStat = OCIAttrGet( parmh, OCI_DTYPE_PARAM, (dvoid *) &ubFuncType, 0, OCI_ATTR_PTYPE, ErrorHandle() ); Trace("status after OCI_DTYPE_PARAM::OCI_ATTR_PTYPE: " << (long)attrStat << " funcType:" << (long)ubFuncType); if ( checkError( attrStat ) ) { throw OracleException( *this, attrStat ); } aStmtType = (ObjectType)ubFuncType; return aStmtType; } OracleConnection::ObjectType OracleConnection::ReadSPDescriptionFromDB( const String &command, Anything &desc ) { StartTrace(OracleConnection.ReadSPDescriptionFromDB); String strErr( "ReadSPDescriptionFromDB: " ); MemChecker aCheckerLocal( "OracleConnection.ReadSPDescriptionFromDB", getEnvironment().getAllocator() ); MemChecker aCheckerGlobal( "OracleConnection.ReadSPDescriptionFromDB", coast::storage::Global()); sword attrStat; DscHandleType aDschp; if ( checkError( ( attrStat = OCIHandleAlloc( getEnvironment().EnvHandle(), aDschp.getVoidAddr(), OCI_HTYPE_DESCRIBE, 0, 0 ) ) ) ) { throw OracleException( *this, attrStat ); } Trace("after HandleAlloc, local allocator:" << reinterpret_cast<long>(getEnvironment().getAllocator())); Trace("after HandleAlloc, global allocator:" << reinterpret_cast<long>(coast::storage::Global())); OCIParam *parmh( 0 ); ObjectType aStmtType = DescribeObjectByName(command, aDschp, parmh); if ( aStmtType == TYPE_SYN ) { Trace("as we identified a synonym, we need to collect the scheme name and the referenced object name to ask for description"); text *name(0); ub4 namelen(0); String strSchemaName; attrStat = OCIAttrGet( (dvoid *) parmh, OCI_DTYPE_PARAM, (dvoid *) &name, (ub4 *) &namelen, OCI_ATTR_SCHEMA_NAME, ErrorHandle() ); if ( checkError( ( attrStat ) ) ) { throw OracleException( *this, attrStat ); } strSchemaName.Append(String( (char *) name, namelen )); Trace("SchemaName: " << strSchemaName); attrStat = OCIAttrGet( (dvoid *) parmh, OCI_DTYPE_PARAM, (dvoid *) &name, (ub4 *) &namelen, OCI_ATTR_NAME, ErrorHandle() ); if ( checkError( ( attrStat ) ) ) { throw OracleException( *this, attrStat ); } if ( strSchemaName.Length() ) { strSchemaName.Append('.'); } strSchemaName.Append(String( (char *) name, namelen )); Trace("trying to get descriptions for " << strSchemaName); aStmtType = DescribeObjectByName(strSchemaName, aDschp, parmh); } bool bIsFunction = ( aStmtType == TYPE_FUNC ); Trace("get the number of arguments and the arg list for stored " << (bIsFunction ? "function" : "procedure")) OCIParam *arglst( 0 ); ub2 numargs = 0; if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) parmh, OCI_DTYPE_PARAM, (dvoid *) &arglst, (ub4 *) 0, OCI_ATTR_LIST_ARGUMENTS, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arglst, OCI_DTYPE_PARAM, (dvoid *) &numargs, (ub4 *) 0, OCI_ATTR_NUM_PARAMS, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } Trace(String("number of arguments: ") << numargs); OCIParam *arg( 0 ); text *name; ub4 namelen; ub2 dtype; OCITypeParamMode iomode; ub4 data_len; // For a procedure, we begin with i = 1; for a function, we begin with i = 0. int start = 0; int end = numargs; if ( !bIsFunction ) { ++start; ++end; } for ( int i = start; i < end; ++i ) { if ( checkError( ( attrStat = OCIParamGet( (dvoid *) arglst, OCI_DTYPE_PARAM, ErrorHandle(), (dvoid **) &arg, (ub4) i ) ) ) ) { throw OracleException( *this, attrStat ); } namelen = 0; name = 0; data_len = 0; if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arg, OCI_DTYPE_PARAM, (dvoid *) &dtype, (ub4 *) 0, OCI_ATTR_DATA_TYPE, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } Trace("Data type: " << dtype) if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arg, OCI_DTYPE_PARAM, (dvoid *) &name, (ub4 *) &namelen, OCI_ATTR_NAME, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } String strName( (char *) name, namelen ); // the first param of a function is the return param if ( bIsFunction && i == start ) { strName = command; Trace("Name: " << strName) } // 0 = IN (OCI_TYPEPARAM_IN), 1 = OUT (OCI_TYPEPARAM_OUT), 2 = IN/OUT (OCI_TYPEPARAM_INOUT) if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arg, OCI_DTYPE_PARAM, (dvoid *) &iomode, (ub4 *) 0, OCI_ATTR_IOMODE, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } Trace("IO type: " << iomode) if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arg, OCI_DTYPE_PARAM, (dvoid *) &data_len, (ub4 *) 0, OCI_ATTR_DATA_SIZE, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } Trace("Size: " << (int)data_len) Anything param( desc.GetAllocator() ); param["Name"] = strName; param["Type"] = dtype; param["Length"] = (int) data_len; param["IoMode"] = iomode; param["Idx"] = (long) ( bIsFunction ? i + 1 : i ); desc.Append( param ); if ( checkError( ( attrStat = OCIDescriptorFree( arg, OCI_DTYPE_PARAM ) ) ) ) { throw OracleException( *this, attrStat ); } } TraceAny(desc, "parameter description"); return aStmtType; } String OracleConnection::ConstructSPStr( String const &command, bool pIsFunction, ROAnything desc, const String &strReturnName ) { String plsql, strParams; plsql << "BEGIN "; AnyExtensions::Iterator<ROAnything> aIter( desc ); ROAnything roaEntry; if ( pIsFunction ) { aIter.Next( roaEntry ); plsql << ":" << ( strReturnName.Length() ? strReturnName : roaEntry["Name"].AsString() ) << " := "; } while ( aIter.Next( roaEntry ) ) { if ( strParams.Length() ) { strParams.Append( ',' ); } strParams.Append( ':' ).Append( roaEntry["Name"].AsString() ); } plsql << command << "(" << strParams << "); END;"; StatTrace(OracleConnection.ConstructSPStr, "SP string [" << plsql << "]", coast::storage::Current()); return plsql; }
36.611111
141
0.683945
zer0infinity
54c39d14d014487a4cdc76357fdbde79e1351641
1,227
cpp
C++
core/src/Behaviors/Actions/Trigger.cpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
36
2015-03-12T10:42:36.000Z
2022-01-12T04:20:40.000Z
core/src/Behaviors/Actions/Trigger.cpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
1
2015-12-17T00:25:43.000Z
2016-02-20T12:00:57.000Z
core/src/Behaviors/Actions/Trigger.cpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
6
2017-06-17T07:57:53.000Z
2019-04-09T21:11:24.000Z
#include "Trigger.hpp" #include "Coding/Encoder.hpp" #include "Coding/Decoder.hpp" using namespace crimild; using namespace crimild::messaging; using namespace crimild::behaviors; using namespace crimild::behaviors::actions; std::list< Trigger * > Trigger::_allTriggers; void Trigger::each( std::function< void( std::string str ) > const &callback ) { for ( const auto &t : _allTriggers ) { callback( t->getTriggerName() ); } } Trigger::Trigger( void ) { } Trigger::Trigger( std::string triggerName ) : _triggerName( triggerName ) { _allTriggers.push_back( this ); } Trigger::~Trigger( void ) { _allTriggers.remove( this ); } void Trigger::init( BehaviorContext *context ) { Behavior::init( context ); } Behavior::State Trigger::step( BehaviorContext *context ) { Log::debug( CRIMILD_CURRENT_CLASS_NAME, "Dispatching behavior event with name ", _triggerName ); broadcastMessage( BehaviorEvent { _triggerName } ); return Behavior::State::SUCCESS; } void Trigger::encode( coding::Encoder &encoder ) { Behavior::encode( encoder ); encoder.encode( "name", _triggerName ); } void Trigger::decode( coding::Decoder &decoder ) { Behavior::decode( decoder ); decoder.decode( "name", _triggerName ); }
20.114754
100
0.715566
hhsaez
54c818ab3a0d5a2e77d409bb2ab68cc3f09a6a44
9,387
cpp
C++
src/QormDefaultSession.cpp
marcobusemann/QMetaOrm
3d133f0e7f9a42cf9abb5dcb9ff79d85f83729b4
[ "MIT" ]
null
null
null
src/QormDefaultSession.cpp
marcobusemann/QMetaOrm
3d133f0e7f9a42cf9abb5dcb9ff79d85f83729b4
[ "MIT" ]
1
2017-07-29T21:22:10.000Z
2017-07-29T21:22:10.000Z
src/QormDefaultSession.cpp
marcobusemann/QMetaOrm
3d133f0e7f9a42cf9abb5dcb9ff79d85f83729b4
[ "MIT" ]
null
null
null
#include <QMetaOrm/QormExceptions.h> #include <QMetaOrm/QormSqlQueryBuilder.h> #include "QormDefaultSession.h" #include "QormEntityMapper.h" #include <QSqlQuery> #include <QUuid> class QormOnDemandRecordMapperImpl : public QormOnDemandRecordMapper { public: QormOnDemandRecordMapperImpl( std::function<QSharedPointer<QObject>(const QormMetaEntity::Ptr&, const QString&)> callback) :m_callback(callback) { } virtual QSharedPointer<QObject> mapToEntity(const QormMetaEntity::Ptr& mapping, const QString& prefix) const override { return m_callback(mapping, prefix); } private: std::function<QSharedPointer<QObject>(const QormMetaEntity::Ptr&, const QString&)> m_callback; }; QString GetThreadIdentifier() { return QUuid::createUuid().toString(); } QormDefaultSession::QormDefaultSession(const QormDatabaseFactory::Ptr& databaseFactory, const QormLogger::Ptr& logger) : m_database(databaseFactory->createDatabase(GetThreadIdentifier())) , m_entityMapper(QormEntityMapper::Ptr(new QormEntityMapper(logger))) , m_entitySqlBuilder(databaseFactory->createSqlQueryBuilder()) { } QormDefaultSession::~QormDefaultSession() { rollback(); } void QormDefaultSession::commit() { m_database.commit(); } void QormDefaultSession::rollback() { m_database.rollback(); } void QormDefaultSession::setupSession() { if (!m_database.isOpen() && !m_database.open()) throw QormConnectToDatabaseException(m_database.lastError()); m_database.transaction(); } int QormDefaultSession::newIdBySequence(const QString &aSequence) { QSqlQuery keyQuery(m_database); if (!keyQuery.exec(m_entitySqlBuilder->buildSequenceSelect(aSequence))) throw QormCouldNotQueryNextSequenceValueException(keyQuery.lastError()); if (!keyQuery.first()) throw QormCouldNotQueryNextSequenceValueException(keyQuery.lastError()); return keyQuery.value(0).value<int>(); } QSharedPointer<QObject> QormDefaultSession::save(const QSharedPointer<QObject>& entity, QormMetaEntity::Ptr mapping) { setupSession(); return mapping->hasValidKey(entity) ? update(entity, mapping) : create(entity, mapping); } void QormDefaultSession::save(const QormSql& sqlQuery) { remove(sqlQuery); } void QormDefaultSession::remove(const QSharedPointer<QObject>& entity, QormMetaEntity::Ptr mapping) { setupSession(); Q_ASSERT_X(mapping->hasValidKey(entity), "remove", "entity has no valid key, removing not possible."); QSqlQuery query(m_database); if (!query.prepare(m_entitySqlBuilder->buildRemove(mapping))) throw QormCouldNotPrepareQueryException(query.lastError()); query.bindValue(0, mapping->getProperty(entity, mapping->getKeyProperty())); if (!query.exec()) throw QormCouldNotExecuteQueryException(query.lastError()); } void QormDefaultSession::remove(const QormSql& sqlQuery) { setupSession(); QSqlQuery query(m_database); if (!query.prepare(sqlQuery.sql)) throw QormCouldNotPrepareQueryException(query.lastError()); auto parameters = sqlQuery.parameters; for (int i = 0; i<parameters.size(); i++) query.bindValue(i, parameters[i]); if (!query.exec()) throw QormCouldNotExecuteQueryException(query.lastError()); } QSharedPointer<QObject> QormDefaultSession::create(const QSharedPointer<QObject>& entity, QormMetaEntity::Ptr mapping) { setupSession(); QSqlQuery query(m_database); auto result = entity; QStringList properties; auto keyStrategy = mapping->getKeyGenerationStrategy(); if (keyStrategy==KeyGenerationStrategy::Sequence) { const auto generatedId = newIdBySequence(mapping->getSequence()); mapping->setProperty(result, mapping->getKeyProperty(), generatedId); if (!query.prepare(m_entitySqlBuilder->buildInsertForSequence(mapping, properties))) throw QormCouldNotPrepareQueryException(query.lastError()); } else if (keyStrategy==KeyGenerationStrategy::Identity) { if (!query.prepare(m_entitySqlBuilder->buildInsertForIdentity(mapping, properties))) throw QormCouldNotPrepareQueryException(query.lastError()); } else Q_ASSERT(false); auto boundedValueIndex = 0; if (keyStrategy == KeyGenerationStrategy::Sequence) { query.bindValue(boundedValueIndex, mapping->getFlatPropertyValue(entity, mapping->getKeyProperty())); ++boundedValueIndex; } for (int propertyIndex = 0; propertyIndex < properties.size(); ++propertyIndex, ++boundedValueIndex) query.bindValue(boundedValueIndex, mapping->getFlatPropertyValue(entity, properties[propertyIndex])); if (!query.exec()) throw QormCouldNotExecuteQueryException(query.lastError()); if (keyStrategy==KeyGenerationStrategy::Identity) mapping->setProperty(result, mapping->getKeyProperty(), query.lastInsertId()); if (query.first()) mapping->setProperty(result, mapping->getKeyProperty(), query.value(0)); return result; } QSharedPointer<QObject> QormDefaultSession::update(const QSharedPointer<QObject>& entity, QormMetaEntity::Ptr mapping) { setupSession(); QSqlQuery query(m_database); QStringList properties; if (!query.prepare(m_entitySqlBuilder->buildUpdate(mapping, properties))) throw QormCouldNotPrepareQueryException(query.lastError()); for (int i = 0; i<properties.size(); i++) query.bindValue(i, mapping->getFlatPropertyValue(entity, properties[i])); query.bindValue(properties.size(), mapping->getProperty(entity, mapping->getKeyProperty())); if (!query.exec()) throw QormCouldNotExecuteQueryException(query.lastError()); return entity; } QSharedPointer<QObject> QormDefaultSession::selectOne(const QVariant& key, QormMetaEntity::Ptr mapping) { return selectOne(QormSql(m_entitySqlBuilder->buildSelect(mapping), QVariantList() << key), mapping); } QSharedPointer<QObject> QormDefaultSession::selectOne(const QormSql& sqlQuery, QormMetaEntity::Ptr mapping) { setupSession(); QSqlQuery query(m_database); if (!query.prepare(sqlQuery.sql)) throw QormCouldNotPrepareQueryException(query.lastError()); auto parameters = sqlQuery.parameters; for (int i = 0; i<parameters.size(); i++) query.bindValue(i, parameters[i]); if (!query.exec()) throw QormCouldNotExecuteQueryException(query.lastError()); auto result = query.next() ? m_entityMapper->mapToEntity(mapping, query.record()) : QSharedPointer<QObject>(); if (query.next()) throw QormMoreThanOneResultException(); return result; } void QormDefaultSession::selectMany( QormMetaEntity::Ptr mapping, std::function<bool(const QSharedPointer<QObject>&)> callback, int skip, int pageSize) { QVariantList conditions; auto sql = m_entitySqlBuilder->buildSelectMany(mapping, skip, pageSize, conditions); selectMany( QormSql(sql, conditions), mapping, callback); } void QormDefaultSession::selectMany( const QormSql& sqlQuery, QormMetaEntity::Ptr mapping, std::function<bool(const QSharedPointer<QObject>&)> callback) { setupSession(); QSqlQuery query(m_database); if (!query.prepare(sqlQuery.sql)) throw QormCouldNotPrepareQueryException(query.lastError()); auto parameters = sqlQuery.parameters; for (int i = 0; i<parameters.size(); i++) query.bindValue(i, parameters[i]); if (!query.exec()) throw QormCouldNotExecuteQueryException(query.lastError()); bool continueWork = true; while (query.next() && continueWork) continueWork = callback(m_entityMapper->mapToEntity(mapping, query.record())); } QList<QSharedPointer<QObject>> QormDefaultSession::selectMany(QormMetaEntity::Ptr mapping, int skip, int pageSize) { QList<QSharedPointer<QObject>> result; auto func = [&result](const QSharedPointer<QObject>& item) -> bool { result.append(item); return true; }; selectMany(mapping, func, skip, pageSize); return result; } QList<QSharedPointer<QObject>> QormDefaultSession::selectMany(const QormSql& sqlQuery, QormMetaEntity::Ptr mapping) { QList<QSharedPointer<QObject>> result; auto func = [&result](const QSharedPointer<QObject>& item) -> bool { result.append(item); return true; }; selectMany(sqlQuery, mapping, func); return result; } void QormDefaultSession::selectManyWithCustomMapping( const QormSql& sqlQuery, std::function<bool(const QormOnDemandRecordMapper*)> callback) { setupSession(); QSqlQuery query(m_database); if (!query.prepare(sqlQuery.sql)) throw QormCouldNotPrepareQueryException(query.lastError()); auto parameters = sqlQuery.parameters; for (int i = 0; i<parameters.size(); i++) query.bindValue(i, parameters[i]); if (!query.exec()) throw QormCouldNotExecuteQueryException(query.lastError()); QormOnDemandRecordMapperImpl recordMapper([&](const QormMetaEntity::Ptr& mapping, const QString& prefix) { return m_entityMapper->mapToEntity(mapping, query.record(), prefix); }); bool continueWork = true; while (query.next() && continueWork) continueWork = callback(&recordMapper); }
30.980198
118
0.712794
marcobusemann
54ca45e4568a6a8d16d2d2924cfa1e7a26ec6d1c
4,250
cpp
C++
code/peakbagger_collection.cpp
akirmse/mountains
a3f119a245ee9f19b1a66ef0c8e7ea002f846ef7
[ "MIT" ]
18
2017-07-11T17:55:45.000Z
2022-03-11T21:37:26.000Z
code/peakbagger_collection.cpp
oargudo/mountains
b295281f81ed93163b71f5caf7465b0a91df8bb2
[ "MIT" ]
1
2019-12-16T23:12:09.000Z
2019-12-17T11:09:48.000Z
code/peakbagger_collection.cpp
oargudo/mountains
b295281f81ed93163b71f5caf7465b0a91df8bb2
[ "MIT" ]
3
2020-04-05T12:13:12.000Z
2021-03-19T13:29:31.000Z
/* * MIT License * * Copyright (c) 2017 Andrew Kirmse * * 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 "peakbagger_collection.h" #include <algorithm> #include <fstream> #include <iostream> #include <sstream> #include <assert.h> #include <string.h> using std::string; static bool StringStartsWith(const std::string &str, const char *prefix) { return 0 == strncmp(str.c_str(), prefix, strlen(prefix)); } PeakbaggerCollection::PeakbaggerCollection() { } bool PeakbaggerCollection::Load(const std::string &filename) { std::ifstream file(filename.c_str()); std::string val; int line = 0; while (file.good()) { ++line; getline(file, val, '>'); // Remove trailing whitespace val.erase(val.find_last_not_of(" \n\r\t") + 1); // Skip blank lines and XML start/end if (val.empty() || StringStartsWith(val, "<?xml") || StringStartsWith(val, "<ex") || StringStartsWith(val, "</ex")) { continue; } float lat, lng, isolation; int id, elevation; char name[1024]; char state[1024]; char prominence_string[1024]; char loj_string[1024]; int num_matched = sscanf(val.c_str(), "<pk i=\"%d\" n=\"%1000[^\"]\" e=\"%d\" r=\"%1000[^ ] s=\"%f\" a=\"%f\" o=\"%f\" l=\"%100[^\"]\" lj=\"%1000[^ /]/>", &id, name, &elevation, (char *) &prominence_string, &isolation, &lat, &lng, state, loj_string); if (num_matched != 9) { fprintf(stderr, "Format error on line %d (%d matched): %s\n", line, num_matched, val.c_str()); return false; } int loj_id = 0; // Is the LoJ ID field non-empty? if (loj_string[0] != '"') { num_matched = sscanf(loj_string, "%d", &loj_id); if (num_matched != 1) { fprintf(stderr, "Format error with LoJ ID on line %d: %s\n", line, loj_string); } } // Has a prominence value? int prominence = atoi(prominence_string); if (prominence_string[0] == '\"') { prominence = PeakbaggerPoint::MISSING_PROMINENCE; } // Replace commas with semicolons in peak name (we use comma as separator) string peak_name(name); std::replace(peak_name.begin(), peak_name.end(), ',', ';'); // Skip non-existent historical peaks if (!StringStartsWith(peak_name, "Pre-")) { PeakbaggerPoint p(id, name, lat, lng, elevation, prominence, isolation, state, loj_id); mPoints.push_back(p); } } return true; } void PeakbaggerCollection::InsertIntoQuadtree(Quadtree *tree) { assert(tree != NULL); for (auto it = mPoints.begin(); it != mPoints.end(); ++it) { tree->Insert(*it); } } void PeakbaggerCollection::SortByProminence() { std::sort(mPoints.begin(), mPoints.end(), [](const PeakbaggerPoint &p1, const PeakbaggerPoint &p2) { return p1.prominence() > p2.prominence(); }); } const std::vector<PeakbaggerPoint> &PeakbaggerCollection::points() const { return mPoints; }
34.274194
133
0.612941
akirmse
54caab7f0befa02f012f05935ffb2d905cb2c762
282
hh
C++
MaxQuadSize.hh
gvissers/quill2
589d7bc3ce20da888547f8f4f6b8da908b3d63a5
[ "Apache-2.0" ]
null
null
null
MaxQuadSize.hh
gvissers/quill2
589d7bc3ce20da888547f8f4f6b8da908b3d63a5
[ "Apache-2.0" ]
null
null
null
MaxQuadSize.hh
gvissers/quill2
589d7bc3ce20da888547f8f4f6b8da908b3d63a5
[ "Apache-2.0" ]
null
null
null
#ifndef MAXQUADSIZE_HH #define MAXQUADSIZE_HH /*! * \file MaxQuadSize * \brief Set of structures to determine the maximum size of a basis function quartet */ #include "CGTOQuad.hh" struct MaxQuadSize { static const size_t size = sizeof(CGTOQuad); }; #endif // MAXQUADSIZE_HH
17.625
85
0.748227
gvissers
54cac30f7cc9070c33f4d5588b42e2682251c684
1,610
cpp
C++
surena4/src/ft_sensor_board/src/main.cpp
amin-amani/humanoid
7493fc566064ff903deb130376eb67e684c6a303
[ "MIT" ]
1
2021-11-16T08:51:26.000Z
2021-11-16T08:51:26.000Z
surena4/src/ft_sensor_board/src/main.cpp
amin-amani/humanoid
7493fc566064ff903deb130376eb67e684c6a303
[ "MIT" ]
1
2018-10-27T13:34:18.000Z
2018-10-27T13:34:18.000Z
surena4/src/ft_sensor_board/src/main.cpp
amin-amani/humanoid
7493fc566064ff903deb130376eb67e684c6a303
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include <QApplication> #include <ros/ros.h> #include <geometry_msgs/Twist.h> #include<std_msgs/Int32MultiArray.h> #include<std_msgs/Int32.h> #include<std_msgs/Float64MultiArray.h> #include <stdlib.h> #include "ft_sensor.h" /// ========================================================================================== /// \brief main /// \param argc /// \param argv /// \return /// ========================================================================================== int main(int argc, char *argv[]) { QApplication a(argc, argv); //Initializes ROS, and sets up a node ros::init(argc, argv, "ft_node"); ros::NodeHandle nh; ROS_INFO("start app"); ros::Rate loop_rate(100); ft_sensor ft; ros::Publisher pub=nh.advertise<std_msgs::Float64MultiArray>("FtSensor",100); qDebug()<<"hid connect "<< ft.Init(0xc251,0x1c01); QVector<double> data; std_msgs::Float64MultiArray msg; std_msgs::MultiArrayDimension msg_dim; msg_dim.label = "ft_sensors"; msg_dim.size = 1; msg.layout.dim.clear(); msg.layout.dim.push_back(msg_dim); while (ros::ok()) { ft.Read(data); // qDebug()<<data[0]<<" "<<data[2]<<" "<<data[4]<<" "<<data[6]<<" "<<data[8]<<" "<<data[10]<<" "<<data[1]<<" "<<data[3]<<" "<<data[5]<<" "<<data[7]<<" "<<data[9]<<" "<<data[11]; msg.data.clear(); for(int i = 0; i < data.count(); i++) msg.data.push_back(data[i]); pub.publish(msg); //ROS_INFO("time"); ros::spinOnce(); //loop_rate.sleep(); } ros::spin(); return 0; // return a.exec(); }
27.288136
184
0.527329
amin-amani
54d0a7a7eb6f6efcad50e315b47e549476edbdd0
294
hh
C++
cycle/restime/_Trapezoidal+/restime.hh
zhanghuanqian/CFDWARP
9340a8526bb263d910f79d79e84dcac7aec211b6
[ "BSD-2-Clause" ]
29
2018-09-13T13:58:18.000Z
2022-03-08T21:44:13.000Z
cycle/restime/_Trapezoidal+/restime.hh
zhanghuanqian/CFDWARP
9340a8526bb263d910f79d79e84dcac7aec211b6
[ "BSD-2-Clause" ]
3
2020-11-10T11:28:30.000Z
2021-11-23T09:21:28.000Z
cycle/restime/_Trapezoidal+/restime.hh
zhanghuanqian/CFDWARP
9340a8526bb263d910f79d79e84dcac7aec211b6
[ "BSD-2-Clause" ]
20
2018-07-26T08:17:37.000Z
2022-03-04T08:41:55.000Z
#define _RESTIME_METHOD "Trapezoidal+ 2nd-Order" #define _RESTIME_BW 2 #define _RESTIME_TRAPEZOIDAL_MUSCL #define _RESTIME_STORAGE_TRAPEZOIDAL #define _RESTIME_STORAGE_TRAPEZOIDAL_MUSCLVARS #define UNSTEADY #define _RESTIME_ACTIONNAME "TrapezoidalPlus" typedef struct { } gl_cycle_restime_t;
24.5
48
0.860544
zhanghuanqian
54d7ceb5ae7b00152ba801e8ba333a7c3df02daa
11,206
hpp
C++
include/algorithm_assembler/utils/heterogeneous_container_functions.hpp
Tristis116/Algorithm-assembler
2da69a7e2842f2c261ce0c81d74b3116687b511f
[ "Apache-2.0" ]
null
null
null
include/algorithm_assembler/utils/heterogeneous_container_functions.hpp
Tristis116/Algorithm-assembler
2da69a7e2842f2c261ce0c81d74b3116687b511f
[ "Apache-2.0" ]
null
null
null
include/algorithm_assembler/utils/heterogeneous_container_functions.hpp
Tristis116/Algorithm-assembler
2da69a7e2842f2c261ce0c81d74b3116687b511f
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019 Ilia S. Kovalev 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 HETEROGENEOUS_CONTAINER_FUNCTIONS_HPP #define HETEROGENEOUS_CONTAINER_FUNCTIONS_HPP #include <type_traits> namespace algorithm_assembler::utils { template<class... Containers> struct concatenation; template<typename... Ts1, typename... Ts2, template<typename...> class C, class C3, class... Containers> struct concatenation<C<Ts1...>, C<Ts2...>, C3, Containers...> { using type = typename concatenation<C<Ts1..., Ts2...>, C3, Containers...>::type; }; template<typename... Ts1, typename... Ts2, template<typename...> class C> struct concatenation<C<Ts1...>, C<Ts2...>> { using type = C<Ts1..., Ts2...>; }; template<class Container> struct concatenation<Container> { using type = Container; }; template<class Container, class... Containers> using concatenation_t = typename concatenation<Container, Containers...>::type; template<typename Container, size_t Index> struct at; template<typename Container, size_t Index> using type_at_t = typename at<Container, Index>::type; template<typename H, typename... Ts, template<typename...> class C> struct at<C<H, Ts...>, 0> { using type = H; }; template<size_t N, typename H, typename... Ts, template<typename...> class C> struct at<C<H, Ts...>, N> { static_assert(N < sizeof...(Ts) + 1, "index out of bounds"); using type = type_at_t<C<Ts...>, N - 1>; }; template<typename, typename...> struct push_front; template<typename... Ts1, typename... Ts2, template<typename...> class C> struct push_front<C<Ts1...>, Ts2...> { using type = C<Ts2..., Ts1...>; }; template<typename Container, typename... Types> using push_front_t = typename push_front<Container, Types...>::type; template<typename, typename...> struct push_back; template<typename... Ts1, typename... Ts2, template<typename...> class C> struct push_back<C<Ts1...>, Ts2...> { using type = C<Ts1..., Ts2...>; }; template<typename Container, typename... Types> using push_back_t = typename push_back<Container, Types...>::type; template<typename Container, typename Type, typename = void> struct contains : public std::false_type {}; template<typename Type, typename H, typename... T, template<typename...> class Container> struct contains < Container<H, T...>, Type, std::enable_if_t<std::is_same_v<Type, H>> > : public std::true_type {}; template<typename Type, typename H, typename... T, template<typename...> class Container> struct contains <Container<H, T...>, Type, std::enable_if_t<!std::is_same_v<Type, H>> > : public contains<Container<T...>, Type> {}; template<typename Container, typename Type> constexpr bool contains_v = contains<Container, Type>::value; template<typename Container> struct tail; template<typename Container> using tail_t = typename tail<Container>::type; template<typename H, typename... T, template<typename...> class Container> struct tail<Container<H, T...>> { using type = Container<T...>; }; template<template<typename...> class Container> struct tail<Container<>> { using type = Container<>; }; template<typename Container, typename T, typename = void> struct remove; template<typename Container, typename T> using remove_t = typename remove<Container, T>::type; template<template<typename...> class Container, typename Type, typename H, typename... T> struct remove<Container<H, T...>, Type, std::enable_if_t<std::is_same_v<H, Type>> > { using type = remove_t<Container<T...>, Type>; }; template<template<typename...> class Container, typename Type, typename H, typename... T> struct remove<Container<H, T...>, Type, std::enable_if_t<!std::is_same_v<H, Type>> > { using type = concatenation_t < Container<H>, remove_t<Container<T...>, Type>>; }; template<template<typename...> class Container, typename Type> struct remove<Container<>, Type> { using type = Container<>; }; template<typename Container> struct unique; template<typename Container> using unique_t = typename unique<Container>::type; template<typename H, typename... T, template<typename...> class Container> struct unique<Container<H, T...>> { using type = push_front_t<unique_t<remove_t<Container<T...>, H>>, H>; }; template<template<typename...> class Container> struct unique<Container<>> { using type = Container<>; }; template<typename Type, class Container, size_t i = 0, typename = void> struct index; template<typename Type, class Container> constexpr size_t index_v = index<Type, Container>::value; template<typename Type, typename H, typename... T, template<typename...> class Container, size_t i> struct index<Type, Container<H, T...>, i, std::enable_if_t<!std::is_same_v<Type, H>> > : public index<Type, Container<T...>, i + 1> {}; template<typename Type, typename H, typename... T, template<typename...> class Container, size_t i> struct index<Type, Container<H, T...>, i, std::enable_if_t<std::is_same_v<Type, H>> > : public std::integral_constant<size_t, i> {}; template<class Container, typename Function> struct map; template<typename T, typename... Ts, template <typename> class F, template<typename...> class Container, typename _> struct map<Container<T, Ts...>, F<_>> { using type = Container< typename F<T>::type, typename F<Ts>::type... >; }; template<template<typename...> class Container, typename F> struct map<Container<>, F> { using type = Container<>; }; template<class Container, class Function> using map_t = typename map<Container, Function>::type; template<class Result, typename Predicate, typename Test, typename... Ts> struct filter_impl; template< class Result, typename H, typename... Ts, template<typename> class Predicate, typename _> struct filter_impl< Result, Predicate<_>, std::enable_if_t<Predicate<H>::value>, H, Ts...> { using type = typename filter_impl<push_back_t<Result, H>, Predicate<_>, void, Ts...>::type; }; template< class Result, typename H, typename... Ts, template<typename> class Predicate, typename _> struct filter_impl< Result, Predicate<_>, std::enable_if_t<!Predicate<H>::value>, H, Ts...> { using type = typename filter_impl<Result, Predicate<_>, void, Ts...>::type; }; template<class Result, typename Predicate, typename Test> struct filter_impl<Result, Predicate, Test> { using type = Result; }; template<class Container, typename Predicate> struct filter; template<template<typename...> class Container, typename Predicate, typename... Ts> struct filter<Container<Ts...>, Predicate> { using type = typename filter_impl<Container<>, Predicate, void, Ts...>::type; }; template<class Container, typename Predicate> using filter_t = typename filter<Container, Predicate>::type; template<class Container, typename Type, typename = void> struct drop_while_type; template<class Container, typename Type> using drop_while_type_t = typename drop_while_type<Container, Type>::type; template<typename Type, template<typename...> class Container, typename H, typename... T> struct drop_while_type<Container<H, T...>, Type, std::enable_if_t<std::is_same_v<Type, H>> > { using type = Container<H, T...>; }; template<typename Type, template<typename...> class Container, typename H, typename... T> struct drop_while_type<Container<H, T...>, Type, std::enable_if_t<!std::is_same_v<Type, H>> > { using type = drop_while_type_t<Container<T...>, Type>; }; template<class Intersection, class Container1, class Container2, typename = void> struct intersection_impl; template< class Intersection, template<typename...> class Container1, typename H, typename... Ts, class Container2 > struct intersection_impl<Intersection, Container1<H, Ts...>, Container2, std::enable_if_t<contains_v<Container2, H>> > { using type = typename intersection_impl<push_back_t<Intersection, H>, Container1<Ts...>, Container2>::type; }; template< class Intersection, template<typename...> class Container1, typename H, typename... Ts, class Container2 > struct intersection_impl<Intersection, Container1<H, Ts...>, Container2, std::enable_if_t<!contains_v<Container2, H>> > { using type = typename intersection_impl<Intersection, Container1<Ts...>, Container2>::type; }; template< class Intersection, template<typename...> class Container1, class Container2 > struct intersection_impl<Intersection, Container1<>, Container2 > { using type = typename Intersection; }; template<class Container, class... Containers> struct intersection; template<template<typename...> class Container1, class Container2, class... Containers, typename... Ts> struct intersection<Container1<Ts...>, Container2, Containers...> { using current_intersection = typename intersection_impl<Container1<>, Container1<Ts...>, Container2>::type; using type = typename intersection<current_intersection, Containers...>::type; }; template<class Container> struct intersection<Container> { using type = Container; }; template<class Container, class... Containers> using intersection_t = typename intersection<unique_t<Container>, Containers...>::type; template<class Substraction, class Container1, class Container2, typename = void> struct substraction_impl; template<class Substraction, template<typename...> class Container1, typename H, typename... Ts, class Container2> struct substraction_impl<Substraction, Container1<H, Ts...>, Container2, std::enable_if_t<contains_v<Container2, H>> > { using type = typename substraction_impl<Substraction, Container1<Ts...>, Container2>::type; }; template<class Substraction, template<typename...> class Container1, typename H, typename... Ts, class Container2> struct substraction_impl<Substraction, Container1<H, Ts...>, Container2, std::enable_if_t<!contains_v<Container2, H>> > { using type = typename substraction_impl<push_back_t<Substraction, H>, Container1<Ts...>, Container2>::type; }; template<class Substraction, template<typename...> class Container1, class Container2> struct substraction_impl<Substraction, Container1<>, Container2> { using type = Substraction; }; template<class Container1, class Container2> struct substraction; template<template<typename...> class Container1, typename... Ts, class Container2> struct substraction<Container1<Ts...>, Container2> { using type = typename substraction_impl<Container1<>, Container1<Ts...>, Container2>::type; }; template<class Container1, class Container2> using substraction_t = typename substraction<Container1, Container2>::type; } #endif
28.2267
109
0.713189
Tristis116
54d9279424de695fb9ccc371637e4293c0936047
312
hh
C++
include/ten/optional.hh
toffaletti/libten
00c6dcc91c8d769c74ed9063277b1120c9084427
[ "Apache-2.0" ]
23
2015-02-28T12:51:54.000Z
2021-07-21T10:34:20.000Z
include/ten/optional.hh
toffaletti/libten
00c6dcc91c8d769c74ed9063277b1120c9084427
[ "Apache-2.0" ]
1
2015-04-26T05:44:18.000Z
2015-04-26T05:44:18.000Z
include/ten/optional.hh
toffaletti/libten
00c6dcc91c8d769c74ed9063277b1120c9084427
[ "Apache-2.0" ]
8
2015-05-04T08:04:11.000Z
2020-09-07T11:30:56.000Z
#ifndef TEN_OPTIONAL_HH #define TEN_OPTIONAL_HH #include "ten/bits/optional.hpp" namespace ten { using std::experimental::optional; using std::experimental::nullopt; using std::experimental::in_place; using std::experimental::in_place_t; using std::experimental::is_not_optional; } #endif
20.8
45
0.74359
toffaletti
54dba8fe7c1f6f30ec133b38c6e952cc9afcf23b
358
cpp
C++
FightingGame/FightingGame/EndingScene.cpp
boxerprogrammer/2d_actiongame_samples
4fb240abe15485ca6299579b208e415eb5d9c8af
[ "MIT" ]
1
2020-10-22T12:03:37.000Z
2020-10-22T12:03:37.000Z
FightingGame/FightingGame/EndingScene.cpp
boxerprogrammer/2d_actiongame_samples
4fb240abe15485ca6299579b208e415eb5d9c8af
[ "MIT" ]
null
null
null
FightingGame/FightingGame/EndingScene.cpp
boxerprogrammer/2d_actiongame_samples
4fb240abe15485ca6299579b208e415eb5d9c8af
[ "MIT" ]
null
null
null
#include "EndingScene.h" #include<DxLib.h> #include"GameMain.h" #include"StaffrollScene.h" EndingScene::EndingScene():_timer(300) { } EndingScene::~EndingScene() { } void EndingScene::Update(const KeyState& key){ DxLib::DrawString(100, 200, "Ending Scene", 0xffffffff); if(--_timer==0){ GameMain::Instance().ChangeScene(new StaffrollScene()); } }
15.565217
57
0.712291
boxerprogrammer