text
stringlengths
8
6.88M
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. ** It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef DOM_DEVICE_ORIENTATION_EVENT_SUPPORT #include "modules/dom/src/orientation/compassneedscalibrationevent.h" #include "modules/device_api/OrientationManager.h" #include "modules/dom/src/domenvironmentimpl.h" #include "modules/dom/src/js/window.h" /* static */ OP_STATUS DOM_CompassNeedsCalibrationEvent::Make(DOM_CompassNeedsCalibrationEvent*& result, DOM_Runtime* runtime) { result = OP_NEW(DOM_CompassNeedsCalibrationEvent, ()); RETURN_IF_ERROR(DOMSetObjectRuntime(result, runtime, runtime->GetPrototype(DOM_Runtime::EVENT_PROTOTYPE), "Event")); result->InitEvent(ONCOMPASSNEEDSCALIBRATION, runtime->GetEnvironment()->GetWindow()); return OpStatus::OK; } /* virtual */ OP_STATUS DOM_CompassNeedsCalibrationEvent::DefaultAction(BOOL /* unused_cancelled */) { OP_ASSERT(GetTarget()->IsA(DOM_TYPE_WINDOW)); g_DAPI_orientation_manager->CompassCalibrationReply(static_cast<JS_Window*>(GetTarget()), prevent_default); return OpStatus::OK; } #endif // DOM_DEVICE_ORIENTATION_EVENT_SUPPORT
#include <cstdio> int main() { int nota; do{ printf("Introduzca la nota [0-10]: "); scanf("%d", &nota); if ((nota<0) || (nota>10)) { printf("Nota no valida. Valor fuera de rango\n"); } }while ((nota<0) || (nota>10)); switch (nota) { case 0: case 1: case 2: case 3: case 4: printf("suspenso"); break; case 5: case 6: printf("bien"); break; case 7: case 8: printf("notable"); break; case 9: case 10: printf("sobresaliente"); break; } return 0; }
#ifndef MYLIBFUNC_H_ #define MYLIBFUNC_H_ #include <opencv2/core/core.hpp> using namespace cv; using namespace std; void find_feature_matches ( const Mat& img_1, const Mat& img_2, vector<KeyPoint>& keypoints_1, vector<KeyPoint>& keypoints_2, vector< DMatch >& matches ); void pose_estimation_2d2d ( vector<KeyPoint> keypoints_1, vector<KeyPoint> keypoints_2, vector< DMatch > matches, Mat& R, Mat& t ); Point2d pixel2cam ( const Point2d& p, const Mat& K ); void triangulation ( const vector< KeyPoint >& keypoint_1, const vector< KeyPoint >& keypoint_2, const vector< DMatch >& matches, const Mat& R, const Mat& t, vector< Point3d >& points ); #endif
#include "chrome/browser/extensions/api/transform/transform_api.h" #include <string> #include "chrome/browser/extensions/extension_tab_util.h" #include "extensions/browser/extension_function_registry.h" #include "extensions/browser/extension_function.h" #include "extensions/common/extension.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/app/chrome_command_ids.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/platform_util.h" namespace extensions { namespace api { TransformOpenFileInCurrentTabFunction::TransformOpenFileInCurrentTabFunction() {} TransformOpenFileInCurrentTabFunction::~TransformOpenFileInCurrentTabFunction() {} bool TransformOpenFileInCurrentTabFunction::RunAsync() { Browser* browser = chrome::FindLastActive(); if (browser) { browser->OpenPDFFile(); } return true; } TransformOpenFileInNewTabFunction::TransformOpenFileInNewTabFunction() {} TransformOpenFileInNewTabFunction::~TransformOpenFileInNewTabFunction() {} bool TransformOpenFileInNewTabFunction::RunAsync() { Browser* browser = chrome::FindLastActive(); if (browser) { content::OpenURLParams params( GURL("chrome-extension://efedgghemmklknfpfmljipnmajjgccpc/content/web/viewer.html"), content::Referrer(), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui::PAGE_TRANSITION_LINK, false); browser->OpenURL(params); browser->OpenPDFFile(); } return true; } TransformShowFileInFloderFunction::TransformShowFileInFloderFunction() {} TransformShowFileInFloderFunction::~TransformShowFileInFloderFunction() {} bool TransformShowFileInFloderFunction::RunAsync() { std::unique_ptr<transform::ShowFileInFloder::Params> params( transform::ShowFileInFloder::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); base::FilePath platform_path(base::UTF8ToWide(params->filename)); DCHECK(!platform_path.empty()); Browser* browser = chrome::FindLastActive(); platform_util::ShowItemInFolder(browser->profile(), platform_path); return true; } ExtensionTransformEventRouter::ExtensionTransformEventRouter( Profile* profile, scoped_refptr<const Extension> extension) : profile_(profile), extension_(extension) { } ExtensionTransformEventRouter::~ExtensionTransformEventRouter() {} void ExtensionTransformEventRouter::SendStartTransform() { if (!EventRouter::Get((content::BrowserContext*)profile_)) return; auto event = std::make_unique<extensions::Event>( events::START_TRANSFORM, transform::OnStartTransform::kEventName, transform::OnStartTransform::Create(), (content::BrowserContext*)profile_); EventRouter::Get((content::BrowserContext*)profile_)->DispatchEventToExtension(extension_->id(), std::move(event)); } } // namespace api } // namespace extensions
// // Created by 송지원 on 2020/06/27. // //바킹독님 덱 강의 STL 사용하지 않고 직접 구현하는 버젼 #include <iostream> using namespace std; const int MAX = 10005; int dat[2*MAX+1]; int head = MAX, tail = MAX; int N; string s; int t; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> N; while (N--) { cin >> s; if (s == "push_front") { cin >> t; dat[--head] = t; } else if (s == "push_back") { cin >> t; dat[tail++] = t; } else if (s == "pop_front") { if (head==tail) cout << "-1\n"; else cout << dat[head++] << "\n"; } else if (s == "pop_back") { if (head==tail) cout << "-1\n"; else cout << dat[--tail] << "\n"; } else if (s == "size") { cout << (tail-head) << "\n"; } else if (s == "empty") { cout << (head==tail) << "\n"; } else if (s == "front") { if (head==tail) cout << "-1\n"; else cout << dat[head] << "\n"; } else { if (head==tail) cout << "-1\n"; else cout << dat[tail-1] << "\n"; } } }
#include "board.h" #include "brick.h" #include <fstream> #include <iostream> using namespace std; Board::Board() { //初始化块,时间间隔,分数 brick = new Brick(this); //从文件读入最高分 FILE *fd =fopen("score.bin","rb+"); for(int i=0;i<10;i++) fscanf(fd, "%d", scoreRank+i); //初始化地图 for(int i=0; i<=21; i++) for(int j=0; j<=11; j++) map[i][j] = '#'; for(int i=0; i<=21; i++) map[i][0] = map[i][11] = '@'; for(int i=1; i<=10; i++) map[21][i] = '@'; } void Board::addTomap() { //将块更新到map for(int i=0; i<4; i++) for(int j=0; j<4; j++) { int tx = brick->x + i; int ty = brick->y + j; if(tx<1 || tx > 20 || ty < 1 || ty > 10) continue; if(brick->block[brick->shape][i][j] != '#') map[tx][ty] = brick->block[brick->shape][i][j]; } //消去完整的行并计算行个数 int cnt = 0; for(int i=20; i>=1; i--) { bool flag = false; for(int j=1; j<=10; j++) if(map[i][j] == '#') { flag = true; break; } if(flag) continue; cnt++; for(int j=i; j>=1; j--) for(int k=1; k<=10; k++) map[j][k] = map[j-1][k]; i++; } if(cnt) score += 1<<(cnt-1); brick->toNext(); } bool Board::endJudge() { for(int i=1; i<=10; i++) if(map[1][i] != '#') { //如果游戏结束,计入排行榜 for(int i=0;i<10;i++) { if(score > scoreRank[i]) { for(int j= 9;j > i;j --) scoreRank[j]=scoreRank[j-1]; scoreRank[i]= score; break; } } FILE *fd =fopen("score.bin","wb+"); for(int i=0;i<10;i++) fprintf(fd, "%d\n", scoreRank[i]); fclose(fd); return true; } return false; }
// Created on: 1995-03-22 // Created by: Jean-Louis Frenkel // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _CDF_StoreList_HeaderFile #define _CDF_StoreList_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <CDM_ListOfDocument.hxx> #include <CDM_MapIteratorOfMapOfDocument.hxx> #include <Standard_Transient.hxx> #include <PCDM_StoreStatus.hxx> class CDM_Document; class CDM_MetaData; class TCollection_ExtendedString; class CDF_StoreList; DEFINE_STANDARD_HANDLE(CDF_StoreList, Standard_Transient) class CDF_StoreList : public Standard_Transient { public: Standard_EXPORT CDF_StoreList(const Handle(CDM_Document)& aDocument); Standard_EXPORT Standard_Boolean IsConsistent() const; //! stores each object of the storelist in the reverse //! order of which they had been added. Standard_EXPORT PCDM_StoreStatus Store (Handle(CDM_MetaData)& aMetaData, TCollection_ExtendedString& aStatusAssociatedText, const Message_ProgressRange& theRange = Message_ProgressRange()); Standard_EXPORT void Init(); Standard_EXPORT Standard_Boolean More() const; Standard_EXPORT void Next(); Standard_EXPORT Handle(CDM_Document) Value() const; DEFINE_STANDARD_RTTIEXT(CDF_StoreList,Standard_Transient) protected: private: Standard_EXPORT void Add (const Handle(CDM_Document)& aDocument); CDM_MapOfDocument myItems; CDM_ListOfDocument myStack; CDM_MapIteratorOfMapOfDocument myIterator; Handle(CDM_Document) myMainDocument; }; #endif // _CDF_StoreList_HeaderFile
static unordered_map<char, int> romandata = { {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}}; int Solution::romanToInt(string s) { int res = 0; int prevNum = 0; for(int i = s.size()-1; i>=0; i--){ int n = romandata[s[i]]; res += (prevNum<=n)?n:-n; prevNum = n; } return res; }
#pragma once #include "stdafx.h" class Payload { public: Payload(_In_ LPCWSTR outName, _Outptr_ IAppxPackageWriter**); ~Payload(); HRESULT GetPackageWriter(); HRESULT AddPayloadFiles(); void cleanup(); private: LPCWSTR encryption; _In_ LPCWSTR outName; _Outptr_ IAppxPackageWriter** writer; HRESULT hr; IStream* outStream; IUri* hashMethod; APPX_PACKAGE_SETTINGS packageSettings; IAppxFactory* appxFactory; };
#pragma once //BaseViewを継承して、ここでオーバライドしたものをLoadBalancingListenerから呼ぶようにしてる class TestView : public BaseView { public: TestView(); ~TestView(); void SetLBC(ExitGames::LoadBalancing::Client* lbc, LoadBalancingListener* lbl); virtual void updateState(int state, const ExitGames::Common::JString& stateStr, const ExitGames::Common::JString& joinedRoomName); private: ExitGames::LoadBalancing::Client* mpLbc; LoadBalancingListener* mpLbl = nullptr; };
#pragma once #define _WINSOCK_DEPRECATED_NO_WARNINGS #pragma comment(lib, "ws2_32.lib") #include <iostream> #include <string> #include <WinSock2.h> #include <shared_mutex> #include "Global.h" #include "PacketManager.h" #include <vector> #include <shared_mutex> #include "Global.h" #include "Connection.h" class Server { public: Server(int port, bool loopBacktoLocalHost = true); ~Server(); bool ListenForNewConnection(); private: bool Getint(std::shared_ptr<Connection> connection, std::int32_t& int32_t); bool GetFloat(std::shared_ptr<Connection> connection, float& flt); bool GetPacketType(std::shared_ptr<Connection> connection, PacketType& packetType); bool sendall(std::shared_ptr<Connection> connection, const char* data, const int totalBytes); bool recvall(std::shared_ptr<Connection> connection, char* data, int totalBytes); void SendString(std::shared_ptr<Connection> connection, const std::string& str); bool GetString(std::shared_ptr<Connection> connection, std::string& str); bool ProcessPacket(std::shared_ptr<Connection> connection, PacketType packetType); void DisconnectClient(std::shared_ptr<Connection> connection); static void ClientHandlerThread(Server& server, std::shared_ptr<Connection> connection); static void PacketSenderThread(Server& server); private: std::vector<std::shared_ptr<Connection>> m_connections; std::shared_mutex m_mutex_connectionMgr; int m_IDCounter = 0; SOCKADDR_IN m_addr; SOCKET m_sListen; bool m_terminateThreads = false; std::vector<std::thread*> m_threads; };
#include "odb/server/tcp-data-server.hh" #include <arpa/inet.h> #include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include "odb/mess/tcp-transfer.hh" namespace odb { namespace { bool err(const char *msg) { std::cerr << "Warning: TCPDataServer: " << msg << "\n"; return false; } } // namespace TCPDataServer::TCPDataServer(int port) : _port(port), _serv_fd(-1), _cli_fd(-1) {} TCPDataServer::~TCPDataServer() { if (_serv_fd != -1) close(_serv_fd); if (_cli_fd != -1) close(_cli_fd); } bool TCPDataServer::connect() { if ((_serv_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return err("Failed to create socket"); // avoid bind error int yes = 1; if (setsockopt(_serv_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) return err("setsockopt SO_REUSEADDR failed"); struct sockaddr_in serv_addr; memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(_port); if (bind(_serv_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) return err("Bind failed"); if (listen(_serv_fd, 10) < 0) return err("Listen failed !"); if ((_cli_fd = accept(_serv_fd, (struct sockaddr *)NULL, NULL)) < 0) return err("Accept failed"); // Disable Nagle algorithm to solve small packets issue if (setsockopt(_cli_fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == -1) return err("setsockopt TCP_NODELAY failed"); return true; } bool TCPDataServer::send_data(const SerialOutBuff &os) { return send_data_tcp(os, _cli_fd); } bool TCPDataServer::recv_data(SerialInBuff &is) { return recv_data_tcp(is, _cli_fd); } } // namespace odb
/* * File: main.cpp * Author: varsha * * Created on July 3, 2013, 11:56 AM */ #include <iostream> #include <sstream> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "libfreenect.h" #include <pthread.h> #include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv/cvaux.h> #include <opencv2/imgproc/imgproc.hpp> #if defined(__APPLE__) #include <GLUT/glut.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #include <GL/glut.h> #include <GL/gl.h> #include <GL/glu.h> #endif #include <math.h> // kinect image reolutions #define DEPTH_XRES 640 #define DEPTH_YRES 480 #define IMAGE_XRES 1280 #define IMAGE_YRES 1024 // Use this to set the size of the display window #define DISPLAY_WINDOW_XRES 640 #define DISPLAY_WINDOW_YRES 512 using namespace std; using namespace cv; string rgb_prefix = "IM_"; string depth_prefix = "DP_"; Mat depthMat(Size(DEPTH_XRES, DEPTH_YRES), CV_16UC1); Mat rgbMat(Size(IMAGE_XRES, IMAGE_YRES), CV_8UC3); Mat leftEye, rightEye; Mat tempMat; int capture_count = 0; class KinectFreenectGl { public: KinectFreenectGl(int xres, int yres); int start(); int stop(); void * startGl(int, char **); void setRGBCallback(void (*cb)(uint8_t*)); void setDepthCallback(void (*cb)(uint16_t*)); static freenect_video_format requested_format; static freenect_video_format current_format; static freenect_resolution requested_resolution; static freenect_resolution current_resolution; static int got_rgb, got_depth; private: pthread_t freenect_thread; int display_xres, display_yres; int window, g_argc; char **argv; static void depth_cb(freenect_device *dev, void *v_depth, uint32_t timestamp); static void rgb_cb(freenect_device *dev, void *v_rgb, uint32_t timestamp); static void *freenect_threadfunc(void* arg); void initGl(int, int); }; static volatile int die; static freenect_device* f_dev; static freenect_context* f_ctx; static pthread_mutex_t gl_backbuf_mutex; static pthread_cond_t gl_frame_cond; static void (*extRGBCb)(uint8_t* rgb); static void (*extDepthCb)(uint16_t* rgb); // back: owned by libfreenect (implicit for depth) // mid: owned by callbacks, "latest frame ready" // front: owned by GL, "currently being drawn" extern uint8_t *depth_mid, *depth_front; extern uint8_t *rgb_back, *rgb_mid, *rgb_front; extern GLuint gl_depth_tex; extern GLuint gl_rgb_tex; extern uint16_t t_gamma[2048]; void resizeGlScene(int, int); void keyPressed(unsigned char key, int x, int y); void drawGlScene(); freenect_video_format KinectFreenectGl::requested_format = FREENECT_VIDEO_RGB; freenect_video_format KinectFreenectGl::current_format = FREENECT_VIDEO_RGB; freenect_resolution KinectFreenectGl::requested_resolution = FREENECT_RESOLUTION_HIGH; freenect_resolution KinectFreenectGl::current_resolution = FREENECT_RESOLUTION_HIGH; int KinectFreenectGl::got_rgb = 0; int KinectFreenectGl::got_depth = 0; // back: owned by libfreenect (implicit for depth) // mid: owned by callbacks, "latest frame ready" // front: owned by GL, "currently being drawn" uint8_t *depth_mid = (uint8_t*) malloc(DEPTH_XRES*DEPTH_YRES * 3); uint8_t *depth_front = (uint8_t*) malloc(DEPTH_XRES*DEPTH_YRES * 3); uint8_t *rgb_back = (uint8_t*) malloc(IMAGE_XRES*IMAGE_YRES * 3); uint8_t *rgb_mid = (uint8_t*) malloc(IMAGE_XRES*IMAGE_YRES * 3); uint8_t *rgb_front = (uint8_t*) malloc(IMAGE_XRES*IMAGE_YRES * 3); GLuint gl_depth_tex; GLuint gl_rgb_tex; uint16_t t_gamma[2048]; KinectFreenectGl::KinectFreenectGl(int xres, int yres) { pthread_mutex_init(&gl_backbuf_mutex, NULL); pthread_cond_init(&gl_frame_cond, NULL); die = 0; display_xres = xres; display_yres = yres; } void resizeGlScene(int Width, int Height) { glViewport(0, 0, Width, Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // left right bottom top znear zfar // bottom left - (0,0) invert the bottom and top....opencv -> opengl glOrtho(0, Width, Height, 0, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void KinectFreenectGl::initGl(int Width, int Height) { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0); glDepthFunc(GL_LESS); glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); glDisable(GL_ALPHA_TEST); glEnable(GL_TEXTURE_2D); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glShadeModel(GL_FLAT); glGenTextures(1, &gl_depth_tex); glBindTexture(GL_TEXTURE_2D, gl_depth_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glGenTextures(1, &gl_rgb_tex); glBindTexture(GL_TEXTURE_2D, gl_rgb_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); resizeGlScene(Width, Height); } void * KinectFreenectGl::startGl(int argc, char **argv) { printf("GL thread\n"); glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH); glutInitWindowSize(display_xres, display_yres); glutInitWindowPosition(0, 0); window = glutCreateWindow("LibFreenect"); glutDisplayFunc(&drawGlScene); glutIdleFunc(&drawGlScene); glutReshapeFunc(&resizeGlScene); glutKeyboardFunc(&keyPressed); initGl(display_xres, display_yres); glutMainLoop(); return NULL; } void KinectFreenectGl::depth_cb(freenect_device *dev, void *v_depth, uint32_t timestamp) { int i; uint16_t *depth = (uint16_t*) v_depth; pthread_mutex_lock(&gl_backbuf_mutex); for (i = 0; i < 640 * 480; i++) { int pval = t_gamma[depth[i]]; int lb = pval & 0xff; switch (pval >> 8) { case 0: depth_mid[3 * i + 0] = 255; depth_mid[3 * i + 1] = 255 - lb; depth_mid[3 * i + 2] = 255 - lb; break; case 1: depth_mid[3 * i + 0] = 255; depth_mid[3 * i + 1] = lb; depth_mid[3 * i + 2] = 0; break; case 2: depth_mid[3 * i + 0] = 255 - lb; depth_mid[3 * i + 1] = 255; depth_mid[3 * i + 2] = 0; break; case 3: depth_mid[3 * i + 0] = 0; depth_mid[3 * i + 1] = 255; depth_mid[3 * i + 2] = lb; break; case 4: depth_mid[3 * i + 0] = 0; depth_mid[3 * i + 1] = 255 - lb; depth_mid[3 * i + 2] = 255; break; case 5: depth_mid[3 * i + 0] = 0; depth_mid[3 * i + 1] = 0; depth_mid[3 * i + 2] = 255 - lb; break; default: depth_mid[3 * i + 0] = 0; depth_mid[3 * i + 1] = 0; depth_mid[3 * i + 2] = 0; break; } } // Send the data to the application's callback function if (extDepthCb != NULL) { extDepthCb(depth); } got_depth++; pthread_cond_signal(&gl_frame_cond); pthread_mutex_unlock(&gl_backbuf_mutex); } void KinectFreenectGl::rgb_cb(freenect_device *dev, void *rgb, uint32_t timestamp) { pthread_mutex_lock(&gl_backbuf_mutex); // swap buffers assert(rgb_back == rgb); rgb_back = rgb_mid; freenect_set_video_buffer(dev, rgb_back); rgb_mid = (uint8_t*) rgb; // Send the data to the application's callback function if (extRGBCb != NULL) { extRGBCb((uint8_t*) rgb); } got_rgb++; pthread_cond_signal(&gl_frame_cond); pthread_mutex_unlock(&gl_backbuf_mutex); } void *KinectFreenectGl::freenect_threadfunc(void* arg) { while (!die && freenect_process_events(f_ctx) >= 0) { } return NULL; } int KinectFreenectGl::start() { int i; for (i = 0; i < 2048; i++) { float v = i / 2048.0; v = powf(v, 3)* 6; t_gamma[i] = v * 6 * 256; } if (freenect_init(&f_ctx, NULL) < 0) { printf("freenect_init() failed\n"); return 1; } freenect_select_subdevices(f_ctx, (freenect_device_flags) (FREENECT_DEVICE_MOTOR | FREENECT_DEVICE_CAMERA)); int nr_devices = freenect_num_devices(f_ctx); printf("Number of devices found: %d\n", nr_devices); int user_device_number = 0; if (nr_devices < 1) { freenect_shutdown(f_ctx); return 1; } if (freenect_open_device(f_ctx, &f_dev, user_device_number) < 0) { printf("Could not open device\n"); freenect_shutdown(f_ctx); return 1; } freenect_set_tilt_degs(f_dev, 10); freenect_set_led(f_dev, LED_RED); freenect_set_depth_callback(f_dev, KinectFreenectGl::depth_cb); freenect_set_video_callback(f_dev, KinectFreenectGl::rgb_cb); freenect_set_video_mode(f_dev, freenect_find_video_mode(current_resolution, current_format)); freenect_set_depth_mode(f_dev, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_11BIT)); freenect_set_video_buffer(f_dev, rgb_back); freenect_start_depth(f_dev); freenect_start_video(f_dev); int res; res = pthread_create(&freenect_thread, NULL, freenect_threadfunc, NULL); if (res) { printf("pthread_create failed\n"); freenect_shutdown(f_ctx); return 1; } } int KinectFreenectGl::stop() { printf("\nshutting down streams..."); die = 1; freenect_stop_depth(f_dev); freenect_stop_video(f_dev); freenect_close_device(f_dev); freenect_shutdown(f_ctx); pthread_join(KinectFreenectGl::freenect_thread, NULL); glutDestroyWindow(window); free(depth_mid); free(depth_front); free(rgb_back); free(rgb_mid); printf("-- done!\n"); // Not pthread_exit because OSX leaves a thread lying around and doesn't exit exit(0); } void KinectFreenectGl::setRGBCallback(void (*cb)(uint8_t* rgb)) { extRGBCb = cb; } void KinectFreenectGl::setDepthCallback(void (*cb)(uint16_t* rgb)) { extDepthCb = cb; } KinectFreenectGl* kinect; void drawGlScene() { pthread_mutex_lock(&gl_backbuf_mutex); freenect_video_format current_format = KinectFreenectGl::current_format; freenect_video_format requested_format = KinectFreenectGl::requested_format; int got_rgb = KinectFreenectGl::got_rgb; int got_depth = KinectFreenectGl::got_depth; // When using YUV_RGB mode, RGB frames only arrive at 15Hz, so we shouldn't force them to draw in lock-step. // However, this is CPU/GPU intensive when we are receiving frames in lockstep. if (current_format == FREENECT_VIDEO_YUV_RGB) { while (!got_depth && !got_rgb) { pthread_cond_wait(&gl_frame_cond, &gl_backbuf_mutex); } } else { while ((!got_depth || !got_rgb) && requested_format != current_format) { pthread_cond_wait(&gl_frame_cond, &gl_backbuf_mutex); } } if (requested_format != current_format) { pthread_mutex_unlock(&gl_backbuf_mutex); return; } uint8_t *tmp; // if facetracker has found eyes and updated the bbox and prob values, // render the updated rgbMat instead of rgb_front if (got_rgb) { int from_to[] = {0, 2, 1, 1, 2, 0}; mixChannels(&rgbMat, 1, &tempMat, 1, from_to, 3); // cvtColor(rgbMat, rgbMat, CV_RGB2BGR); rgb_front = (uint8_t*) tempMat.data; KinectFreenectGl::got_rgb = 0; } pthread_mutex_unlock(&gl_backbuf_mutex); glBindTexture(GL_TEXTURE_2D, gl_rgb_tex); if (current_format == FREENECT_VIDEO_RGB || current_format == FREENECT_VIDEO_YUV_RGB) glTexImage2D(GL_TEXTURE_2D, 0, 3, IMAGE_XRES, IMAGE_YRES, 0, GL_RGB, GL_UNSIGNED_BYTE, rgb_front); else glTexImage2D(GL_TEXTURE_2D, 0, 1, IMAGE_XRES, IMAGE_YRES, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, rgb_front + IMAGE_XRES * 4); glBegin(GL_TRIANGLE_FAN); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glTexCoord2f(0, 0); glVertex3f(0, 0, 0); glTexCoord2f(1, 0); glVertex3f(DISPLAY_WINDOW_XRES, 0, 0); glTexCoord2f(1, 1); glVertex3f(DISPLAY_WINDOW_XRES, DISPLAY_WINDOW_YRES, 0); glTexCoord2f(0, 1); glVertex3f(0, DISPLAY_WINDOW_YRES, 0); glEnd(); if (got_depth) { KinectFreenectGl::got_depth = 0; } glutSwapBuffers(); } void saveKinectData() { string rgb_filename = rgb_prefix + to_string(capture_count) + ".png"; string depth_filename = depth_prefix + to_string(capture_count) + ".png"; imwrite(rgb_filename, rgbMat); for (int i = 0; i < depthMat.rows; i++) { for (int j = 0; j < depthMat.cols; j++) { float d = (float) depthMat.at<ushort>(i,j); if(d<2047) depthMat.at<ushort> (i, j) = 1000.0 / (d * -0.0030711016 + 3.3309495161); else depthMat.at<ushort> (i, j) = 0; } } imwrite(depth_filename, depthMat); cout << "Saved frame " << to_string(capture_count) << endl; capture_count++; } void keyPressed(unsigned char key, int x, int y) { if (key == 27) { // initiate a shutdown kinect->stop(); } if (key == 'c') { // Save rgb and depth image saveKinectData(); } } void rgbCallback(uint8_t* rgb) { // Get the data from the Kinect memcpy(rgbMat.data, rgb, IMAGE_XRES * IMAGE_YRES * 3 * sizeof (uint8_t)); cvtColor(rgbMat, rgbMat, CV_BGR2RGB); } void depthCallback(uint16_t* depth) { memcpy(depthMat.data, depth, DEPTH_YRES * DEPTH_XRES * sizeof (uint16_t)); } int main(int argc, char **argv) { tempMat = Mat(IMAGE_YRES, IMAGE_XRES, CV_8UC3); // Set up Kinect kinect = new KinectFreenectGl(DISPLAY_WINDOW_XRES, DISPLAY_WINDOW_YRES); kinect->start(); kinect->setRGBCallback(rgbCallback); kinect->setDepthCallback(depthCallback); // OS X requires GLUT to run on the main thread kinect->startGl(argc, argv); return 0; }
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include "caf/response_promise.hpp" #include "caf/detail/type_list.hpp" namespace caf { /// A response promise can be used to deliver a uniquely identifiable /// response message from the server (i.e. receiver of the request) /// to the client (i.e. the sender of the request). template <class... Ts> class typed_response_promise { public: using forwarding_stack = response_promise::forwarding_stack; /// Constructs an invalid response promise. typed_response_promise() = default; typed_response_promise(none_t x) : promise_(x) { // nop } typed_response_promise(strong_actor_ptr self, strong_actor_ptr source, forwarding_stack stages, message_id id) : promise_(std::move(self), std::move(source), std::move(stages), id) { // nop } typed_response_promise(strong_actor_ptr self, mailbox_element& src) : promise_(std::move(self), src) { // nop } typed_response_promise(typed_response_promise&&) = default; typed_response_promise(const typed_response_promise&) = default; typed_response_promise& operator=(typed_response_promise&&) = default; typed_response_promise& operator=(const typed_response_promise&) = default; /// Implicitly convertible to untyped response promise. [[deprecated("Use the typed_response_promise directly.")]] operator response_promise&() { return promise_; } /// Satisfies the promise by sending a non-error response message. template <class U, class... Us> typename std::enable_if<(sizeof...(Us) > 0) || !std::is_convertible<U, error>::value, typed_response_promise>::type deliver(U&& x, Us&&... xs) { static_assert( std::is_same<detail::type_list<Ts...>, detail::type_list<typename std::decay<U>::type, typename std::decay<Us>::type...>>::value, "typed_response_promise: message type mismatched"); promise_.deliver(std::forward<U>(x), std::forward<Us>(xs)...); return *this; } /// Satisfies the promise by sending either an error or a non-error response /// message. template <class T> void deliver(expected<T> x) { if (x) return deliver(std::move(*x)); return deliver(std::move(x.error())); } /// Satisfies the promise by delegating to another actor. template <message_priority P = message_priority::normal, class Handle = actor, class... Us> typed_response_promise delegate(const Handle& dest, Us&&... xs) { promise_.template delegate<P>(dest, std::forward<Us>(xs)...); return *this; } /// Satisfies the promise by sending an error response message. /// For non-requests, nothing is done. typed_response_promise deliver(error x) { promise_.deliver(std::move(x)); return *this; } /// Returns whether this response promise replies to an asynchronous message. bool async() const { return promise_.async(); } /// Queries whether this promise is a valid promise that is not satisfied yet. bool pending() const { return promise_.pending(); } /// Returns the source of the corresponding request. const strong_actor_ptr& source() const { return promise_.source(); } /// Returns the remaining stages for the corresponding request. const forwarding_stack& stages() const { return promise_.stages(); } /// Returns the actor that will receive the response, i.e., /// `stages().front()` if `!stages().empty()` or `source()` otherwise. strong_actor_ptr next() const { return promise_.next(); } /// Returns the message ID of the corresponding request. message_id id() const { return promise_.id(); } private: response_promise promise_; }; } // namespace caf
#include "RegularGrid.h" RegularGrid::RegularGrid(QObject *parent): Grid(parent) { rows = 10; cols = 10; } RegularGrid::~RegularGrid() { for (int i=0; i<grid.length(); ++i) delete grid[i]; } PointCloudT *RegularGrid::getCloudData(int row, int col) { return grid[row*cols + col]->getCloud(); } void RegularGrid::run() { if (!cloud) { emit gridError("Regular Grid Error: No input cloud"); return; } emit gridStarted(); // Calculate load bar stuff int maxProgress = rows*cols + 2*cloud->points.size(); int onePercent = 0.01*maxProgress; int progress = 0; int percent = 0; // Calculate the bounding box // PointT minPoint, maxPoint; // pcl::getMinMax3D(*cloud, minPoint, maxPoint); minX = 99999; minY = 99999; maxX = -99999; maxY = -99999; for (int i=0; i<cloud->points.size(); ++i) { if (cloud->points[i].x < minX) minX = cloud->points[i].x; else if (cloud->points[i].x > maxX) maxX = cloud->points[i].x; if (cloud->points[i].y < minY) minY = cloud->points[i].y; else if (cloud->points[i].y > maxY) maxY = cloud->points[i].y; ++progress; if (progress % onePercent == 0) emit gridProgress(percent++); } // minX = minPoint.x; // maxX = maxPoint.x; // minY = minPoint.y; // maxY = maxPoint.y; // Initialize the empty grid grid.reserve(rows*cols); for (int row=0; row<rows; ++row) for (int col=0; col<cols; ++col) grid.append(0); // Calculate grid cell size and spacing double cellWidth = (maxX - minX) / cols; double cellHeight = (maxY - minY) / rows; // Create the grid cells for (int row=0; row<rows; ++row) { for (int col=0; col<cols; ++col) { double cellX = minX + cellWidth*col; double cellY = minY + cellHeight*row; GridCell *cell = new GridCell(cellX, cellX + cellWidth, cellY, cellY + cellHeight, 0); grid[row*cols + col] = cell; ++progress; if (progress % onePercent == 0) emit gridProgress(percent++); } } // Add the points to the grid for (int i=0; i<cloud->points.size(); ++i) { PointT newPoint(cloud->points[i]); int gridRow = floor((newPoint.x - minX) / cellWidth); int gridCol = floor((newPoint.y - minY) / cellHeight); if (gridRow == rows) gridRow -= 1; // The maximum point is going to want if (gridCol == cols) gridCol -= 1; // to be in a cell outside of the grid // std::cout << gridRow << '\t' << gridCol << std::endl; grid[gridRow*rows + gridCol]->addPoint(newPoint); ++progress; if (progress % onePercent == 0) emit gridProgress(percent++); } emit gridFinished(this); } void RegularGrid::setNumRows(int rows) { this->rows = rows; } void RegularGrid::setNumCols(int cols) { this->cols = cols; }
// Problem => We have to find the length of longest arithmetic array #include<iostream> using namespace std; int main(){ int n; cout<<"Please enter the size of array: "; cin>>n; int arr[n]; for(int i=0; i<n; i++){ cout<<"Please enter elements in the array: "; cin>>arr[i]; } int ans = 2; int pd = arr[1] - arr[0]; int j=2; int curr = 2; while(j<n){ if(pd == arr[j] - arr[j-1]){ curr++; } else{ pd = arr[j]; curr =2; } ans = max(ans, curr); j++; } cout<<ans<<endl; } /* Intuition & Approach 1. Loop over the array and find the answer. 2. Maintain the following variables: @ Previous Common Difference (pd) @ Current Arithmetic Subarray (curr) @ Max arithmetic subarray length (ans) */
#pragma once #include "ofMain.h" #include "ofxGui.h" #include "functions.h" #include "kalman.hpp" #include <vector> #include <Eigen/Dense> class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void exit(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); bool bFill; bool bWireframe; //system time float elaspsedTime; //elapsed time on the photdiode float t1=-1,t2=-1,t3=-1,t4=-1; // total time for the 4 sweeping double sampleTime= 10; //timers double timeInit,timeInitAccel,timeAccel; // Scanning flag number int scanningFlag=0; // Rotation spped for the lighthouse double omega=(4*pi)/sampleTime; //minimum scalar product between the lighthouse-object vector and the normal to the plan vector double minDot1=99,minDot2=99,minDot3=99,minDot4=99; //time and position for the acceleration double time1=0,time2=0,time3=0; double posx1=0,posx2=0,posx3=0; double posy1=0,posy2=0,posy3=0; double posz1=0,posz2=0,posz3=0; // Acceleration and computed speed double accelX, accelY, accelZ, vitesseX=0, vitesseY=0, vitesseZ=0; //acceleration frequence time calculus (in second) double accelTime=sampleTime/3; // .dat files for the graphics float dots[100000]; float TIMES[100000]; float TimesR[100000]; float posXOpt[100000]; float posYOpt[100000]; float posZOpt[100000]; float posXReal[100000]; float posYReal[100000]; float posZReal[100000]; float posXAcc[100000]; float posYAcc[100000]; float posZAcc[100000]; float posXKalman[100000]; float posYKalman[100000]; float posZKalman[100000]; //iteration value int i=0; //rotation of lighthouses double rotationZA,rotationYA,rotationXA,rotationZB,rotationYB,rotationXB; //time for Kalman calculus double timeKalman,timeKalman_init; double posAccelX=0,posAccelY=0,posAccelZ=0; // Panel parameters ofxPanel gui; ofxIntSlider width; ofxIntSlider height; ofxIntSlider depth; ofxIntSlider posx; ofxIntSlider posy; ofxIntSlider posz; ofxIntSlider rotx; ofxIntSlider roty; ofxIntSlider rotz; //object orientation ofVec3f euler; //position obtainted with the lighthouse ofVec3f posCalc; // light of the room ofLight pointLight; ofLight pointLight2; ofLight pointLight3; ofMaterial material; ofEasyCam cam; // the room ofBoxPrimitive box; //normal to the plan vector ofVec3f n1,n2,n3,n4; //lighthouse and object position ofVec3f p1,p2,pobj; //vector in the lighthouse-object plan ofVec3f plan1,plan2,plan3,plan4; // lighthouse representation ofSpherePrimitive lightHouse1; ofSpherePrimitive lightHouse2; // balls representing the object and the plan ofSpherePrimitive obj,b1,b2,b3,b4; //ball representing the estimated object zith different methods ofSpherePrimitive objCalc,objKalman,objCalcAccel; //lighthouse flashes ofColor flashColor1; ofColor flashColor2; //toggles ofxToggle objreal; ofxToggle objdiode; ofxToggle objaccel; ofxToggle objkalman; // Kalman filter KalmanFilter kf; }; double calculAccel(double pos1, double pos2, double pos3, double t1, double t2, double t3); ofVec3f calculPosition(float width, float heigth, float depth, float rotationXA, float rotationYA, float rotationZA, float rotationXB, float rotationYB, float rotationZB, float tA1, float tA2, float tB1, float tB2, float sampleTime);
#ifndef FEED_H #define FEED_H #include <QObject> #include <QGraphicsRectItem> #include "bio.h" class Feed : public QObject, public QGraphicsRectItem, public Bio { Q_OBJECT public: Feed(); Feed(QGraphicsScene * s); ~Feed(); void Draw(); void Move(); }; #endif // FEED_H
#pragma once #include <string> class GameProgressManager { public: enum GameProgressState { NOT_STARTED, LOADING_LEVEL, LOADING_SAVED_GAME, IN_PROGRESS, PAUSED, FINISHED, GAME_OVER }; public: friend class Core; GameProgressManager(); ~GameProgressManager(); void init(); GameProgressState getGameProgressState(){return m_gameProgressState;}; void setGameProgressState(GameProgressState state){m_gameProgressState = state;}; int getLevel(){return m_level;}; void setLevel(int x){m_level = x;}; std::string getGameName( ){return m_gameName;}; void setGameName( std::string name ){m_gameName = name;}; private: GameProgressState m_gameProgressState; int m_level; std::string m_gameName; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; -*- * * Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef XML_AIT_SUPPORT #include "modules/dochand/aitparser.h" #include "modules/hardcore/base/baseincludes.h" #include "modules/xmlutils/xmlparser.h" #include "modules/xmlutils/xmlfragment.h" //static OP_STATUS AITParser::Parse(URL &url, AITData &ait_data) { XMLFragment fragment; int retval = fragment.Parse(url); if (OpStatus::IsError(retval)) return retval; fragment.EnterAnyElement(); // Find all Application elemets that are present and collect their // information in one large list. do { while (fragment.HasCurrentElement() && !uni_str_eq(fragment.GetElementName().GetLocalPart(), "Application")) { if (!fragment.HasMoreElements()) fragment.LeaveElement(); fragment.EnterAnyElement(); } // Found an application. if (fragment.HasCurrentElement() && uni_str_eq(fragment.GetElementName().GetLocalPart(), "Application")) { OP_STATUS status; AITApplication *application = OP_NEW(AITApplication, ()); RETURN_OOM_IF_NULL(application); status = ait_data.applications.Add(application); if (OpStatus::IsError(status)) { OP_DELETE(application); return status; } TempBuffer buffer; // Parse the application data. do { if (!fragment.HasMoreElements()) fragment.LeaveElement(); fragment.EnterAnyElement(); const uni_char *name = fragment.GetElementName().GetLocalPart(); buffer.Clear(); if (uni_str_eq(name, "appName")) { fragment.GetAllText(buffer); RETURN_IF_ERROR(application->name.Set(buffer.GetStorage())); buffer.Clear(); fragment.LeaveElement(); } else if (uni_str_eq(name, "applicationIdentifier")) { while (fragment.HasMoreElements()) { if (fragment.EnterAnyElement()) { fragment.GetAllText(buffer); const uni_char *tmp_name = fragment.GetElementName().GetLocalPart(); if (uni_str_eq(tmp_name, "orgId")) application->org_id = uni_atoi(buffer.GetStorage()); else if (uni_str_eq(tmp_name, "appId")) application->app_id = uni_atoi(buffer.GetStorage()); buffer.Clear(); fragment.LeaveElement(); } } fragment.LeaveElement(); } else if (uni_str_eq(name, "applicationDescriptor")) { while (fragment.HasMoreElements()) { if (fragment.EnterAnyElement()) { fragment.GetAllText(buffer); const uni_char *value = buffer.GetStorage(); const uni_char *tmp_name = fragment.GetElementName().GetLocalPart(); if (uni_str_eq(tmp_name, "controlCode") && value) { if (uni_str_eq(value, "AUTOSTART")) application->descriptor.control_code = AITApplicationDescriptor::CONTROL_CODE_AUTOSTART; else if (uni_str_eq(value, "PRESENT")) application->descriptor.control_code = AITApplicationDescriptor::CONTROL_CODE_PRESENT; else if (uni_str_eq(value, "KILL")) application->descriptor.control_code = AITApplicationDescriptor::CONTROL_CODE_KILL; else if (uni_str_eq(value, "DISABLED")) application->descriptor.control_code = AITApplicationDescriptor::CONTROL_CODE_DISABLED; } else if (uni_str_eq(tmp_name, "visibility") && value) { if (uni_str_eq(value, "NOT_VISIBLE_ALL")) application->descriptor.visibility = AITApplicationDescriptor::VISIBILITY_NOT_VISIBLE_ALL; else if (uni_str_eq(value, "NOT_VISIBLE_USERS")) application->descriptor.visibility = AITApplicationDescriptor::VISIBILITY_NOT_VISIBLE_USERS; else if (uni_str_eq(value, "VISIBLE_ALL")) application->descriptor.visibility = AITApplicationDescriptor::VISIBILITY_VISIBLE_ALL; } else if (uni_str_eq(tmp_name, "serviceBound") && value) { if (uni_str_eq(value, "false")) application->descriptor.service_bound = FALSE; else if (uni_str_eq(value, "true")) application->descriptor.service_bound = TRUE; } else if (uni_str_eq(tmp_name, "priority") && value) { application->descriptor.priority = static_cast<unsigned char>(uni_strtoul(value, NULL, 16, NULL)); } else if (uni_str_eq(tmp_name, "mhpVersion")) { AITApplicationMhpVersion *mhp_version = OP_NEW(AITApplicationMhpVersion, ()); RETURN_OOM_IF_NULL(mhp_version); status = application->descriptor.mhp_versions.Add(mhp_version); if (OpStatus::IsError(status)) { OP_DELETE(mhp_version); return status; } TempBuffer buffer2; while (fragment.HasMoreElements()) { fragment.EnterAnyElement(); const uni_char *tag_name = fragment.GetElementName().GetLocalPart(); if (uni_str_eq(tag_name, "profile")) { fragment.GetAllText(buffer2); mhp_version->profile = static_cast<unsigned short>(uni_atoi(buffer2.GetStorage())); } else if (uni_str_eq(tag_name, "versionMajor")) { fragment.GetAllText(buffer2); mhp_version->version_major = static_cast<unsigned char>(uni_atoi(buffer2.GetStorage())); } else if (uni_str_eq(tag_name, "versionMinor")) { fragment.GetAllText(buffer2); mhp_version->version_minor = static_cast<unsigned char>(uni_atoi(buffer2.GetStorage())); } else if (uni_str_eq(tag_name, "versionMicro")) { fragment.GetAllText(buffer2); mhp_version->version_micro = static_cast<unsigned char>(uni_atoi(buffer2.GetStorage())); } buffer2.Clear(); fragment.LeaveElement(); } } buffer.Clear(); fragment.LeaveElement(); } } fragment.LeaveElement(); } else if (uni_str_eq(name, "applicationUsageDescriptor")) { while (fragment.HasMoreElements()) { if (fragment.EnterAnyElement()) { fragment.GetAllText(buffer); const uni_char *tmp_name = fragment.GetElementName().GetLocalPart(); if (uni_str_eq(tmp_name, "ApplicationUsage")) { const uni_char *applicationUsage = buffer.GetStorage(); if (applicationUsage && uni_str_eq(applicationUsage, "urn:dvb:mhp:2009:digitalText")) application->usage = 0x01; } buffer.Clear(); fragment.LeaveElement(); } } fragment.LeaveElement(); } else if (uni_str_eq(name, "applicationTransport")) { AITApplicationTransport *transport = OP_NEW(AITApplicationTransport, ()); RETURN_OOM_IF_NULL(transport); status = application->transports.Add(transport); if (OpStatus::IsError(status)) { OP_DELETE(transport); return status; } const uni_char *transport_type = NULL; XMLCompleteName attr_name; const uni_char *attr_value; while(fragment.GetNextAttribute(attr_name, attr_value)) { if (uni_str_eq(attr_name.GetLocalPart(), "type")) { transport_type = attr_value; break; } } if (!transport_type) transport_type = UNI_L(""); if (uni_str_eq(transport_type, "mhp:HTTPTransportType")) { while (fragment.HasMoreElements()) { fragment.EnterAnyElement(); const uni_char *tag_name = fragment.GetElementName().GetLocalPart(); if (uni_str_eq(tag_name, "URLBase")) { fragment.GetAllText(buffer); RETURN_IF_ERROR(transport->base_url.Set(buffer.GetStorage())); buffer.Clear(); } fragment.LeaveElement(); } transport->protocol = 0x0003; } else if (uni_str_eq(transport_type, "mhp:OCTransportType")) { while (fragment.HasMoreElements()) { fragment.EnterAnyElement(); const uni_char *tag_name = fragment.GetElementName().GetLocalPart(); if (uni_str_eq(tag_name, "DVBTriplet")) { const uni_char *original_network_id = fragment.GetAttribute(UNI_L("OrigNetId")); const uni_char *transport_stream_id = fragment.GetAttribute(UNI_L("TSId")); const uni_char *service_id = fragment.GetAttribute(UNI_L("ServiceId")); transport->original_network_id = (original_network_id ? static_cast<unsigned short>(uni_strtoul(original_network_id, NULL, 10, NULL)) : 0); transport->transport_stream_id = (transport_stream_id ? static_cast<unsigned short>(uni_strtoul(transport_stream_id, NULL, 10, NULL)) : 0); transport->service_id = (service_id ? static_cast<unsigned short>(uni_strtoul(service_id, NULL, 10, NULL)) : 0); transport->remote = TRUE; } else if (uni_str_eq(tag_name, "ComponentTag")) { fragment.GetAllText(buffer); transport->component_tag = static_cast<unsigned char>(uni_strtoul(buffer.GetStorage(), NULL, 16, NULL)); buffer.Clear(); } fragment.LeaveElement(); } transport->protocol = 0x0001; } fragment.LeaveElement(); } else if (uni_str_eq(name, "applicationBoundary")) { while (fragment.HasMoreElements()) { fragment.EnterAnyElement(); const uni_char *tag_name = fragment.GetElementName().GetLocalPart(); if (uni_str_eq(tag_name, "BoundaryExtension")) { fragment.GetAllText(buffer); const uni_char *value = buffer.GetStorage(); if (value) { OpString *boundary = OP_NEW(OpString, ()); RETURN_OOM_IF_NULL(boundary); status = application->boundaries.Add(boundary); if (OpStatus::IsError(status)) { OP_DELETE(boundary); return status; } RETURN_IF_ERROR(boundary->Set(value)); } buffer.Clear(); fragment.LeaveElement(); } } fragment.LeaveElement(); } else if (uni_str_eq(name, "applicationLocation")) { fragment.GetAllText(buffer); RETURN_IF_ERROR(application->location.Set(buffer.GetStorage())); buffer.Clear(); fragment.LeaveElement(); } } while (uni_str_eq(fragment.GetElementName().GetLocalPart(), "Application")); fragment.LeaveElement(); } // Continue parsing until we have no more elements to enter // and are at the root of the fragment. } while (fragment.HasMoreElements() || fragment.HasCurrentElement()); return OpStatus::OK; } #endif // XML_AIT_SUPPORT
/* * Stopping Times * Copyright (C) Leonardo Marchetti 2011 <leonardomarchetti@gmail.com> */ #include "tester.h" using namespace std; namespace StoppingTimes{ namespace Testing{ Tester::~Tester(){ tests_.clear(); } void Tester::add(Test *t) { tests_.push_back(unique_ptr<Test>(t)); } void Tester::loadAll(const char* path) { for(auto it = tests_.cbegin(), end = tests_.cend(); it != end; ++it) { (*it)->load(path); } } void Tester::runAll(Logger* logger){ auto end = tests_.cend(); for(auto it = tests_.cbegin(); it != end; ++it) { (*it)->run(logger); } } }}
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2006 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef DOM_DOMSTRINGMAP #define DOM_DOMSTRINGMAP #include "modules/dom/src/domobj.h" class DOM_Element; /** * In theory this is a generic class, but since it right now is only used for Element.dataset, it * really only implements that behaviour, merging the specs for DOMStringMap and Element.dataset. */ class DOM_DOMStringMap : public DOM_Object { private: DOM_Element *owner; DOM_DOMStringMap(DOM_Element *owner) : owner(owner) {} public: static OP_STATUS Make(DOM_DOMStringMap *&stringmap, DOM_Element *owner); virtual ES_GetState GetName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime); virtual ES_PutState PutName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime); virtual ES_DeleteStatus DeleteName(const uni_char *property_name, ES_Runtime *origining_runtime); virtual ES_GetState FetchPropertiesL(ES_PropertyEnumerator *enumerator, ES_Runtime *origining_runtime); virtual void GCTrace(); }; #endif // DOM_DOMSTRINGMAP
#include <iostream> #include <vector> #include <map> #include <string> #include <bitset> #include <queue> #include <algorithm> #include <functional> #include <cmath> #include <cstdio> #include <sstream> using namespace std; int daya[] = {31,28,31,30,31,30,31,31,30,31,30,31}; int ldaya[] = {31,29,31,30,31,30,31,31,30,31,30,31}; class IDNumberVerification { bool isLeap(int y) { if (y%400==0) { return true; } if (y%100==0) { return false; } if (y%4==0) { return true; } return false; } bool isValidSequentialCode(string str) { return str!="000"; } bool isValidRegionCode(string str,vector<string> &regionCodes){ return find(regionCodes.begin(), regionCodes.end(), str) != regionCodes.end(); } bool isValidBirthDay(string id) { int y = atoi(id.substr(6,4).data()); int m = atoi(id.substr(10,2).data()); int d = atoi(id.substr(12,2).data()); if (y<1900 || 2011<y) return false; if (m > 12 || m < 1) return false; if (d < 1) { return false; } if (isLeap(y)){ if (d > ldaya[m-1] || d < 1) { return false; } } else { if (d > daya[m-1] || d < 1) { return false; } } return true; } bool isValidCode(string id) { long long code; if (id[17]=='X') { code = 10; } else { code = (id[17]-'0'); } for (int i=0; i<id.size()-1; ++i) { code += ((int)(id[i]-'0'))*(1<<(17-i)); code = code%11; } if (code != 1) { return false; } return true; } int calcGender(int i) { if (i%2==0) { return 1; } else { return -1; } } public: string verify(string id, vector <string> regionCodes) { int ans = 1; ans &= isValidSequentialCode(id.substr(14,3)); ans &= isValidRegionCode(id.substr(0,6), regionCodes); ans &= isValidBirthDay(id); ans &= isValidCode(id); ans *= calcGender(id[16]-'0'); if (ans == 1) { return "Female"; } else if (ans == -1) { return "Male"; } else { return "Invalid"; } } };
/* * Md To USB * (Arduino Pro Micro) * *DSUB9P(Md) -- pro micro gpio * 1 -- d4(D0) d4 * 2 -- d5(D1) c6 * 3 -- d6(D2) d7 * 4 -- d7(D3) e6 * 5 -- Vcc(+5V) * 6 -- d2 (D4) d1(int1) * 7 (9) -- d3 (D5) d0(int0) * 8 (7) -- d8 (SEL) b4 * 9 (8) -- GND */ #include <Joystick.h> Joystick_ Joystick = Joystick_( 0x03, // reportid JOYSTICK_TYPE_GAMEPAD, // type 10, // button count 0, // hat switch count true, // x axis enable true, // y axis enable false, // z axis enable false, // right x axis enable false, // right y axis enable false, // right z axis enable false, // rudder enable false, // throttle enable false, // accelerator enable false, // brake enable false // steering enable ); // gpio #define D0 4 #define D1 5 #define D2 6 #define D3 7 #define D4 2 #define D5 3 #define SEL 8 int PIN[10]; #define LOOP_INTERVAL 16 // 入力周期(msec) // セットアップ void setup() { // シリアル初期化 // Serial.begin(115200); // while (!Serial); // pin初期設定 pinMode(D0,INPUT_PULLUP); pinMode(D1,INPUT_PULLUP); pinMode(D2,INPUT_PULLUP); pinMode(D3,INPUT_PULLUP); pinMode(D4,INPUT_PULLUP); pinMode(D5,INPUT_PULLUP) ; pinMode(SEL,OUTPUT) ; // d8(SEL) HIGH PORTB |= 0b00010000 ; // ジョイスティック開始 Joystick.begin(); // ジョイスティック初期設定 Joystick.setXAxisRange(0, 2); Joystick.setYAxisRange(0, 2); } uint8_t btn6; // メインループ void loop() { // d8(SEL) LOW PORTB &= 0b11101111; delayMicroseconds(20); // a start PIN[0] = PIND; // d8(SEL) HIGH PORTB |= 0b00010000 ; delayMicroseconds(20); // 上 下 左 右 b c PIN[1] = PINC; PIN[2] = PIND; PIN[3] = PINE; // d8(SEL) LOW PORTB &= 0b11101111; delayMicroseconds(20); // d8(SEL) HIGH PORTB |= 0b00010000 ; delayMicroseconds(20); // d8(SEL) LOW PORTB &= 0b11101111; delayMicroseconds(20); if((digitalRead(D0) == LOW) && (digitalRead(D1) == LOW) && (digitalRead(D2) == LOW) && (digitalRead(D3) == LOW)) { btn6 = 1; // Serial.println("btn6"); } else { btn6 = 0; // Serial.println("btn3"); } // d8(SEL) HIGH PORTB |= 0b00010000 ; delayMicroseconds(20); // X Y Z mode if (btn6 == 1) { PIN[4] = PINC; PIN[5] = PIND; PIN[6] = PINE; } // d8(SEL) LOW PORTB &= 0b11101111; delayMicroseconds(20); // d8(SEL) HIGH PORTB |= 0b00010000 ; // delayMicroseconds(20); // ボタン入力 ------------ // a if (!(PIN[0] & (1 << 1))) { Joystick.setButton(2, 1); } else { Joystick.setButton(2, 0); } // start if (!(PIN[0] & (1 << 0))) { Joystick.setButton(9, 1); } else { Joystick.setButton(9, 0); } // ボタン入力 ------------ // 上 if (!(PIN[2] & (1 << 4))) { Joystick.setYAxis(0); } // 下 if (!(PIN[1] & (1 << 6))) { Joystick.setYAxis(2); } if (((PIN[2] & (1 << 4))) && ((PIN[1] & (1 << 6)))) { Joystick.setYAxis(1); } // 左 if (!(PIN[2] & (1 << 7))) { Joystick.setXAxis(0); } // 右 if (!(PIN[3] & (1 << 6))) { Joystick.setXAxis(2); } if (((PIN[2] & (1 << 7))) && ((PIN[3] & (1 << 6)))) { Joystick.setXAxis(1); } // b if (!(PIN[2] & (1 << 1))) { Joystick.setButton(1, 1); } else { Joystick.setButton(1, 0); } // c if (!(PIN[2] & (1 << 0))) { Joystick.setButton(5, 1); } else { Joystick.setButton(5, 0); } // ボタン入力 ------------ // X Y Z mode if (btn6 == 1) { // z if (!(PIN[5] & (1 << 4))) { Joystick.setButton(4, 1); } else { Joystick.setButton(4, 0); } // y if (!(PIN[4] & (1 << 6))) { Joystick.setButton(0, 1); } else { Joystick.setButton(0, 0); } // x if (!(PIN[5] & (1 << 7))) { Joystick.setButton(3, 1); } else { Joystick.setButton(3, 0); } // mode if (!(PIN[6] & (1 << 6))) { Joystick.setButton(8, 1); } else { Joystick.setButton(8, 0); } } // //------------------------- // for (int i = 0; i < 7; i++) { // Serial.print(i); // Serial.print(":"); // Serial.print(PIN[i]); // Serial.print(","); // } // Serial.println(""); // //------------------------- // 処理待ち // delay(LOOP_INTERVAL); // HID デバイスへの出力に反映させる Joystick.sendState(); }
#ifndef _GRAPH_REG_H #define _GRAPH_REG_H #include "smat.h" #include "tron.h" #include <algorithm> // Solvers enum { L2R_LS_FULL=0, L2R_LS_MISSING=1, O2R_LS_FULL=10, O2R_LS_MISSING=11, GLR_LS_FULL=20, GLR_LS_MISSING=21, ARR_LS_FULL=30, ARR_LS_MISSING=31, }; // Bilinear Problems with L2/output Regularization Problems // O2R: min_W sum_ij loss(Y_ij, x_i^T W h_j) + 0.5 * sum_i lambda |W^T x_i)|^2 // L2R: min_W sum_ij loss(Y_ij, x_i^T W h_j) + 0.5 * lambda |W|^2 struct bilinear_prob_t { // {{{ smat_t *Y; // m*l sparse matrix union { double *X; // m*f array row major X(i,s) = X[k*i+s] smat_t *spX; // m*f sparse matrix }; double *H; // l*k array row major H(j,s) = H[k*i+s] double *W; // f*k array row major W(t,s) = W[k*t+s] size_t m; // #instance size_t f; // #features size_t l; // #labels size_t k; // row-rank dimension int X_type;// type of X: either 0 for dense, 1 for sparse, 2 for Identity enum {Dense=0, Sparse=1, Identity=2}; bilinear_prob_t(){} bilinear_prob_t(smat_t *Y, void *X, double *H, size_t f, size_t k, int X_type=Dense, double *W=NULL) { this->Y = Y; if(X_type == Dense || X_type == Identity) this->X = (double*) X; else this->spX = (smat_t*) X; this->k = k; this->m = Y->rows; this->f = f; this->l = Y->cols; this->W = W; this->H = H; this->X_type = X_type; } }; struct bilinear_param_t { int solver_type; double lambda; int max_tron_iter, max_cg_iter; double eps; int threads; int verbose; int weighted_reg; int use_chol; bilinear_param_t() { solver_type = O2R_LS_FULL; lambda = 0.1; max_tron_iter = 3; max_cg_iter = 20; eps = 0.1; verbose = 0; threads = 4; weighted_reg = 0; use_chol = 0; } }; // }}} // AutoRegressive Regularized Problems // min_W sum_ij 0.5*|Y - XW^T|^2 + 0.5*lambda1 sum_{r=s}^k sum_{t= midx+1}^T G_{sl} |w_{ts} - w_{(t-l)s}|^2 + 0.5*lambda2 sum_{t=1}^T |w_t|^2 class arr_prob_t { // {{{ public: smat_t *Y; // n*T sparse matrix double *X; // n*k array row major X(i,s) = X[k*i+s] double *W; // T*k array row major W(t,s) = W[k*t+s] size_t m; // #instances size_t T; // #time stamps size_t k; // low-rank dimension size_t *lag_idx; // lag index size_t lag_size; // size of lag set double *lag_val; // lag_size*k array for lag valus lag_val(l, s) = lag_val[k*l + s] arr_prob_t(smat_t *Y, double *X, size_t k, size_t lag_size, size_t *lag_idx, double *lag_val, double *W=NULL) { this->Y = Y; this->X = X; this->k = k; this->m = Y->rows; this->T = Y->cols; this->lag_size = lag_size; this->lag_idx = lag_idx; this->lag_val = lag_val; this->W = W; } }; class arr_param_t : public bilinear_param_t{ public: double lambdaAR; double lambdaI; arr_param_t(): bilinear_param_t() { solver_type = ARR_LS_FULL; max_tron_iter = 3; max_cg_iter = 20; lambdaAR = 0.1; lambdaI = lambda; //0.1; eps = 0.1; verbose = 0; threads = 4; } };// }}} struct solver_t { virtual void init_prob() = 0; virtual void solve(double *w) = 0; virtual double fun(double *w) {return 0;} virtual void grad(double *w, double *g) {return;} virtual void Hv(double *s, double *Hs) {return;} virtual ~solver_t(){} }; struct arr_solver: public solver_t { // {{{ arr_prob_t *prob; arr_param_t *param; function *fun_obj; TRON *tron_obj; solver_t *solver_obj; bool done_init; smat_t Yt; bilinear_prob_t tmp_prob; arr_solver(arr_prob_t *prob, arr_param_t *param); ~arr_solver() { if(tron_obj) delete tron_obj; if(fun_obj) delete fun_obj; if(solver_obj) delete solver_obj; } void init_prob() { if(fun_obj) fun_obj->init(); else if(solver_obj) solver_obj->init_prob(); done_init = true; } void set_eps(double eps) {tron_obj->set_eps(eps);} void solve(double *w) { if(!done_init) {init_prob();} if(tron_obj) { tron_obj->tron(w, false); //tron_obj->tron(w, true); // zero init for w } else if(solver_obj) { solver_obj->solve(w); } } double fun(double *w) { if(!done_init) {init_prob();} if(fun_obj) return fun_obj->fun(w); else if(solver_obj) return solver_obj->fun(w); else return 0; } void grad(double *w, double *g) { if(!done_init) {init_prob();} if(fun_obj) { fun_obj->grad(w, g); } else return ; } void Hv(double *s, double *Hs) { if(!done_init) {init_prob();} if(fun_obj) fun_obj->Hv(s, Hs); } }; // }}} #ifdef __cplusplus extern "C" { #endif double cal_rmse(smat_t &testY, double *W, double *H, size_t k); #ifdef __cplusplus } #endif #endif /* _GRAPH_REG_H */
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */ //bfs class Solution { public: unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mp; UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if(node == NULL) return NULL; UndirectedGraphNode* nodeCopy = new UndirectedGraphNode(node->label); queue<UndirectedGraphNode*> q; q.push(node); mp[node] = nodeCopy; while(!q.empty()){ UndirectedGraphNode* n = q.front(); q.pop(); for(auto v: n->neighbors){ if(!mp.count(v)){ UndirectedGraphNode* u = new UndirectedGraphNode(v->label); mp[v] = u; q.push(v); } mp[n]->neighbors.push_back(mp[v]); } } return nodeCopy; } }; //dfs class Solution { public: unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mp; UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if(node == NULL) return NULL; if(!mp.count(node)){ mp[node] = new UndirectedGraphNode(node->label); for(auto v: node->neighbors){ mp[node]->neighbors.push_back(cloneGraph(v)); } } return mp[node]; } };
#include<vector> using std::vector; #include<iostream> #include<algorithm> #include<memory> using std::shared_ptr; #include<string> using std::string; #include<stack> using std::stack; #include<queue> using std::priority_queue; /* Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place, do not allocate extra memory. Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 1,2,3 ¡ú 1,3,2 3,2,1 ¡ú 1,2,3 1,1,5 ¡ú 1,5,1 */ #include<map> using std::map; class Solution { public: void nextPermutation(vector<int>& nums) { int i = nums.size() - 1; int tail = i; while (i > 0 && nums[i - 1] >= nums[i]) { i--; } for (int j = i; j < tail; j++, tail--) { std::swap(nums[tail], nums[j]); } if (i != 0) { for (int j = i; j < nums.size(); j++) { if (nums[j] > nums[i-1]) { std::swap(nums[i-1], nums[j]); break; } } } } }; int main() { Solution s; vector<int> i({ 1,3,2 }); s.nextPermutation(i); return 0; }
#include "wnd.h" #include <glad/glad.h> Context *activeOpenGLContext = NULL; Context::Context() : windowContext(NULL), openglContext(NULL), window(NULL) { } Context::Context(HDC hdc, HGLRC hglrc, WND *wnd) : windowContext(hdc), openglContext(hglrc), window(wnd) { } void WND::CreateContext(void) { PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, //Flags PFD_TYPE_RGBA, // The kind of framebuffer. RGBA or palette. 32, // Colordepth of the framebuffer. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, // Number of bits for the depthbuffer 8, // Number of bits for the stencilbuffer 0, // Number of Aux buffers in the framebuffer. PFD_MAIN_PLANE, 0, 0, 0, 0 }; int letWindowsChooseThisPixelFormat; letWindowsChooseThisPixelFormat = ChoosePixelFormat(hdc, &pfd); SetPixelFormat(hdc, letWindowsChooseThisPixelFormat, &pfd); hglrc = wglCreateContext(hdc); MakeCurrentContext(new Context(hdc, hglrc, this)); if(!gladLoadGL()) { printf("WND::ERROR_CREATING_OPENGL_CONTEXT::GLAD_LOAD_GL FAILED!\n"); exit(0); } else { printf("OPENGL::VERSIONS::%d.%d\n", GLVersion.major, GLVersion.minor); } glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); } void MakeCurrentContext(Context *context) { activeOpenGLContext = context; wglMakeCurrent(context->windowContext, context->openglContext); } Context *GetCurrentContext(void) { return activeOpenGLContext; } HDC WND::GetContext() { return hdc; }
// // Created by gurumurt on 9/21/18. // #ifndef OPENCLDISPATCHER_SELECTION_H #define OPENCLDISPATCHER_SELECTION_H #endif //OPENCLDISPATCHER_SELECTION_H #include "../include/headers.h" class selection{ string name = "SELECTION"; double execution_time = 0.0; unsigned int* result; enum condition{ EQUAL, LESS_THAN, GREATER_THAN, LESS_EQUAL, GREATER_EQUAL, NOT_EQUAL }; unsigned int* naive_execution(unsigned int* input, condition comp_op,unsigned int comparator, size_t size){ result = new unsigned int[size]; for(int i = 0; i<size;i++){ result[i] = (input[i]==comparator); } return result; } double get_cost_model(size_t size){ //Device Based transfer time //Add cost model return size; } double get_execution_time(double current_time){ return (execution_time + current_time) / 2; } };
/* Name: TimerTest.ino Created: 29.07.2018 0:35:38 Author: Павел */ USBSerial usb; HardwareTimer milli(2); HardwareTimer micro(3); void USBPrintln(char const* text) { if (usb) usb.println(text); } // the setup function runs once when you press reset or power the board void setup() { pinMode(LED_BUILTIN, OUTPUT_OPEN_DRAIN); digitalWrite(LED_BUILTIN, LOW); for (uint16_t i = 0; i < 10000; i++) { if (usb) break; delay(1); } delay(1000); digitalWrite(LED_BUILTIN, HIGH); USBPrintln("Goodnight moon!"); rcc_clk_enable(RCC_TIMER2); rcc_clk_enable(RCC_TIMER3); micro.setPrescaleFactor(72U); //1uS exactly micro.setOverflow(1000); milli.setPrescaleFactor(1); //Somehow default prescaler turned out to be 2 TIMER3->regs.bas->CR2 |= TIMER_CR2_MMS_UPDATE; //Setup reload trigger TRGO3 (TRGO3 <--> ITR2, see RM0008) TIMER2->regs.adv->SMCR |= (TIMER_SMCR_TS_ITR2 | TIMER_SMCR_SMS_EXTERNAL); //Enable internal trigger tied to TIM3 and external clock mode } // the loop function runs over and over again until power down or reset void loop() { micro.pause(); micro.refresh(); milli.refresh(); while (!usb); while (usb.read() != 'D'); micro.resume(); for (int i = 0; i < 40; i++) { uint16 mic = micro.getCount(); uint16 mil = milli.getCount(); if (mic > micro.getCount()) mil = milli.getCount(); //Update if rollover has just happened usb.print(mil); usb.write(':'); usb.println(mic); delay_us(100); } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ /* * Designer/architect: Petter Reinholdtsen <pere@opera.com> */ /* * Implement exception handling abstraction layer: * LEAVE(int i); * TRAP(error, block); * TRAPD(int error, block) * OpStackAutoPtr<type> ptr; * In addition, the CleanupStack::Push() and ...::Pop() functions are * implemented on some platforms. */ #ifndef MODULES_UTIL_EXCEPTS_H #define MODULES_UTIL_EXCEPTS_H #include "modules/util/opautoptr.h" #ifndef THROWCLAUSE # if defined _WIN32_WCE && defined ARM # define THROWCLAUSE # else # define THROWCLAUSE throw() # endif #endif #ifdef EPOC # include <e32cmn.h> # include <e32std.h> # define LEAVE(i) User::Leave(i) # ifdef __LEAVE_EQUALS_THROW__ # define USE_CXX_EXCEPTIONS # endif /** * Cleanup stack item class to approximate behaviour on other platforms. */ class CleanupItem : public CBase { public: // Dummy function. CBase has never added itself to CleanupStack directly, // so it cannot remove itself here. virtual void Cleanup(int /*error*/) { } }; #endif #if defined(USE_CXX_EXCEPTIONS) #ifdef MEMTEST # include "modules/memtools/mem_util.h" #endif #ifdef _DEBUG extern void leave_trapped(); # define CATCH_TRAP() leave_trapped() #else # define CATCH_TRAP() #endif // _DEBUG #ifndef TRAP #define TRAP(var, block) \ do{ \ try { \ do { block; } while (0); \ var = OpStatus::OK; \ } catch (OP_STATUS i__) { \ CATCH_TRAP(); \ var = i__; \ } \ } while(0) #endif // TRAP #ifndef TRAPD #define TRAPD(var, block) \ OP_STATUS var; \ TRAP(var, block) #endif // TRAPD #ifndef LEAVE #define LEAVE(i) \ do { \ throw ((OP_STATUS) i) \ } while(0) #endif // LEAVE // Basically just a rename of OpAutoPtr template <class T> class OpStackAutoPtr : public OpAutoPtr<T> { public: explicit OpStackAutoPtr(T* ptr = 0) THROWCLAUSE : OpAutoPtr<T>(ptr) {} OpStackAutoPtr(OpStackAutoPtr& rhs) THROWCLAUSE : OpAutoPtr<T>(rhs) {} OpStackAutoPtr& operator=(OpStackAutoPtr& rhs) THROWCLAUSE { return static_cast<OpStackAutoPtr&>(OpAutoPtr<T>::operator=(rhs)); } }; template <class T> class OpStackAnchor { public: OpStackAnchor(const T* ref) {} /// Make this template compatible with other platforms. void Cleanup(int error) {} /// Make this template compatible with other platforms. void Close() {} }; template <class T> class OpHeapArrayAnchor { public: OpHeapArrayAnchor(void) : m_ptr(NULL) {} OpHeapArrayAnchor(T* ptr) : m_ptr(ptr) {} ~OpHeapArrayAnchor() { Clear(); } T* release() { T* ptr = m_ptr; m_ptr = 0; return ptr; } void reset(T* ptr) { m_ptr = ptr; } void Clear(void) { if (m_ptr != NULL) { OP_DELETEA(m_ptr); m_ptr = NULL; } } T *Get(void) const { return m_ptr; } void Cleanup(int error) {} void Close() {} OpHeapArrayAnchor &operator=(T *ptr) { Clear(); m_ptr = ptr; return *this; } T &operator[](int index) { return m_ptr[index]; } operator BOOL () const { return m_ptr != NULL; } private: T* m_ptr; }; #elif defined(EPOC) #ifdef __LEAVE_EQUALS_THROW__ # error "This section must not be compiled if __LEAVE_EQUALS_THROW__ is defined" #endif // TRAP and TRAPD is already defined in EPOC API template <class T> class OpStackAutoPtr { private: class Wrapper { public: Wrapper() { iLeaving = EFalse; } void Close() // Called upon cleanup { OP_DELETE(ptr); ptr = NULL; iLeaving = ETrue; // User::Leave() has already taken us of cleanup stack } ~Wrapper() { OP_DELETE(ptr); ptr = NULL; } public: T* ptr; TBool iLeaving; }; public: explicit OpStackAutoPtr(T *aPtr = 0) { CleanupClosePushL(iWrapper); iWrapper.ptr = aPtr; } ~OpStackAutoPtr() { // in a normal return we have to take iWrapper off the cleanup stack if (!iWrapper.iLeaving) { // Just Pop() rather than PopAndDestroy() because the Wrapper // destructor takes care of deleting the pointer in normal // circumstances. CleanupStack::Pop(); // iWrapper } } T* get() const { return iWrapper.ptr; } T& operator*() const { return *iWrapper.ptr; } T* operator->() const { return iWrapper.ptr; } T* release() { T* ptr = iWrapper.ptr; iWrapper.ptr = 0; return ptr; } void reset(T* ptr = 0) { if (iWrapper.ptr != ptr) { OP_DELETE(iWrapper.ptr); iWrapper.ptr = ptr; } } private: Wrapper iWrapper; }; #ifdef __SUPPORT_CPP_EXCEPTIONS__ // This implementation of OpStackAnchor is for Symbian9 where standard C++ exceptions are supported. // It must empty, because C++ destructors are called, otherwise there could be a double deletion in case of exception. template <class T> class OpStackAnchor { public: explicit OpStackAnchor(const T* /*aPtr*/) {} }; #else // This implementation of OpStackAnchor is for pre-Symbian9 where standard C++ exceptions are NOT supported. template <class T> class OpStackAnchor { private: class Wrapper { public: Wrapper() { iLeaving = EFalse; } void Close() // Called upon cleanup { ptr->T::~T(); iLeaving = ETrue; }; public: T* ptr; TBool iLeaving; } public: explicit OpStackAnchor(T* aPtr) { CleanupClosePushL(iWrapper); iWrapper.ptr = aPtr; } ~OpStackAnchor() { // This is Pop() and not PopAndDestroy() because the anchored // object's destructor is called as per normal if the Stack // Anchor's destructor is called. if (iWrapper.iLeaving == EFalse) { CleanupStack::Pop(); // iWrapper } } private: Wrapper iWrapper; }; #endif // __SUPPORT_CPP_EXCEPTIONS__ template <class T> class OpHeapArrayAnchor { private: class Wrapper { public: Wrapper() { iLeaving = EFalse; } void Close() // called by User::Leave() { OP_DELETEA(ptr); iLeaving = ETrue; } public: T* ptr; TBool iLeaving; }; public: OpHeapArrayAnchor(void) { iWrapper.ptr = NULL; } explicit OpHeapArrayAnchor(T* aPtr) { iWrapper.ptr = aPtr; CleanupClosePushL(iWrapper); } ~OpHeapArrayAnchor() { // normal return (not User::Leave()) if (!iWrapper.iLeaving) { // PopAndDestroy() rather than Pop() because nobody else // performs destruction on the controlled object CleanupStack::PopAndDestroy(); // iWrapper } } T* release() { T* ptr = iWrapper.ptr; iWrapper.ptr = 0; return ptr; } void reset(T* ref) { if (iWrapper.ptr != ref) { OP_DELETEA(iWrapper.ptr); iWrapper.ptr = ref; } } T *Get(void) const { return iWrapper.ptr; } OpHeapArrayAnchor &operator=(T *aPtr) { reset(aPtr); return *this; } T &operator[](int index) { return iWrapper.ptr[index]; } operator BOOL () const { return iWrapper.ptr != NULL; } private: Wrapper iWrapper; }; #else // not EPOC and not USE_CXX_EXCEPTIONS #include "modules/util/opautoptr.h" /** * Cleanup stack item used with the OpStackAutoPtr template. Keeps a * thread specific list of items as a simple linked list. */ class CleanupItem { private: /** * Pointer to the previous item on the cleanup stack, or null if * this item is the last item on the stack. */ CleanupItem *next; /** * Dummy copy constructors */ CleanupItem(const CleanupItem&); CleanupItem& operator=(const CleanupItem&); protected: friend class User; // Allow access to the cleanup stack item public: CleanupItem(); virtual ~CleanupItem(); virtual void Cleanup(int error); static void CleanupAll(int error); }; class CleanupCatcher : public CleanupItem { public: jmp_buf catcher; int error; CleanupCatcher() : error(0) {} virtual void Cleanup(int error); }; /** * This class is an OpAutoPtr template for use on the program stack. * It is compatible with the OpAutoPtr implementation, which is * equivalent to Standard C++ auto_ptr. * * @see CleanupItem, OpAutoPtr, auto_ptr */ template <class T> class OpStackAutoPtr : public CleanupItem { private: OpAutoPtr<T> ptr; public: explicit OpStackAutoPtr(T* _ptr = 0) : CleanupItem(), ptr(_ptr) {} virtual void Cleanup(int error) { ptr.reset(0); CleanupItem::Cleanup(error); } T* get() const THROWCLAUSE { return ptr.get(); } T& operator*() const THROWCLAUSE { return ptr.operator*(); } T* operator->() const THROWCLAUSE { return ptr.operator->(); } T* release() THROWCLAUSE { return ptr.release(); } void reset(T* _ptr = 0) THROWCLAUSE { ptr.reset(_ptr); } }; /** * This class is an template to anchor objects used on the program * stack to the cleanup stack. * * @see CleanupItem */ template <class T> class OpStackAnchor : public CleanupItem { T* const m_ref; public: OpStackAnchor(T* ref) : CleanupItem(), m_ref(ref) { #ifdef MEMTEST oom_remove_anchored_object((void *) ref); #endif // MEMTEST } virtual void Cleanup(int error) { CleanupItem::Cleanup(error); m_ref->T::~T(); } /// Make this template compatible with other platforms. void Close() {} }; template <class T> class OpHeapArrayAnchor : public CleanupItem { public: OpHeapArrayAnchor(void) : CleanupItem(), m_ref(0) {} OpHeapArrayAnchor(T* ref) : CleanupItem(), m_ref(ref) {} virtual ~OpHeapArrayAnchor() { OP_DELETEA(m_ref); m_ref = 0; } T* release() { T* ref = m_ref; m_ref = 0; return ref; } void reset(T* ref) { m_ref = ref; } void Clear(void) { if (m_ref != 0) { OP_DELETEA(m_ref); m_ref = 0; } } virtual void Cleanup(int error) { CleanupItem::Cleanup(error); OP_DELETEA(m_ref); m_ref = 0; error = 0; // keep compiler quiet } void Close() {} T *Get(void) const { return m_ref; } OpHeapArrayAnchor &operator=(T *ptr) { Clear(); m_ref = ptr; return *this; } T &operator[](int index) { return m_ref[index]; } operator BOOL () const { return m_ref != NULL; } private: T* m_ref; }; #if defined(MEMTEST) && defined(PARTIAL_LTH_MALLOC) # include "modules/memtools/happy-malloc.h" # define TRAP(var, block) \ do { \ SAVE_MALLOC_STATE(); \ oom_TrapInfo _oom_trap; \ CleanupCatcher _catcher; \ if (0 == op_setjmp(_catcher.catcher)) { \ do { block; } while (0); \ var = OpStatus::OK; \ OpStatus::Ignore(var); \ } else { \ var = _catcher.error; \ } \ RESET_MALLOC_STATE(); \ } while (0) #else // !MEMTEST # define TRAP(var, block) \ do { \ CleanupCatcher _catcher; \ if (0 == op_setjmp(_catcher.catcher)) { \ do { block; } while (0); \ var = OpStatus::OK; \ OpStatus::Ignore(var); \ } else { \ var = (OpStatus::ErrorEnum)_catcher.error; \ } \ } while (0) #endif // MEMTEST #define TRAPD(var, block) \ OP_STATUS var; \ TRAP(var, block) #define LEAVE(i) \ do { \ User::Leave(i); \ } while (0) class User { public: #ifdef USE_DEBUGGING_OP_STATUS static void Leave(OP_STATUS error); #endif // USE_DEBUGGING_OP_STATUS static void Leave(int error); static void LeaveNoMemory(); static int LeaveIfError(int error); }; #endif // not EPOC and not USE_CXX_EXCEPTIONS /* Shorthand for use of OpStackAnchor<> */ #define ANCHOR(type, var) \ OpStackAnchor< type > anchor_variable_ ## var (&var) #define ANCHOR_PTR(type, var) \ OpStackAutoPtr< type > anchor_ptr_variable_ ## var (var) #define ANCHOR_PTR_RELEASE(var) \ anchor_ptr_variable_ ## var.release() /// Similar to TRAPD, ANCHORD defines and anchors the variable in one go #define ANCHORD(type, var) \ type var; \ ANCHOR(type, var) /** * Access macros to make the OpHeapArrayAnchor easier to use. */ #define ANCHOR_ARRAY(type, variable) \ OpHeapArrayAnchor<type> anchor_array_variable_ ## variable (variable) #define ANCHOR_ARRAY_RELEASE(variable) \ anchor_array_variable_ ## variable.release() #define ANCHOR_ARRAY_RESET(variable) \ anchor_array_variable_ ## variable.reset(variable) #define ANCHOR_ARRAY_DELETE(variable) \ do { \ anchor_array_variable_ ## variable.release(); \ delete [] variable; \ } while (0) /** * Various convenience macros */ #define LEAVE_IF_ERROR(expr) \ do { \ OP_STATUS LEAVE_IF_ERROR_TMP = expr; \ if (OpStatus::IsError(LEAVE_IF_ERROR_TMP)) \ LEAVE(LEAVE_IF_ERROR_TMP); \ } while (0) #define LEAVE_IF_NULL(expr) \ do { \ if (NULL == (expr)) \ LEAVE(OpStatus::ERR_NO_MEMORY); \ } while (0) #define LEAVE_IF_FATAL(expr) \ do { \ OP_STATUS LEAVE_IF_FATAL_TMP = expr; \ if (OpStatus::IsFatal(LEAVE_IF_FATAL_TMP)) \ LEAVE(LEAVE_IF_FATAL_TMP); \ } while (0) #define RETURN_IF_ERROR(expr) \ do { \ OP_STATUS RETURN_IF_ERROR_TMP = expr; \ if (OpStatus::IsError(RETURN_IF_ERROR_TMP)) \ return RETURN_IF_ERROR_TMP; \ } while (0) #define RETURN_OOM_IF_NULL(expr) \ do { \ if (NULL == (expr)) \ return OpStatus::ERR_NO_MEMORY; \ } while (0) #define RETURN_VALUE_IF_NULL(expr, val) \ do { \ if (NULL == (expr)) \ return val; \ } while (0) #define RETURN_IF_MEMORY_ERROR(expr) \ do { \ OP_STATUS RETURN_IF_ERROR_TMP = expr; \ if (OpStatus::IsMemoryError(RETURN_IF_ERROR_TMP)) \ return RETURN_IF_ERROR_TMP; \ } while (0) #define RETURN_VALUE_IF_ERROR(expr, val) \ do { \ OP_STATUS RETURN_IF_ERROR_TMP = expr; \ if (OpStatus::IsError(RETURN_IF_ERROR_TMP)) \ return val; \ } while (0) #define RETURN_VOID_IF_ERROR(expr) \ do { \ OP_STATUS RETURN_IF_ERROR_TMP = expr; \ if (OpStatus::IsError(RETURN_IF_ERROR_TMP)) \ return; \ } while (0) #define RAISE_AND_RETURN_IF_ERROR(expr) \ do { \ OP_STATUS RETURN_IF_ERROR_TMP = expr; \ if (OpStatus::IsError(RETURN_IF_ERROR_TMP)) { \ g_memory_manager->RaiseCondition(RETURN_IF_ERROR_TMP); \ return RETURN_IF_ERROR_TMP; \ } \ } while (0) #define RAISE_AND_RETURN_VALUE_IF_ERROR(expr, val) \ do { \ OP_STATUS RETURN_IF_ERROR_TMP = expr; \ if (OpStatus::IsError(RETURN_IF_ERROR_TMP)) { \ g_memory_manager->RaiseCondition(RETURN_IF_ERROR_TMP); \ return val; \ } \ } while (0) #define RAISE_AND_RETURN_VOID_IF_ERROR(expr) \ do { \ OP_STATUS RETURN_IF_ERROR_TMP = expr; \ if (OpStatus::IsError(RETURN_IF_ERROR_TMP)) { \ g_memory_manager->RaiseCondition(RETURN_IF_ERROR_TMP); \ return; \ } \ } while (0) #define TRAP_AND_RETURN(var, expr) \ do { \ TRAPD(var, expr); \ if (OpStatus::IsError(var)) \ return var; \ } while (0) #define RETURN_IF_LEAVE(expr) \ do { \ TRAPD(OP_STATUS_RETURN_IF_LEAVE_TMP, expr); \ if (OpStatus::IsError(OP_STATUS_RETURN_IF_LEAVE_TMP)) \ return OP_STATUS_RETURN_IF_LEAVE_TMP; \ } while (0) #define TRAP_AND_RETURN_VALUE_IF_ERROR(var, expr, val) \ do { \ TRAP(var, expr); \ if (OpStatus::IsError(var)) \ return val; \ } while (0) #define TRAP_AND_RETURN_VOID_IF_ERROR(var, expr) \ do { \ TRAP(var, expr); \ if (OpStatus::IsError(var)) \ return; \ } while (0) #define RAISE_IF_ERROR(expr) \ do { \ OP_STATUS RETURN_IF_ERROR_TMP = expr; \ if (OpStatus::IsError(RETURN_IF_ERROR_TMP)) \ g_memory_manager->RaiseCondition(RETURN_IF_ERROR_TMP); \ } while (0) #ifndef RAISE_IF_MEMORY_ERROR #define RAISE_IF_MEMORY_ERROR(expr) \ do { \ OP_STATUS RETURN_IF_ERROR_TMP = expr; \ if (OpStatus::IsMemoryError(RETURN_IF_ERROR_TMP)) \ g_memory_manager->RaiseCondition(RETURN_IF_ERROR_TMP); \ } while (0) #endif #endif // !MODULES_UTIL_EXCEPTS_H
/***************************************************************************** * ExploringSfMWithOpenCV ****************************************************************************** * by Roy Shilkrot, 5th Dec 2012 * http://www.morethantechnical.com/ ****************************************************************************** * Ch4 of the book "Mastering OpenCV with Practical Computer Vision Projects" * Copyright Packt Publishing 2012. * http://www.packtpub.com/cool-projects-with-opencv/book *****************************************************************************/ #pragma once #include "Common.h" #include "MultiCameraDistance.h" class MultiCameraPnP : public MultiCameraDistance { public: class UpdateListener { public: /*const std::vector<cv::Point3d> &pcld_a, const std::vector<cv::Vec3b> &pcld_a_rgb, const std::vector<cv::Point3d> &pcld_b, const std::vector<cv::Vec3b> &pcld_b_rgb, const std::vector<std::pair<double, cv::Matx34d>> &cameras*/ virtual void update(const MultiCameraPnP &) = 0; virtual void finish(const MultiCameraPnP &) = 0; }; enum INTERNAL_STATE { STATE_OK, STATE_NO_BASELINE_PAIR }; private: std::vector<CloudPoint> pointcloud_beforeBA; std::vector<cv::Vec3b> pointCloudRGB_beforeBA; int m_first_view, m_second_view; std::set<int> done_views, good_views; void PruneMatchesBasedOnF(); void AdjustCurrentBundle(); void GetBaseLineTriangulation(); void Find2D3DCorrespondences(int working_view, std::vector<cv::Point3f>& ppcloud, std::vector<cv::Point2f>& imgPoints); bool FindPoseEstimation(int working_view, cv::Mat_<double>& rvec, cv::Mat_<double>& t, cv::Mat_<double>& R, std::vector<cv::Point3f> ppcloud, std::vector<cv::Point2f> imgPoints); bool TriangulatePointsBetweenViews(int working_view, int second_view, std::vector<struct CloudPoint>& new_triangulated, std::vector<int>& add_to_cloud); int FindHomographyInliers2Views(int vi, int vj); typedef std::list<UpdateListener*> Listeners; Listeners listeners; void notify(bool finish = false) { for (Listeners::iterator l = listeners.begin(), lend = listeners.end(); l != lend; ++l) if (finish) (*l)->finish(*this); else (*l)->update(*this); } INTERNAL_STATE _state; public: MultiCameraPnP(FEATURE_MATCHER_MODE mode, const std::vector<cv::Mat>& imgs_, const std::vector<std::string>& imgs_names_, const cv::Mat &intrinsics, const cv::Mat distortion_vector) : MultiCameraDistance(mode, imgs_,imgs_names_,intrinsics, distortion_vector) { resetState(); } virtual bool RecoverDepthFromImages(); std::vector<cv::Point3d> getPointCloud(bool adjusted = true) const { return adjusted ? MultiCameraDistance::getPointCloud() : CloudPointsToPoints(pointcloud_beforeBA); } const std::vector<cv::Vec3b> getPointCloudRGB(bool adjusted = true) const { return adjusted ? _pointCloudRGBInit() : pointCloudRGB_beforeBA; } void attach(UpdateListener *sul) { assert(sul); listeners.push_back(sul); } void detach(UpdateListener *sul) { assert(sul); Listeners::iterator finder = std::find(listeners.begin(), listeners.end(), sul); if (finder != listeners.end()) listeners.erase(finder); } INTERNAL_STATE getState() { return _state; } void resetState() { features_matched = false; _state = STATE_OK; } };
#include <iostream> #include <opencv2/core/core.hpp> #include <common/utility.hpp> #include "calibration.hpp" //////////////////////////////////////////////////////////////////////////////// static const std::vector<std::string> CAMERA_SERIALS { "810512060827", "747612060748", }; //////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { std::string local_work_dir = Util::getRootPath(); std::string local_res = local_work_dir + "res/"; std::string resource_path_prefix = local_res + std::string(argv[1]) + "/"; /* { // Index board poses that are visible from the camera CameraSensor::Initialize(); cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_6X6_250); Calibration calib(dictionary); for (uint32_t i = 0; i <= 15; i++) { std::string img_file = "ir" + std::to_string(i) + ".png"; cv::Mat img = cv::imread(resource_path_prefix + "calib-images-ir-747612060748/" + img_file, cv::IMREAD_GRAYSCALE); cv::Mat img_copy; cv::cvtColor(img, img_copy, cv::COLOR_GRAY2RGB); cv::Mat board_pose = calib.estimateCharucoPose(img_copy, CameraSensor::connected_devices[0]); cv::imshow("Detection", img_copy); cv::waitKey(0); } } */ std::vector<int> bTe_indices; std::vector<cv::Mat> bTe = Util::readPosesFromFile( resource_path_prefix + "bTe.csv", &bTe_indices); for (uint16_t i = 0; i < CAMERA_SERIALS.size(); i++) { std::vector<int> cTch_indices; std::vector<cv::Mat> cTch = Util::readPosesFromFile(resource_path_prefix + "cTch_" + CAMERA_SERIALS[i] + ".csv", &cTch_indices); std::cout << "read " << cTch.size() << " poses for camera " << CAMERA_SERIALS[i] << std::endl; std::vector<cv::Mat> bTc = Util::readPosesFromFile( resource_path_prefix + "bTc_" + CAMERA_SERIALS[i] + ".csv", NULL); std::vector<cv::Mat> eTch = Calibration::computeEndeffToCharuco(&bTe, &bTe_indices, &cTch, &cTch_indices, bTc[0]); for (uint32_t j = 0; j < eTch.size(); j++) Util::writeToFile(local_res + "eTch-" + CAMERA_SERIALS[i] + ".csv", eTch[j], j); std::string variance_cmd = "python3 " + local_work_dir + "src/avg_quat.py eTch-" + CAMERA_SERIALS[i] + ".csv"; system(variance_cmd.c_str()); } return 0; } /// @file
#pragma once #include <API/Code/Graphics/Texture/Texture2D.h> #include <API/Code/Graphics/Shader/Shader.h> #include <API/Code/Graphics/PostProcess/GaussianBlur.h> /// <summary>Pass generating the normal map from the height map.</summary> class NormalGeneration { public: /// <summary>Initialize the pass.</summary> /// <param name="_TextureSize">The size for the normal map.</param> NormalGeneration( Uint32 _TextureSize ); /// <summary>Run the normal map pass.</summary> /// <param name="_HeightMap">The height map to generate the normal from.</param> void Run( ae::Texture& _HeightMap ); /// <summary>Retrieve the normal map.</summary> /// <returns>The normal map.</returns> ae::Texture2D& GetNormalMap(); /// <summary>Resize the normal map.</summary> /// <param name="_TextureSize">The size to apply.</param> void Resize( Uint32 _TextureSize ); private: /// <summary>Normal map texture.</summary> ae::Texture2D m_NormalMap; /// <summary>Shader processing the normal map from the height map.</summary> ae::Shader m_Shader; /// <summary>Blur post-process for the normal map.</summary> ae::GaussianBlur m_Blur; };
#pragma once #include "StdAfx.h" #include "Npc.h" #include "UIObject.h" #include "Camera.h" #include "Map.h" typedef std::vector<CObject*> OBJECTS; typedef std::vector<CObject*>::iterator OBJ_ITR; class CSceneManager { public: CSceneManager(); ~CSceneManager(){m_pHge->Release();} bool Init(); void Render(); bool Update(float); void Cleanup(); enum Scene { ON_SELECT, GAME_SCENE, ON_ITEMUI }; private: void OnSelect(float); void GameScene(float); void InitGameScene(); void GuiControl(float); void CameraCtrl(float); Pos GetMousePos(); void AddNpc(char* name, float x, float y); private: Scene m_scene; hgeGUI* m_pGUI; hgeSprite* m_pBG; hgeSprite* m_pSltSpr; hgeSprite* m_pMask; C2DCamera* m_pCamera; CRole* m_pRole; CMap* m_pMap; int m_alpha; float m_timer; int m_money; bool m_bUIOn; bool m_bMenuOn; private: OBJECTS m_objs; hgeResourceManager* m_pRs; static HGE* m_pHge; };
//网络杂项 #pragma once #include "xr_include.h" namespace xr { enum FD_TYPE { UNUSED = 0, LISTEN = 1, PIPE = 2, CLIENT = 3, MCAST = 4, ADDR_MCAST = 5, UDP = 6, CONNECT = 7, SERVER = 8, }; struct net_util_t { //用于通过网卡接口(eth0/eth1/lo...)获取对应的IP地址。支持IPv4和IPv6。 //nif 网卡接口.eth0/eth1/lo... //af 网络地址类型。AF_INET或者AF_INET6。 //ipaddr 用于返回nif和af对应的IP地址。 //return: 0:succ:0.-1:fail static int get_ip_addr(const char *nif, int af, std::string &ipaddr); //set a timeout on sending data. If you want to disable timeout, just simply call this function again with millisec set to be 0 //return:0:success.-1:error and errno is set appropriately static inline int set_sock_send_timeo(int sockfd, int milliseconds) { return net_util_t::set_sock_timeo(sockfd, SO_SNDTIMEO, milliseconds); } //set a timeout on receiving data. If you want to disable timeout, just simply call this function again with millisec set to be 0 //return:0:success.-1:error and errno is set appropriately static inline int set_sock_recv_timeo(int sockfd, int milliseconds) { return net_util_t::set_sock_timeo(sockfd, SO_RCVTIMEO, milliseconds); } //set the given fd recv buffer //returns:0:success.-1:error static inline int set_recvbuf(int sockfd, uint32_t len) { return ::setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (char *)&len, sizeof(len)); } static inline int set_sendbuf(int sockfd, uint32_t len) { return ::setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&len, sizeof(len)); } static inline uint32_t ip2int(const char *ip) { return inet_addr(ip); } static inline char *ip2str(uint32_t ip) { struct in_addr a; a.s_addr = ip; return inet_ntoa(a); } //translate the given address family to its corresponding level static int family_to_level(int family); //set the given fd SO_REUSEADDR //returns:0:success.-1:error static int set_reuse_addr(int fd) { const int flag = 1; return ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(flag)); } private: static inline int set_sock_timeo(int sockfd, int optname, int milliseconds) { struct timeval tv; tv.tv_sec = milliseconds / 1000; tv.tv_usec = (milliseconds % 1000) * 1000; return ::setsockopt(sockfd, SOL_SOCKET, optname, (char *)&tv, sizeof(tv)); } }; } //end namespace xr
// // Created by Zhao Xiaodong on 2017/6/4. // #ifndef MINISQL_RECORDMANAGER_H #define MINISQL_RECORDMANAGER_H #include <string> #include <vector> #include <map> #include <limits> #include "../index+catalog+buffer/table.h" #include "../index+catalog+buffer/buffermanager.h" #include "../index+catalog+buffer/catalogmanager.h" #include "../index+catalog+buffer/IndexManager.h" using namespace std; enum DataType { int_t = 1, float_t, char_t }; enum RelationOp { invalidOp, ne, nlt, ngt, lt, gt, eq }; static map<RelationOp, string> relationOps{ {ne, "<>"}, {nlt, ">="}, {ngt, "<="}, {lt, "<"}, {gt, ">"}, {eq, "="} }; struct IndexInfo { string indexName; DataType type; string value; }; struct KeysWithType { DataType type; vector<string> keys; }; struct Restrict { Restrict() {} Restrict(string attrName, RelationOp op, DataType type) : attrName(attrName), op(op), type(type) {} string attrName; RelationOp op; DataType type; }; struct IntRestrict : Restrict { IntRestrict(string attrName, RelationOp op, int value) : Restrict(attrName, op, int_t), value(value) {} int value; }; struct FloatRestrict : Restrict { FloatRestrict(string attrName, RelationOp op, float value) : Restrict(attrName, op, float_t), value(value) {} float value; }; struct StringRestrict : Restrict { StringRestrict(string attrName, RelationOp op, string value) : Restrict(attrName, op, char_t), value(value) {} string value; }; #if 1 struct Range { Range() {} Range(bool valid, DataType type, string attrName) : valid(valid), type(type), attrName(attrName) {} bool valid; DataType type; string attrName; }; struct IntRange : Range { IntRange(string attrName) : Range(true, int_t, attrName), minValue(numeric_limits<int>::min()), maxValue(numeric_limits<int>::max()), includeMin(false), includeMax(false) {} int minValue; bool includeMin; int maxValue; bool includeMax; vector<int> excludeValues; }; struct FloatRange : Range { FloatRange(string attrName) : Range(true, float_t, attrName), minValue(numeric_limits<float>::min()), maxValue(numeric_limits<float>::max()), includeMin(false), includeMax(false) {} float minValue; bool includeMin; float maxValue; bool includeMax; vector<float> excludeValues; }; struct StringRange : Range { StringRange(string attrName) : Range(true, char_t, attrName) {} string value; vector<string> excludeValues; }; #endif class RecordManager { private: string tableName; Table tableInfo; catalogmanager &catalogMgr; buffermanager &bufferMgr; BPLUSTREE &bPlusTree; string generateInsertValues(string rawValues, vector<IndexInfo> &indexInfos); string projectTuple(string tuple, vector<string> &values); void checkSelectTuple(vector<Range *> &ranges, vector<string> &attributes); void checkSelectTupleInBuffer(vector<Range *> &ranges, vector<string> &attributes); void checkDeleteTuple(vector<Range *> &ranges); void checkDeleteTupleInBuffer(vector<Range *> &ranges); bool inIntRange(IntRange *range, int val); bool inFloatRange(FloatRange *range, float val); bool inStringRange(StringRange *range, string val); bool checkInRange(vector<Range *> &ranges, map<string, string> &valueOfAttr); bool updateRange(Range *range, Restrict *restrict); // TODO: be private bool checkUnique(Attribute attr, string value); vector<Restrict *> parseWhere(string rawWhereClause = nullptr); vector<Range *> generateRange(const vector<Restrict *> &restricts); public: RecordManager(const string tableName, catalogmanager &catalogMgr, buffermanager &bufferMgr, BPLUSTREE &bPlusTree) : tableName(tableName), catalogMgr(catalogMgr), bufferMgr(bufferMgr), bPlusTree(bPlusTree) {} bool insertRecord(string rawValues); bool selectRecords(vector<string> &attributes, string rawWhereClause); bool deleteRecords(string rawWhereClause); }; #endif //MINISQL_RECORDMANAGER_H
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define showmap(is, js, x) {rep(i, is){rep(j, js){cout << x[i][j] << " ";}cout << endl;}} #define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;} #define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;} typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> P; typedef pair<ll, ll> llP; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} //大きな数を扱うときは、 //上位桁と下位桁を分離 int main() { ull x; cin >> x; ull ans = 0; ull y = 100; while(y < x){ y = (y/100)*101 + ((y%100)*101/100); ans++; } cout << ans << endl; }
#ifndef HEADER_CURL_THREADS_H #define HEADER_CURL_THREADS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" namespace youmecommon { #if defined(USE_THREADS_POSIX) # define CURL_STDCALL # define curl_mutex_t pthread_mutex_t # define curl_thread_t pthread_t * # define curl_thread_t_null (pthread_t *)0 # define Curl_mutex_init(m) pthread_mutex_init(m, NULL) # define Curl_mutex_acquire(m) pthread_mutex_lock(m) # define Curl_mutex_release(m) pthread_mutex_unlock(m) # define Curl_mutex_destroy(m) pthread_mutex_destroy(m) #elif defined(USE_THREADS_WIN32) # define CURL_STDCALL __stdcall # define curl_mutex_t CRITICAL_SECTION # define curl_thread_t HANDLE # define curl_thread_t_null (HANDLE)0 # if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || \ (_WIN32_WINNT < _WIN32_WINNT_VISTA) # define Curl_mutex_init(m) InitializeCriticalSection(m) # else # define Curl_mutex_init(m) InitializeCriticalSectionEx(m, 0, 1) # endif # define Curl_mutex_acquire(m) EnterCriticalSection(m) # define Curl_mutex_release(m) LeaveCriticalSection(m) # define Curl_mutex_destroy(m) DeleteCriticalSection(m) #endif #if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32) curl_thread_t Curl_thread_create(unsigned int (CURL_STDCALL *func) (void*), void *arg); void Curl_thread_destroy(curl_thread_t hnd); int Curl_thread_join(curl_thread_t *hnd); #endif /* USE_THREADS_POSIX || USE_THREADS_WIN32 */ } #endif /* HEADER_CURL_THREADS_H */
#include <iostream> #include "circle.hpp" int main() { Circle c1, c2(2); std::cout << c1 << ' ' << c2 << '\n'; c1.set_radius(3); std::cout << c1 << '\n'; Circle c3 = c1; c3.set_radius(7); std::cout << c3 << '\n'; /* Sphere s1, s2(2); Sphere s3 = s1; s3.set_radius(5); s2 = s2 * 2; std::cout << s1 << '\n' << s2 << '\n' << s3 << '\n'; */ return 0; }
// Copyright (c) 2012-2017 The Cryptonote developers // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include "Chaingen.h" struct get_tx_validation_base : public test_chain_unit_base { get_tx_validation_base() : m_invalid_tx_index(0) , m_invalid_block_index(0) { REGISTER_CALLBACK_METHOD(get_tx_validation_base, mark_invalid_tx); REGISTER_CALLBACK_METHOD(get_tx_validation_base, mark_invalid_block); } bool check_tx_verification_context(const cn::tx_verification_context& tvc, bool tx_added, size_t event_idx, const cn::Transaction& /*tx*/) { if (m_invalid_tx_index == event_idx) return tvc.m_verification_failed; else return !tvc.m_verification_failed && tx_added; } bool check_block_verification_context(const cn::block_verification_context& bvc, size_t event_idx, const cn::Block& /*block*/) { if (m_invalid_block_index == event_idx) return bvc.m_verification_failed; else return !bvc.m_verification_failed; } bool mark_invalid_block(cn::core& /*c*/, size_t ev_index, const std::vector<test_event_entry>& /*events*/) { m_invalid_block_index = ev_index + 1; return true; } bool mark_invalid_tx(cn::core& /*c*/, size_t ev_index, const std::vector<test_event_entry>& /*events*/) { m_invalid_tx_index = ev_index + 1; return true; } private: size_t m_invalid_tx_index; size_t m_invalid_block_index; }; struct gen_tx_big_version : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_unlock_time : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_no_inputs_no_outputs : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_no_inputs_has_outputs : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_has_inputs_no_outputs : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_invalid_input_amount : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_in_to_key_wo_key_offsets : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_key_offest_points_to_foreign_key : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_sender_key_offest_not_exist : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_mixed_key_offest_not_exist : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_key_image_not_derive_from_tx_key : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_key_image_is_invalid : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_check_input_unlock_time : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_txout_to_key_has_invalid_key : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_output_with_zero_amount : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct gen_tx_signatures_are_invalid : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct GenerateTransactionWithZeroFee : public get_tx_validation_base { explicit GenerateTransactionWithZeroFee(bool keptByBlock); bool generate(std::vector<test_event_entry>& events) const; bool m_keptByBlock; }; // MultiSignature class TestGenerator; struct MultiSigTx_OutputSignatures : public get_tx_validation_base { MultiSigTx_OutputSignatures(size_t givenKeys, uint32_t requiredSignatures, bool shouldSucceed); bool generate(std::vector<test_event_entry>& events) const; bool generate(TestGenerator& generator) const; const size_t m_givenKeys; const uint32_t m_requiredSignatures; const bool m_shouldSucceed; std::vector<cn::AccountBase> m_outputAccounts; }; struct MultiSigTx_InvalidOutputSignature : public get_tx_validation_base { bool generate(std::vector<test_event_entry>& events) const; }; struct MultiSigTx_Input : public MultiSigTx_OutputSignatures { MultiSigTx_Input(size_t givenKeys, uint32_t requiredSignatures, uint32_t givenSignatures, bool shouldSucceed); bool generate(std::vector<test_event_entry>& events) const; const bool m_inputShouldSucceed; const uint32_t m_givenSignatures; }; struct MultiSigTx_BadInputSignature : public MultiSigTx_OutputSignatures { MultiSigTx_BadInputSignature(); bool generate(std::vector<test_event_entry>& events) const; };
// Created by: DAUTRY Philippe // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TDF_Data_HeaderFile #define _TDF_Data_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TDF_LabelNodePtr.hxx> #include <Standard_Integer.hxx> #include <TColStd_ListOfInteger.hxx> #include <TDF_HAllocator.hxx> #include <Standard_Transient.hxx> #include <TDF_Label.hxx> #include <Standard_OStream.hxx> #include <NCollection_DataMap.hxx> class TDF_Delta; class TDF_Label; class TDF_Data; DEFINE_STANDARD_HANDLE(TDF_Data, Standard_Transient) //! This class is used to manipulate a complete independent, //! self sufficient data structure and its services: //! //! Access to the root label; //! //! Opens, aborts, commits a transaction; //! //! Generation and use of Delta, depending on the time. //! This class uses a special allocator //! (see LabelNodeAllocator() method) //! for more efficient allocation of objects in memory. class TDF_Data : public Standard_Transient { public: //! A new and empty Data structure. Standard_EXPORT TDF_Data(); //! Returns the root label of the Data structure. const TDF_Label Root() const; //! Returns the current transaction number. Standard_Integer Transaction() const; //! Returns the current tick. It is incremented each Commit. Standard_Integer Time() const; //! Returns true if <aDelta> is applicable HERE and NOW. Standard_EXPORT Standard_Boolean IsApplicable (const Handle(TDF_Delta)& aDelta) const; //! Apply <aDelta> to undo a set of attribute modifications. //! //! Optional <withDelta> set to True indicates a //! Delta Set must be generated. (See above) Standard_EXPORT Handle(TDF_Delta) Undo (const Handle(TDF_Delta)& aDelta, const Standard_Boolean withDelta = Standard_False); Standard_EXPORT void Destroy(); ~TDF_Data() { Destroy(); } //! Returns the undo mode status. Standard_Boolean NotUndoMode() const; //! Dumps the Data on <aStream>. Standard_EXPORT Standard_OStream& Dump (Standard_OStream& anOS) const; Standard_OStream& operator<< (Standard_OStream& anOS) const { return Dump(anOS); } //! Sets modification mode. void AllowModification (const Standard_Boolean isAllowed); //! returns modification mode. Standard_Boolean IsModificationAllowed() const; //! Initializes a mechanism for fast access to the labels by their entries. //! The fast access is useful for large documents and often access to the labels //! via entries. Internally, a table of entry - label is created, //! which allows to obtain a label by its entry in a very fast way. //! If the mechanism is turned off, the internal table is cleaned. //! New labels are added to the table, if the mechanism is on //! (no need to re-initialize the mechanism). Standard_EXPORT void SetAccessByEntries (const Standard_Boolean aSet); //! Returns a status of mechanism for fast access to the labels via entries. Standard_Boolean IsAccessByEntries() const { return myAccessByEntries; } //! Returns a label by an entry. //! Returns Standard_False, if such a label doesn't exist //! or mechanism for fast access to the label by entry is not initialized. Standard_Boolean GetLabel (const TCollection_AsciiString& anEntry, TDF_Label& aLabel) { return myAccessByEntriesTable.Find(anEntry, aLabel); } //! An internal method. It is used internally on creation of new labels. //! It adds a new label into internal table for fast access to the labels by entry. Standard_EXPORT void RegisterLabel (const TDF_Label& aLabel); //! Returns TDF_HAllocator, which is an //! incremental allocator used by //! TDF_LabelNode. //! This allocator is used to //! manage TDF_LabelNode objects, //! but it can also be used for //! allocating memory to //! application-specific data (be //! careful because this //! allocator does not release //! the memory). //! The benefits of this //! allocation scheme are //! noticeable when dealing with //! large OCAF documents, due to: //! 1. Very quick allocation of //! objects (memory heap is not //! used, the algorithm that //! replaces it is very simple). //! 2. Very quick destruction of //! objects (memory is released not //! by destructors of TDF_LabelNode, //! but rather by the destructor of //! TDF_Data). //! 3. TDF_LabelNode objects do not //! fragmentize the memory; they are //! kept compactly in a number of //! arrays of 16K each. //! 4. Swapping is reduced on large //! data, because each document now //! occupies a smaller number of //! memory pages. const TDF_HAllocator& LabelNodeAllocator() const; //! Dumps the content of me into the stream Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const; friend class TDF_Transaction; friend class TDF_LabelNode; DEFINE_STANDARD_RTTIEXT(TDF_Data,Standard_Transient) protected: private: //! Fixes order of Attributes' Deltas to perform undo/redo without exceptions: //! puts OnRemoval deltas to the end of the list. void FixOrder(const Handle(TDF_Delta)& theDelta); //! Increments the transaction number and returns it. Standard_EXPORT Standard_Integer OpenTransaction(); //! Decrements the transaction number and commits the //! modifications. //! //! Raises if there is no current transaction. //! //! Optional <withDelta> set to True indicates a //! Delta must be generated. Standard_EXPORT Handle(TDF_Delta) CommitTransaction (const Standard_Boolean withDelta = Standard_False); //! Decrements the transaction number and commits the //! modifications until AND including the transaction //! <untilTransaction>. Standard_EXPORT Handle(TDF_Delta) CommitUntilTransaction (const Standard_Integer untilTransaction, const Standard_Boolean withDelta = Standard_False); //! Decrements the transaction number and forgets the //! modifications. //! //! Raises if there is no current transaction. Standard_EXPORT void AbortTransaction(); //! Decrements the transaction number and forgets the //! modifications until AND including the transaction //! <untilTransaction>. Standard_EXPORT void AbortUntilTransaction (const Standard_Integer untilTransaction); //! Decrements the transaction number and commits the //! modifications. Used to implement the recursif //! commit process. The returned boolean says how many //! attributes (new, modified or deleted) has been //! committed from the previous transaction into the //! current one. Standard_EXPORT Standard_Integer CommitTransaction (const TDF_Label& aLabel, const Handle(TDF_Delta)& aDelta, const Standard_Boolean withDelta); TDF_LabelNodePtr myRoot; Standard_Integer myTransaction; Standard_Integer myNbTouchedAtt; Standard_Boolean myNotUndoMode; Standard_Integer myTime; TColStd_ListOfInteger myTimes; TDF_HAllocator myLabelNodeAllocator; Standard_Boolean myAllowModification; Standard_Boolean myAccessByEntries; NCollection_DataMap<TCollection_AsciiString, TDF_Label> myAccessByEntriesTable; }; #include <TDF_Data.lxx> #endif // _TDF_Data_HeaderFile
#include<stdio.h> #include<conio.h> int prime(int); int main() { int num, x; printf ("Enter a number :"); scanf("%d",&num); x=prime(num); if(x==1) { printf("It is a prime number\n\n"); } else { printf("It is not a prime number\n\n"); } main(); getch(); return 0; } int prime(int num) { int ans=1; for(int i = 2; i <= num/2; i++) { if(num % i == 0) { ans = 0; break; } } return ans; }
// 200118 // 백준 #2293 : 동전 1 // DP : 본 풀이 방법으로는 메모리 초과됨. // 4Bytes x (101+101x10001) = 4,080,408 Bytes = 약 3.9MB #include <iostream> int n, k; int c[101]; // int dp[10001]; int d[101][10001]; int main() { scanf("%d %d", &n, &k); for(int i=1; i<=n; i++) { scanf("%d", &c[i]); d[i][0]=1; } for(int i=1; i<=n; i++) { for(int j=1; j<=k; j++) { d[i][j]=d[i-1][j] + d[i][j-c[i]]; // printf(" d[%d][%d] : %d \n", i,j, d[i][j]); } } printf("%d", d[n][k]); return 0; }
// Copyright (C) 2004 Id Software, Inc. // #ifndef __CINEMATIC_H__ #define __CINEMATIC_H__ // RAVEN BEGIN //nrausch: I made some semi-heavy changes to this entire file // - changed to idCinematic to use a private implementation which // is determined & allocated when InitFromFile is called. A different // PIMPL is used depending on if the video file is a roq or a wmv. // This replaces the functionality that was in a few versions ago under the // "StandaloneCinematic" name. // RAVEN END /* =============================================================================== RoQ cinematic Multiple idCinematics can run simultaniously. A single idCinematic can be reused for multiple files if desired. =============================================================================== */ // cinematic states typedef enum { FMV_IDLE, FMV_PLAY, // play FMV_EOF, // all other conditions, i.e. stop/EOF/abort FMV_ID_BLT, FMV_ID_IDLE, FMV_LOOPED, FMV_ID_WAIT } cinStatus_t; // a cinematic stream generates an image buffer, which the caller will upload to a texture typedef struct { int imageWidth, imageHeight; // will be a power of 2 const byte * image; // RGBA format, alpha will be 255 int status; } cinData_t; class idCinematic { idCinematic* PIMPL; // Store off the current mode - wmv or roq // If the cinematic is in the same mode if InitFromFile // is called again on it, this will prevent reallocation // of the PIMPL int mode; public: // initialize cinematic play back data static void InitCinematic( void ); // shutdown cinematic play back data static void ShutdownCinematic( void ); // allocates and returns a private subclass that implements the methods // This should be used instead of new static idCinematic *Alloc(); idCinematic(); // frees all allocated memory virtual ~idCinematic(); enum { SUPPORT_DRAW = 1, SUPPORT_IMAGEFORTIME = 2, SUPPORT_DEFAULT = SUPPORT_IMAGEFORTIME }; // returns false if it failed to load // this interface can take either a wmv or roq file // wmv will imply movie audio, unless there is no audio encoded in the stream // right now there is no way to disable this. virtual bool InitFromFile(const char *qpath, bool looping, int options = SUPPORT_DEFAULT); // returns the length of the animation in milliseconds virtual int AnimationLength(); // the pointers in cinData_t will remain valid until the next UpdateForTime() call // will do nothing if InitFromFile was not called with SUPPORT_IMAGEFORTIME virtual cinData_t ImageForTime(int milliseconds); // closes the file and frees all allocated memory virtual void Close(); // closes the file and frees all allocated memory virtual void ResetTime(int time); // draw the current animation frame to screen // will do nothing if InitFromFile was not called with SUPPORT_DRAW virtual void Draw(); // Set draw position & size // will do nothing if InitFromFile was not called with SUPPORT_DRAW virtual void SetScreenRect(int left, int right, int bottom, int top); // Get draw position & size // will do nothing if InitFromFile was not called with SUPPORT_DRAW virtual void GetScreenRect(int &left, int &right, int &bottom, int &top); // True if the video is playing // will do nothing if InitFromFile was not called with SUPPORT_DRAW virtual bool IsPlaying(); }; /* =============================================== Sound meter. =============================================== */ class idSndWindow : public idCinematic { public: idSndWindow() { showWaveform = false; } ~idSndWindow() {} bool InitFromFile( const char *qpath, bool looping, int options ); cinData_t ImageForTime( int milliseconds ); int AnimationLength(); private: bool showWaveform; }; #endif /* !__CINEMATIC_H__ */
#include "Snitch.h" Snitch::Snitch() { radius = SNITCH_RADIUS; center = Point3(0, SNITCH_HEIGHT, 0); float theta = random(360); theta = jiao2hu(theta); colour = color + BLACK; v.axis[0] = cos(theta) * SNITCH_SPEED; v.axis[1] = sin(theta) * SNITCH_SPEED; colour = color + GOLDEN; } Snitch::~Snitch() { } void Snitch::Run() { Ball::Run(); static int k = 0; if (k < 950) k = random(1000); if (k < 950) center.axis[1] = SNITCH_HEIGHT; else k--; }
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #include "test_precomp.hpp" using namespace cv; namespace { static const char * const keys = "{ h help | | print help }" "{ i info | false | print info }" "{ t true | true | true value }" "{ n unused | | dummy }" ; TEST(CommandLineParser, testFailure) { const char* argv[] = {"<bin>", "-q"}; const int argc = 2; cv::CommandLineParser parser(argc, argv, keys); EXPECT_ANY_THROW(parser.has("q")); EXPECT_ANY_THROW(parser.get<bool>("q")); EXPECT_ANY_THROW(parser.get<bool>(0)); parser.get<bool>("h"); EXPECT_FALSE(parser.check()); } TEST(CommandLineParser, testHas_noValues) { const char* argv[] = {"<bin>", "-h", "--info"}; const int argc = 3; cv::CommandLineParser parser(argc, argv, keys); EXPECT_TRUE(parser.has("help")); EXPECT_TRUE(parser.has("h")); EXPECT_TRUE(parser.has("info")); EXPECT_TRUE(parser.has("i")); EXPECT_FALSE(parser.has("n")); EXPECT_FALSE(parser.has("unused")); } TEST(CommandLineParser, testHas_TrueValues) { const char* argv[] = {"<bin>", "-h=TRUE", "--info=true"}; const int argc = 3; cv::CommandLineParser parser(argc, argv, keys); EXPECT_TRUE(parser.has("help")); EXPECT_TRUE(parser.has("h")); EXPECT_TRUE(parser.has("info")); EXPECT_TRUE(parser.has("i")); EXPECT_FALSE(parser.has("n")); EXPECT_FALSE(parser.has("unused")); } TEST(CommandLineParser, testHas_TrueValues1) { const char* argv[] = {"<bin>", "-h=1", "--info=1"}; const int argc = 3; cv::CommandLineParser parser(argc, argv, keys); EXPECT_TRUE(parser.has("help")); EXPECT_TRUE(parser.has("h")); EXPECT_TRUE(parser.has("info")); EXPECT_TRUE(parser.has("i")); EXPECT_FALSE(parser.has("n")); EXPECT_FALSE(parser.has("unused")); } TEST(CommandLineParser, testHas_FalseValues0) { const char* argv[] = {"<bin>", "-h=0", "--info=0"}; const int argc = 3; cv::CommandLineParser parser(argc, argv, keys); EXPECT_TRUE(parser.has("help")); EXPECT_TRUE(parser.has("h")); EXPECT_TRUE(parser.has("info")); EXPECT_TRUE(parser.has("i")); EXPECT_FALSE(parser.has("n")); EXPECT_FALSE(parser.has("unused")); } TEST(CommandLineParser, testBoolOption_noArgs) { const char* argv[] = {"<bin>"}; const int argc = 1; cv::CommandLineParser parser(argc, argv, keys); EXPECT_FALSE(parser.get<bool>("help")); EXPECT_FALSE(parser.get<bool>("h")); EXPECT_FALSE(parser.get<bool>("info")); EXPECT_FALSE(parser.get<bool>("i")); EXPECT_TRUE(parser.get<bool>("true")); // default is true EXPECT_TRUE(parser.get<bool>("t")); } TEST(CommandLineParser, testBoolOption_noValues) { const char* argv[] = {"<bin>", "-h", "--info"}; const int argc = 3; cv::CommandLineParser parser(argc, argv, keys); EXPECT_TRUE(parser.get<bool>("help")); EXPECT_TRUE(parser.get<bool>("h")); EXPECT_TRUE(parser.get<bool>("info")); EXPECT_TRUE(parser.get<bool>("i")); } TEST(CommandLineParser, testBoolOption_TrueValues) { const char* argv[] = {"<bin>", "-h=TRUE", "--info=true"}; const int argc = 3; cv::CommandLineParser parser(argc, argv, keys); //EXPECT_TRUE(parser.get<bool>("help")); //EXPECT_TRUE(parser.get<bool>("h")); EXPECT_TRUE(parser.get<bool>("info")); EXPECT_TRUE(parser.get<bool>("i")); EXPECT_FALSE(parser.get<bool>("unused")); EXPECT_FALSE(parser.get<bool>("n")); } TEST(CommandLineParser, testBoolOption_FalseValues) { const char* argv[] = {"<bin>", "--help=FALSE", "-i=false"}; const int argc = 3; cv::CommandLineParser parser(argc, argv, keys); EXPECT_FALSE(parser.get<bool>("help")); EXPECT_FALSE(parser.get<bool>("h")); EXPECT_FALSE(parser.get<bool>("info")); EXPECT_FALSE(parser.get<bool>("i")); } static const char * const keys2 = "{ h help | | print help }" "{ @arg1 | default1 | param1 }" "{ @arg2 | | param2 }" "{ n unused | | dummy }" ; TEST(CommandLineParser, testPositional_noArgs) { const char* argv[] = {"<bin>"}; const int argc = 1; cv::CommandLineParser parser(argc, argv, keys2); EXPECT_TRUE(parser.has("@arg1")); EXPECT_FALSE(parser.has("@arg2")); EXPECT_EQ("default1", parser.get<String>("@arg1")); EXPECT_EQ("default1", parser.get<String>(0)); EXPECT_EQ("", parser.get<String>("@arg2")); EXPECT_EQ("", parser.get<String>(1)); } TEST(CommandLineParser, testPositional_default) { const char* argv[] = {"<bin>", "test1", "test2"}; const int argc = 3; cv::CommandLineParser parser(argc, argv, keys2); EXPECT_TRUE(parser.has("@arg1")); EXPECT_TRUE(parser.has("@arg2")); EXPECT_EQ("test1", parser.get<String>("@arg1")); EXPECT_EQ("test2", parser.get<String>("@arg2")); EXPECT_EQ("test1", parser.get<String>(0)); EXPECT_EQ("test2", parser.get<String>(1)); } TEST(CommandLineParser, testPositional_withFlagsBefore) { const char* argv[] = {"<bin>", "-h", "test1", "test2"}; const int argc = 4; cv::CommandLineParser parser(argc, argv, keys2); EXPECT_TRUE(parser.has("@arg1")); EXPECT_TRUE(parser.has("@arg2")); EXPECT_EQ("test1", parser.get<String>("@arg1")); EXPECT_EQ("test2", parser.get<String>("@arg2")); EXPECT_EQ("test1", parser.get<String>(0)); EXPECT_EQ("test2", parser.get<String>(1)); } TEST(CommandLineParser, testPositional_withFlagsAfter) { const char* argv[] = {"<bin>", "test1", "test2", "-h"}; const int argc = 4; cv::CommandLineParser parser(argc, argv, keys2); EXPECT_TRUE(parser.has("@arg1")); EXPECT_TRUE(parser.has("@arg2")); EXPECT_EQ("test1", parser.get<String>("@arg1")); EXPECT_EQ("test2", parser.get<String>("@arg2")); EXPECT_EQ("test1", parser.get<String>(0)); EXPECT_EQ("test2", parser.get<String>(1)); } TEST(CommandLineParser, testEmptyStringValue) { static const char * const keys3 = "{ @pos0 | | empty default value }" "{ @pos1 | <none> | forbid empty default value }"; const char* argv[] = {"<bin>"}; const int argc = 1; cv::CommandLineParser parser(argc, argv, keys3); // EXPECT_TRUE(parser.has("@pos0")); EXPECT_EQ("", parser.get<String>("@pos0")); EXPECT_TRUE(parser.check()); EXPECT_FALSE(parser.has("@pos1")); parser.get<String>(1); EXPECT_FALSE(parser.check()); } TEST(CommandLineParser, positional_regression_5074_equal_sign) { static const char * const keys3 = "{ @eq0 | | }" "{ eq1 | | }"; const char* argv[] = {"<bin>", "1=0", "--eq1=1=0"}; const int argc = 3; cv::CommandLineParser parser(argc, argv, keys3); EXPECT_EQ("1=0", parser.get<String>("@eq0")); EXPECT_EQ("1=0", parser.get<String>(0)); EXPECT_EQ("1=0", parser.get<String>("eq1")); EXPECT_TRUE(parser.check()); } TEST(AutoBuffer, allocate_test) { AutoBuffer<int, 5> abuf(2); EXPECT_EQ(2u, abuf.size()); abuf.allocate(4); EXPECT_EQ(4u, abuf.size()); abuf.allocate(6); EXPECT_EQ(6u, abuf.size()); } } // namespace
#include <Stepper.h> int motorPin1 = 8; int motorPin2 = 13; int motorPin3 = 9; int motorPin4 = 12; int trigger = 5; int echo = 4; int led = 13; long dauer = 0; long entfernung = 0; int motorSpeed = 10; int entfernungZumStartenVomHochziehen = 200; int pauseNachHochziehen = 10000; int umdrehung = 200; int umdrehungenDesMotorsZumHochziehen = 10; int umdrehungenDesMotorsZumRunterfahren = -umdrehungenDesMotorsZumHochziehen; int maximaleEntfernung = 500; Stepper motor(200, 8, 9, 12, 13); void setup()\ { pinMode(motorPin1, OUTPUT); pinMode(motorPin2, OUTPUT); pinMode(motorPin3, OUTPUT); pinMode(motorPin4, OUTPUT); pinMode(trigger, OUTPUT); pinMode(echo, INPUT); pinMode(led, OUTPUT); Serial.begin(9600); motor.setSpeed(motorSpeed); } void loop() { digitalWrite(led, LOW); digitalWrite(trigger, LOW); delay(5); digitalWrite(trigger, HIGH); delay(10); digitalWrite(trigger, LOW); dauer = pulseIn(echo, HIGH); entfernung = (dauer / 2) * 0.03432; Serial.print(entfernung); if (entfernung >= maximaleEntfernung || entfernung <= 0) { Serial.println("Kein Messwert"); } else { if (entfernung <= entfernungZumStartenVomHochziehen) { Serial.print("works"); motor.step(umdrehung * umdrehungenDesMotorsZumHochziehen); Serial.print("breaks"); delay(pauseNachHochziehen); motor.step(umdrehung * umdrehungenDesMotorsZumRunterfahren); Serial.write(100); //start ton delay(10000); Serial.write(0); //stop ton TODO: trigger from PD motor.step(umdrehung * umdrehungenDesMotorsZumHochziehen); delay(3000); motor.step(umdrehung * umdrehungenDesMotorsZumRunterfahren); digitalWrite(led, HIGH); delay(10000); } } /* else{ */ /* digitalWrite(led, LOW); */ /* motor.step(umdrehung * umdrehungenDesMotorsZumRunterfahren); */ /* } */ /* Serial.print(entfernung); */ /* Serial.println(" cm"); */ // if (Serial.available()) // { // int steps = Serial.parseInt(); // motor.step(steps); // } }
#pragma once #include "ICommandMaker.h" #include "CommandFactory.h" template <typename T> class CommandMaker : public ICommandMaker { public: CommandMaker(const std::string& key) { try { CommandFactory::Instance().RegisterMaker(key, this); } catch (std::string e) { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, 12); // Red Color std::cout << "[Error]:"; SetConsoleTextAttribute(hConsole, 15); // White Color std::cout << " " << e << std::endl; exit(0); } } T* Create(std::string parametrs) const { return new T(parametrs); } };
void setup() { Serial.begin(9600); pinMode(2, OUTPUT); pinMode(14, OUTPUT); attachInterrupt(5, blink1, RISING); pinMode(5, INPUT_PULLDOWN); attachInterrupt(6, blink2, RISING); pinMode(6, INPUT_PULLDOWN); attachInterrupt(7, blink3, RISING); pinMode(7, INPUT_PULLDOWN); attachInterrupt(8, blink4, RISING); pinMode(8, INPUT_PULLDOWN); } void loop(){ __bis_status_register(LPM3_bits+GIE); } void blink1(){ digitalWrite(2, LOW); digitalWrite(14, LOW); } void blink2(){ digitalWrite(2, HIGH); digitalWrite(14, LOW); } void blink3(){ digitalWrite(2, HIGH); digitalWrite(14, HIGH); } void blink4(){ digitalWrite(2, LOW); digitalWrite(14, HIGH); }
#include "transform.hpp" using namespace std; using namespace Eigen; int main(int argc, char* argv[]) { // Check to see if there is a text file to read if (argc == 2) { // Open the text file of transformations fstream file; file.open(argv[1]); if (!file) { cout << "no file to read" << endl; file.close(); } // create the vector of matrices to be multiplied vector<Matrix4d> matrices; // read the first string of a line while there are still lines in the // file string m; while (file >> m) { // convert to switch cases? if (m == "t") { string x, y, z; file >> x >> y >> z; Matrix4d m = convert_t(x, y, z);\ matrices.push_back(m); } else if (m == "r") { string x, y, z, d; file >> x >> y >> z >> d; Matrix4d m = convert_r(x, y, z, d); matrices.push_back(m); } else if (m == "s") { string x, y, z; file >> x >> y >> z; Matrix4d m = convert_s(x, y, z); matrices.push_back(m); } else { cout << "incorrect input" << endl; } m = ""; } file.close(); // multiply all of the matrices in the vector together to make the final // transformation while (matrices.size() > 1) { Matrix4d m; Matrix4d m1 = matrices.back(); matrices.pop_back(); Matrix4d m2 = matrices.back(); matrices.pop_back(); m = m1 * m2; matrices.push_back(m); } cout << matrices[0].inverse() << endl; } else { // there are no command line inputs cerr << "no file inputs" << endl; } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "Nerucci.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Nerucci, "Nerucci" ); DEFINE_LOG_CATEGORY(LogNerucci)
#pragma once namespace aeEngineSDK { struct AE_UTILITY_EXPORT aeSphere { /*************************************************************************************************/ /* Constructors declaration /*************************************************************************************************/ public: aeSphere(); aeSphere(const aeSphere& A); aeSphere(const aeVector3& Pos, float Radius); ~aeSphere(); /*************************************************************************************************/ /* Variable declaration /*************************************************************************************************/ public: aeVector3 m_xPosition; float m_fRadius; /*************************************************************************************************/ /* Functions declaration /*************************************************************************************************/ public: bool operator^(const aeSphere& S); }; }
// // Created by Jonathan Gerber on 1/17/17. // #include "TimeMe.hpp" #include "catch.hpp" SCENARIO("testing timeme") { GIVEN("a timeme instance") { TimeMe me{1000}; THEN("lenght should be 1000") REQUIRE(me.getLength() == 1000); } }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <quic/congestion_control/CongestionControllerFactory.h> #include <quic/congestion_control/Bbr.h> #include <quic/congestion_control/Bbr2.h> #include <quic/congestion_control/BbrBandwidthSampler.h> #include <quic/congestion_control/BbrRttSampler.h> #include <quic/congestion_control/Copa.h> #include <quic/congestion_control/Copa2.h> #include <quic/congestion_control/NewReno.h> #include <quic/congestion_control/QuicCubic.h> #include <quic/congestion_control/StaticCwndCongestionController.h> #include <memory> namespace quic { std::unique_ptr<CongestionController> DefaultCongestionControllerFactory::makeCongestionController( QuicConnectionStateBase& conn, CongestionControlType type) { std::unique_ptr<CongestionController> congestionController; auto setupBBR = [&conn](BbrCongestionController* bbr) { bbr->setRttSampler(std::make_unique<BbrRttSampler>( std::chrono::seconds(kDefaultRttSamplerExpiration))); bbr->setBandwidthSampler(std::make_unique<BbrBandwidthSampler>(conn)); }; switch (type) { case CongestionControlType::NewReno: congestionController = std::make_unique<NewReno>(conn); break; case CongestionControlType::Cubic: congestionController = std::make_unique<Cubic>(conn); break; case CongestionControlType::Copa: congestionController = std::make_unique<Copa>(conn); break; case CongestionControlType::Copa2: congestionController = std::make_unique<Copa2>(conn); break; case CongestionControlType::BBRTesting: LOG(ERROR) << "Default CC Factory cannot make BbrTesting. Falling back to BBR."; FOLLY_FALLTHROUGH; case CongestionControlType::BBR: { auto bbr = std::make_unique<BbrCongestionController>(conn); setupBBR(bbr.get()); congestionController = std::move(bbr); break; } case CongestionControlType::BBR2: { auto bbr2 = std::make_unique<Bbr2CongestionController>(conn); congestionController = std::move(bbr2); break; } case CongestionControlType::StaticCwnd: { throw QuicInternalException( "StaticCwnd Congestion Controller cannot be " "constructed via CongestionControllerFactory.", LocalErrorCode::INTERNAL_ERROR); } case CongestionControlType::None: break; case CongestionControlType::MAX: throw QuicInternalException( "MAX is not a valid cc algorithm.", LocalErrorCode::INTERNAL_ERROR); } QUIC_STATS(conn.statsCallback, onNewCongestionController, type); return congestionController; } } // namespace quic
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "CryptoNoteCore/BlockchainMessages.h" namespace cn { NewBlockMessage::NewBlockMessage(const crypto::Hash& hash) : blockHash(hash) {} void NewBlockMessage::get(crypto::Hash& hash) const { hash = blockHash; } NewAlternativeBlockMessage::NewAlternativeBlockMessage(const crypto::Hash& hash) : blockHash(hash) {} void NewAlternativeBlockMessage::get(crypto::Hash& hash) const { hash = blockHash; } ChainSwitchMessage::ChainSwitchMessage(std::vector<crypto::Hash>&& hashes) : blocksFromCommonRoot(std::move(hashes)) {} ChainSwitchMessage::ChainSwitchMessage(const ChainSwitchMessage& other) : blocksFromCommonRoot(other.blocksFromCommonRoot) {} void ChainSwitchMessage::get(std::vector<crypto::Hash>& hashes) const { hashes = blocksFromCommonRoot; } BlockchainMessage::BlockchainMessage(NewBlockMessage&& message) : type(MessageType::NEW_BLOCK_MESSAGE), newBlockMessage(std::move(message)) {} BlockchainMessage::BlockchainMessage(NewAlternativeBlockMessage&& message) : type(MessageType::NEW_ALTERNATIVE_BLOCK_MESSAGE), newAlternativeBlockMessage(std::move(message)) {} BlockchainMessage::BlockchainMessage(ChainSwitchMessage&& message) : type(MessageType::CHAIN_SWITCH_MESSAGE) { chainSwitchMessage = new ChainSwitchMessage(std::move(message)); } BlockchainMessage::BlockchainMessage(const BlockchainMessage& other) : type(other.type) { switch (type) { case MessageType::NEW_BLOCK_MESSAGE: new (&newBlockMessage) NewBlockMessage(other.newBlockMessage); break; case MessageType::NEW_ALTERNATIVE_BLOCK_MESSAGE: new (&newAlternativeBlockMessage) NewAlternativeBlockMessage(other.newAlternativeBlockMessage); break; case MessageType::CHAIN_SWITCH_MESSAGE: chainSwitchMessage = new ChainSwitchMessage(*other.chainSwitchMessage); break; } } BlockchainMessage::~BlockchainMessage() { switch (type) { case MessageType::NEW_BLOCK_MESSAGE: newBlockMessage.~NewBlockMessage(); break; case MessageType::NEW_ALTERNATIVE_BLOCK_MESSAGE: newAlternativeBlockMessage.~NewAlternativeBlockMessage(); break; case MessageType::CHAIN_SWITCH_MESSAGE: delete chainSwitchMessage; break; } } BlockchainMessage::MessageType BlockchainMessage::getType() const { return type; } bool BlockchainMessage::getNewBlockHash(crypto::Hash& hash) const { if (type == MessageType::NEW_BLOCK_MESSAGE) { newBlockMessage.get(hash); return true; } else { return false; } } bool BlockchainMessage::getNewAlternativeBlockHash(crypto::Hash& hash) const { if (type == MessageType::NEW_ALTERNATIVE_BLOCK_MESSAGE) { newAlternativeBlockMessage.get(hash); return true; } else { return false; } } bool BlockchainMessage::getChainSwitch(std::vector<crypto::Hash>& hashes) const { if (type == MessageType::CHAIN_SWITCH_MESSAGE) { chainSwitchMessage->get(hashes); return true; } else { return false; } } }
#include <iostream> using namespace std; int main() { for(int i= 0; i<10; i++){ for(int j=0; j<i; j++){ cout << j+1 ; } cout << endl; } return 0; }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int countUnivalSubtrees(TreeNode* root) { return visit(root, 0); } int visit(TreeNode* node, int len){ if(node == NULL) return 0; if(node->left == NULL && node->right == NULL) return 1 + len; int val = node->val, lLen = 0, rLen = 0; if(node->left != NULL && node->right != NULL){ if(node->left->val== val && node->right->val== val) lLen = len + 1; }else if(node->left == NULL){ if(node->right->val == val) rLen = len + 1; }else{ if(node->left->val== val) lLen = len + 1; } return visit(node->left, lLen) + visit(node->right, rLen); } };
#include <iostream> #include <SFML/Graphics.hpp> #include "fun.h" #include "Pt.h" #include "Ray.h" #include "fps.h" #include <stdio.h> int main() { sf::RenderWindow window(sf::VideoMode(1200, 900), "Ray Casting"); sf::Event ev; Pt point(20, &window); sf::Vertex walls[10][2]; spawnWalls(walls); float size = 400; fps f; window.setMouseCursorVisible(false); window.setFramerateLimit(60); while (window.isOpen()) { while (window.pollEvent(ev)) { if (ev.type == sf::Event::Closed) window.close(); if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Space) { spawnWalls(walls); std::cout << "Walls rearranged.\n"; } if (ev.key.code == sf::Keyboard::Up) { size += 5.0; printf("Ray size inrcreased: %f\n", size); } if (ev.key.code == sf::Keyboard::Down) { if (size > 0) { size -= 5.0; printf("Ray size decreased: %f\n", size); } else printf("Ray size is already 0\n"); } } } window.clear(sf::Color::Black); point.posUpdate(&window); point.drawRay(&window, walls, size); displayWalls(walls, &window); f.drawFps(&window); window.display(); } return 0; }
#ifndef COMMON_HEADER #define COMMON_HEADER #include <stdint.h> #include <time.h> typedef int nrfs; typedef char* nrfsFile; #define MAX_MESSAGE_BLOCK_COUNT 10 /* Max count of block index in a message. */ typedef struct { uint16_t node_id; uint64_t offset; uint64_t size; } file_pos_tuple; struct file_pos_info { uint32_t len; file_pos_tuple tuple[MAX_MESSAGE_BLOCK_COUNT]; }; /* getattr */ struct nrfsfileattr { uint32_t mode; /* 0 - file, 1 - directory */ uint64_t size; uint32_t time; }; /** Definitions. **/ #define MAX_PATH_LENGTH 255 /* Max length of path. */ /** Definitions. **/ #define MAX_FILE_EXTENT_COUNT 20 /* Max extent count in meta of a file. */ #define BLOCK_SIZE (1 * 1024 * 1024) /* Current block size in bytes. */ #define MAX_FILE_NAME_LENGTH 50 /* Max file name length. */ #define MAX_DIRECTORY_COUNT 60 /* Max directory count. */ /** Classes and structures. **/ typedef uint64_t NodeHash; /* Node hash. */ typedef struct { NodeHash hashNode; /* Node hash array of extent. */ uint32_t indexExtentStartBlock; /* Index array of start block in an extent. */ uint32_t countExtentBlock; /* Count array of blocks in an extent. */ } FileMetaTuple; typedef struct /* File meta structure. */ { time_t timeLastModified; /* Last modified time. */ uint64_t count; /* Count of extents. (not required and might have consistency problem with size) */ uint64_t size; /* Size of extents. */ FileMetaTuple tuple[MAX_FILE_EXTENT_COUNT]; } FileMeta; typedef struct { char names[MAX_FILE_NAME_LENGTH]; bool isDirectories; } DirectoryMetaTuple; typedef struct /* Directory meta structure. */ { uint64_t count; /* Count of names. */ DirectoryMetaTuple tuple[MAX_DIRECTORY_COUNT]; } DirectoryMeta; typedef DirectoryMeta nrfsfilelist; static inline void NanosecondSleep(struct timespec *preTime, uint64_t diff) { struct timespec now; uint64_t temp; temp = 0; while (temp < diff) { clock_gettime(CLOCK_MONOTONIC, &now); temp = (now.tv_sec - preTime->tv_sec) * 1000000000 + now.tv_nsec - preTime->tv_nsec; temp = temp / 1000; } } #endif
#include "CaptureImageProvider.h" #include <QImage> #include <QDebug> namespace wpp { namespace qt { CaptureImageProvider::CaptureImageProvider() : QQuickImageProvider(QQuickImageProvider::Image), id(0) { } int CaptureImageProvider::setImage(const QImage& image) { qDebug() << __FUNCTION__ << "param(image):" << image.size(); this->image = image; qDebug() << __FUNCTION__ << "member(image):" << this->image.size(); this->id++; return this->id; } QImage CaptureImageProvider::requestImage(const QString&, QSize*, const QSize& ) { qDebug() << __FUNCTION__ << ":image=" << this->getImage().size() << "==" << this->getImage().width() << "x" << this->getImage().height(); return this->getImage(); } } }
#pragma once #include "MyMainFrame.h" class CTestFrame : public CMyMainFrame { MY_DECLARE_DYNCREATE(CTestFrame) public: CTestFrame(); virtual ~CTestFrame(); };
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <queue> #include <set> using namespace std; struct ListNode{ int val; ListNode* next; ListNode(int x):val(x),next(NULL){} }; void printLL(ListNode* head){ ListNode* temp = head; while(temp!=NULL){ cout<<temp->val<<"->"; temp = temp->next; } } ListNode* addNode(ListNode* head, int val){ if(head==NULL){ head = new ListNode(val); } else{ ListNode* temp = head; while(temp->next!=NULL){ temp = temp->next; } temp->next = new ListNode(val); } return head; } void print(vector<int>&v){ int n = v.size(); for(int i =0;i<n;i++){ cout<<v[i]<<" "; } } void addTwoNumbers(ListNode* A, ListNode* B){ int n1=0,n2=0; vector<int> v1,v2,v; ListNode* t1 = A, *t2 = B; while(t1!=NULL){ v1.push_back(t1->val); t1=t1->next; } while(t2!=NULL){ v2.push_back(t2->val); t2=t2->next; } int l1 = min(v1.size(),v2.size()); int l2 = max(v1.size(),v2.size()); int c = 0,r; for(int i =0;i<l1;i++){ r = c+v1[i]+v2[i]; if(r>=10){ c = 1; v.push_back(r-10); } else{ v.push_back(r); c = 0; } } if(v1.size()>v2.size()){ for(int i =l1;i<l2;i++){ r = v1[i]+c; if(r>=10){ v.push_back(r - 10); c = 1; } else{ v.push_back(r); c = 0; } } } else{ for(int i =l1;i<l2;i++){ r = v2[i]+c; if(r>=10){ v.push_back(r - 10); c = 1; } else{ v.push_back(r); c = 0; } } } if(c==1){ v.push_back(1); } print(v); ListNode* head; if(v.size()){ head = (ListNode*)malloc(sizeof(ListNode)); head->val = v[v.size()-1]; head->next = NULL; } else{ head = NULL; } ListNode* curr = head; for(int i =v.size()-2;i>=0;i--){ ListNode* temp = (ListNode*)malloc(sizeof(ListNode)); temp->val = v[i]; curr->next = temp; curr = temp; } curr->next = NULL; printLL(head); } int main(){ ListNode *head1 = NULL; ListNode *head2 = NULL; ListNode *head; int n1,n2; cin>>n1>>n2; for(int i =0;i<n1;i++){ int val; cin>>val; head1 = addNode(head1,val); } for(int i =0;i<n2;i++){ int val; cin>>val; head2 = addNode(head2,val); } // head = addTwoNumbers(head1,head2); }
#include <bits/stdc++.h> using namespace std; int main(){ map<string, vector<int>, greater<string>> m; m["aa"].push_back(100); m["aa"].push_back(200); m["bb"].push_back(200); for (auto p: m){ cout << p.first << ":" << endl; for (auto i: p.second) cout << i << " "; cout << endl; } /* aa 100 200 */ }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int maxm = 1e6; int f[maxm + 100][5]; int dfs(int r,int k) { if (k == 3) { int x = floor(sqrt(r) + 0.5); if (r == x*x) return 1; else return 0; } if (f[r][k]) return f[r][k]; for (int i = 0;i*i <= r; i++) f[r][k] += dfs(r-i*i,k+1); return f[r][k]; } int main() { int t; scanf("%d",&t);g for (int ca = 1;ca <= t; ca++) { int r; scanf("%d",&r); printf("%d\n",dfs(r,0)); } return 0; }
/* A class that monitors X11 cursor changes and sends the cursor image over the * streaming virtio port. * * \copyright * Copyright 2016-2018 Red Hat Inc. All rights reserved. */ #include "cursor-updater.hpp" #include "error.hpp" #include <spice/stream-device.h> #include <spice/enums.h> #include <cstring> #include <functional> #include <memory> #include <X11/extensions/Xfixes.h> namespace spice { namespace streaming_agent { namespace { void send_cursor(StreamPort &stream_port, unsigned width, unsigned height, int hotspot_x, int hotspot_y, std::function<void(uint32_t *)> fill_cursor) { if (width >= STREAM_MSG_CURSOR_SET_MAX_WIDTH || height >= STREAM_MSG_CURSOR_SET_MAX_HEIGHT) { return; } size_t cursor_size = sizeof(StreamDevHeader) + sizeof(StreamMsgCursorSet) + width * height * sizeof(uint32_t); std::unique_ptr<uint8_t[]> msg(new uint8_t[cursor_size]); StreamDevHeader &dev_hdr(*reinterpret_cast<StreamDevHeader*>(msg.get())); memset(&dev_hdr, 0, sizeof(dev_hdr)); dev_hdr.protocol_version = STREAM_DEVICE_PROTOCOL; dev_hdr.type = STREAM_TYPE_CURSOR_SET; dev_hdr.size = cursor_size - sizeof(StreamDevHeader); StreamMsgCursorSet &cursor_msg(*reinterpret_cast<StreamMsgCursorSet *>(msg.get() + sizeof(StreamDevHeader))); memset(&cursor_msg, 0, sizeof(cursor_msg)); cursor_msg.type = SPICE_CURSOR_TYPE_ALPHA; cursor_msg.width = width; cursor_msg.height = height; cursor_msg.hot_spot_x = hotspot_x; cursor_msg.hot_spot_y = hotspot_y; uint32_t *pixels = reinterpret_cast<uint32_t *>(cursor_msg.data); fill_cursor(pixels); std::lock_guard<std::mutex> guard(stream_port.mutex); stream_port.write(msg.get(), cursor_size); } } // namespace CursorUpdater::CursorUpdater(StreamPort *stream_port) : stream_port(stream_port) { display = XOpenDisplay(nullptr); if (display == nullptr) { throw Error("Failed to open X display"); } int error_base; if (!XFixesQueryExtension(display, &xfixes_event_base, &error_base)) { throw Error("XFixesQueryExtension failed"); } XFixesSelectCursorInput(display, DefaultRootWindow(display), XFixesDisplayCursorNotifyMask); } void CursorUpdater::operator()() { unsigned long last_serial = 0; while (1) { XEvent event; XNextEvent(display, &event); if (event.type != xfixes_event_base + 1) { continue; } XFixesCursorImage *cursor = XFixesGetCursorImage(display); if (!cursor) { continue; } if (cursor->cursor_serial == last_serial) { continue; } last_serial = cursor->cursor_serial; auto fill_cursor = [cursor](uint32_t *pixels) { for (unsigned i = 0; i < cursor->width * cursor->height; ++i) pixels[i] = cursor->pixels[i]; }; send_cursor(*stream_port, cursor->width, cursor->height, cursor->xhot, cursor->yhot, fill_cursor); } } }} // namespace spice::streaming_agent
#include "views/unitviews/unitviewmode.hpp" #include "needs/needssystem.hpp" using namespace ecs; using namespace needs; struct NeedsMode : UnitViewModeInstance<NeedsMode> { static inline string title() { return "Units Roster (Needs)"; } using List_t = std::array<std::string, 3>; static List_t List; static inline const List_t& col_list() { return List; } static inline const string& col_label(const std::string& d) { return d; } static inline void entry(CitizenName* cn, const std::string& l, string& buf) { Ent* e = cn->parent; if (!e->has<Needs>()) { buf = "N/A"; return; } Needs* nai = e->get<Needs>(); int val; if (l == "Food") { val = nai->food; } else if (l == "Sleep") { val = nai->sleep; } else if (l == "Happy") { val = nai->happy; } else { assert(false); exit(0); } buf[5] = '0' + (val % 10); buf[4] = '0' + ((val / 10) % 10); buf[3] = '0' + ((val / 100) % 10); } virtual uint num_cols() const override { return col_list().size(); } virtual void toggle(CitizenName::iterator, uint) override { } }; NeedsMode::List_t NeedsMode::List = {{ "Food", "Sleep", "Happy" }}; NeedsMode needsmode;
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-file-style: "stroustrup" -*- * * Copyright (C) 1995-2005 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "modules/xmlutils/xmlutils.h" #include "modules/util/str.h" #define XML_SPACE 0x01 #define XML_NAMEFIRST 0x02 #define XML_NAME 0x04 #define XML_HEXDIGIT 0x08 #define XML_DECDIGIT 0x10 #define XML_VALID_10 0x20 #define XML_VALID_11 0x40 #define XML_UNRESTRICTED_11 0x80 /* static */ const unsigned char XMLUtils::characters[128] = { 0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0xE1, 0xE1, 0x40, 0x40, 0xE1, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0xE1, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE4, 0xE4, 0xE0, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xE6, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xEE, 0xEE, 0xEE, 0xEE, 0xEE, 0xEE, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE0, 0xE0, 0xE0, 0xE0, 0xE6, 0xE0, 0xEE, 0xEE, 0xEE, 0xEE, 0xEE, 0xEE, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE0, 0xE0, 0xE0, 0xE0, 0x60 }; static const uni_char XMLUtils_namefirst10[] = { 0x00C0, 0x00D6, 0x00D8, 0x00F6, 0x00F8, 0x00FF, 0x0100, 0x0131, 0x0134, 0x013E, 0x0141, 0x0148, 0x014A, 0x017E, 0x0180, 0x01C3, 0x01CD, 0x01F0, 0x01F4, 0x01F5, 0x01FA, 0x0217, 0x0250, 0x02A8, 0x02BB, 0x02C1, 0x0386, 0x0386, 0x0388, 0x038A, 0x038C, 0x038C, 0x038E, 0x03A1, 0x03A3, 0x03CE, 0x03D0, 0x03D6, 0x03DA, 0x03DA, 0x03DC, 0x03DC, 0x03DE, 0x03DE, 0x03E0, 0x03E0, 0x03E2, 0x03F3, 0x0401, 0x040C, 0x040E, 0x044F, 0x0451, 0x045C, 0x045E, 0x0481, 0x0490, 0x04C4, 0x04C7, 0x04C8, 0x04CB, 0x04CC, 0x04D0, 0x04EB, 0x04EE, 0x04F5, 0x04F8, 0x04F9, 0x0531, 0x0556, 0x0559, 0x0559, 0x0561, 0x0586, 0x05D0, 0x05EA, 0x05F0, 0x05F2, 0x0621, 0x063A, 0x0641, 0x064A, 0x0671, 0x06B7, 0x06BA, 0x06BE, 0x06C0, 0x06CE, 0x06D0, 0x06D3, 0x06D5, 0x06D5, 0x06E5, 0x06E6, 0x0905, 0x0939, 0x093D, 0x093D, 0x0958, 0x0961, 0x0985, 0x098C, 0x098F, 0x0990, 0x0993, 0x09A8, 0x09AA, 0x09B0, 0x09B2, 0x09B2, 0x09B6, 0x09B9, 0x09DC, 0x09DD, 0x09DF, 0x09E1, 0x09F0, 0x09F1, 0x0A05, 0x0A0A, 0x0A0F, 0x0A10, 0x0A13, 0x0A28, 0x0A2A, 0x0A30, 0x0A32, 0x0A33, 0x0A35, 0x0A36, 0x0A38, 0x0A39, 0x0A59, 0x0A5C, 0x0A5E, 0x0A5E, 0x0A72, 0x0A74, 0x0A85, 0x0A8B, 0x0A8D, 0x0A8D, 0x0A8F, 0x0A91, 0x0A93, 0x0AA8, 0x0AAA, 0x0AB0, 0x0AB2, 0x0AB3, 0x0AB5, 0x0AB9, 0x0ABD, 0x0ABD, 0x0AE0, 0x0AE0, 0x0B05, 0x0B0C, 0x0B0F, 0x0B10, 0x0B13, 0x0B28, 0x0B2A, 0x0B30, 0x0B32, 0x0B33, 0x0B36, 0x0B39, 0x0B3D, 0x0B3D, 0x0B5C, 0x0B5D, 0x0B5F, 0x0B61, 0x0B85, 0x0B8A, 0x0B8E, 0x0B90, 0x0B92, 0x0B95, 0x0B99, 0x0B9A, 0x0B9C, 0x0B9C, 0x0B9E, 0x0B9F, 0x0BA3, 0x0BA4, 0x0BA8, 0x0BAA, 0x0BAE, 0x0BB5, 0x0BB7, 0x0BB9, 0x0C05, 0x0C0C, 0x0C0E, 0x0C10, 0x0C12, 0x0C28, 0x0C2A, 0x0C33, 0x0C35, 0x0C39, 0x0C60, 0x0C61, 0x0C85, 0x0C8C, 0x0C8E, 0x0C90, 0x0C92, 0x0CA8, 0x0CAA, 0x0CB3, 0x0CB5, 0x0CB9, 0x0CDE, 0x0CDE, 0x0CE0, 0x0CE1, 0x0D05, 0x0D0C, 0x0D0E, 0x0D10, 0x0D12, 0x0D28, 0x0D2A, 0x0D39, 0x0D60, 0x0D61, 0x0E01, 0x0E2E, 0x0E30, 0x0E30, 0x0E32, 0x0E33, 0x0E40, 0x0E45, 0x0E81, 0x0E82, 0x0E84, 0x0E84, 0x0E87, 0x0E88, 0x0E8A, 0x0E8A, 0x0E8D, 0x0E8D, 0x0E94, 0x0E97, 0x0E99, 0x0E9F, 0x0EA1, 0x0EA3, 0x0EA5, 0x0EA5, 0x0EA7, 0x0EA7, 0x0EAA, 0x0EAB, 0x0EAD, 0x0EAE, 0x0EB0, 0x0EB0, 0x0EB2, 0x0EB3, 0x0EBD, 0x0EBD, 0x0EC0, 0x0EC4, 0x0F40, 0x0F47, 0x0F49, 0x0F69, 0x10A0, 0x10C5, 0x10D0, 0x10F6, 0x1100, 0x1100, 0x1102, 0x1103, 0x1105, 0x1107, 0x1109, 0x1109, 0x110B, 0x110C, 0x110E, 0x1112, 0x113C, 0x113C, 0x113E, 0x113E, 0x1140, 0x1140, 0x114C, 0x114C, 0x114E, 0x114E, 0x1150, 0x1150, 0x1154, 0x1155, 0x1159, 0x1159, 0x115F, 0x1161, 0x1163, 0x1163, 0x1165, 0x1165, 0x1167, 0x1167, 0x1169, 0x1169, 0x116D, 0x116E, 0x1172, 0x1173, 0x1175, 0x1175, 0x119E, 0x119E, 0x11A8, 0x11A8, 0x11AB, 0x11AB, 0x11AE, 0x11AF, 0x11B7, 0x11B8, 0x11BA, 0x11BA, 0x11BC, 0x11C2, 0x11EB, 0x11EB, 0x11F0, 0x11F0, 0x11F9, 0x11F9, 0x1E00, 0x1E9B, 0x1EA0, 0x1EF9, 0x1F00, 0x1F15, 0x1F18, 0x1F1D, 0x1F20, 0x1F45, 0x1F48, 0x1F4D, 0x1F50, 0x1F57, 0x1F59, 0x1F59, 0x1F5B, 0x1F5B, 0x1F5D, 0x1F5D, 0x1F5F, 0x1F7D, 0x1F80, 0x1FB4, 0x1FB6, 0x1FBC, 0x1FBE, 0x1FBE, 0x1FC2, 0x1FC4, 0x1FC6, 0x1FCC, 0x1FD0, 0x1FD3, 0x1FD6, 0x1FDB, 0x1FE0, 0x1FEC, 0x1FF2, 0x1FF4, 0x1FF6, 0x1FFC, 0x2126, 0x2126, 0x212A, 0x212B, 0x212E, 0x212E, 0x2180, 0x2182, 0x3007, 0x3007, 0x3021, 0x3029, 0x3041, 0x3094, 0x30A1, 0x30FA, 0x3105, 0x312C, 0x4E00, 0x9FA5, 0xAC00, 0xD7A3 }; static const uni_char XMLUtils_name10[] = { 0x00B7, 0x00B7, 0x02D0, 0x02D1, 0x0300, 0x0345, 0x0360, 0x0361, 0x0387, 0x0387, 0x0483, 0x0486, 0x0591, 0x05A1, 0x05A3, 0x05B9, 0x05BB, 0x05BD, 0x05BF, 0x05BF, 0x05C1, 0x05C2, 0x05C4, 0x05C4, 0x0640, 0x0640, 0x064B, 0x0652, 0x0660, 0x0669, 0x0670, 0x0670, 0x06D6, 0x06DC, 0x06DD, 0x06DF, 0x06E0, 0x06E4, 0x06E7, 0x06E8, 0x06EA, 0x06ED, 0x06F0, 0x06F9, 0x0901, 0x0903, 0x093C, 0x093C, 0x093E, 0x094C, 0x094D, 0x094D, 0x0951, 0x0954, 0x0962, 0x0963, 0x0966, 0x096F, 0x0981, 0x0983, 0x09BC, 0x09BC, 0x09BE, 0x09BE, 0x09BF, 0x09BF, 0x09C0, 0x09C4, 0x09C7, 0x09C8, 0x09CB, 0x09CD, 0x09D7, 0x09D7, 0x09E2, 0x09E3, 0x09E6, 0x09EF, 0x0A02, 0x0A02, 0x0A3C, 0x0A3C, 0x0A3E, 0x0A3E, 0x0A3F, 0x0A3F, 0x0A40, 0x0A42, 0x0A47, 0x0A48, 0x0A4B, 0x0A4D, 0x0A66, 0x0A6F, 0x0A70, 0x0A71, 0x0A81, 0x0A83, 0x0ABC, 0x0ABC, 0x0ABE, 0x0AC5, 0x0AC7, 0x0AC9, 0x0ACB, 0x0ACD, 0x0AE6, 0x0AEF, 0x0B01, 0x0B03, 0x0B3C, 0x0B3C, 0x0B3E, 0x0B43, 0x0B47, 0x0B48, 0x0B4B, 0x0B4D, 0x0B56, 0x0B57, 0x0B66, 0x0B6F, 0x0B82, 0x0B83, 0x0BBE, 0x0BC2, 0x0BC6, 0x0BC8, 0x0BCA, 0x0BCD, 0x0BD7, 0x0BD7, 0x0BE7, 0x0BEF, 0x0C01, 0x0C03, 0x0C3E, 0x0C44, 0x0C46, 0x0C48, 0x0C4A, 0x0C4D, 0x0C55, 0x0C56, 0x0C66, 0x0C6F, 0x0C82, 0x0C83, 0x0CBE, 0x0CC4, 0x0CC6, 0x0CC8, 0x0CCA, 0x0CCD, 0x0CD5, 0x0CD6, 0x0CE6, 0x0CEF, 0x0D02, 0x0D03, 0x0D3E, 0x0D43, 0x0D46, 0x0D48, 0x0D4A, 0x0D4D, 0x0D57, 0x0D57, 0x0D66, 0x0D6F, 0x0E31, 0x0E31, 0x0E34, 0x0E3A, 0x0E46, 0x0E4E, 0x0E50, 0x0E59, 0x0EB1, 0x0EB1, 0x0EB4, 0x0EB9, 0x0EBB, 0x0EBC, 0x0EC6, 0x0EC6, 0x0EC8, 0x0ECD, 0x0ED0, 0x0ED9, 0x0F18, 0x0F19, 0x0F20, 0x0F29, 0x0F35, 0x0F35, 0x0F37, 0x0F37, 0x0F39, 0x0F39, 0x0F3E, 0x0F3E, 0x0F3F, 0x0F3F, 0x0F71, 0x0F84, 0x0F86, 0x0F8B, 0x0F90, 0x0F95, 0x0F97, 0x0F97, 0x0F99, 0x0FAD, 0x0FB1, 0x0FB7, 0x0FB9, 0x0FB9, 0x20D0, 0x20DC, 0x20E1, 0x20E1, 0x3005, 0x3005, 0x302A, 0x302F, 0x3031, 0x3035, 0x3099, 0x3099, 0x309A, 0x309A, 0x309D, 0x309E, 0x30FC, 0x30FE }; static const uni_char XMLUtils_namefirst11[] = { 0x00C0, 0x00D6, 0x00D8, 0x00F6, 0x00F8, 0x02FF, 0x0370, 0x037D, 0x037F, 0x1FFF, 0x200C, 0x200D, 0x2070, 0x218F, 0x2C00, 0x2FEF, 0x3001, 0xD7FF, 0xF900, 0xFDCF, 0xFDF0, 0xFFFD }; static BOOL XMLUtils_FindChar(const uni_char *ranges, unsigned ranges_count, uni_char c) { int low = 0, high = ranges_count - 2, index; while (low <= high) { index = ((low + high) / 2) & ~1u; if (c < ranges[index]) high = index - 2; else if (ranges[index + 1] < c) low = index + 2; else return TRUE; } return FALSE; } /* static */ BOOL XMLUtils::IsSpace(unsigned ch) { return ch < 128 && (characters[ch] & XML_SPACE) != 0; } /* static */ BOOL XMLUtils::IsSpaceExtended(XMLVersion version, unsigned ch) { return IsSpace(ch) || version == XMLVERSION_1_1 && (ch == 0x85 || ch == 0x2028); } static BOOL XMLUtils_IsNameFirst10(unsigned ch) { return XMLUtils_FindChar(XMLUtils_namefirst10, sizeof XMLUtils_namefirst10 / sizeof XMLUtils_namefirst10[0], ch); } static BOOL XMLUtils_IsNameFirst11(unsigned ch) { return XMLUtils_FindChar(XMLUtils_namefirst11, sizeof XMLUtils_namefirst11 / sizeof XMLUtils_namefirst11[0], ch); } /* static */ BOOL XMLUtils::IsNameFirst(XMLVersion version, unsigned ch) { if (ch < 128) return (characters[ch] & XML_NAMEFIRST) != 0; else if (ch < 0x10000) return version == XMLVERSION_1_0 ? XMLUtils_IsNameFirst10(ch) : XMLUtils_IsNameFirst11(ch); else return version != XMLVERSION_1_0 && ch <= 0xeffff; } static BOOL XMLUtils_IsName10(unsigned ch) { return XMLUtils_IsNameFirst10(ch) || XMLUtils_FindChar(XMLUtils_name10, sizeof XMLUtils_name10 / sizeof XMLUtils_name10[0], ch); } static BOOL XMLUtils_IsName11(unsigned ch) { return XMLUtils_IsNameFirst11(ch) || ch == 0x00B7 || ch >= 0x0300 && ch <= 0x036F || ch >= 0x203F && ch <= 0x2040; } /* static */ BOOL XMLUtils::IsName(XMLVersion version, unsigned ch) { if (ch < 128) return (characters[ch] & XML_NAME) != 0; else if (ch < 0x10000) return version == XMLVERSION_1_0 ? XMLUtils_IsName10(ch) : XMLUtils_IsName11(ch); else return FALSE; } /* static */ BOOL XMLUtils::IsDecDigit(unsigned ch) { if (ch < 128) return (characters[ch] & XML_DECDIGIT) != 0; else return FALSE; } /* static */ BOOL XMLUtils::IsHexDigit(unsigned ch) { if (ch < 128) return (characters[ch] & XML_HEXDIGIT) != 0; else return FALSE; } static BOOL XMLUtils_IsCharHigh(unsigned ch) { return !(ch >= 0xd800 && ch <= 0xdfff || ch == 0xfffe || ch == 0xffff || ch > 0x10ffff); } /* static */ BOOL XMLUtils::IsChar10(unsigned ch) { if (ch < 128) return (characters[ch] & XML_VALID_10) != 0; else return XMLUtils_IsCharHigh(ch); } /* static */ BOOL XMLUtils::IsChar11(unsigned ch) { if (ch < 128) return (characters[ch] & XML_VALID_11) != 0; else return XMLUtils_IsCharHigh(ch); } /* static */ BOOL XMLUtils::IsChar(XMLVersion version, unsigned ch) { if (ch < 128) return (characters[ch] & (version == XMLVERSION_1_0 ? XML_VALID_10 : XML_VALID_11)) != 0; else return XMLUtils_IsCharHigh(ch); } /* static */ BOOL XMLUtils::IsRestrictedChar(unsigned ch) { if (ch < 128) return (characters[ch] & XML_UNRESTRICTED_11) == 0; else return ch >= 127 && ch <= 159 && ch != 133; } /* static */ unsigned XMLUtils::GetNextCharacter(const uni_char *&string, unsigned &string_length) { unsigned ch = *string; ++string; --string_length; if (ch >= 0xd800 && ch <= 0xdbff && string_length != 0) { unsigned ch2 = *string; if (ch2 >= 0xdc00 && ch <= 0xdfff) { ++string; --string_length; return ((ch - 0xd800) << 10) + (ch - 0xdc00); } } return ch; } /* static */ BOOL XMLUtils::IsValidName(XMLVersion version, const uni_char *name, unsigned name_length) { if (name_length == ~0u) name_length = uni_strlen(name); if (name_length == 0 || !IsNameFirst(version, XMLUtils::GetNextCharacter(name, name_length))) return FALSE; while (name_length != 0) if (!IsName(version, XMLUtils::GetNextCharacter(name, name_length))) return FALSE; return TRUE; } /* static */ BOOL XMLUtils::IsValidNmToken(XMLVersion version, const uni_char *name, unsigned name_length) { if (name_length == ~0u) name_length = uni_strlen(name); if (name_length == 0) return FALSE; while (name_length != 0) if (!IsName(version, XMLUtils::GetNextCharacter(name, name_length))) return FALSE; return TRUE; } /* static */ BOOL XMLUtils::IsValidQName(XMLVersion version, const uni_char *name, unsigned name_length) { if (name_length == ~0u) name_length = uni_strlen(name); if (!IsValidName(version, name, name_length)) return FALSE; if (XMLUtils::GetNextCharacter(name, name_length) == ':') return FALSE; while (name_length != 0) if (XMLUtils::GetNextCharacter(name, name_length) == ':') { if (name_length == 0) return FALSE; while (name_length != 0) if (XMLUtils::GetNextCharacter(name, name_length) == ':') return FALSE; return TRUE; } return TRUE; } /* static */ BOOL XMLUtils::IsValidNCName(XMLVersion version, const uni_char *name, unsigned name_length) { if (name_length == ~0u) name_length = uni_strlen(name); if (!IsValidName(version, name, name_length)) return FALSE; while (name_length != 0) if (XMLUtils::GetNextCharacter(name, name_length) == ':') return FALSE; return TRUE; } /* static */ BOOL XMLUtils::IsWhitespace(const uni_char *string, unsigned string_length) { if (string_length == ~0u) string_length = uni_strlen(string); while (string_length != 0) if (!IsSpace(XMLUtils::GetNextCharacter(string, string_length))) return FALSE; return TRUE; } /* static */ BOOL XMLUtils::GetLine(XMLVersion version, const uni_char *&data, unsigned &data_length, const uni_char *&line, unsigned &line_length) { if (data_length != 0) { BOOL is_xml_1_1 = version == XMLVERSION_1_1; const uni_char *ptr = data, *ptr_end = data + data_length; line = data; while (ptr != ptr_end) { uni_char ch = *ptr++; if (ch == 0x0a || ch == 0x0d || is_xml_1_1 && (ch == 0x85 || ch == 0x2028)) { line_length = ptr - data - 1; if (ch == 0x0d && ptr != ptr_end && (*ptr == 0x0a || is_xml_1_1 && *ptr == 0x85)) ++ptr; data_length -= ptr - data; data = ptr; return TRUE; } } } return FALSE; } #if defined XML_CONFIGURABLE_DOCTYPES # include "modules/xmlutils/src/xmlparserimpl_internal.h" XmlutilsModule::XmlutilsModule() : OperaModule() #ifdef XML_CONFIGURABLE_DOCTYPES , configureddoctypes(0) #endif // XML_CONFIGURABLE_DOCTYPES { } void XmlutilsModule::InitL(const OperaInitInfo& info) { #if defined XML_CONFIGURABLE_DOCTYPES /* FIXME: OP_NEW_L() doesn't work here, because Head -- base class of XMLConfiguredDoctypes -- overloads operator new. */ configureddoctypes = OP_NEW_L (XMLConfiguredDoctypes, ()); #endif // XML_CONFIGURABLE_DOCTYPES } void XmlutilsModule::Destroy() { #if defined XML_CONFIGURABLE_DOCTYPES /* FIXME: Not using OP_DELETE simply because we didn't use OP_NEW* above. */ OP_DELETE(configureddoctypes); #endif // XML_CONFIGURABLE_DOCTYPES } #endif // XML_CONFIGURABLE_DOCTYPES
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <sstream> #include <string.h> #include <queue> #include <vector> #include <set> #include <map> typedef long long LL; typedef unsigned long long ULL; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; #define N 222222 int n, m, p[N], cyc[N], x, y; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); scanf("%d%d", &n, &m); for (int i =0 ; i < n; i++) { scanf("%d", &p[i]); p[i]--; } int it = 0; for (int i = 0; i < n; i++) if (cyc[i] == 0) { ++it; int x = i; do { cyc[x] = it; x = p[x]; } while (i != x); } for (int i = 0; i < m ; i++) { scanf("%d%d", &x, &y); x--; y--; if (cyc[x] == cyc[y] || cyc[x] == cyc[0] && cyc[y] == cyc[1] || cyc[x] == cyc[1] && cyc[y] == cyc[0]) { puts("Yes"); } else puts("No"); } return 0; }
#include "point.h" #include <algorithm> #include <vector> using namespace std; vector<Cuboid*> CuboidManager; double pointtoplanedistance(const Point3D &o, const Point3D &p, const Point3D &q, const Point3D &r) { Point3D temp = ((r - p) * (q - p)).resize(1); return (o - p) % temp; } inline void pointtolinecheck(double &ret, const Point3D &o, const Point3D &p, const Point3D &q) { if (sgn((p - q) % (o - q)) > 0 && sgn((q - p) % (o - p)) > 0) ret = min(ret, ((p - o) * (q - o)).length() / (p - q).length()); } double realpointtoplanedistance(const Point3D &o, const Point3D &p, const Point3D &q, const Point3D &r) {//fuck this... double ret = min(min((o - p).length(), (o - q).length()), (o - r).length()); pointtolinecheck(ret, o, p, q); pointtolinecheck(ret, o, q, r); pointtolinecheck(ret, o, r, p); Point3D norm = ((q - p) * (r - p)).resize(1), normp = ((q - o) * (r - o)).resize(1), normq = ((r - o) * (p - o)).resize(1), normr = ((p - o) * (q - o)).resize(1); if (sgn(norm%normp) > 0 && sgn(norm%normq) > 0 && sgn(norm%normr) > 0) ret = min(ret, abs(pointtoplanedistance(o, p, q, r))); return ret; } double sqr(const double &x) { return x * x; } int sgn(const double &x) { return x < -eps ? -1 : x > eps; } double dist(const Point3D &A, const Point3D &B) { return sqrt(sqr(A.x - B.x) + sqr(A.y - B.y)); }
#pragma once #include "DijkstraMatrixAlgorithm.h" #include "MyVector.h" class DijkstraListAlgorithm: public DijkstraMatrixAlgorithm { public: DijkstraListAlgorithm(Graph & graph); virtual ~DijkstraListAlgorithm(); protected: virtual void relaxation(int, int) final; virtual void relaxationForNeighborhoods(int) final; };
#include "foo.h" int foo() { return 42; }
// todo 简化之 class RebuildTree { public: TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) { return __reConstructBinaryTree(pre, 0, pre.size() - 1, vin, 0, vin.size() - 1); } TreeNode* __reConstructBinaryTree(vector<int> pre, int p1, int p2, vector<int> vin, int v1, int v2) { TreeNode* root = new TreeNode(pre[p1]); if (p1 == p2) { return root; } int index = v1; while (index <= v2) { if (pre[p1] == vin[index]) break; index++; } if (index == v1) { // 只有右子树 TreeNode* rc = __reConstructBinaryTree(pre, p1 + 1, p2, vin, v1 + 1, v2); root->right = rc; } else if (index == v2) { // 只有左子树 TreeNode* lc = __reConstructBinaryTree(pre, p1 + 1, p2, vin, v1, v2 - 1); root->left = lc; } else { // 左右双全 TreeNode* lc = __reConstructBinaryTree(pre, p1 + 1, p1 + index - v1, vin, v1, index - 1); TreeNode* rc = __reConstructBinaryTree(pre, p1 + index - v1 + 1, p2, vin, index + 1, v2); root->left = lc; root->right = rc; } return root; } void pre_order(TreeNode* root) { if (root == NULL) { return; } cout << root->val << ", "; pre_order(root->left); pre_order(root->right); } void in_order(TreeNode* root) { if (root == NULL) { return; } in_order(root->left); cout << root->val << ", "; in_order(root->right); } void test() { vector<int> pre = { 1, 2, 4, 7, 3, 5, 6, 8 }; vector<int> inOrder = { 4, 7, 2, 1, 5, 3, 8, 6 }; TreeNode* res = reConstructBinaryTree(pre, inOrder); pre_order(res); cout << endl; in_order(res); cout << endl; cout << "=============" << endl; pre.clear(); inOrder.clear(); pre = { 1 }, inOrder = { 1 }; res = reConstructBinaryTree(pre, inOrder); pre_order(res); cout << endl; in_order(res); cout << endl; cout << "=============" << endl; pre.clear(); inOrder.clear(); pre = { 1, 2, 3, 4, 5, 6, 7 }, inOrder = { 7, 6, 5, 4, 3, 2, 1 }; res = reConstructBinaryTree(pre, inOrder); pre_order(res); cout << endl; in_order(res); cout << endl; } };
#include "bst.h" #include <cstring> #include <string> #include <iostream> #include <fstream> #include <cstdlib> using namespace std; void toLower(string & str); int main(int argc, char*argv[]) { //int argc = 3; char*argv[3] = { "a4.exe", "fouly.txt", "frequentWord" }; if (argv[1] == NULL) { cout << "File not found"; return 0; } ifstream fin; fin.open(argv[1], ios::in); bst <string> Bst1; string item; node <string> *temp; //Case InSensitive while (fin >> item) { toLower(item); Bst1.bstInsert(item); } if (Bst1.bstTotCount() == 0) { cout << "File not found"; return 0; } if (strcmp(argv[2],"wordCount")==0) cout << Bst1.bstTotCount() << " words"; else if (strcmp(argv[2], "frequentWord") == 0) cout << "Most frequent word is " << Bst1.bstFreqWord(Bst1.bstGetRoot()); else if (strcmp(argv[2], "distWords") == 0) cout << Bst1.bstDistCount() << " distinct words"; else if (strcmp(argv[2],"printInorder")==0) Bst1.bstTraverseInOrder(Bst1.bstGetRoot()); else if (strcmp(argv[2],"printPreorder")==0) Bst1.bstTraversePreOrder(Bst1.bstGetRoot()); else if (strcmp(argv[2],"printPostorder")==0) Bst1.bstTraversePostOrder(Bst1.bstGetRoot()); else if (strcmp(argv[2],"countWord")==0) { if (argc < 4) cout << "Incorrect number of arguments"; else { string str(argv[3]); toLower(str); temp = (Bst1.bstSearch(Bst1.bstGetRoot(), str)); if (temp == NULL) cout << str << " is repeated 0 times"; else cout << str << " is repeated " << temp->freq << " times"; } } else cout << "Undefined command"; } void toLower(string & str) { for (unsigned int i = 0; i<str.size(); i++) { if (str[i] >= 'A' && str[i] <= 'Z') str[i] -= 'Z' - 'z'; } }
#include "tab.hpp" // no rect button #include "rectbutton.hpp" /* The Scene class contains four tabs, three different buttons, and other * shapes that are needed to be displayed across all tabs (non tab-specific * shapes). * * It manages all the updates and displaying for the programme. */ class Scene { public: Scene(); /* The main redrawAll function that has to be called every loop in * main.cpp */ void redrawAll(sf::RenderWindow &window); /* Takes in different changes to the programme and updates the graphics * accordingly. * Arguments: float x, float y - coordinates of user's click * MANUALCLEAN - 1, if the programme is manual cleaning * REVERT - 1, if the programme is reverting * AUTOCLEAN - 1, if autoclean has been clicked * isAutoActive - 1, if auto cleaning is actually taking place * MODECHANGED - 1, if a new tab has been selected */ void updateAll(float x, float y, int &MANUALCLEAN, int &REVERT, int &AUTOCLEAN, int isAutoActive, int &MODECHANGED); /* Write all the changes to the appropriate config file. This is to be * called before every clean, and after the programme has been closed. */ int writeChanges(void); /* Gets the tab the user is currently seeing. This will be assigned to the * reference passed in as an argument. */ void getMode(TabMode &mode); /* To be called at the beginning of main.cpp to initialise the interface. * Arguments: monitorPath - the absolute path to the directory that is to * be monitored * resPath - the absolute path to the directory that contains * the resources (/res/) */ void loadConfig(std::string monitorPath, std::string resPath); /* The following functions are called to be used in main.cpp */ int getWidth(void); int getHeight(void); sf::Color getBgColour(void); int getWidth2(void); int getHeight2(void); /* These functions are to be called after the corresponding clean/revert * function has stopped running. It updates the interface accordingly. */ void finishManualC(int &MANUALCLEAN); void finishRevert(int &REVERT); void finishAutoC(int &AUTOCLEAN); private: TabMode mode; sf::Font font; int width, height; //of screen int width2, height2; // resized screen for groupings and ignorelist int tabHeight; sf::Color bgColour, lesserBgColour; // don't need an array for this, just check all cases. A bit more tedious, // but it will be clearer Tab manualTab, autoTab, grpTab, ignTab; // for all the "function buttons" RectButton manualButton; RectButton revertButton; RectButton autoButton; // for all the tab names std::vector<sf::Text> tabNameArray; // for the horizontal lines below the tabs sf::RectangleShape tabLineL, tabLineR; // dark line on top sf::RectangleShape upperTabLine; // for ignore/group tabs // starting position for texts in the tab int startTextX, startTextX2, startTextY; int space; // space between each lines /** Private helper functions **/ bool modeChange(float x, float y); };
#pragma once #include <random> class Util { public: static float getRandomFloat(float min, float max){ return ((static_cast <float>(rand())) * (max - min) / (static_cast<float>(RAND_MAX))) + min; } static int getRandomInt(int min, int max){ int r = getRandomFloat(min-1, max+1); if(r < min || r > max) r = getRandomInt(min, max); return r; } };
#include "SpaceShip.h" #include "Bullet.h" SpaceShip::SpaceShip(std::shared_ptr<Model> model, std::shared_ptr<Shader> shader, std::shared_ptr<Texture> texture) : Sprite2D(model, shader, texture) { Init(); } SpaceShip::SpaceShip(std::shared_ptr<Model> model, std::shared_ptr<Shader> shader, std::shared_ptr<Texture> texture, int speed) : Sprite2D(model, shader, texture) { Init(); m_speed = speed; } SpaceShip::SpaceShip(std::shared_ptr<Model> model, std::shared_ptr<Shader> shader, std::shared_ptr<Texture> texture, int speed, int hp) : Sprite2D(model, shader, texture) { SpaceShip(model, shader, texture, speed); m_hp = hp; } SpaceShip::~SpaceShip() { } void SpaceShip::Update(GLfloat deltaTime) { m_shootTime += deltaTime; for (int i = 0; i < m_listBullet.size(); i++) { m_listBullet[i]->Update(deltaTime); if (m_listBullet[i]->GetPosition().y < -45 || m_listBullet[i]->GetPosition().y > Globals::screenHeight || m_listBullet[i]->GetPosition().x < -10 || m_listBullet[i]->GetPosition().x > Globals::screenWidth) { removeBullet(i); } } } std::vector<std::shared_ptr<Bullet>> SpaceShip::getBullet() { return m_listBullet; } void SpaceShip::removeBullet(int index) { if (index >= m_listBullet.size()) { index = m_listBullet.size() - 1; } m_bulletPool.push_back(m_listBullet[index]); m_listBullet.erase(m_listBullet.begin() + index); } void SpaceShip::SetSpeed(int speed) { m_speed = speed; } int SpaceShip::GetSpeed() { return m_speed; } int SpaceShip::GetHp() { return m_hp; } void SpaceShip::AddHp(int hp) { m_hp += hp; } void SpaceShip::SubHp(int hp) { m_hp -= hp; } void SpaceShip::SetHp(int hp) { m_hp = hp; } void SpaceShip::SetShootInterval(int shootInterval) { m_shootInterval = shootInterval; }
#include <iostream> #include <vector> #include <algorithm> #include <string> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int n; std::cin >> n; for (int i = 1; i <= n; ++i) { int a, b; std::cin >> a >> b; std::cout << "Case #" << i << ": " << a + b << '\n'; } return 0; }
#ifndef _TIMER_H #define _TIMER_H #if (ARDUINO >= 100) # include <Arduino.h> #else # include <WProgram.h> #endif static const uint8_t TIMER_PB = 0; static const uint8_t TIMER_IN = 1; struct tcon_s { union { uint32_t val; struct { unsigned _unused:1; unsigned tcs:1; unsigned tsync:1; unsigned _spare:1; unsigned tckps:3; unsigned tgate:1; unsigned _space:3; unsigned twip:1; unsigned twdis:1; unsigned sidl:1; unsigned frz:1; unsigned on:1; unsigned _blank:16; }; }; } __attribute__((packed)); class Timer { public: int _vec; int _irq; int _spl; int _ipl; volatile uint32_t *_pr; volatile uint32_t *_tmr; volatile tcon_s *_tcon; int _ps_size; Timer(); void begin(); void setFrequency(uint32_t f); void start(); void stop(); void attachInterrupt(void (*isr)()); void detatchInterrupt(); void setClockSource(uint8_t src); void setPrescaler(uint16_t ps); void setPeriod(uint32_t per); void reset(); uint32_t getCount(); uint32_t getAndResetCount(); void enableGate(); void disableGate(); }; class Timer1 : public Timer { public: Timer1(); Timer1(int); }; class Timer2 : public Timer { public: Timer2(); Timer2(int); }; class Timer3 : public Timer { public: Timer3(); Timer3(int); }; class Timer4 : public Timer { public: Timer4(); Timer4(int); }; class Timer5 : public Timer { public: Timer5(); Timer5(int); }; #ifdef __PIC32MZ__ class Timer6 : public Timer { public: Timer6(); Timer6(int); }; class Timer7 : public Timer { public: Timer7(); Timer7(int); }; class Timer8 : public Timer { public: Timer8(); Timer8(int); }; class Timer9 : public Timer { public: Timer9(); Timer9(int); }; #endif #endif
// Copyright (c) 2015 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StdObject_gp_Curves_HeaderFile #define _StdObject_gp_Curves_HeaderFile #include <StdObject_gp_Axes.hxx> #include <gp_Lin2d.hxx> #include <gp_Circ2d.hxx> #include <gp_Elips2d.hxx> #include <gp_Hypr2d.hxx> #include <gp_Parab2d.hxx> #include <gp_Circ.hxx> #include <gp_Elips.hxx> #include <gp_Hypr.hxx> #include <gp_Parab.hxx> inline StdObjMgt_ReadData& operator >> (StdObjMgt_ReadData& theReadData, gp_Lin2d& theLin) { gp_Ax2d anAx; theReadData >> anAx; theLin.SetPosition (anAx); return theReadData; } inline StdObjMgt_WriteData& operator << (StdObjMgt_WriteData& theWriteData, const gp_Lin2d& theLin) { const gp_Ax2d& anAx = theLin.Position(); write (theWriteData, anAx); return theWriteData; } inline StdObjMgt_ReadData& operator >> (StdObjMgt_ReadData& theReadData, gp_Circ2d& theCirc) { gp_Ax22d anAx; Standard_Real aRadius; theReadData >> anAx >> aRadius; theCirc.SetAxis (anAx); theCirc.SetRadius (aRadius); return theReadData; } inline StdObjMgt_WriteData& operator << (StdObjMgt_WriteData& theWriteData, const gp_Circ2d& theCirc) { const gp_Ax22d& anAx = theCirc.Position(); Standard_Real aRadius = theCirc.Radius(); theWriteData << anAx << aRadius; return theWriteData; } inline StdObjMgt_ReadData& operator >> (StdObjMgt_ReadData& theReadData, gp_Elips2d& theElips) { gp_Ax22d anAx; Standard_Real aMajorRadius, aMinorRadius; theReadData >> anAx >> aMajorRadius >> aMinorRadius; theElips.SetAxis (anAx); theElips.SetMajorRadius (aMajorRadius); theElips.SetMinorRadius (aMinorRadius); return theReadData; } inline StdObjMgt_WriteData& operator << (StdObjMgt_WriteData& theWriteData, const gp_Elips2d& theElips) { const gp_Ax22d& anAx = theElips.Axis(); Standard_Real aMajorRadius = theElips.MajorRadius(); Standard_Real aMinorRadius = theElips.MinorRadius(); theWriteData << anAx << aMajorRadius << aMinorRadius; return theWriteData; } inline StdObjMgt_ReadData& operator >> (StdObjMgt_ReadData& theReadData, gp_Hypr2d& theHypr) { gp_Ax22d anAx; Standard_Real aMajorRadius, aMinorRadius; theReadData >> anAx >> aMajorRadius >> aMinorRadius; theHypr.SetAxis (anAx); theHypr.SetMajorRadius (aMajorRadius); theHypr.SetMinorRadius (aMinorRadius); return theReadData; } inline StdObjMgt_WriteData& operator << (StdObjMgt_WriteData& theWriteData, const gp_Hypr2d& theHypr) { const gp_Ax22d& anAx = theHypr.Axis(); Standard_Real aMajorRadius = theHypr.MajorRadius(); Standard_Real aMinorRadius = theHypr.MinorRadius(); theWriteData << anAx << aMajorRadius << aMinorRadius; return theWriteData; } inline StdObjMgt_ReadData& operator >> (StdObjMgt_ReadData& theReadData, gp_Parab2d& theParab) { gp_Ax22d anAx; Standard_Real aFocalLength; theReadData >> anAx >> aFocalLength; theParab.SetAxis (anAx); theParab.SetFocal (aFocalLength); return theReadData; } inline StdObjMgt_WriteData& operator << (StdObjMgt_WriteData& theWriteData, const gp_Parab2d& theParab) { const gp_Ax22d& anAx = theParab.Axis(); Standard_Real aFocalLength = theParab.Focal(); theWriteData << anAx << aFocalLength; return theWriteData; } inline StdObjMgt_ReadData& operator >> (StdObjMgt_ReadData& theReadData, gp_Lin& theLin) { gp_Ax1 anAx; theReadData >> anAx; theLin.SetPosition (anAx); return theReadData; } inline StdObjMgt_WriteData& operator << (StdObjMgt_WriteData& theWriteData, const gp_Lin& theLin) { const gp_Ax1& anAx = theLin.Position(); write (theWriteData, anAx); return theWriteData; } inline StdObjMgt_ReadData& operator >> (StdObjMgt_ReadData& theReadData, gp_Circ& theCirc) { gp_Ax2 anAx; Standard_Real aRadius; theReadData >> anAx >> aRadius; theCirc.SetPosition (anAx); theCirc.SetRadius (aRadius); return theReadData; } inline StdObjMgt_WriteData& operator << (StdObjMgt_WriteData& theWriteData, const gp_Circ& theCirc) { const gp_Ax2& anAx = theCirc.Position(); Standard_Real aRadius = theCirc.Radius(); theWriteData << anAx << aRadius; return theWriteData; } inline StdObjMgt_ReadData& operator >> (StdObjMgt_ReadData& theReadData, gp_Elips& theElips) { gp_Ax2 anAx; Standard_Real aMajorRadius, aMinorRadius; theReadData >> anAx >> aMajorRadius >> aMinorRadius; theElips.SetPosition (anAx); theElips.SetMajorRadius (aMajorRadius); theElips.SetMinorRadius (aMinorRadius); return theReadData; } inline StdObjMgt_WriteData& operator << (StdObjMgt_WriteData& theWriteData, const gp_Elips& theElips) { const gp_Ax2& anAx = theElips.Position(); Standard_Real aMajorRadius = theElips.MajorRadius(); Standard_Real aMinorRadius = theElips.MinorRadius(); theWriteData << anAx << aMajorRadius << aMinorRadius; return theWriteData; } inline StdObjMgt_ReadData& operator >> (StdObjMgt_ReadData& theReadData, gp_Hypr& theHypr) { gp_Ax2 anAx; Standard_Real aMajorRadius, aMinorRadius; theReadData >> anAx >> aMajorRadius >> aMinorRadius; theHypr.SetPosition (anAx); theHypr.SetMajorRadius (aMajorRadius); theHypr.SetMinorRadius (aMinorRadius); return theReadData; } inline StdObjMgt_WriteData& operator << (StdObjMgt_WriteData& theWriteData, const gp_Hypr& theHypr) { const gp_Ax2& anAx = theHypr.Position(); Standard_Real aMajorRadius = theHypr.MajorRadius(); Standard_Real aMinorRadius = theHypr.MinorRadius(); theWriteData << anAx << aMajorRadius << aMinorRadius; return theWriteData; } inline StdObjMgt_ReadData& operator >> (StdObjMgt_ReadData& theReadData, gp_Parab& theParab) { gp_Ax2 anAx; Standard_Real aFocalLength; theReadData >> anAx >> aFocalLength; theParab.SetPosition (anAx); theParab.SetFocal (aFocalLength); return theReadData; } inline StdObjMgt_WriteData& operator << (StdObjMgt_WriteData& theWriteData, const gp_Parab& theParab) { const gp_Ax2& anAx = theParab.Position(); Standard_Real aFocalLength = theParab.Focal(); theWriteData << anAx << aFocalLength; return theWriteData; } #endif
/* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ #include "thunk.hh" #include <unistd.h> #include <cstring> #include <iostream> #include <unordered_map> #include <algorithm> #include <numeric> #include <regex> #include "protobufs/util.hh" #include "thunk/ggutils.hh" #include "thunk/factory.hh" #include "thunk/placeholder.hh" #include "thunk/thunk_writer.hh" #include "util/digest.hh" #include "util/system_runner.hh" #include "util/temp_file.hh" using namespace std; using namespace gg; using namespace gg::thunk; using namespace CryptoPP; string thunk::data_placeholder( const string & hash ) { return DATA_PLACEHOLDER_START + hash + DATA_PLACEHOLDER_END; } string data_to_string( const pair<const string, string> & item ) { if ( item.second.length() > 0 ) { return item.first + '=' + item.second; } else { return item.first; } } pair<const string, string> Thunk::string_to_data( const string & str ) { auto eqpos = str.find( '=' ); if ( eqpos == string::npos ) { return make_pair( str, string {} ); } else { return make_pair( str.substr( 0, eqpos ), str.substr( eqpos + 1 ) ); } } void Thunk::throw_if_error() const { if ( outputs_.size() == 0 ) { throw runtime_error( "a thunk needs at least one output" ); } if ( executables_.size() == 0 ) { throw runtime_error( "a thunk needs at least one executable" ); } if ( function_.args().size() == 0 ) { throw runtime_error( "a thunk needs at least one argument (argv0)" ); } } Thunk::Thunk( const Function & function, const vector<DataItem> & data, const vector<DataItem> & executables, const vector<string> & outputs ) : function_( function ), values_(), thunks_(), executables_( executables.cbegin(), executables.cend() ), outputs_( outputs ) { for ( const DataItem & item : data ) { switch ( hash::type( item.first ) ) { case ObjectType::Value: values_.emplace( item ); break; case ObjectType::Thunk: thunks_.emplace( item ); break; } } throw_if_error(); } Thunk::Thunk( Function && function, vector<DataItem> && data, vector<DataItem> && executables, vector<string> && outputs ) : function_( move( function ) ), values_(), thunks_(), executables_(), outputs_( move( outputs ) ) { for ( DataItem & item : data ) { switch ( hash::type( item.first ) ) { case ObjectType::Value: values_.emplace( move( item ) ); break; case ObjectType::Thunk: thunks_.emplace( move( item ) ); break; } } for ( DataItem & item : executables ) { executables_.emplace( move( item ) ) ; } throw_if_error(); } Thunk::Thunk( Function && function, vector<DataItem> && values, vector<DataItem> && thunks, vector<DataItem> && executables, vector<string> && outputs ) : function_( move( function ) ), values_(), thunks_(), executables_(), outputs_( move( outputs ) ) { for ( DataItem & item : values ) { values_.emplace( move( item ) ); } for ( DataItem & item : thunks ) { thunks_.emplace( move( item ) ); } for ( DataItem & item : executables ) { executables_.emplace( move( item ) ) ; } throw_if_error(); } Thunk::Thunk( Function && function, DataList && values, DataList && thunks, DataList && executables, vector<string> && outputs ) : function_( move( function ) ), values_( move( values ) ), thunks_( move( thunks ) ), executables_( move( executables ) ), outputs_( move( outputs ) ) { throw_if_error(); } Thunk::Thunk( const gg::protobuf::Thunk & thunk_proto ) : function_( thunk_proto.function() ), values_(), thunks_(), executables_(), outputs_( thunk_proto.outputs().cbegin(), thunk_proto.outputs().cend() ), timeout_( thunk_proto.timeout() ), localonly_( thunk_proto.localonly() ) { for ( const string & item : thunk_proto.values() ) { values_.emplace( string_to_data( item ) ); } for ( const string & item : thunk_proto.thunks() ) { thunks_.emplace( string_to_data( item ) ); } for ( const string & item : thunk_proto.executables() ) { executables_.emplace( string_to_data( item ) ); } throw_if_error(); } int Thunk::execute() const { if ( thunks_.size() != 0 ) { throw runtime_error( "cannot execute thunk with unresolved dependencies" ); } bool verbose = ( getenv( "GG_VERBOSE" ) != nullptr ); // preparing argv vector<string> args = function_.args(); vector<string> envars { function_.envars() }; auto replace_data_placeholder = []( string & str ) -> void { if ( regex_search( str, DATA_PLACEHOLDER_REGEX ) ) { string new_path = regex_replace( str, DATA_PLACEHOLDER_REGEX, gg::paths::blob( "$1" ).string() ); swap( str, new_path ); } }; /* do we need to replace a hash placeholder with the actual path? */ for ( string & arg : args ) { replace_data_placeholder( arg ); } for ( string & envar : envars ) { replace_data_placeholder( envar ); } const roost::path thunk_path = gg::paths::blob( hash() ); // preparing envp envars.insert( envars.end(), { "__GG_THUNK_PATH__=" + thunk_path.string(), "__GG_DIR__=" + gg::paths::blobs().string(), "__GG_ENABLED__=1", } ); if ( verbose ) { envars.emplace_back( "__GG_VERBOSE__=1" ); } int retval; if ( verbose ) { string exec_string = "+ exec(" + hash() + ") {" + roost::rbasename( function_.args().front() ).string() + "}\n"; cerr << exec_string; } if ( ( retval = ezexec( gg::paths::blob( function_.hash() ).string(), args, envars ) ) < 0 ) { throw runtime_error( "execvpe failed" ); } return retval; } protobuf::RequestItem Thunk::execution_request( const Thunk & thunk ) { protobuf::RequestItem request_item; string base64_thunk; StringSource s( ThunkWriter::serialize( thunk ), true, new Base64Encoder( new StringSink( base64_thunk ), false ) ); request_item.set_data( base64_thunk ); request_item.set_hash( thunk.hash() ); for ( const string & output : thunk.outputs() ) { request_item.add_outputs( output ); } return request_item; } string Thunk::execution_payload( const Thunk & thunk ) { return Thunk::execution_payload( vector<Thunk>{ thunk } ); } string Thunk::execution_payload( const vector<Thunk> & thunks ) { static const bool timelog = ( getenv( "GG_TIMELOG" ) != nullptr ); protobuf::ExecutionRequest request; for ( const Thunk & thunk : thunks ) { *request.add_thunks() = execution_request( thunk ); } request.set_storage_backend( gg::remote::storage_backend_uri() ); request.set_timelog( timelog ); return protoutil::to_json( request ); } protobuf::Thunk Thunk::to_protobuf() const { protobuf::Thunk thunk_proto; *thunk_proto.mutable_function() = function_.to_protobuf(); for ( const auto & h : values_ ) { thunk_proto.add_values( data_to_string( h ) ); } for ( const auto & h : thunks_ ) { thunk_proto.add_thunks( data_to_string( h ) ); } for ( const auto & h : executables_ ) { thunk_proto.add_executables( data_to_string( h ) ); } for ( const string & output : outputs_ ) { thunk_proto.add_outputs( output ); } thunk_proto.set_timeout( timeout_.count() ); thunk_proto.set_localonly( localonly_ ); return thunk_proto; } bool Thunk::operator==( const Thunk & other ) const { return ( function_ == other.function_ ) and ( values_ == other.values_ ) and ( thunks_ == other.thunks_ ) and ( executables_ == other.executables_ ) and ( outputs_ == other.outputs_ ) and ( timeout_ == other.timeout_ ); } void Thunk::set_timeout( const std::chrono::milliseconds & timeout ) { hash_.clear(); timeout_ = timeout; } string Thunk::hash() const { if ( not hash_.initialized() ) { hash_.reset( gg::hash::compute( ThunkWriter::serialize( *this ), ObjectType::Thunk ) ); } return *hash_; } string Thunk::output_hash( const string & tag ) const { return gg::hash::for_output( hash(), tag ); } string Thunk::executable_hash() const { const string combined_hashes = accumulate( executables_.begin(), executables_.end(), string {}, []( const auto & a, const auto & b ) { return a + b.first; } ); return digest::sha256( combined_hashes ); } void Thunk::update_data( const string & original_hash, const vector<ThunkOutput> & outputs ) { hash_.clear(); /* invalidating the cached hash */ bool first_output = true; /* NOTE Okay, to prevent a performance hit here, we say that the first output must never be referenced with its tag */ for ( const auto & output : outputs ) { const string old_hash = ( first_output ) ? original_hash : hash::for_output( original_hash, output.tag ); const string new_hash = ( first_output or hash::type( output.hash ) == ObjectType::Value ) ? output.hash : hash::for_output( output.hash, output.tag ); auto result = thunks_.equal_range( old_hash ); vector<string> old_names; for ( auto it = result.first; it != result.second; ) { old_names.emplace_back( move( it->second ) ); it = thunks_.erase( it ); } for ( const auto & old_name : old_names ) { switch ( hash::type( new_hash ) ) { case ObjectType::Thunk: thunks_.insert( { new_hash, old_name } ); break; case ObjectType::Value: values_.insert( { new_hash, old_name } ); break; } } /* let's update the args/envs as necessary */ const string srcstr = data_placeholder( old_hash ); const string dststr = data_placeholder( new_hash ); auto update_placeholder = []( string & str, const string & src, const string & dst ) { size_t index = 0; while ( true ) { index = str.find( src, index ); if ( index == string::npos ) break; str.replace( index, src.length(), dst ); index += dst.length(); } }; for ( string & arg : function_.args() ) { update_placeholder( arg, srcstr, dststr ); } for ( string & envar : function_.envars() ) { update_placeholder( envar, srcstr, dststr ); } first_output = false; } } unordered_map<string, Permissions> Thunk::get_allowed_files() const { unordered_map<string, Permissions> allowed_files; for ( const DataItem & item : values_ ) { allowed_files[ gg::paths::blob( item.first ).string() ] = { true, false, false }; } for ( const DataItem & item : executables_ ) { allowed_files[ gg::paths::blob( item.first ).string() ] = { true, false, true }; } allowed_files[ gg::paths::blobs().string() ] = { true, false, false }; allowed_files[ gg::paths::blob( hash() ).string() ] = { true, false, false }; for ( const string & output : outputs_ ) { allowed_files[ output ] = { true, true, false }; } return allowed_files; } size_t Thunk::infiles_size( const bool include_executables ) const { size_t total_size = 0; for ( const DataItem & item : values_ ) { total_size += gg::hash::size( item.first ); } if ( include_executables ) { for ( const DataItem & item : executables_ ) { total_size += gg::hash::size( item.first ); } } return total_size; } bool Thunk::matches_filesystem( const DataItem & item ) { const string & hash = item.first; const string & filename = item.second; if ( filename.length() == 0 ) { return false; } if ( not roost::exists( filename ) ) { return false; } if ( gg::hash::size( hash ) != roost::file_size( filename ) ) { return false; } return hash == gg::hash::file( filename, gg::hash::type( hash ) ); }
// Created on: 1993-01-09 // Created by: CKY / Contract Toubro-Larsen ( TCD ) // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IGESGraph_LineFontPredefined_HeaderFile #define _IGESGraph_LineFontPredefined_HeaderFile #include <Standard.hxx> #include <Standard_Integer.hxx> #include <IGESData_IGESEntity.hxx> class IGESGraph_LineFontPredefined; DEFINE_STANDARD_HANDLE(IGESGraph_LineFontPredefined, IGESData_IGESEntity) //! defines IGESLineFontPredefined, Type <406> Form <19> //! in package IGESGraph //! //! Provides the ability to specify a line font pattern //! from a predefined list rather than from //! Directory Entry Field 4 class IGESGraph_LineFontPredefined : public IGESData_IGESEntity { public: Standard_EXPORT IGESGraph_LineFontPredefined(); //! This method is used to set the fields of the class //! LineFontPredefined //! - nbProps : Number of property values (NP = 1) //! - aLineFontPatternCode : Line Font Pattern Code Standard_EXPORT void Init (const Standard_Integer nbProps, const Standard_Integer aLineFontPatternCode); //! returns the number of property values in <me> Standard_EXPORT Standard_Integer NbPropertyValues() const; //! returns the Line Font Pattern Code of <me> Standard_EXPORT Standard_Integer LineFontPatternCode() const; DEFINE_STANDARD_RTTIEXT(IGESGraph_LineFontPredefined,IGESData_IGESEntity) protected: private: Standard_Integer theNbPropertyValues; Standard_Integer theLineFontPatternCode; }; #endif // _IGESGraph_LineFontPredefined_HeaderFile
#include<iostream> using namespace std; typedef enum{dg,fg }L; int main(){ L d = fg; cout<<d; return 0; }
#pragma once #include <vector> #include "AbstractScreen.h" class MinecraftClient; class TilePos; class UIRenderContext; class InputMode; class DirectionId; class MCOEvent; class MojangConnectionStatus; class Button; class GuiElement; class StickDirection; class Font; class TextBox; //Size : 212 class Screen : public AbstractScreen { public: char filler1[4]; //76 int width; //80 int height; //84 MinecraftClient* mc; //88 std::vector<Button*> buttonList; //92 std::vector<TextBox*> textBoxList; //104 char filler2[24]; //104 std::vector<GuiElement*> elementList; //140 char filler3[12]; //152 Font* fontObj; //164 Button* selectedButton; //168 char filler4[28]; //172 mce::MaterialPtr ui_cubemap; //200 public: Screen(); virtual ~Screen(); virtual void _init(MinecraftClient&, int, int); virtual void setSize(int, int); virtual void onSetKeyboardHeight(int); virtual void setAssociatedTilePos(TilePos const&); virtual void lostFocus(); virtual void removed(); virtual void onInternetUpdate(); virtual void tick(); virtual void updateEvents(); virtual void render(UIRenderContext&, int, int, float); virtual void handleInputModeChanged(InputMode); virtual void handleButtonPress(MinecraftClient*, short); virtual void handleButtonRelease(MinecraftClient*, short); virtual void handlePointerLocation(short, short); virtual void handlePointerPressed(bool); virtual void handleDirection(DirectionId, float, float); virtual bool handleBackEvent(bool); virtual void handleTextChar(std::string const&, bool); virtual void setTextboxText(std::string const&); virtual void handleLicenseChanged(); virtual bool renderGameBehind() const; virtual bool closeOnPlayerHurt() const; virtual void render(int, int, float); virtual void init(); virtual void setupPositions(); virtual void checkForPointerEvent(); virtual void controllerEvent(); virtual void renderBackground(int); virtual void renderDirtBackground(); virtual void renderMenuBackground(float); virtual void confirmResult(bool, int); virtual void toGUICoordinate(int&, int&); virtual void feedMCOEvent(MCOEvent); virtual bool supppressedBySubWindow(); virtual void onTextBoxUpdated(int); virtual void onMojangConnectorStatus(MojangConnectionStatus); virtual void handleScrollWheel(float); virtual void handlePointerAction(int, int, bool); virtual void updateTabButtonSelection(); virtual void buttonClicked(Button*); virtual void guiElementClicked(GuiElement*); virtual void pointerPressed(int, int); virtual void pointerReleased(int, int); virtual void controllerDirectionChanged(int, StickDirection); virtual void controllerDirectionHeld(int, StickDirection); void tabNext(); void tabPrev(); void renderProgressBar(float) const; void processControllerDirection(int); void getCursorMoveThrottle(); };
//==================================================================================== // @Title: TEXTBOX //------------------------------------------------------------------------------------ // @Location: /prolix/interface/include/cmpTextbox.cpp // @Author: Kevin Chen // @Rights: Copyright(c) 2011 Visionary Games //==================================================================================== #include "../include/cmpTextbox.h" //==================================================================================== // cmpTextbox //==================================================================================== cmpTextbox::cmpTextbox(cFont rFont, std::string rText, Point rPos, Dimensions rDim, cTextureId rSkinId): font(rFont), text(rText), cmpWindow(rPos, rDim, rSkinId) { LogMgr->Write(VERBOSE, "cmpTextbox::cmpTextbox >>>> Created a textbox of type interface window"); // set top display to 0 currentLine = 0; // create commands scrollDown = new cCommand(SDLK_DOWN, 100); scrollUp = new cCommand(SDLK_UP, 100); // process text Process(text); } void cmpTextbox::Process(std::string text) { // refresh data structures strlines.clear(); lines.clear(); // Format text strlines = LineWrap(font, text, dim.w - 32); // pre-render text line-by-line for (unsigned int i=0; i<strlines.size(); i++) { lines.push_back(Engine->Text->Prerender(font, strlines[i])); } // calculate display range int lineheight = lines[0]->dim.h; for (displayRange = 0; displayRange*lineheight < dim.h-32; displayRange++); displayRange--; // determine if an overlow will occur if ((unsigned int)displayRange >= lines.size()) { overflow = false; displayRange = lines.size(); } else { overflow = true; } } void cmpTextbox::Draw() { // draw window cmpWindow::Draw(); // display text int line = 0; for (int i=currentLine; i<currentLine + displayRange; i++) { int linespacing = line*lines[0]->dim.h; lines[i]->Draw(Point(pos.x + 16, pos.y + 16 + linespacing)); line++; } // draw continuation arrow if necessary if (overflow) { if (currentLine > 0) { frames->DrawFrame(F_L1N1, Point(pos.x + (dim.w - frames->spriteset[F_L1N1].dim.w)/2, pos.y + 8)); } if (currentLine < (int)(lines.size() - displayRange)) { frames->DrawFrame(F_L2N2, Point(pos.x + (dim.w - frames->spriteset[F_L2N2].dim.w)/2, pos.y + dim.h - 35)); } } } void cmpTextbox::ShiftUp() { if (currentLine == 0) { currentLine = 0; } else { currentLine--; } } void cmpTextbox::ShiftDown() { if (currentLine == lines.size() - displayRange) { currentLine = lines.size() - displayRange; } else { currentLine++; } } void cmpTextbox::Move() { if (overflow) { if (scrollDown->Pollable()) ShiftDown(); if (scrollUp->Pollable()) ShiftUp(); } } void cmpTextbox::Update() { Draw(); Move(); } cmpTextbox::~cmpTextbox() { // remove all lines of text from text stack for (unsigned int i=0;i<strlines.size();i++) { AssetMgr->Remove<Texture>(font.id + font.color.Format() + strlines[i]); } LogMgr->Write(VERBOSE, "cmpTextbox::~cmpTextbox >>>> Deleted a textbox window"); }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef TWEEN_FACTORY_H_ #define TWEEN_FACTORY_H_ #include "ITargetResolver.h" #include <core/Object.h> namespace Tween { class ITween; /** * Interfejs fabryki tweenów. Definicję podajemy (raczej) JSONem, a tatget objecty * są resolvowane w metodzie resolve i to ona definiuje jak podajemy referencję * do targetów. */ struct ITweenFactory : public ITargetResolver, public Core::Object { virtual ~ITweenFactory () {} virtual Tween::ITween *create () = 0; }; } // nam #endif /* TWEENPARSER_H_ */
// Created on: 2002-10-29 // Created by: Michael SAZONOV // Copyright (c) 2002-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BinMDF_ADriverTable_HeaderFile #define _BinMDF_ADriverTable_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <BinMDF_TypeADriverMap.hxx> #include <BinMDF_TypeIdMap.hxx> #include <Standard_Transient.hxx> #include <Standard_Integer.hxx> #include <TColStd_IndexedMapOfTransient.hxx> #include <TColStd_SequenceOfAsciiString.hxx> class BinMDF_ADriver; class BinMDF_ADriverTable; DEFINE_STANDARD_HANDLE(BinMDF_ADriverTable, Standard_Transient) //! A driver table is an object building links between //! object types and object drivers. In the //! translation process, a driver table is asked to //! give a translation driver for each current object //! to be translated. class BinMDF_ADriverTable : public Standard_Transient { public: //! Constructor Standard_EXPORT BinMDF_ADriverTable(); //! Adds a translation driver <theDriver>. Standard_EXPORT void AddDriver (const Handle(BinMDF_ADriver)& theDriver); //! Adds a translation driver for the derived attribute. The base driver must be already added. //! @param theInstance is newly created attribute, detached from any label Standard_EXPORT void AddDerivedDriver (const Handle(TDF_Attribute)& theInstance); //! Adds a translation driver for the derived attribute. The base driver must be already added. //! @param theDerivedType is registered attribute type using IMPLEMENT_DERIVED_ATTRIBUTE macro Standard_EXPORT const Handle(Standard_Type)& AddDerivedDriver (Standard_CString theDerivedType); //! Assigns the IDs to the drivers of the given Types. //! It uses indices in the map as IDs. //! Useful in storage procedure. Standard_EXPORT void AssignIds (const TColStd_IndexedMapOfTransient& theTypes); //! Assigns the IDs to the drivers of the given Type Names; //! It uses indices in the sequence as IDs. //! Useful in retrieval procedure. Standard_EXPORT void AssignIds (const TColStd_SequenceOfAsciiString& theTypeNames); //! Gets a driver <theDriver> according to <theType>. //! Returns Type ID if the driver was assigned an ID; 0 otherwise. Standard_Integer GetDriver (const Handle(Standard_Type)& theType, Handle(BinMDF_ADriver)& theDriver); //! Returns a driver according to <theTypeId>. //! Returns null handle if a driver is not found Handle(BinMDF_ADriver) GetDriver (const Standard_Integer theTypeId); DEFINE_STANDARD_RTTIEXT(BinMDF_ADriverTable,Standard_Transient) protected: private: //! Assigns the ID to the driver of the Type void AssignId (const Handle(Standard_Type)& theType, const Standard_Integer theId); BinMDF_TypeADriverMap myMap; BinMDF_TypeIdMap myMapId; }; #include <BinMDF_ADriverTable.lxx> #endif // _BinMDF_ADriverTable_HeaderFile
/***************************************************************** * Copyright (C) 2017-2018 Robert Valler - All rights reserved. * * This file is part of the project: DevPlatformAppCMake. * * This project can not be copied and/or distributed * without the express permission of the copyright holder *****************************************************************/ #ifndef IMAINWND_H #define IMAINWND_H #include "ObjectParameters.h" enum listDataReturnVal { ok, error, typeNotFound, indexOutOfRange, endOfList }; enum ItemSlotAction { AddGraphicsItem=1, RemoveGraphicsItem }; // todo: remove. class QGraphicsItem; class IMainWnd { public: virtual ~IMainWnd(){} virtual void mainWndRegister(QGraphicsItem*)=0; virtual void mainWndDeRegister(QGraphicsItem*)=0; virtual int mainWndGetMousePosX()=0; virtual int mainWndGetMousePosY()=0; virtual bool mainWndIsNewMouseEvent()=0; virtual void mainWndPositionUpdate(QGraphicsItem*, float, float, float)=0; virtual unsigned int mainWndGetLayoutContainerData(ObjectParameters&, int, int)=0; }; #endif // IMAINWND_H
#ifndef WEZEL_H #define WEZEL_H #include <iostream> #include <string> #include <cstdlib> template <typename T> class MyList; template <typename T> class MyNode{ private: T element; // zawartosc elementu MyNode<T>* next; // wskaznik na nastepny element friend class MyList<T>; // lista zaprzyjaznionych klas public: T getElement() {return element;} // zwraca element MyNode<T>* getNext() {return next;} // zwraca next void setElement(T newE) {element=newE;} // ustala element void setNext(MyNode<T> newN) {next=newN;} // ustala next }; #endif // WEZEL_H
#include <cppunit/extensions/HelperMacros.h> #include <Poco/Exception.h> #include <Poco/NamedMutex.h> #include <Poco/Process.h> #include "cppunit/BetterAssert.h" #include "util/SingleInstanceChecker.h" using namespace std; using namespace Poco; namespace BeeeOn { class SingleInstanceCheckerTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SingleInstanceCheckerTest); CPPUNIT_TEST(testCheckPass); CPPUNIT_TEST(testFailUnlocksIfSuccessful); CPPUNIT_TEST(testFailWouldFailAndNotUnlock); CPPUNIT_TEST(testIgnoreDoesNotUnlock); CPPUNIT_TEST(testRecoverAutomaticallyUnlocks); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void testCheckPass(); void testFailUnlocksIfSuccessful(); void testFailWouldFailAndNotUnlock(); void testIgnoreDoesNotUnlock(); void testRecoverAutomaticallyUnlocks(); private: string name() const; }; CPPUNIT_TEST_SUITE_REGISTRATION(SingleInstanceCheckerTest); string SingleInstanceCheckerTest::name() const { return to_string(Process::id()); } void SingleInstanceCheckerTest::setUp() { NamedMutex lock(name()); CPPUNIT_ASSERT(lock.tryLock()); lock.unlock(); } /** * @brief Test the very basic scenario. We pass and after * that, the lock is still held. */ void SingleInstanceCheckerTest::testCheckPass() { SingleInstanceChecker checker; checker.setName(name()); checker.setMode("fail"); CPPUNIT_ASSERT_NO_THROW(checker.check()); NamedMutex lock(name()); CPPUNIT_ASSERT(!lock.tryLock()); } /** * @brief Test we can lock after SingleInstanceChecker is destroyed. */ void SingleInstanceCheckerTest::testFailUnlocksIfSuccessful() { NamedMutex lock(name()); { SingleInstanceChecker checker; checker.setName(name()); checker.setMode("fail"); CPPUNIT_ASSERT_NO_THROW(checker.check()); CPPUNIT_ASSERT(!lock.tryLock()); } CPPUNIT_ASSERT(lock.tryLock()); lock.unlock(); } /** * @brief When the checker fails in fail mode, it does not unlock. */ void SingleInstanceCheckerTest::testFailWouldFailAndNotUnlock() { NamedMutex lock(name()); { CPPUNIT_ASSERT(lock.tryLock()); SingleInstanceChecker checker; checker.setName(name()); checker.setMode("fail"); CPPUNIT_ASSERT_THROW(checker.check(), IllegalStateException); } CPPUNIT_ASSERT(!lock.tryLock()); lock.unlock(); } /** * @brief Test that SingleInstanceChecker in ignore mode * does not unlock when it is destroyed. */ void SingleInstanceCheckerTest::testIgnoreDoesNotUnlock() { NamedMutex lock(name()); { CPPUNIT_ASSERT(lock.tryLock()); SingleInstanceChecker checker; checker.setName(name()); checker.setMode("ignore"); CPPUNIT_ASSERT_NO_THROW(checker.check()); CPPUNIT_ASSERT(!lock.tryLock()); // still locked } // no unlock expected CPPUNIT_ASSERT(!lock.tryLock()); lock.unlock(); } /** * @brief Test that SingleInstanceChecker in recover mode does * unlock when it is destroyed. */ void SingleInstanceCheckerTest::testRecoverAutomaticallyUnlocks() { NamedMutex lock(name()); { CPPUNIT_ASSERT(lock.tryLock()); SingleInstanceChecker checker; checker.setName(name()); checker.setMode("recover"); CPPUNIT_ASSERT_NO_THROW(checker.check()); CPPUNIT_ASSERT(!lock.tryLock()); // locked } // unlock would occur CPPUNIT_ASSERT(lock.tryLock()); lock.unlock(); } }
#include "AncillaryRecords/AncillaryRecord.h" #include "AncillaryRecords/LongIdRecord.h" #include "PrimaryRecord.h" #include <sstream> #include "StreamUtilities.h" using namespace OpenFlight; using namespace std; //------------------------------------------------------------------------- //--- PrimaryRecord //------------------------------------------------------------------------- PrimaryRecord::PrimaryRecord(PrimaryRecord* ipParent) : Record(), mpParent(ipParent), mpLongId(nullptr), mUseCount(1) {} //------------------------------------------------------------------------- PrimaryRecord::~PrimaryRecord() { // delete all ancillary for(size_t i = 0; i < mAncillaryRecords.size(); ++i) { delete mAncillaryRecords[i]; } mAncillaryRecords.clear(); // delete all childs PrimaryRecord *c = nullptr; for(size_t i = 0; i < mChilds.size(); ++i) { c = mChilds[i]; if(c->decrementUseCount() == 1) { delete c; } } mChilds.clear(); } //------------------------------------------------------------------------- void PrimaryRecord::addAncillaryRecord(AncillaryRecord* ipAncillary) { mAncillaryRecords.push_back(ipAncillary); handleAddedAncillaryRecord(ipAncillary); } //------------------------------------------------------------------------- void PrimaryRecord::addChild(PrimaryRecord* iChild) { if (iChild != nullptr) { mChilds.push_back(iChild); } } //------------------------------------------------------------------------- // Arg! this should be recursive // int PrimaryRecord::decrementUseCount() { int r = mUseCount; incrementUseCount(this, -1); return r; } //------------------------------------------------------------------------- AncillaryRecord* PrimaryRecord::getAncillaryRecord(int iIndex) const { return mAncillaryRecords.at(iIndex); } //------------------------------------------------------------------------- PrimaryRecord* PrimaryRecord::getChild(int iIndex) const { return mChilds.at(iIndex); } //------------------------------------------------------------------------- LongIdRecord* PrimaryRecord::getLongIdRecord() const { return mpLongId; } //------------------------------------------------------------------------- int PrimaryRecord::getNumberOfAncillaryRecords() const { return (int)mAncillaryRecords.size(); } //------------------------------------------------------------------------- int PrimaryRecord::getNumberOfChilds() const { return (int)mChilds.size(); } //------------------------------------------------------------------------- PrimaryRecord* PrimaryRecord::getParent() const { return mpParent; } //------------------------------------------------------------------------- int PrimaryRecord::getUseCount() const {return mUseCount; } //------------------------------------------------------------------------- void PrimaryRecord::handleAddedAncillaryRecord(AncillaryRecord* ipAncillary) { switch (ipAncillary->getOpCode()) { case ocLongId: mpLongId = (LongIdRecord*)ipAncillary; break; default: break; } } //------------------------------------------------------------------------- bool PrimaryRecord::hasLongIdRecord() const { return mpLongId != nullptr; } //------------------------------------------------------------------------- bool PrimaryRecord::isExternalReference() const { return getParent() != nullptr && getParent()->getOpCode() == ocExternalReference; } //------------------------------------------------------------------------- void PrimaryRecord::incrementUseCount() { incrementUseCount(this, 1); } //------------------------------------------------------------------------- void PrimaryRecord::incrementUseCount(PrimaryRecord* ipR, int iInc) { ipR->mUseCount += iInc; for (int i = 0; i < ipR->getNumberOfChilds(); ++i) { incrementUseCount( ipR->mChilds[i], iInc ); } }
// Created on: 1992-04-03 // Created by: Laurent BUCHARD // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IntRes2d_Transition_HeaderFile #define _IntRes2d_Transition_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Boolean.hxx> #include <IntRes2d_Position.hxx> #include <IntRes2d_TypeTrans.hxx> #include <IntRes2d_Situation.hxx> //! Definition of the type of transition near an //! intersection point between two curves. The transition //! is either a "true transition", which means that one of //! the curves goes inside or outside the area defined by //! the other curve near the intersection, or a "touch //! transition" which means that the first curve does not //! cross the other one, or an "undecided" transition, //! which means that the curves are superposed. class IntRes2d_Transition { public: DEFINE_STANDARD_ALLOC //! Empty constructor. Standard_EXPORT IntRes2d_Transition(); //! Creates an IN or OUT transition. IntRes2d_Transition(const Standard_Boolean Tangent, const IntRes2d_Position Pos, const IntRes2d_TypeTrans Type); //! Creates a TOUCH transition. IntRes2d_Transition(const Standard_Boolean Tangent, const IntRes2d_Position Pos, const IntRes2d_Situation Situ, const Standard_Boolean Oppos); //! Creates an UNDECIDED transition. IntRes2d_Transition(const IntRes2d_Position Pos); //! Sets the values of an IN or OUT transition. void SetValue (const Standard_Boolean Tangent, const IntRes2d_Position Pos, const IntRes2d_TypeTrans Type); //! Sets the values of a TOUCH transition. void SetValue (const Standard_Boolean Tangent, const IntRes2d_Position Pos, const IntRes2d_Situation Situ, const Standard_Boolean Oppos); //! Sets the values of an UNDECIDED transition. void SetValue (const IntRes2d_Position Pos); //! Sets the value of the position. void SetPosition (const IntRes2d_Position Pos); //! Indicates if the intersection is at the beginning //! (IntRes2d_Head), at the end (IntRes2d_End), or in //! the middle (IntRes2d_Middle) of the curve. IntRes2d_Position PositionOnCurve() const; //! Returns the type of transition at the intersection. //! It may be IN or OUT or TOUCH, or UNDECIDED if the //! two first derivatives are not enough to give //! the tangent to one of the two curves. IntRes2d_TypeTrans TransitionType() const; //! Returns TRUE when the 2 curves are tangent at the //! intersection point. //! Theexception DomainError is raised if the type of //! transition is UNDECIDED. Standard_Boolean IsTangent() const; //! returns a significant value if TransitionType returns //! TOUCH. In this case, the function returns : //! INSIDE when the curve remains inside the other one, //! OUTSIDE when it remains outside the other one, //! UNKNOWN when the calculus, based on the second derivatives //! cannot give the result. //! If TransitionType returns IN or OUT or UNDECIDED, the //! exception DomainError is raised. IntRes2d_Situation Situation() const; //! returns a significant value if TransitionType //! returns TOUCH. In this case, the function returns //! true when the 2 curves locally define two //! different parts of the space. If TransitionType //! returns IN or OUT or UNDECIDED, the exception //! DomainError is raised. Standard_Boolean IsOpposite() const; protected: private: Standard_Boolean tangent; IntRes2d_Position posit; IntRes2d_TypeTrans typetra; IntRes2d_Situation situat; Standard_Boolean oppos; }; #include <IntRes2d_Transition.lxx> #endif // _IntRes2d_Transition_HeaderFile
#include <iostream> #include <vector> using namespace std; int findHigher(int now, std::vector<int> vec, int gap) { int max = 0; for(int i = 0; i < vec.size(); i++) { if((now < vec[i]) && ((now + gap) >= vec[i])) { if(vec[i] > max) { max = vec[i]; } } } return max; } int main() { int boardNum = 0; int jumpTimes = 0; int hignDiff = 0; int temp = 0; int nowHeight = 0; int nextHeight = 0; std::vector<int> vecHeight; // 读取数据 cin>>boardNum>>jumpTimes>>hignDiff; for(int i = 0; i < boardNum; i++) { cin>>temp; vecHeight.push_back(temp); } for(int j = 0; j < jumpTimes; j++) { nextHeight = findHigher(nowHeight, vecHeight, hignDiff); // 跳 nowHeight += (nextHeight - nowHeight) * 2; } cout<<nowHeight<<endl; // cout<<boardNum<<jumpTimes<<hignDiff<<endl; // for(int i = 0; i < boardNum; i++) { // cout<<vecHeight[i]<<" "; // } // cout<<endl; return 0; }
#ifndef Stash_h #define Stash_h #include "EtherCard.h" /** This structure describes the structure of memory used within the ENC28J60 network interface. */ typedef struct { uint8_t count; ///< Number of allocated pages uint8_t first; ///< First allocated page uint8_t last; ///< Last allocated page } StashHeader; /** This class provides access to the memory within the ENC28J60 network interface. */ class Stash : public /*Stream*/ Print, private StashHeader { uint8_t curr; //!< Current page uint8_t offs; //!< Current offset in page typedef struct { union { uint8_t bytes[64]; uint16_t words[32]; struct { StashHeader head; // StashHeader is only stored in first block uint8_t filler[59]; uint8_t tail; // only meaningful if bnum==last; number of bytes in last block uint8_t next; // pointer to next block }; }; uint8_t bnum; } Block; static uint8_t allocBlock (); static void freeBlock (uint8_t block); static uint8_t fetchByte (uint8_t blk, uint8_t off); static Block bufs[2]; static uint8_t map[SCRATCH_MAP_SIZE]; public: static void initMap (uint8_t last=SCRATCH_PAGE_NUM); static void load (uint8_t idx, uint8_t blk); static uint8_t freeCount (); Stash () : curr (0) { first = 0; } Stash (uint8_t fd) { open(fd); } uint8_t create (); uint8_t open (uint8_t blk); void save (); void release (); void put (char c); char get (); uint16_t size (); virtual WRITE_RESULT write(uint8_t b) { put(b); WRITE_RETURN } // virtual int available() { // if (curr != last) // return 1; // load(1, last); // return offs < bufs[1].tail; // } // virtual int read() { // return available() ? get() : -1; // } // virtual int peek() { // return available() ? bufs[1].bytes[offs] : -1; // } // virtual void flush() { // curr = last; // offs = 63; // } static void prepare (const char* fmt); static void prepare (const uint8_t* fmt, byte length); static uint16_t length (); static void extract (uint16_t offset, uint16_t count, void* buf); static void cleanup (); friend void dumpBlock (const char* msg, uint8_t idx); // optional friend void dumpStash (const char* msg, void* ptr); // optional }; #endif
// Delwin Rosa // CSCI 238 // Program 6 - Pets // Date: 04/25/2020 // Program Assignment 6 - Polymorphic Pets Program P3 /* Add a virtual method called eat to the base class Pet this method should say "" in the base class of Pet then in dog class it should say "petname eats dog food" Add a new class Cat that inherits from Pet it should override the speak method to say "petname says 'Meow!'" it should override the eat method and say "petname eats cat food" it should override the sit method and say "petname sits proudly" add a new class Poodle that inherits from Dog it should override the sit virtual method and say "petname sits precisely" change the main program to do the following NO PROMPTS from standard input (cin) read an integer that represents the number of pets for each pet read in its type which will be a string - "pet", "dog", “poodle” or "cat" followed by the pet's name - string with no spaces create an array of pointers, maximum 100, to Pet objects for each pet that you read in once you've read in each pet and created a pet object and stored address in your array, read in a list of integers, one per line, and for each integer call the corresponding pet's speak, eat and sit methods stop when user enters a number that is invalid (less than 1 or greater than number of pets) don't forget to destroy each of your dynamically created pet objects before you exit the Program SAMPLE INPUT 4 dog fred cat fretta poodle pretty dog fido 2 1 3 4 0 SAMPLE OUTPUT fretta says 'Meow!' fretta eats cat food fretta sits proudly fred says 'Bark!' fred eats dog food fred sits boldly pretty says ‘Bark!’ pretty eats dog food pretty sits precisely fido says 'Bark!' fido eats dog food fido sits boldly submit pets.cpp to codepost complete form - https://form.jotform.com/200302477347046 */ #include <iostream> #include <string> using namespace std; class Pet { private: string petName; public: Pet(const string& petName) : petName(petName) {} virtual string name() const { return petName; } virtual string speak() const { return ""; } virtual string sit() const { return ""; } virtual string eat() const { return ""; } virtual ~Pet() {} }; class Dog : public Pet { private: string name; public: Dog(const string& petName) : Pet(petName) {} // New virtual function in the Dog class: string sit() const { return Pet::name() + " sits boldly"; } string eat() const { return Pet::name() + " eats dog food"; } string speak() const { // Override return Pet::name() + " says 'Bark!'"; } ~Dog() {} }; class Cat : public Pet { private: string name; public: Cat(const string& petName) : Pet(petName) {} // New virtual function in the Cat class: string sit() const { return Pet::name() + " sits proudly"; } string eat() const { return Pet::name() + " eats cat food"; } string speak() const { // Override return Pet::name() + " says 'Meow!'"; } ~Cat() {} }; class Poodle : public Pet { private: string name; public: Poodle(const string& petName) : Pet(petName) {} // New virtual function in the Poodle class: string sit() const { return Pet::name() + " sits precisely"; } string eat() const { return Pet::name() + " eats dog food"; } string speak() const { // Override return Pet::name() + " says 'Bark!'"; } ~Poodle() {} }; // here's the logic that will solve the program assignment main() #define MAXPETS 100 int main(int argc, char** argv) { // declare variables for number of pets, pet number selected name of pet and type of pet int numOfPets; int petNum; string petName; string petType; // also declare an array of pointers to class Pet - make it able to hold MAXPETS Pet* p[MAXPETS] = {}; // read in number of pets from cin (standard input) // NO PROMPTS! cin >> numOfPets; // loop to input each pet type and pet name for (int i = 0; i < numOfPets; ++i) { //inside loop create the appropriate type of pet based upon the pet type that you read in - this can be done with 4 if statements cin >> petType >> petName; if (petType == "pet") { p[i] = new Pet(petName); } else if (petType == "dog") { p[i] = new Dog(petName); } else if (petType == "cat") { p[i] = new Cat(petName); } else if (petType == "poodle") { p[i] = new Poodle(petName); } } // input from cin the number that represents which pet the user wants to access // NO PROMPTS! cin >> petNum; // loop until this number is invalid while (petNum > 0 && petNum <= numOfPets) { //inside of loop call the speak, eat, and sit methods of the pet and output what each one returns cout << p[petNum - 1]->speak() << endl; cout << p[petNum - 1]->eat() << endl; cout << p[petNum - 1]->sit() << endl; //read the next number at the end of the loop cin >> petNum; } // google how to destroy dynamically allocated objects in C++ // you will need a loop to go thru the pet array and destroy each one for (int i = 0; i < numOfPets; ++i) { delete p[i]; } return 0; }
/*SOLUTION*/ #include <bits/stdc++.h> using namespace std; bool arr[1000010]; long long i,j,k,a,b,arr1[1000010],m,x; void prime(long long b){ m=0; for(i=2;i<=sqrt(b);i++){ if(!arr[i]) for(j=i+i;j<=b;j=j+i){ arr[j]=1; } } for(k=2;k<=b;k++){ if(!arr[k]) if(k+b-k==b && arr[k]==0 && arr[b-k]==0){ printf("%lld = %lld + %lld\n",b,k,b-k); return ; } } } int main() { while(scanf("%lld",&a)!=EOF){ if(a==0) break; prime(a); } return 0; }
// // Created by abel_ on 01-07-2022. // #include <bits/stdc++.h> #include <string.h> using namespace std; int main(){ // write a code to extract integers 012 and 045 from string '012,045' string s = "122,145"; int n = s.length(); string pwl = s.substr(0, 3); string pwr = s.substr(4, 3); cout << pwl << endl; cout << pwr << endl; // convert pwl to integer int pwl_int = stoi(pwl); int pwr_int = stoi(pwr); cout << pwl_int << endl; cout << pwr_int << endl; return 0; }
#include<iostream> #include<stdlib.h> using namespace std; int main(){ int t; int max; int l,r; cin>>l>>r; max=-1; for(int j=l;j<=r;j++){ for(int k=l;k<=r;k++){ if(max<(j^k)) max=j^k; } } cout<<max<<"\n"; return 0; }
#ifndef _POPULATION_H_ #define _POPULATION_H_ #include <map> #include <vector> #include <random> #include <algorithm> #include "NanoTimer.h" #include "Individual.h" #include "Pool.h" using namespace std; class Population{ private: // unsigned int n_inds; vector<Individual> inds; // Notar que el pool es de la simulation por ahora Pool *pool; // Notar que el profile es de la simulation por ahora Profile *profile; public: Population(); Population(unsigned int _n_inds, Profile *_profile, Pool *_pool, mt19937 &generator); // Population(const Population &original); // Population& operator=(const Population& original); // virtual Population *clone(); virtual ~Population(); unsigned int size(); void increase(unsigned int num, mt19937 &generator); void decrease(unsigned int num, mt19937 &generator); void add(Population *pop, unsigned int num, mt19937 &generator); void add(Individual &individual); vector<Individual> &getIndividuals(); Individual &get(unsigned int pos); Pool *getPool(); }; #endif
#include <Eigen/Dense> #include <Eigen/Eigenvalues> #include <map> #include <list> using Eigen::MatrixXd; using Eigen::VectorXd; class TICAEstimator { public: double dt; int lag; int nDescriptors; int nReplicas; std::map<int, std::list<VectorXd> > rData; VectorXd rsum; int nsum; MatrixXd rcross; MatrixXd rcross0; MatrixXd c00; MatrixXd c0t; MatrixXd c0tc; MatrixXd transform; MatrixXd w; MatrixXd v; int ncross; int ncross0; TICAEstimator(double dt_, int lag_, int nDescriptors_, int nReplicas_){ dt=dt_; lag=lag_; nDescriptors=nDescriptors_; nReplicas=nReplicas_; rsum=VectorXd::Zero(nDescriptors); nsum=0; rcross=MatrixXd::Zero(nDescriptors, nDescriptors); ncross=0; c00=MatrixXd::Zero(nDescriptors, nDescriptors); c0t=MatrixXd::Zero(nDescriptors, nDescriptors); c0tc=MatrixXd::Zero(nDescriptors, nDescriptors); }; void appendData(int index, VectorXd &data){ rData[index].push_back(data); rsum+=data; nsum+=1; rcross0+=data*data.transpose(); ncross0+=1; if(rData[index].size()>lag) { rcross+=rData[index].front()*rData[index].back().transpose(); rcross+=rData[index].back()*rData[index].front().transpose(); ncross+=2; } while(rData[index].size()>=lag) { rData[index].pop_front(); } }; void update(){ double th=1e-12; VectorXd mu=rsum/nsum; //form c00 c00=rcross0/ncross0; c00-=mu*mu.transpose(); //diagonalize Eigen::SelfAdjointEigenSolver<MatrixXd> solver0(c00); VectorXd scale=VectorXd::Zero(nDescriptors); //build the whitening matrix for(int i=0; i<nDescriptors; i++) { if(solver0.eigenvalues()[i]>th) { scale(i)=1/sqrt(solver0.eigenvalues()[i]); } else{ scale(i)=1; } } transform=scale.asDiagonal()*solver0.eigenvectors(); //transform the means mu=transform*mu; //builds the correlation matrix c0tc=rcross/ncross; c0t=transform*c0tc*transform.transpose() - mu*mu.transpose(); //diagonalize Eigen::SelfAdjointEigenSolver<MatrixXd> solver(c0t); w=solver.eigenvalues(); v=solver.eigenvectors(); }; double distance(double dTime, VectorXd &ci, VectorXd &cj){ double texp=dTime/dt; VectorXd si=transform*ci; VectorXd sj=transform*cj; double d=0; for(int i=0; i<nDescriptors; i++) { double c=v.col(i).transpose()*(si-sj); d+=pow(pow(w(i),texp)*c,2 ); } return sqrt(d); }; };