text
stringlengths
8
6.88M
// Copyright (c) 1991-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 _gp_Trsf2d_HeaderFile #define _gp_Trsf2d_HeaderFile #include <gp_TrsfForm.hxx> #include <gp_Mat2d.hxx> #include <gp_XY.hxx> #include <Standard_OutOfRange.hxx> class gp_Trsf; class gp_Pnt2d; class gp_Ax2d; class gp_Vec2d; //! Defines a non-persistent transformation in 2D space. //! The following transformations are implemented : //! - Translation, Rotation, Scale //! - Symmetry with respect to a point and a line. //! Complex transformations can be obtained by combining the //! previous elementary transformations using the method Multiply. //! The transformations can be represented as follow : //! @code //! V1 V2 T XY XY //! | a11 a12 a13 | | x | | x'| //! | a21 a22 a23 | | y | | y'| //! | 0 0 1 | | 1 | | 1 | //! @endcode //! where {V1, V2} defines the vectorial part of the transformation //! and T defines the translation part of the transformation. //! This transformation never change the nature of the objects. class gp_Trsf2d { public: DEFINE_STANDARD_ALLOC //! Returns identity transformation. gp_Trsf2d(); //! Creates a 2d transformation in the XY plane from a //! 3d transformation . gp_Trsf2d (const gp_Trsf& theT); //! Changes the transformation into a symmetrical transformation. //! theP is the center of the symmetry. void SetMirror (const gp_Pnt2d& theP); //! Changes the transformation into a symmetrical transformation. //! theA is the center of the axial symmetry. Standard_EXPORT void SetMirror (const gp_Ax2d& theA); //! Changes the transformation into a rotation. //! theP is the rotation's center and theAng is the angular value of the //! rotation in radian. void SetRotation (const gp_Pnt2d& theP, const Standard_Real theAng); //! Changes the transformation into a scale. //! theP is the center of the scale and theS is the scaling value. void SetScale (const gp_Pnt2d& theP, const Standard_Real theS); //! Changes a transformation allowing passage from the coordinate //! system "theFromSystem1" to the coordinate system "theToSystem2". Standard_EXPORT void SetTransformation (const gp_Ax2d& theFromSystem1, const gp_Ax2d& theToSystem2); //! Changes the transformation allowing passage from the basic //! coordinate system //! {P(0.,0.,0.), VX (1.,0.,0.), VY (0.,1.,0.)} //! to the local coordinate system defined with the Ax2d theToSystem. Standard_EXPORT void SetTransformation (const gp_Ax2d& theToSystem); //! Changes the transformation into a translation. //! theV is the vector of the translation. void SetTranslation (const gp_Vec2d& theV); //! Makes the transformation into a translation from //! the point theP1 to the point theP2. void SetTranslation (const gp_Pnt2d& theP1, const gp_Pnt2d& theP2); //! Replaces the translation vector with theV. Standard_EXPORT void SetTranslationPart (const gp_Vec2d& theV); //! Modifies the scale factor. Standard_EXPORT void SetScaleFactor (const Standard_Real theS); //! Returns true if the determinant of the vectorial part of //! this transformation is negative.. Standard_Boolean IsNegative() const { return (matrix.Determinant() < 0.0); } //! Returns the nature of the transformation. It can be an //! identity transformation, a rotation, a translation, a mirror //! (relative to a point or an axis), a scaling transformation, //! or a compound transformation. gp_TrsfForm Form() const { return shape; } //! Returns the scale factor. Standard_Real ScaleFactor() const { return scale; } //! Returns the translation part of the transformation's matrix const gp_XY& TranslationPart() const { return loc; } //! Returns the vectorial part of the transformation. It is a //! 2*2 matrix which includes the scale factor. Standard_EXPORT gp_Mat2d VectorialPart() const; //! Returns the homogeneous vectorial part of the transformation. //! It is a 2*2 matrix which doesn't include the scale factor. //! The coefficients of this matrix must be multiplied by the //! scale factor to obtain the coefficients of the transformation. const gp_Mat2d& HVectorialPart() const { return matrix; } //! Returns the angle corresponding to the rotational component //! of the transformation matrix (operation opposite to SetRotation()). Standard_EXPORT Standard_Real RotationPart() const; //! Returns the coefficients of the transformation's matrix. //! It is a 2 rows * 3 columns matrix. //! Raises OutOfRange if theRow < 1 or theRow > 2 or theCol < 1 or theCol > 3 Standard_Real Value (const Standard_Integer theRow, const Standard_Integer theCol) const; Standard_EXPORT void Invert(); //! Computes the reverse transformation. //! Raises an exception if the matrix of the transformation //! is not inversible, it means that the scale factor is lower //! or equal to Resolution from package gp. Standard_NODISCARD gp_Trsf2d Inverted() const { gp_Trsf2d aT = *this; aT.Invert(); return aT; } Standard_NODISCARD gp_Trsf2d Multiplied (const gp_Trsf2d& theT) const { gp_Trsf2d aTresult (*this); aTresult.Multiply (theT); return aTresult; } Standard_NODISCARD gp_Trsf2d operator * (const gp_Trsf2d& theT) const { return Multiplied (theT); } //! Computes the transformation composed from <me> and theT. //! <me> = <me> * theT Standard_EXPORT void Multiply (const gp_Trsf2d& theT); void operator *= (const gp_Trsf2d& theT) { Multiply (theT); } //! Computes the transformation composed from <me> and theT. //! <me> = theT * <me> Standard_EXPORT void PreMultiply (const gp_Trsf2d& theT); Standard_EXPORT void Power (const Standard_Integer theN); //! Computes the following composition of transformations //! <me> * <me> * .......* <me>, theN time. //! if theN = 0 <me> = Identity //! if theN < 0 <me> = <me>.Inverse() *...........* <me>.Inverse(). //! //! Raises if theN < 0 and if the matrix of the transformation not //! inversible. gp_Trsf2d Powered (const Standard_Integer theN) { gp_Trsf2d aT = *this; aT.Power (theN); return aT; } void Transforms (Standard_Real& theX, Standard_Real& theY) const; //! Transforms a doublet XY with a Trsf2d void Transforms (gp_XY& theCoord) const; //! Sets the coefficients of the transformation. The //! transformation of the point x,y is the point //! x',y' with : //! @code //! x' = a11 x + a12 y + a13 //! y' = a21 x + a22 y + a23 //! @endcode //! The method Value(i,j) will return aij. //! Raises ConstructionError if the determinant of the aij is null. //! If the matrix as not a uniform scale it will be orthogonalized before future using. Standard_EXPORT void SetValues (const Standard_Real a11, const Standard_Real a12, const Standard_Real a13, const Standard_Real a21, const Standard_Real a22, const Standard_Real a23); friend class gp_GTrsf2d; protected: //! Makes orthogonalization of "matrix" Standard_EXPORT void Orthogonalize(); private: Standard_Real scale; gp_TrsfForm shape; gp_Mat2d matrix; gp_XY loc; }; #include <gp_Trsf.hxx> #include <gp_Pnt2d.hxx> //======================================================================= //function : gp_Trsf2d // purpose : //======================================================================= inline gp_Trsf2d::gp_Trsf2d() { shape = gp_Identity; scale = 1.0; matrix.SetIdentity(); loc.SetCoord (0.0, 0.0); } //======================================================================= //function : gp_Trsf2d // purpose : //======================================================================= inline gp_Trsf2d::gp_Trsf2d (const gp_Trsf& theT) : scale (theT.ScaleFactor()), shape (theT.Form()), loc (theT.TranslationPart().X(), theT.TranslationPart().Y()) { const gp_Mat& M = theT.HVectorialPart(); matrix(1,1) = M(1,1); matrix(1,2) = M(1,2); matrix(2,1) = M(2,1); matrix(2,2) = M(2,2); } //======================================================================= //function : SetRotation // purpose : //======================================================================= inline void gp_Trsf2d::SetRotation (const gp_Pnt2d& theP, const Standard_Real theAng) { shape = gp_Rotation; scale = 1.0; loc = theP.XY (); loc.Reverse (); matrix.SetRotation (theAng); loc.Multiply (matrix); loc.Add (theP.XY()); } //======================================================================= //function : SetMirror // purpose : //======================================================================= inline void gp_Trsf2d::SetMirror (const gp_Pnt2d& theP) { shape = gp_PntMirror; scale = -1.0; matrix.SetIdentity(); loc = theP.XY(); loc.Multiply (2.0); } //======================================================================= //function : SetScale // purpose : //======================================================================= inline void gp_Trsf2d::SetScale (const gp_Pnt2d& theP, const Standard_Real theS) { shape = gp_Scale; scale = theS; matrix.SetIdentity(); loc = theP.XY(); loc.Multiply (1.0 - theS); } //======================================================================= //function : SetTranslation // purpose : //======================================================================= inline void gp_Trsf2d::SetTranslation (const gp_Vec2d& theV) { shape = gp_Translation; scale = 1.0; matrix.SetIdentity(); loc = theV.XY(); } //======================================================================= //function : SetTranslation // purpose : //======================================================================= inline void gp_Trsf2d::SetTranslation (const gp_Pnt2d& theP1, const gp_Pnt2d& theP2) { shape = gp_Translation; scale = 1.0; matrix.SetIdentity(); loc = (theP2.XY()).Subtracted (theP1.XY()); } //======================================================================= //function : Value // purpose : //======================================================================= inline Standard_Real gp_Trsf2d::Value (const Standard_Integer theRow, const Standard_Integer theCol) const { Standard_OutOfRange_Raise_if (theRow < 1 || theRow > 2 || theCol < 1 || theCol > 3, " "); if (theCol < 3) { return scale * matrix.Value (theRow, theCol); } else { return loc.Coord (theRow); } } //======================================================================= //function : Transforms // purpose : //======================================================================= inline void gp_Trsf2d::Transforms (Standard_Real& theX, Standard_Real& theY) const { gp_XY aDoublet(theX, theY); aDoublet.Multiply (matrix); if (scale != 1.0) { aDoublet.Multiply (scale); } aDoublet.Add (loc); aDoublet.Coord (theX, theY); } //======================================================================= //function : Transforms // purpose : //======================================================================= inline void gp_Trsf2d::Transforms (gp_XY& theCoord) const { theCoord.Multiply (matrix); if (scale != 1.0) { theCoord.Multiply (scale); } theCoord.Add (loc); } #endif // _gp_Trsf2d_HeaderFile
/* * MessageBuild.h * * Created on: Jun 11, 2017 * Author: root */ #ifndef MESSAGEBUILD_H_ #define MESSAGEBUILD_H_ #include "Smart_Ptr.h" #include "Network/MessageManager.h" #include "Network/NetWorkConfig.h" #include "./google/protobuf/message.h" #include "ServerManager.h" using namespace std; using namespace CommBaseOut; Safe_Smart_Ptr<CommBaseOut::Message> build_message(int messageID, Safe_Smart_Ptr<CommBaseOut::Message> &message, google::protobuf::Message *content, int messageType = Ack, int timeOut = 10); Safe_Smart_Ptr<CommBaseOut::Message> build_message(int messageID, google::protobuf::Message *content, SvrItem *handler, int messageType = Ack, int timeOut = 10); Safe_Smart_Ptr<CommBaseOut::Message> build_message(int messageID, char *content, int len, SvrItem *handler, int messageType = Ack, int timeOut = 10); Safe_Smart_Ptr<CommBaseOut::Message> build_message(int messageID, google::protobuf::Message *content, int channel, int messageType = Ack, int timeOut = 10); Safe_Smart_Ptr<CommBaseOut::Message> build_message(int messageID, string &content, int channel, int messageType = Ack, int timeOut = 10); Safe_Smart_Ptr<CommBaseOut::Message> build_message(int messageID, Safe_Smart_Ptr<CommBaseOut::Message> &message, int channel, int messageType = Ack, int timeOut = 10); Safe_Smart_Ptr<CommBaseOut::Message> build_message(int messageID, char *content, int len, int channel, int messageType = Ack, int timeOut = 10); #endif /* MESSAGEBUILD_H_ */
#include <cstdio> #include <iostream> #include <stack> using namespace std; struct ListNode{ int val; ListNode *next; ListNode(int x) : val(x) , next(NULL){} }; ListNode *hasCycle(ListNode *head){ ListNode *fast = head; ListNode *slow = head; if(head ==NULL || head->next ==NULL) return NULL; while(fast->next != NULL && fast->next->next !=NULL){ fast = fast->next->next; slow = slow->next; if(fast == slow){ fast = head; while(fast != slow){ fast = fast->next; slow = slow->next; } return fast; } } return NULL; } int main(){ int x; cin >> x; ListNode *head = new ListNode(x); ListNode *p = head; while(cin >> x){ ListNode *n = new ListNode(x); p->next = n; p = p->next; } cout << "Finish Input" << endl; hasCycle(head); p = head; while(p != NULL){ cout << p->val << endl; p = p->next; } }
/* * 2013+ Copyright (c) Ruslan Nigatullin <euroelessar@yandex.ru> * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include "stockreplies_p.hpp" namespace ioremap { namespace thevoid { namespace stock_replies { template <size_t N> static boost::asio::const_buffer to_buffer(const char (&str)[N]) { return boost::asio::buffer(str, N - 1); } namespace status_strings { const char ok[] = "HTTP/1.1 200 OK\r\n"; const char created[] = "HTTP/1.1 201 Created\r\n"; const char accepted[] = "HTTP/1.1 202 Accepted\r\n"; const char no_content[] = "HTTP/1.1 204 No Content\r\n"; const char multiple_choices[] = "HTTP/1.1 300 Multiple Choices\r\n"; const char moved_permanently[] = "HTTP/1.1 301 Moved Permanently\r\n"; const char moved_temporarily[] = "HTTP/1.1 302 Moved Temporarily\r\n"; const char not_modified[] = "HTTP/1.1 304 Not Modified\r\n"; const char bad_request[] = "HTTP/1.1 400 Bad Request\r\n"; const char unauthorized[] = "HTTP/1.1 401 Unauthorized\r\n"; const char forbidden[] = "HTTP/1.1 403 Forbidden\r\n"; const char not_found[] = "HTTP/1.1 404 Not Found\r\n"; const char internal_server_error[] = "HTTP/1.1 500 Internal Server Error\r\n"; const char not_implemented[] = "HTTP/1.1 501 Not Implemented\r\n"; const char bad_gateway[] = "HTTP/1.1 502 Bad Gateway\r\n"; const char service_unavailable[] = "HTTP/1.1 503 Service Unavailable\r\n"; boost::asio::const_buffer to_buffer(int status) { using ioremap::thevoid::stock_replies::to_buffer; switch (status) { case swarm::network_reply::ok: return to_buffer(ok); case swarm::network_reply::created: return to_buffer(created); case swarm::network_reply::accepted: return to_buffer(accepted); case swarm::network_reply::no_content: return to_buffer(no_content); case swarm::network_reply::multiple_choices: return to_buffer(multiple_choices); case swarm::network_reply::moved_permanently: return to_buffer(moved_permanently); case swarm::network_reply::moved_temporarily: return to_buffer(moved_temporarily); case swarm::network_reply::not_modified: return to_buffer(not_modified); case swarm::network_reply::bad_request: return to_buffer(bad_request); case swarm::network_reply::unauthorized: return to_buffer(unauthorized); case swarm::network_reply::forbidden: return to_buffer(forbidden); case swarm::network_reply::not_found: return to_buffer(not_found); case swarm::network_reply::internal_server_error: return to_buffer(internal_server_error); case swarm::network_reply::not_implemented: return to_buffer(not_implemented); case swarm::network_reply::bad_gateway: return to_buffer(bad_gateway); case swarm::network_reply::service_unavailable: return to_buffer(service_unavailable); default: return to_buffer(internal_server_error); } } } // namespace status_strings namespace misc_strings { const char name_value_separator[] = { ':', ' ' }; const char crlf[] = { '\r', '\n' }; } // namespace misc_strings namespace default_content { const char ok[] = ""; const char created[] = "<html>" "<head><title>Created</title></head>" "<body><h1>201 Created</h1></body>" "</html>"; const char accepted[] = "<html>" "<head><title>Accepted</title></head>" "<body><h1>202 Accepted</h1></body>" "</html>"; const char no_content[] = "<html>" "<head><title>No Content</title></head>" "<body><h1>204 Content</h1></body>" "</html>"; const char multiple_choices[] = "<html>" "<head><title>Multiple Choices</title></head>" "<body><h1>300 Multiple Choices</h1></body>" "</html>"; const char moved_permanently[] = "<html>" "<head><title>Moved Permanently</title></head>" "<body><h1>301 Moved Permanently</h1></body>" "</html>"; const char moved_temporarily[] = "<html>" "<head><title>Moved Temporarily</title></head>" "<body><h1>302 Moved Temporarily</h1></body>" "</html>"; const char not_modified[] = "<html>" "<head><title>Not Modified</title></head>" "<body><h1>304 Not Modified</h1></body>" "</html>"; const char bad_request[] = "<html>" "<head><title>Bad Request</title></head>" "<body><h1>400 Bad Request</h1></body>" "</html>"; const char unauthorized[] = "<html>" "<head><title>Unauthorized</title></head>" "<body><h1>401 Unauthorized</h1></body>" "</html>"; const char forbidden[] = "<html>" "<head><title>Forbidden</title></head>" "<body><h1>403 Forbidden</h1></body>" "</html>"; const char not_found[] = "<html>" "<head><title>Not Found</title></head>" "<body><h1>404 Not Found</h1></body>" "</html>"; const char internal_server_error[] = "<html>" "<head><title>Internal Server Error</title></head>" "<body><h1>500 Internal Server Error</h1></body>" "</html>"; const char not_implemented[] = "<html>" "<head><title>Not Implemented</title></head>" "<body><h1>501 Not Implemented</h1></body>" "</html>"; const char bad_gateway[] = "<html>" "<head><title>Bad Gateway</title></head>" "<body><h1>502 Bad Gateway</h1></body>" "</html>"; const char service_unavailable[] = "<html>" "<head><title>Service Unavailable</title></head>" "<body><h1>503 Service Unavailable</h1></body>" "</html>"; static boost::asio::const_buffer to_buffer(int status) { using ioremap::thevoid::stock_replies::to_buffer; switch (status) { case swarm::network_reply::ok: return to_buffer(ok); case swarm::network_reply::created: return to_buffer(created); case swarm::network_reply::accepted: return to_buffer(accepted); case swarm::network_reply::no_content: return to_buffer(no_content); case swarm::network_reply::multiple_choices: return to_buffer(multiple_choices); case swarm::network_reply::moved_permanently: return to_buffer(moved_permanently); case swarm::network_reply::moved_temporarily: return to_buffer(moved_temporarily); case swarm::network_reply::not_modified: return to_buffer(not_modified); case swarm::network_reply::bad_request: return to_buffer(bad_request); case swarm::network_reply::unauthorized: return to_buffer(unauthorized); case swarm::network_reply::forbidden: return to_buffer(forbidden); case swarm::network_reply::not_found: return to_buffer(not_found); case swarm::network_reply::internal_server_error: return to_buffer(internal_server_error); case swarm::network_reply::not_implemented: return to_buffer(not_implemented); case swarm::network_reply::bad_gateway: return to_buffer(bad_gateway); case swarm::network_reply::service_unavailable: return to_buffer(service_unavailable); default: return to_buffer(internal_server_error); } } } // default_content boost::asio::const_buffer status_to_buffer(swarm::network_reply::status_type status) { return status_strings::to_buffer(status); } boost::asio::const_buffer status_content(swarm::network_reply::status_type status) { return default_content::to_buffer(status); } swarm::network_reply stock_reply(swarm::network_reply::status_type status) { const size_t buffer_size = boost::asio::buffer_size(status_content(status)); swarm::network_reply reply; reply.set_code(status); reply.set_content_length(buffer_size); reply.set_content_type("text/html"); return reply; } std::vector<boost::asio::const_buffer> to_buffers(const swarm::network_reply &reply, const boost::asio::const_buffer &content) { std::vector<boost::asio::const_buffer> buffers; buffers.push_back(status_strings::to_buffer(reply.get_code())); const auto &headers = reply.get_headers(); for (std::size_t i = 0; i < headers.size(); ++i) { auto &header = headers[i]; buffers.push_back(boost::asio::buffer(header.first)); buffers.push_back(boost::asio::buffer(misc_strings::name_value_separator)); buffers.push_back(boost::asio::buffer(header.second)); buffers.push_back(boost::asio::buffer(misc_strings::crlf)); } buffers.push_back(boost::asio::buffer(misc_strings::crlf)); buffers.push_back(content); return buffers; } } // namespace stock_replies } } // namespace ioremap::thevoid
/* Blink Turns on an LED on for one second, then off for one second, repeatedly. Most Arduinos have an on-board LED you can control. On the Uno and Leonardo, it is attached to digital pin 13. If you're unsure what pin the on-board LED is connected to on your Arduino model, check the documentation at http://www.arduino.cc This example code is in the public domain. modified 8 May 2014 by Scott Fitzgerald */ int ledPinGreenOne = 13; // choose the pin for the LED int ledPinGreenTwo = 11; // choose the pin for the LED int ledPinRed = 12; // choose the pin for the LED int echoPin = 2; // choose the input pin (for PIR sensor) int ledOff = LOW; // we start, assuming no motion detected int ledOn = HIGH; // we start, assuming no motion detected int val = 0; // variable for reading the pin status int pirState = LOW; // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin 13 as an output. pinMode(ledPinGreenOne, OUTPUT); pinMode(ledPinRed, OUTPUT); pinMode(ledPinGreenTwo, OUTPUT); pinMode(inputPin, INPUT); // declare sensor as input Serial.begin(9600); } // the loop function runs over and over again forever void loop() { val = digitalRead(inputPin); // read input value if (val == HIGH) { // check if the input is HIGH digitalWrite(ledPinGreenOne, HIGH); // turn LED ON if (pirState == LOW) { // we have just turned on Serial.println("Motion detected!"); // We only want to print on the output change, not state pirState = HIGH; } } else { digitalWrite(ledPinGreenOne, LOW); // turn LED OFF if (pirState == HIGH){ // we have just turned of Serial.println("Motion ended!"); // We only want to print on the output change, not state pirState = LOW; } } }
#include <iostream> #include <fstream> #include <cctype> #include <vector> #include <list> #include <queue> #include <deque> using std::vector; using std::list; using std::string; using std::priority_queue; using std::deque; struct Vertex { unsigned index, weight; }; inline bool operator > (const Vertex& lhs, const Vertex& rhs) { return lhs.weight > rhs.weight; } typedef vector<list<Vertex> > AdjList; typedef priority_queue<Vertex, vector<Vertex>, std::greater<Vertex> > priorityQueue; void addAdjVertex (priorityQueue&, const list<Vertex>&, const deque<bool>&); int main() { std::ifstream networkFile("C:/Users/s521059/CLionProjects/Euler Project/EulerP107/p107_network.txt"); AdjList network(40); unsigned origNetworkWeight = 0; /* Create an adjacency list on the fly while reading an adacency * matrix from the input file */ for (AdjList::iterator vertexItr = network.begin(); vertexItr != network.end() && networkFile.good(); ++vertexItr) { char c; Vertex vertex; for (unsigned adjVertex = 0; adjVertex < network.size(); ++adjVertex) { c = networkFile.peek(); if (isdigit(c)) { networkFile >> std::noskipws >> vertex.weight >> c; vertex.index = adjVertex; vertexItr->push_back(vertex); origNetworkWeight += vertex.weight; } else networkFile >> c >> c; } } origNetworkWeight >>= 1; networkFile.close(); //----------------------------------------------------------------------------- deque<bool> isInNetwork (network.size(), false); priorityQueue pq; unsigned minNetworkWeight = 0, minNetworkSize = 0; isInNetwork.front() = true; addAdjVertex (pq, network[0], isInNetwork); while (++minNetworkSize != network.size()) { Vertex minAdjVertex = pq.top(); while (isInNetwork[minAdjVertex.index]) { pq.pop(); minAdjVertex = pq.top(); } isInNetwork[minAdjVertex.index] = true; minNetworkWeight += minAdjVertex.weight; addAdjVertex (pq, network[minAdjVertex.index], isInNetwork); } std::cout << origNetworkWeight - minNetworkWeight; } void addAdjVertex (priorityQueue& pq, const list<Vertex>& adjVertices, const deque<bool>& isInNetwork) { for (list<Vertex>::const_iterator it = adjVertices.begin(); it != adjVertices.end(); ++it) { if (!isInNetwork[it->index]) pq.push(*it); } }
#include<iostream.h> #include<conio.h> #include<graphics.h> #include<stdio.h> #include<stdlib.h> #include<dos.h> #include<math.h> #define pi 3.142 void main() { /*----------------------------------------------------------------------------------------------------------*/ void initialize(); void draw(int,int); void draw2(int,double,double); // void draw3(int); /*....Why it is commented is explained in function draw2()....*/ void amplifier(int,int,int); void amplitude(int,double,int,int); void frequency(int,double,int,int); void plotgraph(int); /*---------------------------------------------------------------------------------------------------------*/ clrscr(); int gd=DETECT,gm,color; int option,A,noise,gain,vsat,f1,f2; double f,theta,m; initialize(); /*---------------------------------------------------------------------------------------------------------------*/ restart: { clrscr(); cout<<"-------------------------------------MENU----------------------------------"<<"\n"; cout<<"1. y=Asin(theta)"<<"\n"; cout<<"2. y=Asin(wt)"<<"\n"; cout<<"3. y=Asin(wt+theta)"<<"\n"; cout<<"4. Effects of noise on a sine wave"<<"\n"; cout<<"5. Amplifier"<<"\n"; cout<<"6. Amplitude Modulation"<<"\n"; cout<<"7. Frequency Modulation"<<"\n"; cout<<"Enter your option"<<"\n"; cin>>option; switch(option) { case 1:cout<<"Enter the value of A"<<"\n"; cin>>A; break; case 2:cout<<"Enter the value of A,f respectively"<<"\n"; cin>>A>>f; theta=0.0; break; case 3:cout<<"Enter value of A,f,theta respectively"<<"\n"; cin>>A>>f>>theta; break; case 4:cout<<"Enter the value of A,noise"<<"\n"; cin>>A>>noise; break; case 5:cout<<"Enter the value of input voltage,supply voltage,gain"<<"\n"; cin>>A>>vsat>>gain; break; case 6:cout<<"Enter A,modulation index,carrier frequency,modulating frequency"<<"\n"; cin>>A>>m>>f1>>f2; break; case 7:cout<<"Enter A,modulation index,carrier frequency,modulating frequency"<<"\n"; cin>>A>>m>>f1>>f2; break; default:cout<<"Invalid option"<<"\n"; goto restart; } } /*-----------------------------------------DRAWING-----------------------------------------------------------------*/ initgraph(&gd,&gm,"C:\\TC\\BGI"); plotgraph(A); /*---------------------------PLOTTING OF THE GRAPH----------------------------*/ /*-----------------------INTERSECTION POINT------------------------------*/ //setcolor(10); //line(100,275,100,275); /*-------------------------FUNCTION CALL------------------------------------*/ switch(option) { case 1:draw(A,0); break; case 2:draw2(A,f,theta); break; case 3:draw2(A,f,theta); break; case 4:draw(A,noise); break; case 5:amplifier(A,vsat,gain); break; case 6:amplitude(A,m,f1,f2); break; case 7:frequency(A,m,f1,f2); break; } /*------------------------------------ENDING-------------------------------------*/ getch(); closegraph(); cout<<"Do you want to continue.....If yes Press Y"<<"\n"; char c; cin>>c; if(c=='Y'||c=='y') goto restart; cout<<"THANK YOU.......HAVE A NICE DAY"<<"\n"; //getch(); /*if you want exit to be user controlled*/ delay(2000); } /*------------------------------------------OUTSIDE MAIN--------------------------------------------------*/ void draw(int A,int noise) { double x=100; double y=275; double theta=0; void draw3(int); if(noise!=0) { draw3(A); /* Since in c function prototype(declaration) must reside int the function that calls it */ } for(x=100;x<=600;x+=pi/5) { y=275; y-=A*sin(theta)+noise; delay(10); theta+=pi/180; putpixel(x,y,10); } } /*------------------------------------------to generate original sine wave----------------------------------------*/ void draw3(int A) { double x,y; double theta=0; setcolor(8); rectangle(50,50,600,150); for(y=50;y<150;y+=30) line(50,y,600,y); for(x=50;x<=600;x+=30) line(x,50,x,150); setcolor(7); line(100,50,100,150); line(50,100,600,100); line(50,100-A,600,100-A); line(50,100+A,600,100+A); for(x=100;x<=600;x+=pi/5) { y=100; y-=A*sin(theta); delay(10); theta+=pi/180; putpixel(x,y,10); } } /*------------------------------------------------------------------------------------------------------------------*/ void draw2(int A,double f,double theta) { double x=100; double y=275; double w; w=2*pi*f; int sign; if(theta==0) sign=1; else sign=theta/theta; for(x=0.0;x<=500;x+=0.1) { y=0; y=A*sin(w*x*sign+(theta*pi/180)); /* since it is sin(180+theta) */ delay(3); putpixel(x+100,275-y,10); } } /*-----------------------------------------INITIAL HOUSEKEEPING-----------------------------------------------*/ void plotgraph(int A) { setcolor(8); int x,y; x=0; y=150; /*-----------------X-AXIS-----------------*/ for(y=150;y<=400;y+=30) line(50,y,600,y); /*---------------Y-AXIS-------------------*/ for(x=50;x<=600;x+=30) line(x,150,x,400); rectangle(50,150,600,400); /*-----------REFERENCE AXES----------------*/ /* Includes the co ordinate axes and the axes for marking the highest value of the wave ie Amplitude */ setcolor(7); line(100,150,100,400); line(50,275,600,275); line(50,275-A,600,275-A); line(50,275+A,600,275+A); } /*------------------------------------------------------------------------------------------------------------*/ void amplifier(int A,int vsat,int gain) { void draw3(int); double x,y,v; double theta=0; v=gain*A; draw3(A); for(x=100;x<=600;x+=pi/5) { y=0; y=v*sin(theta); if(y>vsat) { y=vsat; theta+=pi/180; putpixel(x,275-y,10); delay(3); continue; } else if(vsat*(-1)>y) { y=vsat; theta+=pi/180; putpixel(x,275+y,10); delay(3); continue; } else { delay(10); theta+=pi/180; putpixel(x,275-y,10); } } } /*------------------------------------------Amplitude Modulation-------------------------------------------*/ void amplitude(int A,double m,int f1,int f2) { double x,y,w1,w2,carrier,upper,lower,k; w1=2*pi*f1; w2=2*pi*f2; k=m*A/2; for(x=0.0;x<=500;x+=0.1) { y=0; carrier=A*sin(w1*x); lower=k*cos((w1-w2)*x); upper=k*cos((w1+w2)*x); y=carrier+lower-upper; delay(3); putpixel(x+100,275-y,10); } } void frequency(int A,double m,int f1,int f2) { double x,y,w1,w2,term1,term2; w1=2*pi*f1; w2=2*pi*f2; for(x=0.0;x<=500;x+=0.1) { y=0; term1=w1*x; term2=m*sin(w2*x); y=A*sin(term1+term2); delay(3); putpixel(x+100,275-y,10); } } void initialize() { int gd=DETECT,gm; initgraph(&gd,&gm,"C:\\TC\\BGI"); setcolor(WHITE); rectangle(50,50,600,450); settextstyle(SANS_SERIF_FONT,HORIZ_DIR,0); outtextxy(300,50,"CRO"); delay(1000); settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2); outtextxy(100,150,"Initializing"); for(int i=1,x=200;i<=3;i++,x+=5) { outtextxy(x,150,"."); delay(1000); } outtextxy(100,175,"Loading graphics"); for(i=1,x=275;i<=3;i++,x+=5) { outtextxy(x,175,"."); delay(1500); } closegraph(); }
#include "../headers/shop.h" #include "../headers/Safe_Input.h" #include "../headers/item.h" #include "../headers/party.h" #include "../headers/FileFunctions.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> int getShopRange() { int cnt = lineCount("./files/Shop_List.txt"); return cnt; } shop* getShop(int ID) { int cnt = lineCount("./files/Shop_List.txt"); if ((ID > cnt)||(ID == 0)) return NULL; shop *temp = NULL; char *line_in; int id; char name[32]; int size; int *item_ids; double sell_rate; line_in = getWholeLine("./files/Shop_List.txt", ID); printf("Line in: %s\n", line_in); FILE *fp = fopen("./files/tempShop.txt", "w"); assert(fp != NULL); fprintf(fp, "%s \n", line_in); fclose(fp); free(line_in); fp = fopen("./files/tempShop.txt", "r"); assert(fp != NULL); temp = new shop; temp->loadShop(fp); fclose(fp); return temp; } //------------------------------------------------- shop::shop() { sprintf(name, "Default Shop"); int size = 0; goods = NULL; sell_rate = 1.0; customer = NULL; } shop::~shop() { for (int i=0; i<size; i++) { delete goods[i]; } if (goods != NULL) delete [] goods; } shop::shop(int ID, char* NAME, int* IDs, int SIZE, double RATE) { setShop(ID, NAME, IDs, SIZE, RATE); } void shop::setShop(int ID, char* NAME, int* IDs, int SIZE, double RATE) { customer = NULL; id = ID; sprintf(name, "%s", NAME); size = SIZE; sell_rate = RATE; goods = new item*[size]; for (int i=0; i < size; i++) { goods[i] = NULL; goods[i] = getItem(IDs[i]); } } void shop::loadShop(FILE *fp) { customer = NULL; fscanf(fp, " %d '%[^']' %lf %d ", &id, name, &sell_rate, &size); goods = new item*[size]; for (int i=0; i < size; i++) { int temp; fscanf(fp, " %d ", &temp); goods[i] = NULL; goods[i] = getItem(temp); } } void shop::saveShop(FILE *fp) { fprintf(fp, "%d '%s' %lf %d ", id, name, sell_rate, size); for (int i=0; i<size; i++) { fprintf(fp, "%d ", goods[i]->getID()); } fprintf(fp, "\n"); } int shop::getSellPrice(int value) { /* if ((idx < 0)||(idx >= size)) { printf("Invalid index...\n"); return -1; } */ // double price_d = sell_rate*goods[idx]->getGoldValue(); double price_d = sell_rate*value; return (int)price_d; } void shop::printGoods() { printf("%s's Selection\n", name); printf("--------------------------------------------\n"); printf("ID Name Price\n"); printf("=== ==================== =========\n"); for (int i=0; i<size; i++) { // char temp[32]; // sprintf(""); printf("%2d. %-20s %-5d gld\n", i+1, goods[i]->getName(), goods[i]->getGoldValue()); } printf("\n"); } void shop::enterShop(party* in) { customer = in; bool in_shop = true; while (in_shop) { printf("%s\n", name); printf("---------------------\n"); int shop_sel = getSel("1. Buy", "2. Sell", "3. Leave Shop"); switch (shop_sel) { case 1: { buyGoods(); break; } case 2: { sellGoods(); break; } case 3: { printf("Come again soon...\n"); in_shop = false; customer = NULL; break; } } } } void shop::buyGoods() { bool buyGoods = true; while (buyGoods) { printf("Current gold: %d\n\n", customer->getGold()); printGoods(); printf("%d. Cancel Action\n", size+1); int buy_sel = getSel(size+1); if (buy_sel < size+1) { buy_sel--; printf("How many %ss do you want to buy: ", goods[buy_sel]->getName()); int count = getInt(); if (count > 0) { int price = count*goods[buy_sel]->getGoldValue(); printf("Buying %d %ss will cost %d gold. Is this ok?\n", count, goods[buy_sel]->getName(), price); int confirm = getSel("1. Yes", "2. No"); if (confirm == 1) { if (customer->goldCheck(price)) { item *purchase = getItem(goods[buy_sel]->getID()); purchase->setStock(count); customer->recieveItem(purchase); customer->loseGold(price); printf("Purchase complete, you have %d gold left\n", customer->getGold()); } else { printf("You do not have enough gold to make this purchase.\n"); printf("Cancelling transaction...\n"); } /* printf("Would you like to keep shopping?\n"); int cont_sel = getSel("1. Yes", "2. No"); if (cont_sel == 2) { printf("Exiting buy menu...\n"); buyGoods = false; } else { printf("Take your time...\n"); } */ } else { printf("Cancelling transaction...\n"); } printf("Would you like to keep shopping?\n"); int cont_sel = getSel("1. Yes", "2. No"); if (cont_sel == 2) { printf("Exiting buy menu...\n"); buyGoods = false; } else { printf("Take your time...\n"); } } else { printf("Sorry, you must select at least 1 item to buy\n\n"); } } else { printf("Cancelling action...\n"); buyGoods = false; } } } void shop::sellGoods() { bool sellGoods = true; while (sellGoods) { printf("Current gold: %d\n\n", customer->getGold()); customer->printInventory(); printf("%d. Cancel\n", customer->getInventorySize()+1); int sell_sel = getSel(customer->getInventorySize()+1); if (sell_sel < customer->getInventorySize()+1) { sell_sel--; if (customer->checkItem(sell_sel)) { printf("How many %s do you want to sell: ", customer->getItemName(sell_sel)); int count = getInt(); int price = count*getSellPrice(customer->getItemValue(sell_sel)); printf("Do you want to sell %d %ss for a total of %d gold?\n", count, customer->getItemName(sell_sel), price); int confirm = getSel("1. Yes", "2. No"); if (confirm == 1) { if (customer->checkStock(sell_sel, count)) { item *temp = customer->removeItems(sell_sel, count); customer->recieveGold(price); delete temp; printf("Sale complete, you now have %d gold.\n", customer->getGold()); } else { printf("You do not have enough %ss to make this sale.\n", customer->getItemName(sell_sel)); printf("Cancelling transaction...\n"); } } else { printf("Cancelling transaction...\n"); } } else { printf("You did not select anything to sell...\n"); printf("Cancelling transaction...\n"); } printf("Would you like to sell more items?\n"); int cont_sel = getSel("1. Yes", "2. No"); if (cont_sel == 2) { printf("Exiting sell menu...\n"); sellGoods = false; } else { printf("Take your time...\n"); } } else { printf("Cancelling action...\n"); sellGoods = false; } } }
#include <iostream> using namespace std; int main () { char str[80]; char ch; cin.getline(str, sizeof (str)); int n = sizeof(str); cin >> ch; int i = 0, index; while(i < n) { if (str[i] == ch) { index = i; while (index < n) { str[index] = str[index + 1]; index++; } } i++; } cout << str; return 0; }
#include "Physics.h" #define MAX_LINEAR_VELOCITY 340.0f #define MAX_ANGULAR_VELOCITY (PI * 60.0f) //็ฉๅˆ† void Physics::Integrate(RigidbodyState &state, unsigned int numRigidbodys, float timestep){ Quat dAng = Quat(state.m_angularVelocity, 0)*state.m_orientation*0.5f; state.m_position += state.m_linearVelocity * timestep; state.m_orientation = normalize(state.m_orientation + dAng*timestep); } //ๅค–ๅŠ›่จˆ็ฎ— void Physics::ApplyExternalForce(RigidbodyState &state, const RigidBodyElements &bodyelements, const Vector3 &externalForce, const Vector3 &externalTorque, float timeStep){ //ๅ‹•ใ‹ใชใ„็‰ฉไฝ“ใชใ‚‰ๅค–ๅŠ›่จˆ็ฎ—ใชใ— if (state.m_motionType == MotionType::TypeStatic){ return; } //TODO:ๅงฟๅ‹ข่จˆ็ฎ— Matrix3 orientation(state.m_orientation); Matrix3 worldInertia = orientation * bodyelements.m_inertia * transpose(orientation); Matrix3 worldInertiaInv = orientation * inverse(bodyelements.m_inertia) * transpose(orientation); Vector3 angularMomentum = worldInertia * state.m_angularVelocity; state.m_linearVelocity += externalForce / bodyelements.m_mass * timeStep; angularMomentum += externalTorque * timeStep; state.m_angularVelocity = worldInertiaInv * angularMomentum; //TODO:้€Ÿๅบฆใ‚ชใƒผใƒใƒผๅ‡ฆ็† float velocitySqrt = lengthSqr(state.m_linearVelocity); if (velocitySqrt > (MAX_LINEAR_VELOCITY*MAX_LINEAR_VELOCITY)){ state.m_linearVelocity = (state.m_linearVelocity / sqrtf(velocitySqrt)) * MAX_LINEAR_VELOCITY; } //TODO:่ง’้€Ÿๅบฆใ‚ชใƒผใƒใƒผๅ‡ฆ็† float angleVelocitySqrt = lengthSqr(state.m_angularVelocity); if (angleVelocitySqrt > (MAX_ANGULAR_VELOCITY * MAX_ANGULAR_VELOCITY)){ state.m_angularVelocity = (state.m_angularVelocity / sqrtf(angleVelocitySqrt))*MAX_ANGULAR_VELOCITY; } }
#include <iostream> #include <limits> using namespace std; int main() { //Variable for creating spaces for the triangles int space; //this loop creates the rows for the first triangle for (int i = 1; i <= 5; ++i) { //this loop populates rows with * for (int k = 1; k <= i; ++k) { cout << "*"; } cout << "\n"; } //this creates the second triangle //this loop sets variables and intiates other loops for (int i = 1, k = 0; i <= 5; ++i, k = 0) { //this loop then creates the spaces needed to shift the triangle over for (space = 1; space <= 5-i; ++space) { cout << " "; } //this while loop makes sure that each row has the right amount of astriks while (k !=i) { cout << "*"; ++k; } cout << endl; } //this is very similar to the loop above but instead creates a pyriamd with 4 rows for (int i = 1, k = 0; i <= 4; ++i, k = 0) { for (space = 1; space <= 4 - i; ++space) { cout << " "; } //this is the main difference between the loop for the 2 triangle, it instead //creates an uneven row of astriks which starts at 1 and then goes up to each odd //number until it gets to the amount of rows we want, ie row 1 has 1 astrik row 2 has 3 etc. while (k !=2*i-1) { cout << "*"; ++k; } cout << endl; } //this loop is part of the diamond but it is the same as the loop above for (int i = 1,k = 0;i <= 4; ++i,k = 0) { for (space = 1;space <= 4 - i;++space) { cout << " "; } while (k !=2*i-1) { cout << "*"; ++k; } cout << endl; } //this loop is similar to the one above but it creates a pyriaymd downwards //here instead we have i start at 3 which is the number of rows we want, //then go down until i>=1 and then stops. this makes the other parts of the loop //to work backwards for (int i = 3, k = 0; i >= 1; --i, k = 0) { for (space = 1; space <= 4 - i; ++space) { cout << " "; } while (k !=2*i-1) { cout << "*"; ++k; } cout << endl; } system("PAUSE"); return 0; }
#ifndef MENU_H #define MENU_H #include "../Shoikoth/person.hpp" class Menu { protected: public: void mainMenu() { cout<<"1.Log in."<<endl; cout<<"2.Sign up."<<endl; cout<<"3.Forgot Password."<<endl; } private: void display(Person* p) { if(p->getType() == "c") cMenu(p); if(p->getType() == "e") eMenu(p); if(p->getType() == "v") vMenu(p); if(p->getType() == "p") pMenu(p); } void cMenu(Person* p) { } void eMenu(Person* p) { } void vMenu(Person* p) { } void pMenu(Person* p) { } }; #endif // MENU_H
#include <iostream> #include <string> #include <vector> using namespace std; int main(){ vector<string> song{ "Happy", "birthday", "to", "you", "Happy", "birthday", "to", "you", "Happy", "birthday", "to", "Rujia", "Happy", "birthday", "to", "you"}; vector<string> names(100); int song_index{0}; int name_index{0}; int n{}; cin >> n; for(int i = 0; i < n; ++i){ cin >> names[i]; cout << names[i] << ": " << song[song_index++] << endl; song_index %= song.size(); } if(song_index != 0){ for(int i = song_index; i < song.size(); ++i){ cout << names[name_index++] << ": " << song[i] << endl; name_index %= n; } } return 0; }
// File: Main.cpp // Author: Rionaldi Chandraseta - 13515077 // Written on 2017-03-31 #include <algorithm> #include <chrono> #include <fstream> #include "Matrix.h" #include "RCMatrix.h" #include "CTMatrix.h" int main() { std::chrono::time_point<std::chrono::system_clock> start, end; std::string FileName; std::cout << "Enter the file name: "; std::cin >> FileName; std::string extLess = FileName.substr(0, FileName.size()-3); std::cout << "Checking files..." << "\n"; Path shortestPath; if ((FileName.at(0) == 'r') && (FileName.at(1) == 'c')) { RCMatrix M(FileName); std::cout << "Finished loading data" << "\n" << "\n"; std::cout << "== Travelling Salesman Problem with Reduced Cost Matrix ==" << "\n"; M.getMatrix().write(); std::cout << "\n"; start = std::chrono::system_clock::now(); shortestPath = M.getShortestPath(); end = std::chrono::system_clock::now(); std::cout << "Shortest path: "; int numNode = shortestPath.getPath().size(); for (int i=0; i<numNode; i++) { std::cout << shortestPath.getPath().at(i); if (i<numNode-1) { std::cout << " -> "; } } std::cout << "\n"; std::cout << "Cost = " << shortestPath.getTotalCost() << "\n"; std::cout << "Checked " << M.getNumCheckedNode() << " nodes" << "\n"; std::chrono::duration<double> elapsed_seconds = end-start; std::cout << "Time taken: " << elapsed_seconds.count()*1000 << " ms\n"; // Output .gv std::vector<int> path = shortestPath.getPath(); Matrix G(FileName); path.pop_back(); std::string fullPath = "../usr/graph_" + extLess + ".gv"; std::cout << "GraphViz file generated to " << fullPath << "\n"; std::ofstream oFile; oFile.open(fullPath.c_str()); oFile << "digraph {\n"; oFile << "\tgraph [layout=circo, overlap=scale, splines=true, mindist=2.5]\n"; oFile << "\tnode [shape=circle]\n"; oFile << "\t1 [peripheries=2]\n"; for (int row=1; row<=G.getSize(); row++) { std::ptrdiff_t index = find(path.begin(), path.end(), row) - path.begin(); for (int col=1; col<=G.getSize(); col++) { if (row != col) { oFile << "\t" << row << " -> " << col << " [label=" << G.getDist(row, col); if (index == path.size()-1) { if (path.at(0) == col) { oFile << ", color=red, penwidth=3.0, fontcolor=red]\n"; } else { oFile << "]\n"; } } else { if (path.at(index+1) == col) { oFile << ", color=red, penwidth=3.0, fontcolor=red]\n"; } else { oFile << "]\n"; } } } } } oFile << "}"; oFile.close(); } else if ((FileName.at(0) == 'c') && (FileName.at(1) == 't')) { CTMatrix M(FileName); std::cout << "Finished loading data" << "\n"; std::cout << "== Travelling Salesman Problem with Complete Tour ==" << "\n"; M.getMatrix().write(); std::cout << "\n"; start = std::chrono::system_clock::now(); shortestPath = M.getShortestPath(); end = std::chrono::system_clock::now(); std::cout << "Shortest path: "; int numNode = shortestPath.getPath().size(); for (int i=0; i<numNode; i++) { std::cout << shortestPath.getPath().at(i); if (i<numNode-1) { std::cout << " -> "; } } std::cout << "\n"; std::cout << "Cost = " << shortestPath.getTotalCost() << "\n"; std::cout << "Checked " << M.getNumCheckedNode() << " nodes" << "\n"; std::chrono::duration<double> elapsed_seconds = end-start; std::cout << "Time taken: " << elapsed_seconds.count()*1000 << " ms\n"; // Output .gv std::vector<int> path = shortestPath.getPath(); Matrix G(FileName); path.pop_back(); std::string fullPath = "../usr/graph_" + extLess + ".gv"; std::cout << "GraphViz file generated to " << fullPath << "\n"; std::ofstream oFile; oFile.open(fullPath); oFile << "graph {\n"; oFile << "\tgraph [layout=circo, overlap=scale, splines=true, mindist=2.5]\n"; oFile << "\tnode [shape=circle]\n"; oFile << "\t1 [peripheries=2]\n"; for (int row=1; row<=G.getSize(); row++) { std::ptrdiff_t index = find(path.begin(), path.end(), row) - path.begin(); for (int col=1; col<row; col++) { if (row != col) { oFile << "\t" << row << " -- " << col << " [label=" << G.getDist(row, col); if (index == path.size()-1) { if ((col == path.at(0)) || (col == path.at(index-1))) { oFile << ", color=red, penwidth=3.0, fontcolor=red]\n"; } else { oFile << "]\n"; } } else { if ((path.at(index+1) == col) || (path.at(index-1) == col)) { oFile << ", color=red, penwidth=3.0, fontcolor=red]\n"; } else { oFile << "]\n"; } } } } } oFile << "}"; oFile.close(); } else { std::cout << "File not found!" << "\n"; std::cout << "Exiting program..." << "\n"; } return 0; }
#include <bits/stdc++.h> using namespace std; ofstream fout ("paint.out"); ifstream fin ("paint.in"); int main() { int a,b,c,d; fin >> a>>b>>c>>d; if (b < c || a > d){ fout << (b+d-a-c)<<"\n"; } else{ fout << max(b,d) - min(a,c)<<"\n"; } return 0; }
// // IMService.cpp // MyCppGame // // Created by ๆœ็บข on 2017/1/22. // // #include "IMService.hpp" #include <string> #include <ctime> #include "cocos2d.h" USING_NS_CC; #include "YouMeVoiceEngineImp.hpp" IMService* IMService::_instance = NULL; extern string g_roomName; extern string g_userID; #include "AutoRandTest.hpp" extern IMAutoRandTest* g_imtest ; IMService * IMService::getInstance() { if(NULL == _instance) { _instance = new IMService(); } return _instance; } IMService::~IMService(){ } void IMService::start(){ //YOUME //ๆณจๅ†Œๅ„ไธชๅ›ž่ฐƒไปฃ็†็ฑป YIMManager::CreateInstance()->SetLoginCallback(this); YIMManager::CreateInstance()->SetMessageCallback(this); YIMManager::CreateInstance()->SetChatRoomCallback(this); YIMManager::CreateInstance()->SetDownloadCallback(this); YIMManager::CreateInstance()->SetContactCallback(this); YIMManager::CreateInstance()->SetNoticeCallback( this ); YIMManager::CreateInstance()->SetLocationCallback( this ); //YOUME /*! * ๅˆๅง‹ๅŒ– * @param appKey ็”จๆˆทๆธธๆˆไบงๅ“ๅŒบๅˆซไบŽๅ…ถๅฎƒๆธธๆˆไบงๅ“็š„ๆ ‡่ฏ†๏ผŒๅฏไปฅๅœจๆธธๅฏ†ๅฎ˜็ฝ‘่Žทๅ–ใ€ๆŸฅ็œ‹ * @param appSecurity ็”จๆˆทๆธธๆˆไบงๅ“็š„ๅฏ†้’ฅ๏ผŒๅฏไปฅๅœจๆธธๅฏ†ๅฎ˜็ฝ‘่Žทๅ–ใ€ๆŸฅ็œ‹ * @param packageName ็›ฎๅ‰ๅกซ""ๅฐฑๅฅฝ * @return ้”™่ฏฏ็  */ YIMErrorcode ymErrorcode = YIMManager::CreateInstance()->Init("YOUMEBC2B3171A7A165DC10918A7B50A4B939F2A187D0", "r1+ih9rvMEDD3jUoU+nj8C7VljQr7Tuk4TtcByIdyAqjdl5lhlESU0D+SoRZ30sopoaOBg9EsiIMdc8R16WpJPNwLYx2WDT5hI/HsLl1NJjQfa9ZPuz7c/xVb8GHJlMf/wtmuog3bHCpuninqsm3DRWiZZugBTEj2ryrhK7oZncBAAE=", ""); if(ymErrorcode != YIMErrorcode_Success) { YouMe_Log("ๅˆๅง‹ๅŒ–ๅคฑ่ดฅ๏ผŒ้”™่ฏฏ็ ๏ผš%d\n", ymErrorcode); } else{ YouMe_Log("ๅˆๅง‹ๅŒ–ๆˆๅŠŸ!\n"); } } void IMService::OnLogin(YIMErrorcode errorcode, const XString& userID){ YouMe_Log("็™ปๅฝ•ๅ›ž่ฐƒ๏ผš%d\n", errorcode ); if( errorcode != 0 ){ return ; } //็™ป้™†ๆˆๅŠŸๅŽ๏ผŒ่ฟ›ๅ…ฅๆˆฟ้—ด /*! * ๅŠ ๅ…ฅ่Šๅคฉ้ข‘้“ * @param roomID ้ข‘้“ID * @return ้”™่ฏฏ็  */ // YIMErrorcode ymErrorcode; // ymErrorcode = YIMManager::CreateInstance()->GetChatRoomManager()->JoinChatRoom( g_roomName.c_str() ); // if(ymErrorcode != YIMErrorcode_Success) // { // YouMe_Log("่ฟ›ๅ…ฅ่Šๅคฉ้ข‘้“ๅคฑ่ดฅ๏ผŒ้”™่ฏฏ็ ๏ผš%d\n", ymErrorcode); // } // else{ // YouMe_Log("่ฟ›ๅ…ฅ่Šๅคฉ้ข‘้“ๆˆๅŠŸ!\n"); // } } //็™ปๅ‡บๅ›ž่ฐƒ void IMService::OnLogout(YIMErrorcode errorcode){ YouMe_Log("็™ปๅ‡บๅ›ž่ฐƒ๏ผš%d\n", errorcode ); } //่ขซ่ธขไธ‹็บฟ void IMService::OnKickOff(){ YouMe_Log("่ขซ่ธขไธ‹็บฟ้€š็Ÿฅ\n" ); } void IMService::OnSendMessageStatus(XUINT64 requestID, YIMErrorcode errorcode, bool isForbidRoom, int reasonType, XUINT64 forbidEndTime ){ YouMe_Log("ๅ‘้€ๆถˆๆฏๅ›ž่ฐƒ๏ผŒ่ฏทๆฑ‚ID๏ผš%llu,้”™่ฏฏ็ ๏ผš%d\n",requestID, errorcode ); } //ๅ‘้€่ฏญ้Ÿณๆถˆๆฏๅ›ž่ฐƒ void IMService::OnSendAudioMessageStatus(XUINT64 requestID, YIMErrorcode errorcode, const XString& text, const XString& audioPath, unsigned int audioTime, bool isForbidRoom, int reasonType, XUINT64 forbidEndTime ){ YouMe_Log("ๅ‘้€่ฏญ้Ÿณๆถˆๆฏๅ›ž่ฐƒ๏ผŒ่ฏทๆฑ‚ID๏ผš%llu,้”™่ฏฏ็ ๏ผš%d\n",requestID, errorcode ); //YIMErrorcode_PTT_ReachMaxDuration๏ผŒๅ‘้€่ฏญ้Ÿณๆœ‰ๆ—ถ้•ฟ้™ๅˆถ๏ผŒ่ถ…้•ฟๆ—ถไผš่‡ชๅŠจๅ‘ๆถˆๆฏ๏ผŒๆญคๆ—ถ้”™่ฏฏ็ ๆ˜ฏReachMaxDuration if( errorcode == YIMErrorcode_Success || errorcode == YIMErrorcode_PTT_ReachMaxDuration ){ EventCustom evtVoice("SendVoice"); Msg* msg = new Msg(); msg->sender = g_userID ; msg->bSelf = true ; msg->createTime = time(NULL); msg->bTxt = false; msg->voicePath = audioPath; msg->content = text; msg->voiceLen = audioTime; evtVoice.setUserData( msg ); Director::getInstance()->getEventDispatcher()->dispatchEvent(&evtVoice); } } //ๆ”ถๅˆฐๆถˆๆฏ void IMService::OnRecvMessage(std::shared_ptr<IYIMMessage> message){ YouMe_Log("ๆ”ถๅˆฐๆถˆๆฏๅ›ž่ฐƒ\n"); YIMMessageBodyType msgType = message->GetMessageBody()->GetMessageType(); if( msgType == YIMMessageBodyType::MessageBodyType_TXT ){ IYIMMessageBodyText* pMsgText = (IYIMMessageBodyText*)message->GetMessageBody(); YouMe_Log("ๆ”ถๅˆฐๆ–‡ๆœฌๆถˆๆฏ๏ผš %s๏ผŒๅ‘้€่€…๏ผš%s, ๆŽฅๅ—่€…๏ผš%s", pMsgText->GetMessageContent(), message->GetReceiveID(), message->GetSenderID() ); EventCustom evtText("RecvText"); Msg* msg = new Msg(); msg->msgID = message->GetMessageID(); msg->sender = message->GetSenderID(); msg->bSelf = false; msg->createTime = message->GetCreateTime(); msg->bTxt = true; msg->content = pMsgText->GetMessageContent(); evtText.setUserData( msg ); Director::getInstance()->getEventDispatcher()->dispatchEvent(&evtText); } else if ( msgType == YIMMessageBodyType::MessageBodyType_Voice ){ IYIMMessageBodyAudio* pMsgVoice = (IYIMMessageBodyAudio*)message->GetMessageBody(); YouMe_Log("ๆ”ถๅˆฐ่ฏญ้Ÿณๆถˆๆฏ๏ผŒๆ–‡ๆœฌๅ†…ๅฎน๏ผš %s, ๆถˆๆฏID๏ผš %llu, ้™„ๅŠ ๅ‚ๆ•ฐ๏ผš %s ,่ฏญ้Ÿณๆ—ถ้•ฟ๏ผš %d\n", pMsgVoice->GetText(), message->GetMessageID(), pMsgVoice->GetExtraParam(), pMsgVoice->GetAudioTime() ); //ไธ‹่ฝฝ่ฏญ้Ÿณๆ–‡ไปถ // stringstream fileS; // fileS<<strTempDir<<message->GetMessageID()<<".wav"; // std::string file = fileS.str(); // YIMManager::CreateInstance()->GetMessageManager()->DownloadFile( message->GetMessageID(), file.c_str() ); std::lock_guard< mutex > lock( g_imtest->m_paramMutex ); g_imtest->m_recvMessageID = message->GetMessageID(); // //้€š็Ÿฅๅœบๆ™ฏ // EventCustom evtVoice("RecvVoice"); // Msg* msg = new Msg(); // msg->msgID = message->GetMessageID(); // msg->sender = message->GetSenderID(); // msg->bSelf = false ; // msg->createTime = message->GetCreateTime(); // msg->bTxt = false; // msg->voicePath = file.c_str(); // msg->content = pMsgVoice->GetText(); // msg->voiceLen = pMsgVoice->GetAudioTime(); // evtVoice.setUserData( msg ); // Director::getInstance()->getEventDispatcher()->dispatchEvent(&evtVoice); } } void IMService::OnQueryRoomHistoryMessage(YIMErrorcode errorcode, std::list<std::shared_ptr<IYIMMessage> > messageList){ //ๆš‚ๆ—ถไธ้œ€่ฆ๏ผŒๆ‰€ไปฅๆฒกๅค„็† } #include <iostream> using namespace std; void IMService::OnStopAudioSpeechStatus(YIMErrorcode errorcode, std::shared_ptr<IAudioSpeechInfo> audioSpeechInfo){ if( errorcode == 0 ){ cout<<"id:"<<audioSpeechInfo->GetRequestID()<<endl; cout<<"text:"<<audioSpeechInfo->GetText()<<endl; cout<<"time:"<<audioSpeechInfo->GetAudioTime()<<endl; cout<<"url:"<<audioSpeechInfo->GetDownloadURL()<<endl; } std::lock_guard< mutex > lock( g_imtest->m_paramMutex ); g_imtest->m_url = audioSpeechInfo->GetDownloadURL(); // //ไธ‹่ฝฝ่ฏญ้Ÿณๆ–‡ไปถ // stringstream fileS; // fileS<<strTempDir<<audioSpeechInfo->GetRequestID()<<".wav"; // std::string file = fileS.str(); // YIMManager::CreateInstance()->GetMessageManager()->DownloadFile( audioSpeechInfo->GetDownloadURL(), file.c_str() ); } void IMService::OnReceiveMessageNotify(YIMChatType chatType, const XString& targetID){ //ๆš‚ๆ—ถไธ้œ€่ฆ๏ผŒๆ‰€ไปฅๆฒกๅค„็† } void IMService::OnQueryHistoryMessage(YIMErrorcode errorcode, const XString& targetID, int remain, std::list<std::shared_ptr<IYIMMessage> > messageList){ //ๆš‚ๆ—ถไธ้œ€่ฆ๏ผŒๆ‰€ไปฅๆฒกๅค„็† } //ๅŠ ๅ…ฅ้ข‘้“ๅ›ž่ฐƒ void IMService::OnJoinChatRoom(YIMErrorcode errorcode, const XString& chatRoomID){ YouMe_Log("่ฟ›ๅ…ฅ่Šๅคฉ้ข‘้“ๅ›ž่ฐƒ\n"); if( errorcode == YIMErrorcode_Success ){ YouMe_Log("่ฟ›ๅ…ฅ่Šๅคฉ้ข‘้“ %s ๆˆๅŠŸ \n", chatRoomID.c_str() ); } else{ YouMe_Log("่ฟ›ๅ…ฅ่Šๅคฉ้ข‘้“ %s ๅคฑ่ดฅ, ้”™่ฏฏ็ ๏ผš %d \n", chatRoomID.c_str(), errorcode ); } } //็ฆปๅผ€้ข‘้“ๅ›ž่ฐƒ void IMService::OnLeaveChatRoom(YIMErrorcode errorcode, const XString& chatRoomID){ YouMe_Log("็ฆปๅผ€่Šๅคฉ้ข‘้“ๅ›ž่ฐƒ\n"); if( errorcode == YIMErrorcode_Success ){ YouMe_Log("็ฆปๅผ€่Šๅคฉ้ข‘้“ %s ๆˆๅŠŸ ", chatRoomID.c_str() ); } else{ YouMe_Log("็ฆปๅผ€่Šๅคฉ้ข‘้“ %s ๅคฑ่ดฅ, ้”™่ฏฏ็  ๏ผš %d\n ", chatRoomID.c_str(), errorcode ); } } void IMService::OnDownload( YIMErrorcode errorcode, std::shared_ptr<IYIMMessage> message, const XString& savePath ){ YouMe_Log("ไธ‹่ฝฝๆ–‡ไปถๅ›ž่ฐƒ\n" ); if( errorcode == YIMErrorcode_Success ){ YouMe_Log("ไธ‹่ฝฝๆ–‡ไปถ %s ๆˆๅŠŸ \n", savePath.c_str() ); IYIMMessageBodyAudio* pMsgVoice = (IYIMMessageBodyAudio*)message->GetMessageBody(); YouMe_Log("ๆ”ถๅˆฐ่ฏญ้Ÿณๆถˆๆฏ๏ผŒๆ–‡ๆœฌๅ†…ๅฎน๏ผš %s, ๆถˆๆฏID๏ผš %llu, ้™„ๅŠ ๅ‚ๆ•ฐ๏ผš %s ,่ฏญ้Ÿณๆ—ถ้•ฟ๏ผš %d\n", pMsgVoice->GetText(), message->GetMessageID(), pMsgVoice->GetExtraParam(), pMsgVoice->GetAudioTime() ); //้€š็Ÿฅๅœบๆ™ฏ EventCustom evtDownloadOK("DownloadOK"); Msg* msg = new Msg(); msg->msgID = message->GetMessageID(); msg->sender = message->GetSenderID(); msg->bSelf = false ; msg->createTime = message->GetCreateTime(); msg->bTxt = false; msg->voicePath = savePath.c_str(); msg->content = pMsgVoice->GetText(); msg->voiceLen = pMsgVoice->GetAudioTime(); evtDownloadOK.setUserData( msg ); Director::getInstance()->getEventDispatcher()->dispatchEvent( &evtDownloadOK ); } else{ YouMe_Log("ไธ‹่ฝฝๆ–‡ไปถ %s ๅคฑ่ดฅ, error = %d \n ", savePath.c_str(), errorcode ); } } void IMService::OnDownloadByUrl( YIMErrorcode errorcode, const XString& strFromUrl, const XString& savePath ){ YouMe_Log("ไธ‹่ฝฝๆ–‡ไปถๅ›ž่ฐƒ,err:%d, url:%s\n", errorcode, strFromUrl.c_str() ); YouMe_Log("ไธ‹่ฝฝๆ–‡ไปถๅ›ž่ฐƒ,path:%s\n", savePath.c_str() ); } //่Žทๅ–ๆœ€่ฟ‘่”็ณปไบบๅ›ž่ฐƒ void IMService::OnGetRecentContacts(YIMErrorcode errorcode, std::list<XString>& contactList){ //ๆš‚ๆ—ถไธ้œ€่ฆ๏ผŒๆ‰€ไปฅๆฒกๅค„็† } //่Žทๅ–็”จๆˆทไฟกๆฏๅ›ž่ฐƒ(็”จๆˆทไฟกๆฏไธบJSONๆ ผๅผ) void IMService::OnGetUserInfo(YIMErrorcode errorcode, const XString& userID, const XString& userInfo){ //ๆš‚ๆ—ถไธ้œ€่ฆ๏ผŒๆ‰€ไปฅๆฒกๅค„็† } void IMService::OnUserJoinChatRoom(const XString& chatRoomID, const XString& userID) { } //ๅ…ถไป–็”จๆˆท้€€ๅ‡บ้ข‘้“้€š็Ÿฅ void IMService::OnUserLeaveChatRoom(const XString& chatRoomID, const XString& userID) { } void IMService::OnAccusationResultNotify(AccusationDealResult result, const XString& userID, unsigned int accusationTime) { }
/* * Kimura * * Copyright (c) 2009-2010 Chris Barber <chris@cb1inc.com> * All rights reserved. * * Use and distribution licensed under the BSD license. See the * COPYING file in the root project directory for full text. */
/***************************************************************************************************************** * File Name : linearprobing.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\tutorials\nptel\DSAndAlgo\lecture05\linearprobing.h * Created on : Dec 30, 2013 :: 11:59:03 AM * Author : AVINASH * Testing Status : TODO * URL : TODO *****************************************************************************************************************/ /************************************************ Namespaces ****************************************************/ using namespace std; using namespace __gnu_cxx; /************************************************ User Includes *************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <programming/ds/tree.h> #include <programming/ds/linkedlist.h> #include <programming/utils/treeutils.h> #include <programming/utils/llutils.h> /************************************************ User defined constants *******************************************/ #define null NULL #define SIZE_OF_HASH_MAP 20 #define DELETION_MARKER INT_MIN #define EMPTY_MARKER INT_MAX /************************************************* Main code ******************************************************/ #ifndef LINEARPROBING_H_ #define LINEARPROBING_H_ unsigned int hashmap[SIZE_OF_HASH_MAP] = {EMPTY_MARKER}; unsigned int current_size = 0; unsigned int getHashcode(unsigned int key){ return key % SIZE_OF_HASH_MAP; } void insertIntoHashmap(unsigned int userInput){ if(current_size == SIZE_OF_HASH_MAP){ printf("Hash map is full"); return; } unsigned int hashcode = getHashcode(userInput); while(hashmap[hashcode] != EMPTY_MARKER){ hashcode = (hashcode + 1)%SIZE_OF_HASH_MAP; } hashmap[hashcode] = userInput; current_size++; } bool searchForNodeHashmap(unsigned int userInput){ unsigned int hashcode = getHashcode(userInput); unsigned int counter = 0; while(hashmap[hashcode] != userInput && hashmap[hashcode] == EMPTY_MARKER && counter != SIZE_OF_HASH_MAP){ hashcode += 1; counter++; } if(hashmap[hashcode] == userInput){ return true; } return false; } unsigned int getHashCodeFromHashmap(unsigned int userInput){ unsigned int hashcode = getHashcode(userInput); unsigned int counter = 0; while(hashmap[hashcode] != userInput && hashmap[hashcode] == EMPTY_MARKER && counter != SIZE_OF_HASH_MAP){ hashcode += 1; counter++; } if(hashmap[hashcode] == userInput){ return hashcode; } return UINT_MAX; } void deleteFromHashmap(unsigned int userInput){ unsigned int hashcode = getHashCodeFromHashmap(userInput); if(hashcode != UINT_MAX){ hashmap[hashcode] = DELETION_MARKER; } } #endif /* LINEARPROBING_H_ */ /************************************************* End code *******************************************************/
#pragma once #include "Vector.h" #include "Value.h" class GC; class Array { void append(Array *a) { append(a->buf(), a->size()); } void append(char *s, int size); static Array *alloc(GC *gc, Vector<Value> *vect); public: Vector<Value> vect; static Value sizeField(VM *vm, int op, void *data, Value *stack, int nArgs); Array(int iniSize = 0); ~Array(); static Array *alloc(GC *gc, int iniSize = 0); void traverse(GC *gc); Value getI(int pos); void setI(int pos, Value val); Value indexGet(Value pos); bool indexSet(Value pos, Value v); Value getSliceV(GC *gc, Value pos1, Value pos2); Value getSliceI(GC *gc, int pos1, int pos2); void setSliceV(Value pos1, Value pos2, Value v); void setSliceI(int pos1, int pos2, Value v); void append(Value *buf, int size) { vect.append(buf, size); } void push(Value val) { vect.push(val); } unsigned size() { return vect.size(); } void setSize(unsigned sz); Value *buf() { return vect.buf(); } void add(Value v); bool equals(Array *a); bool lessThan(Array *a); Array *copy(GC *gc) { return alloc(gc, &vect); } };
// kumaran_14 // #include <boost/multiprecision/cpp_int.hpp> // using boost::multiprecision::cpp_int; #include <bits/stdc++.h> using namespace std; // ยฏ\_(ใƒ„)_/ยฏ #define f first #define s second #define p push #define mp make_pair #define pb push_back #define eb emplace_back #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define foi(i, a, n) for (i = (a); i < (n); ++i) #define foii(i, a, n) for (i = (a); i <= (n); ++i) #define fod(i, a, n) for (i = (a); i > (n); --i) #define fodd(i, a, n) for (i = (a); i >= (n); --i) #define debug(x) cout << '>' << #x << ':' << x << endl; #define all(v) v.begin(), v.end() #define sz(x) ((int)(x).size()) #define endl " \n" #define MAXN 100005 #define MOD 1000000007LL #define EPS 1e-13 #define INFI 1000000000 // 10^9 #define INFLL 1000000000000000000ll //10^18 // ยฏ\_(ใƒ„)_/ยฏ #define l long int #define d double #define ll long long int #define ld long double #define vi vector<int> #define vll vector<long long> #define vvi vector<vector<int>> #define vvll vector<vll> //vector<vector<int>> v(10, vector<int>(20,500)); 2d vector initialization. of 10 rows and 20 columns, with value 500. #define mii map<int, int> #define mll map<long long, long long> #define pii pair<int, int> #define pll pair<long long, long long> #define fast_io() \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); ll tc, n, m, k; // ll ans = 0, c = 0; ll i, j; // ll a, b; // ll x, y; // O(n^2) void LIS_1(ll pp) { ll ans = INT_MIN; cin>>n; vll arr(n+1, 0); foi(i, 0, n) cin>>arr[i]; // max sum decreasing subsequence starting from left to right vll dp1(n+1, 0), dp2(n+1, 0); dp1[n-1] = arr[n-1]; fodd(i, n-2, 0) { foi(j, i+1, n) { if(arr[i] > arr[j]) { dp1[i] = max(dp1[i], arr[i] + dp1[j]); } } dp1[i] = max(dp1[i], arr[i]); } // max sum increasing subsequence starting from left to right dp2[0] = arr[0]; foi(i, 1, n) { foi(j, 0, i) { if(arr[i] > arr[j]) { dp2[i] = max(dp2[i], arr[i] + dp2[j]); } } dp2[i] = max(dp2[i], arr[i]); } foi(i, 0, n) ans = max(ans, dp1[i] + dp2[i] - arr[i]); cout<<ans<<endl; } // longest bitonic subsequence using two lis. void LIS_2() { vll dpi(n, 0), dpd(n, 0); dpi[0] = 1; dpd[n-1] = 1; vll nums(n, 0); rep(i, 0, n) cin>>nums[i]; rep(i, 1, n) { ll mx = 0; rep(j, 0, i) if(nums[j] < nums[i]) mx = max(mx, dpi[j]); dpi[i] += mx + 1; } rep(i, n-1, 0) { ll mx = 0; rep(j, n, i+1) if(nums[j] < nums[i]) mx = max(mx, dpd[j]); dpd[i] += mx + 1; } // rep(i, 0, n) cout<<dpi[i]<<endl[i==n-1]; // rep(i, 0, n) cout<<dpd[i]<<endl[i==n-1]; ll ans = INT_MIN; rep(i, 0, n) ans = max(ans, dpi[i] + dpd[i] - 1); cout<<ans<<endl; } int main() { fast_io(); freopen("./input.txt", "r", stdin); freopen("./output.txt", "w", stdout); cin>>tc; while(tc--) { LIS_1(tc); } return 0; } /* 2 6 80 60 30 40 20 10 9 1 15 51 45 33 100 12 18 9 */
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <quic/api/QuicStreamAsyncTransport.h> #include <quic/client/QuicClientTransport.h> namespace quic { /** * Adaptor from QuicClientTransport to folly::AsyncTransport, * for experiments with QUIC in code using folly::AsyncSockets. */ class QuicClientAsyncTransport : public QuicStreamAsyncTransport, public QuicSocket::ConnectionSetupCallback, public QuicSocket::ConnectionCallback { public: using UniquePtr = std::unique_ptr< QuicClientAsyncTransport, folly::DelayedDestruction::Destructor>; explicit QuicClientAsyncTransport( const std::shared_ptr<QuicClientTransport>& clientSock); protected: ~QuicClientAsyncTransport() override; // // QuicSocket::ConnectionCallback // void onNewBidirectionalStream(StreamId id) noexcept override; void onNewUnidirectionalStream(StreamId id) noexcept override; void onStopSending(StreamId id, ApplicationErrorCode error) noexcept override; void onConnectionEnd() noexcept override; void onConnectionSetupError(QuicError code) noexcept override { onConnectionError(std::move(code)); } void onConnectionError(QuicError code) noexcept override; void onConnectionEnd(QuicError /* error */) noexcept override {} void onTransportReady() noexcept override; }; } // namespace quic
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; const string st[7] = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}; int main() { string a,b; cin >> a >> b; int x,y; for (int i = 0;i < 7; i++) if (a == st[i]) {x = i;break;} for (int i = 0;i < 7; i++) if (b == st[i]) {y = i;break;} x = (y+7-x)%7; if (x == 0 || x == 2 || x == 3) puts("YES"); else puts("NO"); return 0; }
// Created on: 1995-12-01 // Created by: EXPRESS->CDL V0.2 Translator // 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 _StepGeom_SurfaceCurve_HeaderFile #define _StepGeom_SurfaceCurve_HeaderFile #include <Standard.hxx> #include <StepGeom_HArray1OfPcurveOrSurface.hxx> #include <StepGeom_PreferredSurfaceCurveRepresentation.hxx> #include <StepGeom_Curve.hxx> #include <Standard_Integer.hxx> class TCollection_HAsciiString; class StepGeom_PcurveOrSurface; class StepGeom_SurfaceCurve; DEFINE_STANDARD_HANDLE(StepGeom_SurfaceCurve, StepGeom_Curve) class StepGeom_SurfaceCurve : public StepGeom_Curve { public: //! Returns a SurfaceCurve Standard_EXPORT StepGeom_SurfaceCurve(); Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aName, const Handle(StepGeom_Curve)& aCurve3d, const Handle(StepGeom_HArray1OfPcurveOrSurface)& aAssociatedGeometry, const StepGeom_PreferredSurfaceCurveRepresentation aMasterRepresentation); Standard_EXPORT void SetCurve3d (const Handle(StepGeom_Curve)& aCurve3d); Standard_EXPORT Handle(StepGeom_Curve) Curve3d() const; Standard_EXPORT void SetAssociatedGeometry (const Handle(StepGeom_HArray1OfPcurveOrSurface)& aAssociatedGeometry); Standard_EXPORT Handle(StepGeom_HArray1OfPcurveOrSurface) AssociatedGeometry() const; Standard_EXPORT StepGeom_PcurveOrSurface AssociatedGeometryValue (const Standard_Integer num) const; Standard_EXPORT Standard_Integer NbAssociatedGeometry() const; Standard_EXPORT void SetMasterRepresentation (const StepGeom_PreferredSurfaceCurveRepresentation aMasterRepresentation); Standard_EXPORT StepGeom_PreferredSurfaceCurveRepresentation MasterRepresentation() const; DEFINE_STANDARD_RTTIEXT(StepGeom_SurfaceCurve,StepGeom_Curve) protected: private: Handle(StepGeom_Curve) curve3d; Handle(StepGeom_HArray1OfPcurveOrSurface) associatedGeometry; StepGeom_PreferredSurfaceCurveRepresentation masterRepresentation; }; #endif // _StepGeom_SurfaceCurve_HeaderFile
๏ปฟ#ifndef _CCHECK_MNICK_h_ #define _CCHECK_MNICK_h_ #include <string> #include "CHttpRequestHandler.h" class CCheckMnick : public CHttpRequestHandler { public: CCheckMnick(){} ~CCheckMnick(){} virtual int do_request(const Json::Value& root, char *client_ip, HttpResult& out); }; #endif
#ifndef PGTOOLS_SIMPLEPGMATCHER_H #define PGTOOLS_SIMPLEPGMATCHER_H #include "../pseudogenome/PseudoGenomeBase.h" #include "../pseudogenome/readslist/SeparatedExtendedReadsList.h" #include "TextMatchers.h" namespace PgTools { using namespace PgSAIndex; struct PgMatch; class SimplePgMatcher { private: uint32_t targetMatchLength; TextMatcher* matcher = 0; const string& srcPg; uint64_t destPgLength; vector<TextMatch> textMatches; bool revComplMatching; void exactMatchPg(string& destPg, bool destPgIsSrcPg, uint32_t minMatchLength); void correctDestPositionDueToRevComplMatching(); void resolveMappingCollisionsInTheSameText(); string getTotalMatchStat(uint_pg_len_max totalMatchLength); static void compressPgSequence(ostream &pgrcOut, string &pgSequence, uint8_t coder_level, bool noNPgSequence, bool testAndValidation = false); public: SimplePgMatcher(const string& srcPg, uint32_t targetMatchLength, uint32_t minMatchLength = UINT32_MAX); virtual ~SimplePgMatcher(); void markAndRemoveExactMatches(bool destPgIsSrcPg, string &destPg, string &resPgMapOff, string& resPgMapLen, bool revComplMatching, uint32_t minMatchLength = UINT32_MAX); static void matchPgsInPg(string &hqPgSequence, string &lqPgSequence, string &nPgSequence, bool separateNReads, ostream &pgrcOut, uint8_t coder_level, const string &hqPgPrefix, const string &lqPgPrefix, const string &nPgPrefix, uint_pg_len_max targetMatchLength, uint32_t minMatchLength = UINT32_MAX); static void restoreMatchedPgs(istream &pgrcIn, uint_pg_len_max orgHqPgLen, string &hqPgSequence, string &lqPgSequence, string &nPgSequence); static string restoreMatchedPg(string &srcPg, size_t orgSrcLen, const string& destPg, istream &pgMapOffSrc, istream &pgMapLenSrc, bool revComplMatching, bool plainTextReadMode, bool srcIsDest = false); static string restoreMatchedPg(string &srcPg, const string& destPgPrefix, bool revComplMatching, bool plainTextReadMode); static string restoreAutoMatchedPg(const string &pgPrefix, bool revComplMatching); static void writeMatchingResult(const string &pgPrefix, const string &pgMapped, const string &pgMapOff, const string& pgMapLen); static char MATCH_MARK; }; } #endif //PGTOOLS_SIMPLEPGMATCHER_H
/**************************************************************************** ** Copyright (C) 2017 Olaf Japp ** ** This file is part of FlatSiteBuilder. ** ** FlatSiteBuilder 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. ** ** FlatSiteBuilder is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with FlatSiteBuilder. If not, see <http://www.gnu.org/licenses/>. ** ****************************************************************************/ #ifndef SECTIONPROPERTYEDITOR_H #define SECTIONPROPERTYEDITOR_H #include <QLineEdit> #include <QGridLayout> #include <QCheckBox> #include "interfaces.h" #include "animateableeditor.h" class QXmlStreamReader; class SectionPropertyEditor : public AnimateableEditor { Q_OBJECT public: SectionPropertyEditor(); void setContent(QString content); static QString getHtml(QXmlStreamReader *xml, QString filename); public slots: void closeEditor() override; private: QLineEdit *m_cssclass; QLineEdit *m_style; QLineEdit *m_attributes; QLineEdit *m_id; QGridLayout *m_grid; bool m_fullwidth; }; #endif // SECTIONPROPERTYEDITOR_H
class OsVersionChecker { public: bool IsOS(AnsiString szOsName); AnsiString GetSystemVersion(void); }; class SystemSoftware { private: public: // OSInfo OS; // SystemSoftware(); // ~SystemSoftware(); };
// MFCApplication1Dlg.cpp : implementation file // #include "stdafx.h" #include "MFCApplication1.h" #include "MFCApplication1Dlg.h" #include "afxdialogex.h" //#include <shellapi.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // CMFCApplication1Dlg dialog CMFCApplication1Dlg::CMFCApplication1Dlg(CWnd* pParent /*=NULL*/) : CDialogEx(CMFCApplication1Dlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CMFCApplication1Dlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CMFCApplication1Dlg, CDialogEx) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, &CMFCApplication1Dlg::OnBnClickedButton1) END_MESSAGE_MAP() // CMFCApplication1Dlg message handlers BOOL CMFCApplication1Dlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMFCApplication1Dlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMFCApplication1Dlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } /* HINSTANCE ShellExecuteW( HWND hwnd, LPCTSTR lpOperation, LPCTSTR lpFile, LPCTSTR lpParameters, LPCTSTR lpDirectory, INT nShowCmd ); */ void CMFCApplication1Dlg::OnBnClickedButton1() { ShowWindow(SW_HIDE); // ็‚นๅ‡ปๅฎŒๅŽ้š่—ๆญคๅฏน่ฏๆก† FILE *fp = fopen("voice\\temp.vbs", "a"); //FILE *fp2 = fopen("1.vbs", "r"); FILE *fp4 = fopen("voice\\temp.bat", "a"); char* s = "CreateObject(\"SAPI.SpVoice\").Speak(\""; char* s4 = "@echo off\ntype voice\\*.txt >>voice\\temp.vbs\necho \^\"\^\) >>voice\\temp.vbs\nvoice\\temp.vbs\ndel voice\\temp.vbs\ndel voice\\temp.bat\n"; //char* s2 = "\")"; //char* s3 = "\@echo off\n"; //char txt[500]; //char buf[500]; //fputs(s3, fp); fputs(s, fp); fclose(fp); //fgets(buf, 500, fp2); //strcat(txt, buf); //fputs(txt, fp); fclose(fp); fputs(s4, fp4); fclose(fp4); //system("temp.bat"); WinExec("voice\\temp.bat", SW_HIDE); //WinExec(cmd, SW_HIDE); //WinExec(cmd.c_str(), SW_HIDE); //system("type 1.txt >>temp.vbs"); //system("echo \^\"\^\) >>temp.vbs"); //ShellExecuteA(NULL,"open","temp.bat",NULL,NULL,SW_HIDE); //fseek(fp, 0, SEEK_SET); //fwrite(s, strlen(s), 1, fp); //system("echo \"^) >> temp.txt"); //system("exit"); //fprintf(fp, "%s\")", *fp2); //fopen("temp.txt", "w"); //fseek(fp, 0, 0); //fwrite(s2, strlen(s2),1,fp); //system("echo off"); //ShellExecuteA(NULL, "open", "temp.vbs", NULL, NULL, SW_HIDE); //system("temp.vbs"); //system("del temp.vbs"); //Sleep(500); exit(0); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2003 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef MAILSTOREUPDATEDIALOG_H #define MAILSTOREUPDATEDIALOG_H #ifdef M2_SUPPORT #ifdef M2_MERLIN_COMPATIBILITY #include "adjunct/quick_toolkit/widgets/Dialog.h" #include "adjunct/m2/src/engine/store/storeupdater.h" class ProgressInfo; class MailStoreUpdateDialog : public Dialog, public StoreUpdateListener { public: MailStoreUpdateDialog(); ~MailStoreUpdateDialog(); Type GetType() {return DIALOG_TYPE_REINDEX_MAIL;} const char* GetWindowName() {return "Mail Store Update Dialog";} BOOL GetModality() {return FALSE;} const uni_char* GetOkText(); void OnInit(); void OnCancel(); BOOL OnInputAction(OpInputAction* action); // From StoreUpdateListener void OnStoreUpdateProgressChanged(int progress, int total); private: OpString m_ok_text; BOOL m_paused; double m_start_tick; INT32 m_start_progress; StoreUpdater m_store_updater; }; #endif // M2_MERLIN_COMPATIBILITY #endif // M2_SUPPORT #endif // MAILSTOREUPDATEDIALOG_H
#include<bits/stdc++.h> using namespace std; main() { char main_string[1000], reserve[1000], output_string[1000]; int i, j; while(gets(main_string)) { int len1 = strlen(main_string); int pos = 0, k = 0; for(i=0; i<=len1; i++) { if(main_string[i]!= 32 && i<len1) { reserve[pos] = main_string[i]; pos++; } else if(main_string[i]==32 || i==len1) { reserve[pos] = '\0'; // cout<<reserve<<endl; int len2 = strlen(reserve); for(j=len2-1; j>=0; j--) { output_string[k] = reserve[j]; k++; } pos =0; output_string[k] = 32; k++; } } output_string[k-1] = '\0'; cout<<output_string<<endl; } return 0; }
//--------------------------------------------------------------------------- #ifndef udpsocketH #define udpsocketH #include <vcl.h> #include <winsock.h> #include "CommFunc.h" //udp socketๅฏน่ฑก,ๅณๆ˜ฏๅฎขๆˆท็ซฏๅˆๆ˜ฏๆœๅŠกๅ™จ็ซฏ typedef void __fastcall (__closure *TOnUDPError)(int ErrorCode,const String &ErrorInfo); typedef void __fastcall (__closure *TOnUDPRead)(char * SenderIP,char * Data,int Len); class CUDPSocket { private: WORD Port; WSADATA wsd; SOCKET ServerSocket; SOCKET ClientSocket; SOCKADDR_IN Sender; SOCKADDR_IN Local; bool CreateSocket(); bool InitClientSocket(); bool Active; int SYSRecvBuffer; //็ณป็ปŸๆŽฅๆ”ถ็ผ“ๅ†ฒๅŒบๅ•ไฝKB protected: void ShowError(int ErrorCode,const String &Info); static DWORD WINAPI RecvThreadFunc(LPVOID Parameter); //ๆŽฅๆ”ถๅฐๅŒ…็บฟ็จ‹ๅ‡ฝๆ•ฐ public: CUDPSocket(); ~CUDPSocket(); void Open(); void Stop(); bool IsActive(){return Active;} void SetPort(WORD _Port){Port = _Port;} int __fastcall SendData(String DesIP,WORD DesPort,char * Data,int Len); void SetRecvBufSize(int KBSize){SYSRecvBuffer = KBSize*1024;} //็ณป็ปŸๆŽฅๆ”ถ็ผ“ๅ†ฒๅŒบๅ•ไฝKB //ๅ›ž่ฐƒ้€š็ŸฅๆŽฅๅฃ TOnUDPError OnError; TOnUDPRead OnRead; //OnReadๆ˜ฏๅœจ็บฟ็จ‹ไธญ่ฟ่กŒ,่ฏทๆณจๆ„ไปฃ็ ็š„็บฟ็จ‹ๅฎ‰ๅ…จไฟๆŠค }; //--------------------------------------------------------------------------- #endif
//ใ‚ใ‹ใ‚‰ใชใ‹ใฃใŸๅ•้กŒใฎ่งฃ่ชฌใ‚’ใฒใจใคใšใคใ‹ใฟ็ •ใ„ใŸ int main(void) { int h, w; cin >> h >> w; string board[50]; for (int i = 0; i < h; ++i) cin >> board[i]; const int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1}; const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1}; //ใใ‚Œใžใ‚Œใ‚‚ใจใซใชใ‚‹ใƒžใ‚นใ‹ใ‚‰ไธŠไธ‹ๅทฆๅณๆ–œใ‚ใซ1ใƒžใ‚นใšใ‚ŒใŸๅบงๆจ™ for (int i = 0; i < h; ++i) { // iๅ›ž็นฐใ‚Š่ฟ”ใ™๏ผˆ็ธฆ่ปธ๏ผ‰ for (int j = 0; j < w; ++j) { // wๅ›ž็นฐใ‚Š่ฟ”ใ™๏ผˆๆจช่ปธ๏ผ‰ if (board[i][j] == โ€™#โ€™) continue; //iๅ€‹็›ฎใฎ็ธฆ่ปธใฎๆจช่ปธjๅ€‹็›ฎใชใฎใงใƒžใ‚น็›ฎใซใชใ‚‹๏ผ๏ผใ“ใ“ใŒใ‚ใ‹ใฃใฆใชใ‹ใฃใŸ int num = 0; for (int d = 0; d < 8; ++ d) { const int ni = i + dy[d]; const int nj = j + dx[d]; // (ni,nj)ใƒžใ‚นใฏใ€็พๅœจใฎใƒžใ‚นใ‹ใ‚‰8ๆ–นๅ‘ใซ็งปๅ‹•ใ—ใŸๅ…ˆใฎๅบงๆจ™ if (ni < 0 or h <= ni) continue; if (nj < 0 or w <= nj) continue; //(ni,nj)ใƒžใ‚นใŒ่กจใฎ็ฏ„ๅ›ฒๅ†…ใซใ„ใชใ‘ใ‚Œใฐๅผพใ if (board[ni][nj] == โ€™#โ€™) num++; //็งปๅ‹•ใ—ใŸๅ…ˆใฎๅบงๆจ™ใซ็ˆ†ๅผพใŒใ‚ใฃใŸใจใใ€ใ‚ซใ‚ฆใƒณใƒˆๅค‰ๆ•ฐใ‚’+1ใ™ใ‚‹๏ผ๏ผ๏ผ๏ผ } board[i][j] = char(num + โ€™0โ€™); //ใใ‚Œใ‚’ๆ–‡ๅญ—ใจใ—ใฆๅ‡บๅŠ›ใ™ใ‚‹ใฎใงchar } } for (int i = 0; i < h; ++i) cout << board[i] << endl; //ๆ›ธใๆ›ใˆใ‚‰ใ‚ŒใŸ้…ๅˆ—boardใ‚’ๆ›ธใใ ใ™ใ€‚ return 0; }
๏ปฟ // LANScannerDlg.h: ๅคดๆ–‡ไปถ // #pragma once #include "NIC.h" #include "Device.h" #include "EthernetFrame.h" #include "PDU.h" #include "ARP.h" // Declare user message ID #define WM_COMPLETE (WM_USER + 100) #define WM_HOST (WM_USER + 101) // CLANScannerDlg ๅฏน่ฏๆก† class CLANScannerDlg : public CDHtmlDialog { // ๆž„้€  public: CLANScannerDlg(CWnd* pParent = nullptr); // ๆ ‡ๅ‡†ๆž„้€ ๅ‡ฝๆ•ฐ // ๅฏน่ฏๆก†ๆ•ฐๆฎ #ifdef AFX_DESIGN_TIME enum { IDD = IDD_LANSCANNER_DIALOG, IDH = IDR_HTML_LANSCANNER_DIALOG }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV ๆ”ฏๆŒ HRESULT OnButtonScan(IHTMLElement* pElement); HRESULT OnButtonCancel(IHTMLElement* pElement); HRESULT OnButtonAbout(IHTMLElement* pElement); // ๅฎž็Žฐ protected: HICON m_hIcon; // ็”Ÿๆˆ็š„ๆถˆๆฏๆ˜ ๅฐ„ๅ‡ฝๆ•ฐ virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); // custom afx_msg LRESULT OnComplete(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() DECLARE_DHTML_EVENT_MAP() public: DWORD hostipp; NIC nic; int index; Device device; BYTE dstmac[6]; BYTE srcmac[6]; DWORD localip; DWORD netmask; DWORD ipbeg; DWORD ipend; bool started = false; CWinThread* hThreadsend; CWinThread* hThreadrecv; SYSTEMTIME timesend; SYSTEMTIME timerecv; time_t diff; DWORD hostip; BYTE hostmac[6]; CString btnScanText; CComboBox m_CComboBox; CString m_nic_select; CString m_nic_ipaddress; CString m_nic_subnetmask; CString m_nic_macaddress; CString m_nic_gatewayipaddress; CString m_nic_gatewaymac; CString m_host_list; CString m_host_list_table_head = "<table width=100% class=list border=1 bgcolor=black cellspacing=0 style=font-size:12px><thead><tr><th width=25%>IP Address</th><th width=25%>MAC Address</th><th width=25%>Host Name</th><th width=25%>Arp Time</th></tr></thead><tbody style=text-align:center>"; CString m_host_list_table_tail = "</tbody></table>"; CString m_host_list_table_content; public: afx_msg void OnSelectChangeNic(); static UINT sendPacket(LPVOID lpParam); static UINT recvPacket(LPVOID lpParam); };
// // Hora.cpp // Aeropuerto // // Created by Daniel on 01/11/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #include "Hora.h" Hora::Hora(){ hour =0; minutes = 0; } Hora::Hora(int รฑ){ std::string ho; std::string temp; std::cin>>ho; for(int i = 0;i < 2; i++){ temp += ho[i]; } hour = atoi(temp.c_str()); temp = ""; for (int j = 2; j< 4; j++) { temp += ho[j]; } minutes = atoi(temp.c_str()); } Hora::Hora(std::string ho){ std::string temp; for(int i = 0;i < 2; i++){ temp += ho[i]; } hour = atoi(temp.c_str()); temp = ""; for (int j = 2; j< 4; j++) { temp += ho[j]; } minutes = atoi(temp.c_str()); } bool Hora::operator<(Hora h){ if (this->hour < h.hour) { return true; } else if((this->hour == h.hour) && (this->minutes < h.minutes)){ return true; } return false; } std::ostream & operator <<(std::ostream & os, Hora & h){ if(h.hour < 10){ os << "0"; } os << h.hour << ":"; if (h.minutes < 10) { os << "0"; } os << h.minutes << std::endl; return os; }
#include <iostream> using namespace std; int main() { double x,y,z; cin>>x>>y>>z; if (x<0||y<0||z<0) cout<<"-1"; else if(x+y>z&&y+z>x&&z+x>y) if(x*x+y*y==z*z||y*y+z*z==x*x||z*z+x*x==y*y) cout<<"1"; else cout<<"0"; else cout<<"-1"; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2003 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef LINK_STYLE_DIALOG_H #define LINK_STYLE_DIALOG_H #include "adjunct/quick_toolkit/widgets/Dialog.h" #include "adjunct/desktop_pi/DesktopColorChooser.h" class LinkStyleDialog : public Dialog, public OpColorChooserListener { Window* m_current_window; public: Type GetType() {return DIALOG_TYPE_LINK_STYLE;} const char* GetWindowName() {return "Link Style Dialog";} const char* GetHelpAnchor() {return "fonts.html";} void Init(DesktopWindow* parent_window); void OnInit(); void OnColorSelected(COLORREF color); UINT32 OnOk(); BOOL OnInputAction(OpInputAction* action); private: BOOL m_choose_visited; }; #endif //this file
/* Solver for the linear hyperbolic equation du/dt + div (b u) = 0 by an explicit time-stepping method */ #include <solve.hpp> #include <python_ngstd.hpp> #include <general/seti.hpp> using namespace ngsolve; using ngfem::ELEMENT_TYPE; template<int D> class Convection { protected: shared_ptr<L2HighOrderFESpace> finiteElementSpace; shared_ptr<CoefficientFunction> flowCoefficientFunction; class FacetData { public: int adjacentElementNumbers[2]; int elementLocalFacetNumber[2]; int facetId; Array<int> adjacentRanks; Vector<> innerProductOfFlowWithNormalVectorAtIntegrationPoint; FacetData() = default; FacetData(int facetId, size_t numberOfIntegrationPoints) : facetId(facetId), innerProductOfFlowWithNormalVectorAtIntegrationPoint( numberOfIntegrationPoints) { ; } }; class ElementData { public: MatrixFixWidth<D> flowAtIntegrationPoint; ElementData() = default; ElementData(size_t numberOfIntegrationPoints) : flowAtIntegrationPoint(numberOfIntegrationPoints) { ; } }; Array<int> adjacentRanks; Array<Array<FacetData>> sharedFacetsDataByRank; Array<Array<double>> receivedData; Array<FacetData> boundaryFacetsData; Array<FacetData> innerFacetsData; Array<ElementData> elementsData; shared_ptr<MeshAccess> meshAccess; public: Convection(const shared_ptr<FESpace>& finiteElementSpace, shared_ptr<CoefficientFunction> aflow) : finiteElementSpace(dynamic_pointer_cast<L2HighOrderFESpace>(finiteElementSpace)), flowCoefficientFunction(aflow), meshAccess(finiteElementSpace->GetMeshAccess()) { LocalHeap localHeap(1000000); elementsData.SetAllocSize(meshAccess->GetNE()); if (!this->finiteElementSpace->AllDofsTogether()) throw Exception("mlngs-Convection needs 'all_dofs_together=True' for L2-FESpace"); PrecomputeElements(localHeap); PrecomputeFacets(localHeap); } private: void PrecomputeElements(LocalHeap& localHeap) { for (auto elementId : meshAccess->Elements()) { HeapReset heapReset(localHeap); auto& finiteElement = dynamic_cast<const DGFiniteElement<D>&>(finiteElementSpace->GetFE(elementId, localHeap)); const IntegrationRule integrationRule(finiteElement.ElementType(), 2 * finiteElement.Order()); const_cast<DGFiniteElement<D>&>(finiteElement).PrecomputeShapes(integrationRule); const_cast<DGFiniteElement<D>&>(finiteElement).PrecomputeTrace(); auto& elementTransform = meshAccess->GetTrafo(elementId, localHeap); MappedIntegrationRule<D, D> mappedIntegrationRule(integrationRule, elementTransform, localHeap); ElementData elementData(integrationRule.Size()); flowCoefficientFunction->Evaluate(mappedIntegrationRule, elementData.flowAtIntegrationPoint); for (size_t j = 0; j < integrationRule.Size(); j++) { Vec<D> flow = mappedIntegrationRule[j].GetJacobianInverse() * elementData.flowAtIntegrationPoint.Row(j); flow *= mappedIntegrationRule[j].GetWeight(); // weight times Jacobian elementData.flowAtIntegrationPoint.Row(j) = flow; } elementsData.Append(move(elementData)); } } void PrecomputeFacets(LocalHeap& localHeap) { Array<int> facetElementNumbers, facetNumbers, vertexNumbers; Array<FacetData> facetsData(meshAccess->GetNFacets()); for (auto i : Range(meshAccess->GetNFacets())) { HeapReset heapReset(localHeap); const auto& finiteElementFacet = dynamic_cast<const DGFiniteElement<D - 1>&>(finiteElementSpace->GetFacetFE(i, localHeap)); IntegrationRule facetIntegrationRule = GetFacetIntegrationRule(finiteElementFacet); const_cast<DGFiniteElement<D - 1>&>(finiteElementFacet).PrecomputeShapes(facetIntegrationRule); FacetData facetData(i, facetIntegrationRule.Size()); meshAccess->GetFacetElements(i, facetElementNumbers); facetData.adjacentElementNumbers[1] = -1; for (size_t j : Range(facetElementNumbers)) { facetData.adjacentElementNumbers[j] = facetElementNumbers[j]; auto facetNumbers = meshAccess->GetElFacets(ElementId(VOL, facetElementNumbers[j])); facetData.elementLocalFacetNumber[j] = facetNumbers.Pos(i); } ELEMENT_TYPE elementType = meshAccess->GetElType(ElementId(VOL, facetElementNumbers[0])); vertexNumbers = meshAccess->GetElVertices(ElementId(VOL, facetElementNumbers[0])); Facet2ElementTrafo transform(elementType, vertexNumbers); FlatVec<D> referenceNormal = ElementTopology::GetNormals(elementType)[facetData.elementLocalFacetNumber[0]]; size_t numberOfIntegrationPoints = facetIntegrationRule.Size(); // transform facet coordinates to element coordinates IntegrationRule& elementIntegrationRule = transform(facetData.elementLocalFacetNumber[0], facetIntegrationRule, localHeap); MappedIntegrationRule<D, D> mappedElementIntegrationRule(elementIntegrationRule, meshAccess->GetTrafo( ElementId(VOL, facetElementNumbers[0]), localHeap), localHeap); FlatMatrixFixWidth<D> flowAtMappedElementIntegrationPoints(numberOfIntegrationPoints, localHeap); flowCoefficientFunction->Evaluate(mappedElementIntegrationRule, flowAtMappedElementIntegrationPoints); for (size_t j = 0; j < numberOfIntegrationPoints; j++) { Vec<D> normal = Trans(mappedElementIntegrationRule[j].GetJacobianInverse()) * referenceNormal; facetData.innerProductOfFlowWithNormalVectorAtIntegrationPoint(j) = InnerProduct(normal, flowAtMappedElementIntegrationPoints.Row( j)); facetData.innerProductOfFlowWithNormalVectorAtIntegrationPoint(j) *= facetIntegrationRule[j].Weight() * mappedElementIntegrationRule[j].GetJacobiDet(); } meshAccess->GetDistantProcs(NodeId(StdNodeType(NT_FACET, meshAccess->GetDimension()), i), facetData.adjacentRanks); facetsData.Append(move(facetData)); } Array<FacetData> sharedFacetsData; sharedFacetsData.SetAllocSize(NumberOfSharedFacets(facetsData)); FindSharedFacets(facetsData, sharedFacetsData); adjacentRanks = FindAdjacentRanks(sharedFacetsData); Array<size_t> numberOfSharedFacetsByRank(adjacentRanks.Size()); FindNumberOfSharedFacetsByRank(sharedFacetsData, adjacentRanks, numberOfSharedFacetsByRank); sharedFacetsDataByRank.SetSize(numberOfSharedFacetsByRank.Size()); for (auto i: Range(numberOfSharedFacetsByRank.Size())) { sharedFacetsDataByRank[i].SetAllocSize(numberOfSharedFacetsByRank[i]); } FindSharedFacetsByRank(sharedFacetsData, adjacentRanks, sharedFacetsDataByRank); innerFacetsData.SetAllocSize(NumberOfInnerFacets(facetsData)); FindInnerFacets(facetsData, innerFacetsData); boundaryFacetsData.SetAllocSize(NumberOfBoundaryFacets(facetsData)); FindBoundaryFacets(facetsData, boundaryFacetsData); } static bool IsInnerFacet(const FacetData& facet) { return facet.adjacentRanks.Size() == 0 && facet.adjacentElementNumbers[1] != -1; } static size_t NumberOfInnerFacets(const Array<FacetData>& facets) { size_t numberOfInnerFacets = 0; for (auto facet: facets) { if (IsInnerFacet(facet)) { numberOfInnerFacets++; } } return numberOfInnerFacets; } static void FindInnerFacets(const Array<FacetData>& facets, Array<FacetData>& innerFacets) { for (auto facet: facets) { if (IsInnerFacet(facet)) { innerFacets.Append(move(facet)); } } } static bool IsBoundaryFacet(const FacetData& facet) { return facet.adjacentRanks.Size() == 0 && facet.adjacentElementNumbers[1] == -1; } static size_t NumberOfBoundaryFacets(const Array<FacetData>& facets) { size_t numberOfBoundaryFacets = 0; for (auto facet: facets) { if (IsBoundaryFacet(facet)) { numberOfBoundaryFacets++; } } return numberOfBoundaryFacets; } static void FindBoundaryFacets(const Array<FacetData>& facets, Array<FacetData>& boundaryFacets) { for (auto facet: facets) { if (IsBoundaryFacet(facet)) { boundaryFacets.Append(move(facet)); } } } static bool IsSharedFacet(const FacetData& facet) { return facet.adjacentRanks.Size() > 0; } static size_t NumberOfSharedFacets(const Array<FacetData>& facets) { size_t numberOfSharedFacets = 0; for (auto facet: facets) { if (IsSharedFacet(facet)) { numberOfSharedFacets++; } } return numberOfSharedFacets; } static void FindSharedFacets(const Array<FacetData>& facets, Array<FacetData>& sharedFacets) { for (auto facet : facets) { if (IsSharedFacet(facet)) { sharedFacets.Append(move(facet)); } } } Array<size_t> FindAdjacentRanks(const Array<FacetData>& sharedFacets) { netgen::IndexSet adjacentRanksSet(MyMPI_GetNTasks()); for (auto facet : sharedFacets) { adjacentRanksSet.Add(facet.adjacentRanks[0]); } const netgen::Array<int>& a = adjacentRanksSet.GetArray(); Array<size_t> adjacentRanks; adjacentRanks.SetAllocSize(a.Size()); for (int i = 0; i < a.Size(); i++) { adjacentRanks.Append(static_cast<size_t&&>(a[i])); } return adjacentRanks; } void FindNumberOfSharedFacetsByRank(const Array<FacetData>& sharedFacets, const Array<int>& adjacentRanks, Array<size_t>& numberOfSharedFacets) { for (auto i : Range(numberOfSharedFacets.Size())) { numberOfSharedFacets[i] = 0; } for (auto facetData: sharedFacets) { size_t position = adjacentRanks.Pos(facetData.adjacentRanks[0]); numberOfSharedFacets[position]++; } } void FindSharedFacetsByRank(const Array<FacetData>& sharedFacets, const Array<int>& adajcentRanks, Array<Array<FacetData>>& sharedFacetsByRank) { for (auto facetData: sharedFacets) { size_t position = adjacentRanks.Pos(facetData.adjacentRanks[0]); sharedFacetsByRank[position].Append(move(facetData)); } } public: void Apply(BaseVector& _vecu, BaseVector& _conv) { static Timer timer("Convection::Apply"); RegionTimer reg(timer); LocalHeap localHeap(1000 * 1000); auto concentration = _vecu.FV<double>(); auto convection = _conv.FV<double>(); Array<MPI_Request> mpiRequests; mpiRequests.SetAllocSize(adjacentRanks.Size()); SendSharedFacetData(concentration, mpiRequests, localHeap); ApplyToElements(concentration, convection, localHeap); ApplyToInnerFacets(concentration, convection, localHeap); ApplyToBoundaryFacets(concentration, convection, localHeap); ApplyToSharedFacets(mpiRequests, concentration, convection, localHeap); } private: void SendSharedFacetData(const FlatVector<double>& concentration, Array<MPI_Request>& mpiRequests, const LocalHeap& localHeap) { Array<MPI_Request> sendRequests(adjacentRanks.Size()); receivedData.SetSize(adjacentRanks.Size()); ParallelFor(Range(adjacentRanks.Size()), [&](size_t i) { LocalHeap threadLocalHeap = localHeap.Split(); int destination = adjacentRanks[i]; Array<double> data; for (auto j: Range(sharedFacetsDataByRank[i].Size())) { const FacetData& sharedFacet = sharedFacetsDataByRank[i][j]; FlatVector<> trace = GetTraceValuesOnFacetFromElementCoefficients( concentration, sharedFacet.adjacentElementNumbers[0], sharedFacet.elementLocalFacetNumber[0], threadLocalHeap); data.Append(FlatVectorToFlatArray(trace, threadLocalHeap)); } MPI_Request sendRequest = MyMPI_ISend(data, destination); sendRequests[i] = sendRequest; receivedData[i].SetSize(data.Size()); MPI_Request receiveRequest = MyMPI_IRecv(receivedData[i], destination); mpiRequests.Append(receiveRequest); }); // MyMPI_WaitAll(sendRequests); } void ApplyToBoundaryFacets(const FlatVector<double>& concentration, const FlatVector<double>& convection, const LocalHeap& localHeap) const { static mutex add_mutex; ParallelFor(Range(boundaryFacetsData.Size()), [&](size_t i) { LocalHeap threadLocalHeap = localHeap.Split(); const FacetData& facetData = boundaryFacetsData[i]; FlatVector<> traceOnFacet = GetTraceValuesOnFacetFromElementCoefficients(concentration, facetData.adjacentElementNumbers[0], facetData.elementLocalFacetNumber[0], threadLocalHeap); FlatVector<> upwindTraceAtIntegrationPoints = GetUpwindTrace(traceOnFacet, [](size_t j) { return 0; }, facetData.innerProductOfFlowWithNormalVectorAtIntegrationPoint, threadLocalHeap); FlatVector<> convectionCoefficients = GetElementCoefficientsFromTraceValuesOnFacet( upwindTraceAtIntegrationPoints, facetData.adjacentElementNumbers[0], facetData.elementLocalFacetNumber[0], threadLocalHeap); IntRange dofNumbers = finiteElementSpace->GetElementDofs( static_cast<size_t>(facetData.elementLocalFacetNumber[0])); { lock_guard<mutex> guard(add_mutex); convection.Range(dofNumbers) -= convectionCoefficients; } }); } void ApplyToInnerFacets(const FlatVector<double>& concentration, const FlatVector<double>& convection, const LocalHeap& localHeap) const { static mutex add_mutex; ParallelFor(Range(innerFacetsData.Size()), [&](size_t i) { LocalHeap threadLocalHeap = localHeap.Split(); const FacetData& facetData = innerFacetsData[i]; FlatVector<> traceAtIntegrationPoints0 = GetTraceValuesOnFacetFromElementCoefficients( concentration, facetData.adjacentElementNumbers[0], facetData.elementLocalFacetNumber[0], threadLocalHeap); FlatVector<> traceAtIntegrationPoints1 = GetTraceValuesOnFacetFromElementCoefficients( concentration, facetData.adjacentElementNumbers[1], facetData.elementLocalFacetNumber[1], threadLocalHeap); FlatVector<> upwindTraceAtIntegrationPoints = GetUpwindTrace( traceAtIntegrationPoints0, traceAtIntegrationPoints1, facetData.innerProductOfFlowWithNormalVectorAtIntegrationPoint, threadLocalHeap); FlatVector<> upwindTraceCoefficients = GetFacetCoefficientsFromTraceValuesOnFacet( upwindTraceAtIntegrationPoints, facetData.adjacentElementNumbers[0], facetData.elementLocalFacetNumber[0], threadLocalHeap); FlatVector<> convectionCoefficients0 = GetElementCoefficientsFromTraceCoefficients( upwindTraceCoefficients, facetData.adjacentElementNumbers[0], facetData.elementLocalFacetNumber[0], threadLocalHeap); FlatVector<> convectionCoefficients1 = GetElementCoefficientsFromTraceCoefficients( upwindTraceCoefficients, facetData.adjacentElementNumbers[1], facetData.elementLocalFacetNumber[1], threadLocalHeap); IntRange dofNumbers0 = finiteElementSpace->GetElementDofs( static_cast<size_t>(facetData.adjacentElementNumbers[0])); IntRange dofNumbers1 = finiteElementSpace->GetElementDofs( static_cast<size_t>(facetData.adjacentElementNumbers[1])); { lock_guard<mutex> guard(add_mutex); convection.Range(dofNumbers0) -= convectionCoefficients0; convection.Range(dofNumbers1) += convectionCoefficients1; } }); } void ApplyToElements(const FlatVector<double>& concentration, const FlatVector<double>& convection, const LocalHeap& localHeap) const { ParallelFor(Range(meshAccess->GetNE()), [&](size_t i) { LocalHeap threadLocalHeap = localHeap.Split(); auto& finiteElement = static_cast<const ScalarFiniteElement<D>&>(finiteElementSpace->GetFE( ElementId(VOL, i), threadLocalHeap)); const IntegrationRule integrationRule(finiteElement.ElementType(), 2 * finiteElement.Order()); FlatMatrixFixWidth<D> flowAtIntegrationPoint = elementsData[i].flowAtIntegrationPoint; /* // use this for time-dependent flow (updated version not yet tested) MappedIntegrationRule<D,D> mappedIntegrationRule(integrationRule, meshAccess->GetTrafo (i, 0, threadLocalHeap), threadLocalHeap); FlatMatrixFixWidth<D> flowAtIntegrationPoint(mappedIntegrationRule.Size(), threadLocalHeap); flowCoefficientFunction -> Evaluate (mappedIntegrationRule, flowAtIntegrationPoint); for (size_t j = 0; j < integrationRule.Size(); j++) { Vec<D> flow = mappedIntegrationRule[j].GetJacobianInverse() * flowAtIntegrationPoint.Row(j); flow *= mappedIntegrationRule[j].GetWeight(); flowAtIntegrationPoint.Row(j) = flow; } */ IntRange elementDofs = finiteElementSpace->GetElementDofs(i); size_t numberOfIntegrationPoints = integrationRule.Size(); FlatVector<> concentrationAtElementIntegrationPoints(numberOfIntegrationPoints, threadLocalHeap); FlatMatrixFixWidth<D> flowTimesConcentrationAtElementIntegrationPoints(numberOfIntegrationPoints, threadLocalHeap); finiteElement.Evaluate(integrationRule, concentration.Range(elementDofs), concentrationAtElementIntegrationPoints); for (auto k : Range(numberOfIntegrationPoints)) flowTimesConcentrationAtElementIntegrationPoints.Row(k) = concentrationAtElementIntegrationPoints(k) * flowAtIntegrationPoint.Row(k); finiteElement.EvaluateGradTrans(integrationRule, flowTimesConcentrationAtElementIntegrationPoints, convection.Range(elementDofs)); }); } void ApplyToSharedFacets(const Array<MPI_Request>& mpiRequests, const FlatVector<>& concentration, const FlatVector<>& convection, const LocalHeap& localHeap) { static mutex add_mutex; ParallelFor(Range(mpiRequests.Size()), [&](size_t i) { LocalHeap threadLocalHeap = localHeap.Split(); MPI_Request receiveRequest = mpiRequests[i]; int receivedIndex = MyMPI_WaitAny(mpiRequests); size_t startFacetIndex = 0; for (auto j: Range(sharedFacetsDataByRank[receivedIndex].Size())) { const FacetData& facetData = sharedFacetsDataByRank[receivedIndex][j]; FlatVector<> thisTraceAtIntegrationPoints = GetTraceValuesOnFacetFromElementCoefficients( concentration, facetData.adjacentElementNumbers[0], facetData.elementLocalFacetNumber[0], threadLocalHeap); FlatVector<> otherTraceAtIntegrationPoints(thisTraceAtIntegrationPoints.Size(), threadLocalHeap); otherTraceAtIntegrationPoints = FlatArrayToFlatVector( receivedData[receivedIndex].Range(startFacetIndex, startFacetIndex + thisTraceAtIntegrationPoints.Size()), threadLocalHeap); FlatVector<> upwindTraceAtIntegrationPoints = GetUpwindTrace( thisTraceAtIntegrationPoints, otherTraceAtIntegrationPoints, facetData.innerProductOfFlowWithNormalVectorAtIntegrationPoint, threadLocalHeap); FlatVector<> convectionCoefficients = GetElementCoefficientsFromTraceValuesOnFacet( upwindTraceAtIntegrationPoints, facetData.adjacentElementNumbers[0], facetData.elementLocalFacetNumber[0], threadLocalHeap); IntRange dofNumbers = finiteElementSpace->GetElementDofs( static_cast<size_t>(facetData.adjacentElementNumbers[0])); { lock_guard<mutex> guard(add_mutex); convection.Range(dofNumbers) -= convectionCoefficients; } startFacetIndex += thisTraceAtIntegrationPoints.Size(); } }); } const DGFiniteElement<D>& GetElement(int elementId, LocalHeap& localHeap) const { return dynamic_cast<const DGFiniteElement<D>&>( finiteElementSpace->GetFE(ElementId(VOL, elementId), localHeap)); } const DGFiniteElement<D - 1>& GetFacetElement(int elementId, int localFacetId, LocalHeap& localHeap) const { const auto globalFacetId = meshAccess->GetElFacets(ElementId(VOL, elementId))[localFacetId]; return dynamic_cast<const DGFiniteElement<D - 1>&>( finiteElementSpace->GetFacetFE(globalFacetId, localHeap)); } FlatVector<> GetTraceValuesOnFacetFromElementCoefficients( const FlatVector<>& coefficients, int elementId, int localFacetId, LocalHeap& localHeap) const { const auto& finiteElement = GetElement(elementId, localHeap); const auto& finiteElementFacet = GetFacetElement(elementId, localFacetId, localHeap); const auto numberOfFacetDofs = static_cast<size_t>(finiteElementFacet.GetNDof()); FlatVector<> traceCoefficients(numberOfFacetDofs, localHeap); IntRange dofNumbers = finiteElementSpace->GetElementDofs(elementId); finiteElement.GetTrace(localFacetId, coefficients.Range(dofNumbers), traceCoefficients); IntegrationRule facetIntegrationRule = GetFacetIntegrationRule(finiteElementFacet); size_t numberOfIntegrationPoints = facetIntegrationRule.Size(); FlatVector<> traceAtIntegrationPoints(numberOfIntegrationPoints, localHeap); finiteElementFacet.Evaluate(facetIntegrationRule, traceCoefficients, traceAtIntegrationPoints); return traceAtIntegrationPoints; } IntegrationRule GetFacetIntegrationRule(const DGFiniteElement<D - 1>& facet) const { return IntegrationRule(facet.ElementType(), 2 * facet.Order()); } FlatVector<> GetElementCoefficientsFromTraceValuesOnFacet(const FlatVector<>& traceValues, int elementId, int localFacetId, LocalHeap& localHeap) const { FlatVector<> traceCoefficients = GetFacetCoefficientsFromTraceValuesOnFacet(traceValues, elementId, localFacetId, localHeap); return GetElementCoefficientsFromTraceCoefficients(traceCoefficients, elementId, localFacetId, localHeap); } FlatVector<> GetElementCoefficientsFromTraceCoefficients(const FlatVector<>& traceCoefficients, int elementId, int localFacetId, LocalHeap& localHeap) const { const auto& element = GetElement(elementId, localHeap); auto numberOfElementDofs = static_cast<const size_t>(element.GetNDof()); FlatVector<> elementCoefficients(numberOfElementDofs, localHeap); element.GetTraceTrans(localFacetId, traceCoefficients, elementCoefficients); return elementCoefficients; } FlatVector<> GetFacetCoefficientsFromTraceValuesOnFacet(const FlatVector<>& traceValues, int elementId, int localFacetId, LocalHeap& localHeap) const { const auto& facet = GetFacetElement(elementId, localFacetId, localHeap); const auto facetIntegrationRule = GetFacetIntegrationRule(facet); FlatVector<> traceCoefficients(facetIntegrationRule.Size(), localHeap); facet.EvaluateTrans(GetFacetIntegrationRule(facet), traceValues, traceCoefficients); return traceCoefficients; } FlatVector<> GetUpwindTrace( const function<double(size_t)>& thisTraceOnFacet, const function<double(size_t)>& otherTraceOnFacet, const FlatVector<>& thisInnerProductOfFlowWithNormalVectorAtIntegrationPoint, LocalHeap& localHeap) const { FlatVector<> upwindTraceAtIntegrationPoints(thisInnerProductOfFlowWithNormalVectorAtIntegrationPoint.Size(), localHeap); for (auto j: Range(thisInnerProductOfFlowWithNormalVectorAtIntegrationPoint.Size())) { upwindTraceAtIntegrationPoints(j) = thisInnerProductOfFlowWithNormalVectorAtIntegrationPoint(j) * ((thisInnerProductOfFlowWithNormalVectorAtIntegrationPoint(j) > 0) ? thisTraceOnFacet(j) : otherTraceOnFacet(j)); } return upwindTraceAtIntegrationPoints; } template<typename T> FlatVector<T> FlatArrayToFlatVector(FlatArray<T> flatArray, LocalHeap& localHeap) { FlatVector<T> vector(flatArray.Size(), localHeap); for (auto i: Range(flatArray.Size())) { vector(i) = flatArray[i]; } return vector; } template<typename T> FlatArray<T> FlatVectorToFlatArray(FlatVector<T> flatVector, LocalHeap& localHeap) { FlatArray<T> array(flatVector.Size(), localHeap); for (auto i: Range(flatVector.Size())) { array[i] = flatVector(i); } return array; } }; PYBIND11_MODULE(liblinhyp, m) { py::class_<Convection<2>>(m, "Convection") .def(py::init<shared_ptr<FESpace>, shared_ptr<CoefficientFunction>>()) .def("Apply", &Convection<2>::Apply); }
#include <fstream> #include <stdio.h> #include "Errors.h" #include "SortedFile.h" #include "HeapFile.h" using std::ifstream; using std::ofstream; using std::string; extern char *catalog_path; extern char *dbfile_dir; extern char *tpch_dir; int SortedFile::Create(char *fpath, void *startup) { if (fpath == NULL || startup == NULL) return -1; assignTable(fpath); createHelper(fpath, startup); return GenericDBFile::Create(fpath, startup); } int SortedFile::Open(char *fpath) { if (fpath == NULL) return -1; allocMem(); assignTable(fpath); openHelper(fpath); return GenericDBFile::Open(fpath); } int SortedFile::Close() { closeHelper(); if (mode == WRITE) merge(); freeMem(); return theFile.Close(); } void SortedFile::Add(Record &addme) { startWrite(); in->Insert(&addme); } void SortedFile::Load(Schema &myschema, char *loadpath) { startWrite(); GenericDBFile::Load(myschema, loadpath); } void SortedFile::MoveFirst() { startRead(); theFile.GetPage(&curPage, curPageIdx = 0); } int SortedFile::GetNext(Record &fetchme) { return GenericDBFile::GetNext(fetchme); } int SortedFile::GetNext(Record &fetchme, CNF &cnf, Record &literal) { OrderMaker queryorder, cnforder; OrderMaker::queryOrderMaker(*myOrder, cnf, queryorder, cnforder); ComparisonEngine cmp; if (!binarySearch(fetchme, queryorder, literal, cnforder, cmp)) return 0; do { if (cmp.Compare(&fetchme, &queryorder, &literal, &cnforder)) return 0; if (cmp.Compare(&fetchme, &literal, &cnf)) return 1; } while (GetNext(fetchme)); return 0; } void SortedFile::merge() { in->ShutDown(); Record fromFile, fromPipe; bool fileNotEmpty = !theFile.empty(), pipeNotEmpty = out->Remove(&fromPipe); HeapFile tmp; tmp.Create(const_cast<char *>(tmpfName()), NULL); ComparisonEngine ce; if (fileNotEmpty) { theFile.GetPage(&curPage, curPageIdx = 0); fileNotEmpty = GetNext(fromFile); } while (fileNotEmpty || pipeNotEmpty) if (!fileNotEmpty || (pipeNotEmpty && ce.Compare(&fromFile, &fromPipe, myOrder) > 0)) { tmp.Add(fromPipe); pipeNotEmpty = out->Remove(&fromPipe); } else if (!pipeNotEmpty || (fileNotEmpty && ce.Compare(&fromFile, &fromPipe, myOrder) <= 0)) { tmp.Add(fromFile); fileNotEmpty = GetNext(fromFile); } else FATAL("Pipe and File Both might be empty. Two-way merge failed."); tmp.Close(); FATALIF(rename(tmpfName(), tpath.c_str()), "TempfName write failed. Merge write failed."); deleteQ(); } int SortedFile::binarySearch(Record &fetchme, OrderMaker &queryorder, Record &literal, OrderMaker &cnforder, ComparisonEngine &cmp) { if (!GetNext(fetchme)) return 0; int result = cmp.Compare(&fetchme, &queryorder, &literal, &cnforder); if (result > 0) return 0; else if (result == 0) return 1; off_t low = curPageIdx, high = theFile.lastIndex(), mid = (low + high) / 2; for (; low < mid; mid = (low + high) / 2) { theFile.GetPage(&curPage, mid); FATALIF(!GetNext(fetchme), "empty page found"); result = cmp.Compare(&fetchme, &queryorder, &literal, &cnforder); if (result < 0) low = mid; else if (result > 0) high = mid - 1; else high = mid; } theFile.GetPage(&curPage, low); do { if (!GetNext(fetchme)) return 0; result = cmp.Compare(&fetchme, &queryorder, &literal, &cnforder); } while (result < 0); return result == 0; } const char *SortedFile::metafName() const { std::string p(dbfile_dir); return (p + table + ".meta").c_str(); } void SortedFile::allocMem() { FATALIF(myOrder != NULL, "File already open."); myOrder = new OrderMaker(); useMem = true; } void SortedFile::assignTable(char *fPath) { table = getTableName((tpath = fPath).c_str()); } void SortedFile::freeMem() { if (useMem) safeDelete(myOrder); useMem = false; } void SortedFile::createHelper(char *fpath, void *startup) { typedef struct { OrderMaker *o; int l; } * pOrder; pOrder po = (pOrder)startup; myOrder = po->o; runLength = po->l; } void SortedFile::openHelper(char *fpath) { int ftype; ifstream ifs(metafName()); FATALIF(!ifs, "Meta file missing."); ifs >> ftype >> *myOrder >> runLength; ifs.close(); } void SortedFile::closeHelper() { ofstream ofs(metafName()); ofs << "1\n" << *myOrder << '\n' << runLength << std::endl; ofs.close(); }
#include <sstream> #include <cppunit/extensions/HelperMacros.h> #include <Poco/AtomicCounter.h> #include <Poco/Environment.h> #include <Poco/Event.h> #include <Poco/NumberParser.h> #include <Poco/Thread.h> #include <Poco/RunnableAdapter.h> #include <Poco/Net/SocketAddress.h> #include <Poco/Net/StreamSocket.h> #include "cppunit/BetterAssert.h" #include "io/TCPConsole.h" using namespace std; using namespace Poco; using namespace Poco::Net; namespace BeeeOn { #define TIMEOUT_SECS 4 #define TIMEOUT_MSECS (TIMEOUT_SECS * 1000) static const Timespan CONSOLE_TIMEOUT = 4 * Timespan::SECONDS; class TCPConsoleTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(TCPConsoleTest); CPPUNIT_TEST(testReadLine); CPPUNIT_TEST(testReadMultiLine); CPPUNIT_TEST_SUITE_END(); public: TCPConsoleTest(); void testReadLine(); void testReadMultiLine(); protected: void connect(StreamSocket &socket); void setupConsole(TCPConsole &console) const; void echoLoop(); void reconnectingLoop(); private: Thread m_thread; RunnableAdapter<TCPConsoleTest> m_echoRunnable; Event m_listening; }; CPPUNIT_TEST_SUITE_REGISTRATION(TCPConsoleTest); TCPConsoleTest::TCPConsoleTest(): m_echoRunnable(*this, &TCPConsoleTest::echoLoop) { } void TCPConsoleTest::setupConsole(TCPConsole &console) const { console.setPort( NumberParser::parse( Environment::get("TEST_TCP_CONSOLE_PORT", "6000") ) ); console.setSendTimeout(CONSOLE_TIMEOUT); console.setRecvTimeout(CONSOLE_TIMEOUT); } /** * Echo loop running in a separate thread. */ void TCPConsoleTest::echoLoop() { TCPConsole console; setupConsole(console); console.startListen(); // notify tests that we have started to listen m_listening.set(); ConsoleSession session(console); while (!session.eof()) { const string &input = session.readLine(); session.print(input); } } void TCPConsoleTest::connect(StreamSocket &socket) { SocketAddress address( "127.0.0.1", NumberParser::parse( Environment::get("TEST_TCP_CONSOLE_PORT", "6000") ) ); socket.connect(address, Timespan(TIMEOUT_SECS * Timespan::SECONDS)); socket.setReceiveTimeout(Timespan(TIMEOUT_SECS * Timespan::SECONDS)); } void TCPConsoleTest::testReadLine() { m_thread.start(m_echoRunnable); CPPUNIT_ASSERT_NO_THROW( m_listening.wait(TIMEOUT_MSECS) ); StreamSocket socket; connect(socket); SocketInputStream in(socket); SocketOutputStream out(socket); CPPUNIT_ASSERT_EQUAL('>', in.get()); CPPUNIT_ASSERT_EQUAL(' ', in.get()); out << "first\n" << flush; CPPUNIT_ASSERT_EQUAL('f', in.get()); CPPUNIT_ASSERT_EQUAL('i', in.get()); CPPUNIT_ASSERT_EQUAL('r', in.get()); CPPUNIT_ASSERT_EQUAL('s', in.get()); CPPUNIT_ASSERT_EQUAL('t', in.get()); CPPUNIT_ASSERT_EQUAL('\n', in.get()); CPPUNIT_ASSERT_EQUAL('>', in.get()); CPPUNIT_ASSERT_EQUAL(' ', in.get()); out << "second\n" << flush; CPPUNIT_ASSERT_EQUAL('s', in.get()); CPPUNIT_ASSERT_EQUAL('e', in.get()); CPPUNIT_ASSERT_EQUAL('c', in.get()); CPPUNIT_ASSERT_EQUAL('o', in.get()); CPPUNIT_ASSERT_EQUAL('n', in.get()); CPPUNIT_ASSERT_EQUAL('d', in.get()); CPPUNIT_ASSERT_EQUAL('\n', in.get()); CPPUNIT_ASSERT_EQUAL('>', in.get()); CPPUNIT_ASSERT_EQUAL(' ', in.get()); socket.close(); CPPUNIT_ASSERT_NO_THROW( m_thread.join(TIMEOUT_MSECS) ); } void TCPConsoleTest::testReadMultiLine() { m_thread.start(m_echoRunnable); CPPUNIT_ASSERT_NO_THROW( m_listening.wait(TIMEOUT_MSECS) ); StreamSocket socket; connect(socket); SocketInputStream in(socket); SocketOutputStream out(socket); CPPUNIT_ASSERT_EQUAL('>', in.get()); CPPUNIT_ASSERT_EQUAL(' ', in.get()); out << "third\\\nx\n" << flush; CPPUNIT_ASSERT_EQUAL('t', in.get()); CPPUNIT_ASSERT_EQUAL('h', in.get()); CPPUNIT_ASSERT_EQUAL('i', in.get()); CPPUNIT_ASSERT_EQUAL('r', in.get()); CPPUNIT_ASSERT_EQUAL('d', in.get()); CPPUNIT_ASSERT_EQUAL('x', in.get()); CPPUNIT_ASSERT_EQUAL('\n', in.get()); CPPUNIT_ASSERT_EQUAL('>', in.get()); CPPUNIT_ASSERT_EQUAL(' ', in.get()); socket.close(); CPPUNIT_ASSERT_NO_THROW( m_thread.join(TIMEOUT_MSECS) ); } }
// // EPITECH PROJECT, 2018 // zappy // File description: // StaticText.cp // #include "StaticText.hpp" StaticText::StaticText(irr::gui::IGUIStaticText *tx, int id) { _id = id; txt = tx; } StaticText::~StaticText() { } int StaticText::getId() const { return _id; } void StaticText::setText(const char *str) { const wchar_t *text = char_to_wchar(str); txt->setText(text); } void StaticText::setVisible(bool visible) { txt->setVisible(visible); }
// // Created by glyphack on 7/11/19. // #ifndef CRAWLLALA_FOOD_H #define CRAWLLALA_FOOD_H #include <SFML/Graphics.hpp> #include <iostream> namespace game { /* Food: represents the Food object snake eats. It is represented by a sf::RectangleShape */ class Food { public: Food(sf::RenderWindow *, sf::Vector2f loc); sf::RectangleShape getFood(); void drawFood(); ~Food() { std::cout << "Food\n"; } private: sf::Color color; sf::Vector2f location; sf::RectangleShape food; sf::RenderWindow *screen; }; } #endif //CRAWLLALA_FOOD_H
#include <iostream> int firstConversion(int number, int system) { int convertNumber = 0; int index = 1; while (0 != number) { convertNumber += (number % system) * index; number /= system; index = index * 10; } return convertNumber; } void secondConversion(int number, int system) { std::string convertNumber = " "; int index = 0; while (0 != number) { int remainder = number % system; if (10 > remainder) { convertNumber[index] = remainder + 48; ++index; } else { convertNumber[index] = remainder + 55; ++index; } number /= system; } for (int i = index - 1; i >= 0; --i) { std::cout << convertNumber[i]; } std::cout << std::endl; } void validNumber(int& number) { while (std::cin.fail() || 0 > number) { std::cout << "Invalid Value: Try again!" << std::endl; std::cin.clear(); std::cin.ignore(256,'\n'); std::cout << "Please enter the intager number: "; std::cin>> number; } } int main() { int number = 0; std::cout << "Enter number: "; std::cin >> number; validNumber(number); int system = 0; std::cout << "Enter system(2, 3, 4, ... , 16): "; do { std::cin >> system; if (1 < system && 9 > system) { std::cout << "Conversion: " << firstConversion(number, system) << std::endl; return 0; } if (10 < system && 16 >= system) { std::cout << "Conversion: "; secondConversion(number, system); return 0; } std::cout << "Invalid systema! Please enter 2 or 3 or 4 ... 16 -> "; } while (1 > system || 16 < system); return 0; }
#include<iostream> using namespace std; struct node { int data; node *left, *right; }*root; node* addNode(int); void traverse(node *); int diameter(node *); int height(node *); int diameterOpt(node *, int *); int max(int, int); int main() { root = addNode(10); root->left = addNode(12); root->right = addNode(0); root->left->left = addNode(210); root->left->right = addNode(110); root->right->right = addNode(11230); int h = height(root); traverse(root); cout << "\nheight: " << h << endl; cout << "Diameter: " << diameter(root) << endl; cout << "DiameterOpt: " << diameterOpt(root, &h) << endl; return 0; } node* addNode(int x) { node *temp = new node; temp->data = x; temp->left = NULL; temp->right = NULL; return temp; } void traverse(node *q) { if(q != NULL) { traverse(q->left); cout << q->data << " "; traverse(q->right); } } int height(node *q) { if(q == NULL) return 0; int l = height(q->left); int r = height(q->right); return 1 + max(l, r); } int diameter(node *q) { if(q == NULL) return 0; int lh = height(q->left); int rh = height(q->right); int ld = diameter(q->left); int rd = diameter(q->right); return max(1+lh+rh, max(ld, rd)); } int diameterOpt(node *q, int *height) { int lh=0; int rh=0; int ld=0; int rd=0; if(q == NULL) { *height = 0; return 0; } ld = diameterOpt(q->left, &lh); rd = diameterOpt(q->right, &rh); *height = max(lh, rh) + 1; return max(lh+rh+1, max(ld,rd)); } int max(int x, int y) { return x>y ? x :y; }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <common/init/Init.h> #include <folly/Benchmark.h> #include <quic/state/QuicPriorityQueue.h> #include <vector> using namespace std; using namespace folly; static inline void benchmarkPriority(quic::Priority pri, size_t n) { quic::PriorityQueue pq; size_t numConcurrentStreams = 200; for (size_t i = 0; i < numConcurrentStreams; i++) { pq.insertOrUpdate(i, pri); } size_t removeStreamId = 0; size_t insertStreamId = 200; while (n--) { const auto& level = pq.levels[quic::PriorityQueue::priority2index(pri)]; // Iterate the PriorityQueue level.iterator->begin(); do { (void)level.iterator->current(); level.iterator->next(); } while (!level.iterator->end()); // Remove some old streams pq.erase(removeStreamId++); pq.erase(removeStreamId++); pq.erase(removeStreamId++); // Add some new streams pq.insertOrUpdate(insertStreamId++, pri); pq.insertOrUpdate(insertStreamId++, pri); pq.insertOrUpdate(insertStreamId++, pri); } } BENCHMARK(sequential, n) { quic::Priority pri(0, false); benchmarkPriority(pri, n); } BENCHMARK(incremental, n) { quic::Priority pri(0, true); benchmarkPriority(pri, n); } int main(int argc, char** argv) { facebook::initFacebook(&argc, &argv); runBenchmarks(); return 0; }
#include "stdafx.h" #include <Windows.h> #include <Shlwapi.h> #include <assert.h> #include "DiskFile.h" IFile* OpenDiskFile(const char* name, IFile::OpenMode mode) { if(!PathFileExistsA(name) && mode != IFile::O_Truncate) return 0; else return new DiskFile(name, mode); } DiskFile::DiskFile(const char* name, OpenMode mode):m_eMode(mode) { DWORD access = GENERIC_READ; DWORD create = OPEN_EXISTING; switch(mode) { case O_ReadOnly: access = GENERIC_READ; create = OPEN_EXISTING; break; case O_Write: access = GENERIC_READ|GENERIC_WRITE; create = OPEN_EXISTING; break; case O_Truncate: access = GENERIC_READ|GENERIC_WRITE; create = CREATE_ALWAYS; break; default: assert(0); } m_hFile = CreateFileA(name, access, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, create, FILE_ATTRIBUTE_NORMAL, NULL); if(m_hFile == INVALID_HANDLE_VALUE) assert(0); } DiskFile::~DiskFile(void) { CloseHandle(m_hFile); } offset_type DiskFile::Read( void* buffer, offset_type size ) { offset_type ret; DWORD bytes_read = 0; assert(size.offset < 0xffffffff); BOOL result = ReadFile(m_hFile, buffer, (DWORD)size.offset, &bytes_read, NULL); assert(result); ret.offset = bytes_read; return ret; } offset_type DiskFile::Write( const void* buffer, offset_type size ) { assert(m_eMode != IFile::O_ReadOnly); assert(size.offset<0xffffffff); offset_type ret; DWORD bytes_write = 0; BOOL result = WriteFile(m_hFile, buffer, (DWORD)size.offset, &bytes_write, NULL); assert(result); //FlushFileBuffers(m_hFile); ret.offset = bytes_write; return ret; } offset_type DiskFile::Seek( offset_type pos, enum SeekMode mode ) { int api_mode = FILE_BEGIN; switch(mode) { case S_Begin: api_mode = FILE_BEGIN; break; case S_Current: api_mode = FILE_CURRENT; break; case S_End: api_mode = FILE_END; break; default: assert(0); break; } long distancelow = pos.low; long distancehigh = pos.high; offset_type ret; DWORD result = SetFilePointer(m_hFile, distancelow, &distancehigh, api_mode); assert(result != INVALID_SET_FILE_POINTER || NO_ERROR == GetLastError()); ret.low = result; ret.high = distancehigh; return ret; } offset_type DiskFile::GetSize() { offset_type ret; ret.low = GetFileSize(m_hFile, (LPDWORD)&ret.high); return ret; } void DiskFile::ReserveSpace( offset_type size ) { assert(m_eMode != O_ReadOnly); Seek(size, S_Begin); DWORD result = SetEndOfFile(m_hFile); assert(result); }
#include "_pch.h" #include "ViewBrowser.h" #include "globaldata.h" #include "wxDataViewIconMLTextRenderer.h" #include "wxComboBtn.h" #include "config.h" #include <wx/uiaction.h> using namespace wh; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- class wxAuiPanel : public wxPanel { public: wxAuiPanel(wxWindow* wnd) :wxPanel(wnd) { mAuiMgr.SetManagedWindow(this); } ~wxAuiPanel() { mAuiMgr.UnInit(); } wxAuiManager mAuiMgr; }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- ViewTableBrowser::ViewTableBrowser(const std::shared_ptr<IViewWindow>& parent) :ViewTableBrowser(parent->GetWnd()) {} //----------------------------------------------------------------------------- ViewTableBrowser::ViewTableBrowser(wxWindow* parent) { auto table = new wxDataViewCtrl(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize , wxDV_ROW_LINES | wxDV_VERT_RULES | wxDV_MULTIPLE //| wxDV_HORIZ_RULES //| wxDV_MULTIPLE ); mTable = table; mTable->GetTargetWindow()->GetToolTip()->SetAutoPop(10000); mDvModel = new wxDVTableBrowser(); table->AssociateModel(mDvModel); mDvModel->DecRef(); mDvModel->sigSetQty.connect([this](const ObjectKey& k, const wxString& v) { return sigSetQty(k,v).operator bool(); }); #define ICON_HEIGHT 24+2 int row_height = table->GetCharHeight() + 2;// + 1px in bottom and top if(ICON_HEIGHT > row_height ) row_height = ICON_HEIGHT; table->SetRowHeight(row_height); ResetColumns(); table->GetTargetWindow()->Bind(wxEVT_LEFT_UP, &ViewTableBrowser::OnCmd_LeftUp, this); table->GetTargetWindow()->Bind(wxEVT_MOTION, &ViewTableBrowser::OnCmd_MouseMove, this); mToolTipTimer.Bind(wxEVT_TIMER, [this](wxTimerEvent& evt) { ShowToolTip(); }); table->Bind(wxEVT_DATAVIEW_COLUMN_HEADER_CLICK, [this](wxDataViewEvent& evt) { StoreSelect(); evt.Skip(); }); table->Bind(wxEVT_DATAVIEW_COLUMN_SORTED, [this](wxDataViewEvent& evt) { RestoreSelect(); } ); table->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED , &ViewTableBrowser::OnCmd_Activate, this); table->Bind(wxEVT_DATAVIEW_ITEM_EXPANDING , &ViewTableBrowser::OnCmd_Expanding, this); table->Bind(wxEVT_DATAVIEW_ITEM_EXPANDED , &ViewTableBrowser::OnCmd_Expanded, this); table->Bind(wxEVT_DATAVIEW_ITEM_COLLAPSED , &ViewTableBrowser::OnCmd_Collapseded, this); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigRefresh(); }, wxID_REFRESH); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) { const auto finded = GetTopChildCls(); if (finded) { auto dvitem = wxDataViewItem((void*)finded); mTable->EnsureVisible(dvitem); mTable->SetCurrentItem(dvitem); mTable->Select(dvitem); } sigUp(); }, wxID_UP); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigAct(); }, wxID_EXECUTE); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigMove(); }, wxID_REPLACE); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigShowDetail(); }, wxID_VIEW_DETAILS); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigDelete(); }, wxID_DELETE); table->GetTargetWindow()->Bind(wxEVT_MIDDLE_UP, [this](wxMouseEvent&) {sigShowDetail(); }); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {SetInsertType(); }, wxID_NEW_TYPE); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {SetInsertObj(); }, wxID_NEW_OBJECT); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {SetUpdateSelected(); }, wxID_EDIT); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) { sigToggleGroupByType(); }, wxID_VIEW_LIST); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) { SetShowFav(); }, wxID_PROPERTIES); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) { sigShowSettings(); }, wxID_HELP_INDEX); table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) { sigShowHelp("ViewBrowserPage"); }, wxID_HELP_INDEX); // multiselect support table->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) { SetSelected(); }, wxID_FILE1); table->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED , &ViewTableBrowser::OnCmd_SelectionChanged, this); table->Bind(wxEVT_DESTROY, [this](wxWindowDestroyEvent& evt) { if (evt.GetWindow() != mTable) return; mTable = nullptr; mDvModel = nullptr; }); wxAcceleratorEntry entries[16]; char i = 0; entries[i++].Set(wxACCEL_CTRL, (int) 'R', wxID_REFRESH); entries[i++].Set(wxACCEL_NORMAL, WXK_F5, wxID_REFRESH); entries[i++].Set(wxACCEL_NORMAL, WXK_BACK, wxID_UP); entries[i++].Set(wxACCEL_NORMAL, WXK_F6, wxID_REPLACE); entries[i++].Set(wxACCEL_NORMAL, WXK_F7, wxID_EXECUTE); entries[i++].Set(wxACCEL_CTRL, WXK_RETURN, wxID_VIEW_DETAILS); entries[i++].Set(wxACCEL_CTRL, (int) 'T', wxID_NEW_TYPE); entries[i++].Set(wxACCEL_CTRL, (int) 'O', wxID_NEW_OBJECT); entries[i++].Set(wxACCEL_NORMAL, WXK_F8, wxID_DELETE); entries[i++].Set(wxACCEL_NORMAL, WXK_F4, wxID_EDIT); entries[i++].Set(wxACCEL_CTRL, (int) 'G', wxID_VIEW_LIST); entries[i++].Set(wxACCEL_CTRL, (int) 'P', wxID_PROPERTIES); entries[i++].Set(wxACCEL_CTRL, (int) 'N', wxID_SETUP); entries[i++].Set(wxACCEL_NORMAL, WXK_F1, wxID_HELP_INDEX); entries[i++].Set(wxACCEL_CTRL, (int) 'W', wxID_CLOSE); entries[i++].Set(wxACCEL_NORMAL, WXK_INSERT, wxID_FILE1); wxAcceleratorTable accel(i+1, entries); table->SetAcceleratorTable(accel); } //----------------------------------------------------------------------------- void ViewTableBrowser::ShowToolTip() { if (!mTable || !mTable->GetMainWindow()->IsMouseInWindow()) return; wxPoint pos = wxGetMousePosition(); pos = mTable->ScreenToClient(pos); wxDataViewItem item(nullptr); wxDataViewColumn* col = nullptr; mTable->HitTest(pos, item, col); if (!col || !item.IsOk()) return; wxString val; wxVariant var; mDvModel->GetValue(var, item, col->GetModelColumn()); if (col->GetModelColumn()==0) { wxDataViewIconText d; d << var; val = d.GetText(); } else val = var.GetString(); const IIdent64* ident = static_cast<const IIdent64*> (item.GetID()); if (!ident) return; wxString item_str; const auto cls = dynamic_cast<const ICls64*>(ident); if (cls) { item_str = wxString::Format("%s #[%s]" , cls->GetTitle() , cls->GetIdAsString()); } const auto obj = dynamic_cast<const IObj64*>(ident); if (obj) { auto cls = obj->GetCls(); item_str = wxString::Format("[%s] %s \t#[%s] %s" , cls->GetTitle(), obj->GetTitle() , cls->GetIdAsString(), obj->GetIdAsString()); if(!mDvModel->IsTop(item) && !obj->GetLockUser().empty()) { item_str += wxString::Format("\nLocked by %s at %s" , obj->GetLockUser() , obj->GetLockTime() ); } } mTable->GetTargetWindow()->SetToolTip(val+"\n\n"+ item_str); } //----------------------------------------------------------------------------- void ViewTableBrowser::OnCmd_MouseMove(wxMouseEvent& evt) { mTable->GetTargetWindow()->SetToolTip(wxEmptyString); mToolTipTimer.StartOnce(1500); SetCursorStandard(); if (!evt.AltDown()) return; auto pos = evt.GetPosition(); pos = mTable->ScreenToClient((mTable->GetMainWindow()->ClientToScreen(pos))); wxDataViewItem item(nullptr); wxDataViewColumn* col = nullptr; mTable->HitTest(pos, item, col); if (!col || !item.IsOk() || mDvModel->IsTop(item)) return; const auto model_column = col->GetModelColumn(); switch (model_column) { case 1:case 3: { wxVariant var; mDvModel->GetValue( var, item, model_column); if(!var.GetString().empty()) SetCursorHand(); return; } default:break; } auto pval = mDvModel->GetPropVal(item, col->GetModelColumn()); if (pval && pval->mProp->IsLinkOrFile() && !pval->mValue.empty() ) SetCursorHand(); } //----------------------------------------------------------------------------- void ViewTableBrowser::OnCmd_LeftUp(wxMouseEvent& evt) { evt.Skip(); if (!evt.AltDown()) return; auto pos = evt.GetPosition(); pos = mTable->ScreenToClient((mTable->GetMainWindow()->ClientToScreen(pos))); wxDataViewItem item(nullptr); wxDataViewColumn* col = nullptr; mTable->HitTest(pos, item, col); if (!col || !item.IsOk() || mDvModel->IsTop(item)) return; const auto model_column = col->GetModelColumn(); const IIdent64* ident = static_cast<const IIdent64*> (item.GetID()); const auto& obj = dynamic_cast<const IObj64*>(ident); if (obj) switch (model_column) { default:break; case 1:{ sigGotoCls(obj->GetClsId()); return; }break; case 3: { sigGotoObj(obj->GetParentId()); return; }break; }//switch (model_column) auto pval = mDvModel->GetPropVal(item, col->GetModelColumn()); if (!pval || pval->mValue.empty() || !pval->mProp->IsLinkOrFile() ) return; const wxString full_path = pval->mValue; const _TCHAR* path = full_path.wc_str(); const _TCHAR* parametrs = L""; SHELLEXECUTEINFOW ShExecInfo = { 0 }; ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; ShExecInfo.hwnd = NULL; ShExecInfo.lpVerb = NULL; ShExecInfo.lpFile = path; ShExecInfo.lpParameters = parametrs; ShExecInfo.lpDirectory = NULL; ShExecInfo.nShow = SW_SHOW; ShExecInfo.hInstApp = NULL; BOOL ret = ShellExecuteExW(&ShExecInfo); } //----------------------------------------------------------------------------- bool ViewTableBrowser::IsCursorHand()const { //const auto& cur_cursor = mTable->GetMainWindow()->GetCursor(); //const auto& hand_cursor = wxCursor(wxCURSOR_HAND); return mIsCursorHand; } //----------------------------------------------------------------------------- void ViewTableBrowser::SetCursorHand() { if (!IsCursorHand()) { mIsCursorHand = true; mTable->GetMainWindow()->SetCursor(wxCursor(wxCURSOR_HAND)); } } //----------------------------------------------------------------------------- void ViewTableBrowser::SetCursorStandard() { if (IsCursorHand()) { mIsCursorHand = false; mTable->GetMainWindow()->SetCursor(*wxSTANDARD_CURSOR); } } //----------------------------------------------------------------------------- void ViewTableBrowser::OnCmd_Activate(wxDataViewEvent& evt) { TEST_FUNC_TIME; auto item = evt.GetItem(); if (mTable->GetModel()->IsContainer(item)) { if (mTable->IsExpanded(item)) mTable->Collapse(item); else mTable->Expand(item); } else { wxBusyCursor busyCursor; const IIdent64* node = static_cast<const IIdent64*> (item.GetID()); if (node->GetId() == mParentCid) sigUp(); else { const int mode = mDvModel->GetMode(); if (0 == mode) { const ICls64* cls = dynamic_cast<const ICls64*> (node); if (cls) { // ะตัะปะธ ัƒะฑั€ะฐั‚ัŒ ัั‚ะพั‚ ะปะพะบะตั€, ะฒั‹ะดะตะปะธั‚ัั ะฟะตั€ะฒั‹ะน ัะปะตะผะตะฝั‚, // ะดะฐะถะต ะฒ ะพะฑั€ะฐั‚ะฝะพะน ัะพั€ั‚ะธั€ะพะฒะบะต wxWindowUpdateLocker lock(mTable); sigActivate(cls->GetId()); } } else if (1 == mode) { const IObj64* obj = dynamic_cast<const IObj64*> (node); if (obj) { wxWindowUpdateLocker lock(mTable); sigActivate(obj->GetId()); } } } }// else if (mTable->GetModel()->IsContainer(item)) } //----------------------------------------------------------------------------- void ViewTableBrowser::OnCmd_Expanding(wxDataViewEvent& evt) { TEST_FUNC_TIME; auto item = evt.GetItem(); const IIdent64* node = static_cast<const IIdent64*> (item.GetID()); const ICls64* cls = dynamic_cast<const ICls64*> (node); if (cls) { mSortCol = mTable->GetSortingColumn(); if (mSortCol) { mSortAsc = mSortCol->IsSortOrderAscending(); mSortCol->UnsetAsSortKey(); } wxBusyCursor busyCursor; wxWindowUpdateLocker lock(mTable); //sigActivate(cls->GetId()); sigRefreshClsObjects(cls->GetId()); const std::shared_ptr<const ICls64::ObjTable> ot = cls->GetObjTable(); if (ot && ot->size()) { std::vector<const IIdent64*> vec; for (const auto& obj : *ot) vec.emplace_back(obj.get()); RebuildClsColumns(vec); } } } //----------------------------------------------------------------------------- void ViewTableBrowser::OnCmd_Expanded(wxDataViewEvent& evt) { TEST_FUNC_TIME; if (mSortCol) { mSortCol->SetSortable(true); mSortCol->SetSortOrder(mSortAsc); wxBusyCursor busyCursor; wxWindowUpdateLocker lock(mTable); mTable->GetModel()->Resort(); } AutosizeColumns(); auto item = evt.GetItem(); const IIdent64* node = static_cast<const IIdent64*> (item.GetID()); const ICls64* cls = dynamic_cast<const ICls64*> (node); if (cls) mExpandedCls.insert(cls->GetId()); } //----------------------------------------------------------------------------- void ViewTableBrowser::OnCmd_Collapseded(wxDataViewEvent& evt) { auto item = evt.GetItem(); if (item.IsOk()) { auto model = mTable->GetModel(); auto dvparent = evt.GetItem(); wxDataViewItemArray arr; model->GetChildren(dvparent, arr); model->ItemsDeleted(dvparent, arr); const IIdent64* node = static_cast<const IIdent64*> (item.GetID()); const ICls64* cls = dynamic_cast<const ICls64*> (node); if (cls) mExpandedCls.erase(cls->GetId()); } } //----------------------------------------------------------------------------- const IIdent64* ViewTableBrowser::FindChildCls(const int64_t& id)const { //wxDataViewItem dvparent(nullptr); //auto model = mTable->GetModel(); //wxDataViewItemArray arr; //model->GetChildren(dvparent, arr); //for (size_t i = 0; i < arr.size() ; i++) //{ // const auto ident = static_cast<const IIdent64*> (arr[i].GetID()); // const auto cls = dynamic_cast<const ICls64*>(ident); // if (cls && cls->GetId() == id) // return cls; //} const auto& cls_list = mDvModel->GetClsList(); if (cls_list.empty()) return nullptr; auto it = std::find_if(cls_list.cbegin(), cls_list.cend() , [&id](const IIdent64* it) { return it->GetId() == id; }); if (cls_list.cend() != it) return (*it); return nullptr; } //----------------------------------------------------------------------------- const IIdent64* ViewTableBrowser::GetTopChildCls()const { //wxDataViewItem dvparent(nullptr); //auto model = mTable->GetModel(); //wxDataViewItemArray arr; //model->GetChildren(dvparent, arr); //const auto ident = static_cast<const IIdent64*> (arr[0].GetID()); //const auto cls = dynamic_cast<const ICls64*>(ident); //if (cls) // return cls; //return nullptr; if (1 < mParentCid) //(mParent && 1 != mParent->GetId()) return mDvModel->GetCurrentRoot(); if (!mDvModel->GetClsList().empty()) return mDvModel->GetClsList().front(); return nullptr; } //----------------------------------------------------------------------------- void ViewTableBrowser::StoreSelect() { // if UP action add to stored current auto item = mTable->GetCurrentItem(); auto ident = static_cast<const IIdent64*> (item.GetID()); if (!ident) return; const ICls64* cls = dynamic_cast<const ICls64*>(ident); const IObj64* obj = dynamic_cast<const IObj64*>(ident); if (obj) { mObjSelected.emplace(ObjectKey(obj->GetId(), obj->GetParentId())); mExpandedCls.emplace(obj->GetClsId()); } else if (cls) { mClsSelected.emplace(cls->GetId()); mExpandedCls.emplace(cls->GetId()); } } //----------------------------------------------------------------------------- void ViewTableBrowser::RestoreSelect() { wxDataViewItem dvitem; wxDataViewItemArray arr; // indexing std::map<int64_t, const IIdent64*> clsIdx; std::map<ObjectKey, const IIdent64*> objIdx; const auto& top_list = mDvModel->GetClsList(); for (const auto& ident : top_list) { const auto obj = dynamic_cast<const IObj64*>(ident); if (obj) objIdx.emplace(ObjectKey(obj->GetId(), obj->GetParentId()), ident); else { const auto cls = dynamic_cast<const ICls64*>(ident); if (cls) { const auto ex = mExpandedCls.find(cls->GetId()); if (mExpandedCls.end() != ex) { wxDataViewEvent evt; evt.SetItem(wxDataViewItem((void*)cls)); //OnCmd_Expanding(evt); } clsIdx.emplace(cls->GetId(), ident); const auto objTable = cls->GetObjTable(); if (objTable) { const std::vector<std::shared_ptr<const IObj64>> ot = *objTable; for (size_t i = 0; i < ot.size(); ++i) { const auto idnt = ot[i].get(); objIdx.emplace( ObjectKey(ot[i]->GetId(), ot[i]->GetParentId()), idnt); }// for (const auto& obj : ot); }//if (objTable) }//if (cls) } } // select if (mObjSelected.empty()) { for (const auto& cls_id : mClsSelected) { const auto find_it = clsIdx.find(cls_id); if (clsIdx.end() != find_it) { const IIdent64* finded = find_it->second; dvitem = wxDataViewItem((void*)finded); arr.Add(dvitem); } }// for }// if else //if (mClsSelected.empty()) { for (const auto& okey : mObjSelected) { const auto find_it = objIdx.find(okey); if (objIdx.end() != find_it) { const IIdent64* finded = find_it->second; dvitem = wxDataViewItem((void*)finded); arr.Add(dvitem); } }// for }//else if if(arr.empty()) { dvitem = mTable->GetTopItem(); arr.Add(dvitem); } mTable->SetSelections(arr); if (arr.size()) { dvitem = *arr.rbegin(); if (dvitem.IsOk()) { mTable->EnsureVisible(dvitem); mTable->SetCurrentItem(dvitem); } } return; } //----------------------------------------------------------------------------- void ViewTableBrowser::AutosizeColumns() { if (!mColAutosize) return; TEST_FUNC_TIME; wxBusyCursor busyCursor; //for (size_t i = 0; i < mTable->GetColumnCount(); i++) for (size_t i = 0; i < 4; i++) { auto col_pos = mTable->GetModelColumnIndex(i); auto col = mTable->GetColumn(col_pos); if (col) { auto bs = mTable->GetBestColumnWidth(i); if (bs > 300) bs = 300; col->SetWidth(bs); } } } //----------------------------------------------------------------------------- void ViewTableBrowser::ResetColumns() { wxWindowUpdateLocker lock(mTable); auto table = mTable; if (4 == table->GetColumnCount() ) return; table->ClearColumns(); mDvModel->mActColumns.clear(); mDvModel->mCPropColumns.clear(); mDvModel->mOPropColumns.clear(); auto renderer1 = new wxDataViewIconTextRenderer(); //auto attr = renderer1->GetAttr(); //attr.SetColour(*wxBLACK); //renderer1->SetAttr(attr); //table->AppendTextColumn("#", 0,wxDATAVIEW_CELL_INERT,-1, wxALIGN_LEFT // , wxDATAVIEW_COL_RESIZABLE /*| wxDATAVIEW_COL_HIDDEN*/); auto col1 = new wxDataViewColumn("ะ˜ะผั" , renderer1, 0, 150, wxALIGN_NOT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE); table->AppendColumn(col1); //col1->SetSortOrder(true); auto col3 = table->AppendTextColumn("ะขะธะฟ",1, wxDATAVIEW_CELL_INERT, -1 , wxALIGN_NOT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE); //col3->GetRenderer()->EnableEllipsize(wxELLIPSIZE_START); wxDataViewCellMode qtyMode = mDvModel->IsEditableQty() ? wxDATAVIEW_CELL_EDITABLE : wxDATAVIEW_CELL_INERT; auto col2 = table->AppendTextColumn("ะšะพะปะธั‡ะตัั‚ะฒะพ", 2, qtyMode, 150 , wxALIGN_NOT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE); col2->SetHidden(!mVisibleQtyCol); auto col4 = table->AppendTextColumn("ะœะตัั‚ะพะฟะพะปะพะถะตะฝะธะต", 3, wxDATAVIEW_CELL_INERT, -1 , wxALIGN_NOT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE); col4->GetRenderer()->EnableEllipsize(wxELLIPSIZE_START); table->SetExpanderColumn(col1); } //----------------------------------------------------------------------------- void ViewTableBrowser::RebuildClsColumns(const std::vector<const IIdent64*>& vec) { const auto col_qty = mTable->GetColumnCount(); auto last_col = mTable->GetColumnAt(col_qty - 1); for (const auto& ident : vec) { const auto cls = dynamic_cast<const ICls64*>(ident); if (cls) { const auto& fav_cprop = cls->GetFavCPropValue(); for (const auto& cprop : fav_cprop) AppendPropColumn(mDvModel->mCPropColumns, cprop); const auto& fav_act = cls->GetFavAProp(); for (const auto& aprop : fav_act) AppendActColumn(aprop); } else { const auto obj = dynamic_cast<const IObj64*>(ident); if (obj) { const auto cls = obj->GetCls(); const auto& fav_cprop = cls->GetFavCPropValue(); for (const auto& cprop : fav_cprop) AppendPropColumn(mDvModel->mCPropColumns, cprop); const auto& fav_cact = cls->GetFavAProp(); for (const auto& aprop : fav_cact) AppendActColumn(aprop); const auto& fav_oact = obj->GetFavAPropValue(); for (const auto& aprop_val : fav_oact) AppendActColumn(aprop_val->mFavActProp); const auto& fav_prop = obj->GetFavOPropValue(); for (const auto& oprop : fav_prop) AppendPropColumn(mDvModel->mOPropColumns, oprop); }//if (obj) } }//for (const auto& obj : *ot) if(col_qty != mTable->GetColumnCount()) last_col->SetWidth(GetTitleWidth(last_col->GetTitle())); } //----------------------------------------------------------------------------- void ViewTableBrowser::AppendActColumn(const std::shared_ptr<const FavAProp>& aprop) { auto aid = aprop->mAct->GetId(); FavAPropInfo info = aprop->mInfo; auto& idx0 = mDvModel->mActColumns.get<0>(); auto it = idx0.find(boost::make_tuple(aid, info)); if (idx0.end() == it) { const auto column_idx = mTable->GetColumnCount(); const wxString title = wxString::Format("%s %s" , aprop->mAct->GetTitle() , FavAPropInfo2Text(info)); auto col = AppendTableColumn(title, column_idx); const auto& ico = GetIcon(info); col->SetBitmap(ico); ActColumn acol(aid, info, column_idx); mDvModel->mActColumns.emplace(acol); } } //----------------------------------------------------------------------------- void ViewTableBrowser::AppendPropColumn(PropColumns& prop_column ,const std::shared_ptr<const PropVal>& prop_val) { const int64_t pid = prop_val->mProp->GetId(); auto& pcolIdx = prop_column; auto it = pcolIdx.find(pid); if (pcolIdx.end() == it) { const auto column_idx = mTable->GetColumnCount(); const wxString& title = prop_val->mProp->GetTitle().empty() ? prop_val->mProp->GetIdAsString() : prop_val->mProp->GetTitle(); AppendTableColumn(title, column_idx); PropColumn prop_col(pid, column_idx); pcolIdx.emplace(prop_col); } } //----------------------------------------------------------------------------- wxDataViewColumn* ViewTableBrowser::AppendTableColumn(const wxString& title, int model_id) { auto col = mTable->AppendTextColumn(title, model_id , wxDATAVIEW_CELL_INERT , GetTitleWidth(title) , wxALIGN_NOT , wxDATAVIEW_COL_REORDERABLE | wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE); col->SetMinWidth(80); return col; } //----------------------------------------------------------------------------- int ViewTableBrowser::GetTitleWidth(const wxString& title)const { const int spw = mTable->GetTextExtent(" ").GetWidth(); int hw = mTable->GetTextExtent(title).GetWidth()+ spw*4 + 24; if (hw < 80) hw = -1; // default width else if (hw > 300) hw = 300; return hw; } //----------------------------------------------------------------------------- //virtual void ViewTableBrowser::SetBeforeRefreshCls(const std::vector<const IIdent64*>& vec , const IIdent64* parent , const wxString& , bool group_by_type , int mode ) //override; { TEST_FUNC_TIME; StoreSelect(); /* mClsSelected = 0; mObjSelected = 0; if (parent && mParentCid) { auto curr_id = mParentCid; auto new_id = parent->GetId(); if(curr_id== new_id) StoreSelect(); else mClsSelected = curr_id; } else if(parent) { mClsSelected = parent->GetId(); } */ ResetColumns(); mParentCid = 0; mDvModel->SetClsList(vec, nullptr, group_by_type, mode); //wxBusyCursor busyCursor; //wxWindowUpdateLocker lock(mTable); //OnCmd_Select(wxDataViewEvent()); } //----------------------------------------------------------------------------- //virtual void ViewTableBrowser::SetAfterRefreshCls(const std::vector<const IIdent64*>& vec , const IIdent64* root , const wxString& ss , bool group_by_type , int mode ) //override; { TEST_FUNC_TIME; { wxBusyCursor busyCursor; wxWindowUpdateLocker lock(mTable); auto clsColumn = mTable->GetColumn(1); auto pathColumn = mTable->GetColumn(3); switch (mode) { case 0: { pathColumn->SetHidden(false); if (root) clsColumn->SetHidden(true); else clsColumn->SetHidden(!mTable->GetModel()->IsListModel()); }break; case 1: { clsColumn->SetHidden(!mTable->GetModel()->IsListModel()); pathColumn->SetHidden((bool)root); }break; default: break; } mParentCid = root ? root->GetId() : 0; mDvModel->SetClsList(vec , (root && 1 != root->GetId()) ? root : nullptr , group_by_type , mode ); if (!mDvModel->IsListModel()) { bool tmp_autosize = mColAutosize; mColAutosize = false; for (const auto& cid : mExpandedCls) { auto ident = FindChildCls(cid); if (ident) { wxDataViewItem item((void*)ident); mTable->Expand(item); } }//for (const auto& cid : mExpandedCls) mColAutosize = tmp_autosize; } //else { RebuildClsColumns(vec); } AutosizeColumns(); RestoreSelect(); } } //----------------------------------------------------------------------------- //virtual void ViewTableBrowser::SetObjOperation(Operation op, const std::vector<const IIdent64*>& obj_list)// override; { TEST_FUNC_TIME; wxBusyCursor busyCursor; wxWindowUpdateLocker lock(mTable); switch (op) { case Operation::BeforeInsert: break; case Operation::AfterInsert: // ั‚ะพั€ะผะพะทะธั‚ ะฟั€ะธ ะดะพะฑะฐะฒะปะตะฝะธะธ ะฑะพะปัŒัˆะพะณะพ ะบะพะปะธั‡ะตัั‚ะฒะฐ ัะปะตะผะตะฝั‚ะพะฒ //for (const auto& item : obj_list) //{ // wxDataViewItem cls((void*)item->GetCls().get()); // wxDataViewItem obj((void*)item); // dvmodel->ItemAdded(cls, obj); //} RebuildClsColumns(obj_list); break; case Operation::BeforeUpdate: break; case Operation::AfterUpdate: for (const auto& item : obj_list) { //wxDataViewItem cls((void*)item->GetCls().get()); wxDataViewItem obj((void*)item); mDvModel->ItemChanged(obj); } break; case Operation::BeforeDelete: for (const auto& item : obj_list) { const auto obj = dynamic_cast<const IObj64*>(item); wxDataViewItem item_cls((void*)obj->GetCls().get()); wxDataViewItem item_obj((void*)item); mDvModel->ItemDeleted(item_cls, item_obj); } break; case Operation::AfterDelete: break; default: break; } //AutosizeColumns(); } //----------------------------------------------------------------------------- void wh::ViewTableBrowser::SetShowFav() { const IIdent64* ident = static_cast<const IIdent64*> (mTable->GetCurrentItem().GetID()); if (ident) { const auto& obj = dynamic_cast<const IObj64*>(ident); if (obj) sigShowFav(obj->GetClsId() ); else { const auto& cls = dynamic_cast<const ICls64*>(ident); if (cls) sigShowFav(cls->GetId()); } }//if (ident) } //----------------------------------------------------------------------------- //virtual void wh::ViewTableBrowser::SetInsertType() const //override; { int64_t parent_cid = 1; auto rootIdent = mDvModel->GetCurrentRoot(); if (rootIdent) { const auto* cls = dynamic_cast<const ICls64*>(rootIdent); if(cls) parent_cid = cls->GetId(); } sigClsInsert(parent_cid); } //----------------------------------------------------------------------------- //virtual void wh::ViewTableBrowser::SetInsertObj() const //override; { const IIdent64* ident = static_cast<const IIdent64*> (mTable->GetCurrentItem().GetID()); if (!ident) return; const auto& cls = dynamic_cast<const ICls64*>(ident); if (cls) { int64_t cid = cls->GetId(); sigObjInsert(cid); } const auto& obj = dynamic_cast<const IObj64*>(ident); if (obj) { int64_t cid = obj->GetCls()->GetId(); sigObjInsert(cid); } } //----------------------------------------------------------------------------- //virtual void wh::ViewTableBrowser::SetUpdateSelected() const //override; { const IIdent64* ident = static_cast<const IIdent64*> (mTable->GetCurrentItem().GetID()); if (!ident) return; const auto& cls = dynamic_cast<const ICls64*>(ident); if (cls) { int64_t cid = cls->GetId(); sigClsUpdate(cid); } else { const auto& obj = dynamic_cast<const IObj64*>(ident); if (obj) { int64_t oid = obj->GetId(); int64_t parent_oid = obj->GetParentId(); sigObjUpdate(oid, parent_oid); } } } //----------------------------------------------------------------------------- //virtual void wh::ViewTableBrowser::GetSelection(std::vector<const IIdent64*>& sel)const { const IIdent64* ident = nullptr; wxDataViewItemArray arr; mTable->GetSelections(arr); for (size_t i = 0; i < arr.size(); i++) { ident = static_cast<const IIdent64*> (arr[i].GetID()); sel.emplace_back(ident); } } //----------------------------------------------------------------------------- //virtual void wh::ViewTableBrowser::SetSelected() const //override; { wxUIActionSimulator sim; sim.KeyDown(WXK_DOWN, wxMOD_SHIFT); sim.KeyUp(WXK_DOWN, wxMOD_SHIFT); } //----------------------------------------------------------------------------- void wh::ViewTableBrowser::OnCmd_SelectionChanged(wxDataViewEvent& evt) { std::set<int64_t>& clsSel = mClsSelected; std::set<ObjectKey>& objSel = mObjSelected; clsSel.clear(); objSel.clear(); const auto sel_count = mTable->GetSelectedItemsCount(); if (0 == sel_count) { mTable->UnselectAll(); return; } wxDataViewItemArray arr; mTable->GetSelections(arr); size_t i = 0; wxDataViewItem selected_item; const IIdent64* ident=nullptr; for (; i < sel_count; i++) { selected_item = arr[i]; ident = static_cast<const IIdent64*> (selected_item.GetID()); if (!ident || mDvModel->IsTop(selected_item)) { mTable->Unselect(selected_item); ident = nullptr; } else { i++; break; } } const ICls64* cls = dynamic_cast<const ICls64*>(ident); const IObj64* obj = dynamic_cast<const IObj64*>(ident); if (obj) objSel.emplace(ObjectKey(obj->GetId(), obj->GetParentId())); else if (cls) clsSel.emplace(cls->GetId()); else mTable->UnselectAll(); for ( ; i < sel_count; i++) { selected_item = arr[i]; ident = static_cast<const IIdent64*> (selected_item.GetID()); if (!ident || mDvModel->IsTop(selected_item)) mTable->Unselect(selected_item); cls = dynamic_cast<const ICls64*>(ident); obj = dynamic_cast<const IObj64*>(ident); if (clsSel.empty()) { if (obj) objSel.emplace(ObjectKey(obj->GetId(), obj->GetParentId())); else mTable->Unselect(selected_item); } else if (objSel.empty()) { if (cls) clsSel.emplace(cls->GetId()); else mTable->Unselect(selected_item); } else mTable->Unselect(selected_item); } } //----------------------------------------------------------------------------- void ViewTableBrowser::SetEditableQty(bool editable) { if (mDvModel->IsEditableQty() == editable) return; mDvModel->SetEditableQty(editable); mTable->ClearColumns(); ResetColumns(); } //----------------------------------------------------------------------------- void ViewTableBrowser::SetVisibleQty(bool visible) { auto col_idx = mTable->GetModelColumnIndex(2); auto col = mTable->GetColumn(col_idx); if (!col) return; if (col->IsShown() == visible) return; mVisibleQtyCol = visible; mTable->ClearColumns(); ResetColumns(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- ViewToolbarBrowser::ViewToolbarBrowser(const std::shared_ptr<IViewWindow>& parent) :ViewToolbarBrowser(parent->GetWnd()) {} //----------------------------------------------------------------------------- ViewToolbarBrowser::ViewToolbarBrowser(wxWindow* parent) { const auto& currBaseGroup = whDataMgr::GetInstance()->mDbCfg->mBaseGroup->GetData(); auto mgr = ResMgr::GetInstance(); long style = wxAUI_TB_DEFAULT_STYLE | wxAUI_TB_PLAIN_BACKGROUND | wxAUI_TB_TEXT //| wxAUI_TB_HORZ_TEXT | wxAUI_TB_OVERFLOW ; auto tool_bar = new wxAuiToolBar(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, style); tool_bar->AddTool(wxID_REFRESH, "ะžะฑะฝะพะฒะธั‚ัŒ", mgr->m_ico_refresh24, "ะžะฑะฝะพะฒะธั‚ัŒ (CTRL+R ะธะปะธ CTRL+F5)"); //tool_bar->AddTool(wxID_UP,"ะ’ะฒะตั€ั…", mgr->m_ico_back24, "ะ’ะฒะตั€ั…(BACKSPACE)"); tool_bar->AddTool(wxID_REPLACE, "ะŸะตั€ะตะผะตัั‚ะธั‚ัŒ", mgr->m_ico_move24, "ะŸะตั€ะตะผะตัั‚ะธั‚ัŒ (F6)"); tool_bar->AddTool(wxID_EXECUTE, "ะ’ั‹ะฟะพะปะฝะธั‚ัŒ", mgr->m_ico_act24, "ะ’ั‹ะฟะพะปะฝะธั‚ัŒ (F7)"); tool_bar->AddTool(wxID_VIEW_DETAILS, "ะŸะพะดั€ะพะฑะฝะพ", mgr->m_ico_views24, "ะŸะพะดั€ะพะฑะฝะพ (CTRL+ENTER)"); if ((int)currBaseGroup > (int)bgUser) { tool_bar->AddSeparator(); auto add_tool = tool_bar->AddTool(wxID_ADD, "ะกะพะทะดะฐั‚ัŒ", mgr->m_ico_plus24 , "ะกะพะทะดะฐั‚ัŒ ั‚ะธะฟ ะธะปะธ ะพะฑัŒะตะบั‚ (CTRL+INSERT)"); add_tool->SetHasDropDown(true); tool_bar->Bind(wxEVT_AUITOOLBAR_TOOL_DROPDOWN , [this, mgr, &currBaseGroup](wxCommandEvent& evt) { wxAuiToolBar* tb = static_cast<wxAuiToolBar*>(evt.GetEventObject()); tb->SetToolSticky(evt.GetId(), true); wxMenu add_menu; if ((int)currBaseGroup >= (int)bgTypeDesigner) AppendBitmapMenu(&add_menu, wxID_NEW_TYPE, "ะกะพะทะดะฐั‚ัŒ ั‚ะธะฟ (CTRL+T)", mgr->m_ico_add_type24); if ((int)currBaseGroup >= (int)bgObjDesigner) AppendBitmapMenu(&add_menu, wxID_NEW_OBJECT, "ะกะพะทะดะฐั‚ัŒ ะพะฑัŠะตะบั‚ (CTRL+O)", mgr->m_ico_add_obj24); wxRect rect = tb->GetToolRect(evt.GetId()); wxPoint pt = tb->ClientToScreen(rect.GetBottomLeft()); pt = tb->ScreenToClient(pt); tb->PopupMenu(&add_menu, pt); tb->SetToolSticky(evt.GetId(), false); tb->Refresh(); } , wxID_ADD); tool_bar->AddTool(wxID_DELETE, "ะฃะดะฐะปะธั‚ัŒ", mgr->m_ico_delete24, "ะฃะดะฐะปะธั‚ัŒ (F8)"); tool_bar->AddTool(wxID_EDIT, "ะ ะตะดะฐะบั‚ะธั€ะพะฒะฐั‚ัŒ", mgr->m_ico_edit24, "ะ ะตะดะฐะบั‚ะธั€ะพะฒะฐั‚ัŒ (F4)"); } tool_bar->AddSeparator(); tool_bar->AddTool(wxID_VIEW_LIST, "ะ“ั€ัƒะฟะฟะธั€ะพะฒะฐั‚ัŒ", mgr->m_ico_group_by_type24, "ะ“ั€ัƒะฟะฟะธั€ะพะฒะฐั‚ัŒ ะฟะพ ั‚ะธะฟัƒ (CTRL+G)"); tool_bar->AddTool(wxID_PROPERTIES, "ะกะฒะพะนัั‚ะฒะฐ", mgr->m_ico_favprop_select24, "ะ’ั‹ะฑั€ะฐั‚ัŒ ัะฒะพะนัั‚ะฒะฐ (CTRL+P)"); //tool_bar->AddTool(wxID_SETUP, "ะะฐัั‚ั€ะพะนะบะธ", mgr->m_ico_options24 // , "ะะฐัั‚ั€ะพะนะบะธ ะฒะฝะตัˆะฝะตะณะพ ะฒะธะดะฐ ั‚ะฐะฑะปะธะนั‹ ะธัั‚ะพั€ะธะธ (CTRL+N)"); tool_bar->AddTool(wxID_HELP_INDEX, "ะกะฟั€ะฐะฒะบะฐ", wxArtProvider::GetBitmap(wxART_HELP, wxART_TOOLBAR), "ะกะฟั€ะฐะฒะบะฐ (F1)"); //tool_bar->AddSeparator(); //auto mFindCtrl = new wxComboBtn(tool_bar, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); //wxBitmap bmp(wxArtProvider::GetBitmap(wxART_FIND, wxART_MENU)); //mFindCtrl->SetButtonBitmaps(bmp, true); ////mFindCtrl->Bind(wxEVT_COMMAND_TEXT_ENTER, fn); //tool_bar->AddControl(mFindCtrl, "ะŸะพะธัะบ"); tool_bar->Realize(); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigRefresh();}, wxID_REFRESH); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigUp();}, wxID_UP); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigAct();}, wxID_EXECUTE); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigMove();}, wxID_REPLACE); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigShowDetail();}, wxID_VIEW_DETAILS); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigInsertType(); }, wxID_NEW_TYPE); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigInsertObject(); }, wxID_NEW_OBJECT); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigDelete(); }, wxID_DELETE); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigUpdate(); }, wxID_EDIT); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED , &ViewToolbarBrowser::OnCmd_GroupByType, this, wxID_VIEW_LIST); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigShowFav(); }, wxID_PROPERTIES); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) { sigShowSettings(); }, wxID_SETUP); tool_bar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigShowHelp("PageBrowserByType"); }, wxID_HELP_INDEX); mToolbar = tool_bar; } //----------------------------------------------------------------------------- void ViewToolbarBrowser::OnCmd_GroupByType(wxCommandEvent& evt) { int state = mToolbar->FindTool(wxID_VIEW_LIST)->GetState(); int enable = state & wxAUI_BUTTON_STATE_CHECKED; sigGroupByType(enable ? false : true); } //----------------------------------------------------------------------------- //virtual void ViewToolbarBrowser::SetVisibleFilters(bool enable)// override; { } //----------------------------------------------------------------------------- //virtual void ViewToolbarBrowser::SetAfterRefreshCls(const std::vector<const IIdent64*>& vec , const IIdent64* root , const wxString& ss , bool group_by_type , int mode ) //override; { int show; show = group_by_type ? wxAUI_BUTTON_STATE_CHECKED : wxAUI_BUTTON_STATE_NORMAL; mToolbar->FindTool(wxID_VIEW_LIST)->SetState(show); mToolbar->Refresh(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- ViewPathBrowser::ViewPathBrowser(const std::shared_ptr<IViewWindow>& parent) :ViewPathBrowser(parent->GetWnd()) { } //----------------------------------------------------------------------------- ViewPathBrowser::ViewPathBrowser(wxWindow* parent) { mPathCtrl = new wxTextCtrl(parent, wxID_ANY, wxEmptyString , wxDefaultPosition, wxDefaultSize, 0 | wxTE_READONLY /*| wxNO_BORDER*/); //auto window_colour = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW); //mPathCtrl->SetBackgroundColour(window_colour); } //----------------------------------------------------------------------------- //virtual void ViewPathBrowser::SetPathMode(const int mode)// override; { } //----------------------------------------------------------------------------- //virtual void ViewPathBrowser::SetPathString(const wxString& str)// override; { mPathCtrl->SetValue(str); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- ViewBrowserPage::ViewBrowserPage(const std::shared_ptr<IViewWindow>& parent) :ViewBrowserPage(parent->GetWnd()) { } //----------------------------------------------------------------------------- ViewBrowserPage::ViewBrowserPage(wxWindow* parent) { auto mgr = ResMgr::GetInstance(); auto panel = new wxAuiPanel(parent); mAuiMgr = &panel->mAuiMgr; //mAuiMgr->SetFlags(wxAUI_MGR_LIVE_RESIZE); mPanel = panel; auto window_colour = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW); auto face_colour = wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE); panel->mAuiMgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BACKGROUND_COLOUR, face_colour); //panel->mAuiMgr.GetArtProvider()->SetColor(wxAUI_DOCKART_SASH_COLOUR, face_colour); //panel->mAuiMgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BORDER_COLOUR, face_colour); //panel->mAuiMgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BACKGROUND_COLOUR, *wxRED); //panel->mAuiMgr.GetArtProvider()->SetColor(wxAUI_DOCKART_SASH_COLOUR, *wxGREEN); //panel->mAuiMgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BORDER_COLOUR, *wxBLUE); //panel->mAuiMgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_SASH_SIZE,2); panel->mAuiMgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE, 0); // toolbar mViewToolbarBrowser = std::make_shared<ViewToolbarBrowser>(panel); panel->mAuiMgr.AddPane(mViewToolbarBrowser->GetWnd(), wxAuiPaneInfo().Name(wxT("BrowserToolBar")) .CaptionVisible(false).PaneBorder(false) .Top().Dock().Floatable(false).ToolbarPane().Gripper(false) ); // path panel auto path_panel = new wxAuiPanel(panel); path_panel->mAuiMgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BACKGROUND_COLOUR, face_colour); path_panel->mAuiMgr.GetArtProvider()->SetColor(wxAUI_DOCKART_SASH_COLOUR, face_colour); // browswer mode long style = wxAUI_TB_DEFAULT_STYLE | wxAUI_TB_PLAIN_BACKGROUND //| wxAUI_TB_TEXT //| wxAUI_TB_HORZ_TEXT //| wxAUI_TB_OVERFLOW ; mModeToolBar = new wxAuiToolBar(path_panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, style); //tool_bar->AddTool(wxID_REFRESH, "ะžะฑะฝะพะฒะธั‚ัŒ", mgr->m_ico_refresh16, "ะžะฑะฝะพะฒะธั‚ัŒ (CTRL+R ะธะปะธ CTRL+F5)"); mModeTool = mModeToolBar->AddTool(whID_CATALOG_SELECT, "ะšะฐั‚ะฐะปะพะณ", mgr->m_ico_dir_obj16 , "ะ’ั‹ะฑั€ะฐั‚ัŒ ะšะฐั‚ะฐะปะพะณ(CTRL+D)"); mModeTool->SetHasDropDown(true); mModeToolBar->Bind(wxEVT_AUITOOLBAR_TOOL_DROPDOWN , [this, mgr](wxCommandEvent& evt) { wxAuiToolBar* tb = static_cast<wxAuiToolBar*>(evt.GetEventObject()); tb->SetToolSticky(evt.GetId(), true); wxMenu add_menu; AppendBitmapMenu(&add_menu, whID_CATALOG_PATH, "ะšะฐั‚ะฐะปะพะณ ะฟะพ ะผะตัั‚ะพะฟะพะปะพะถะตะฝะธัŽ", mgr->m_ico_dir_obj16); AppendBitmapMenu(&add_menu, whID_CATALOG_TYPE, "ะšะฐั‚ะฐะปะพะณ ะฟะพ ั‚ะธะฟัƒ", mgr->m_ico_dir_cls16); //auto fav_item = AppendBitmapMenu(&add_menu, whID_CATALOG_FAVORITE, "ะ˜ะทั€ะฐะฝะฝะพะต", mgr->m_ico_favorite16); //fav_item->Enable(false); wxRect rect = tb->GetToolRect(evt.GetId()); wxPoint pt = tb->ClientToScreen(rect.GetBottomLeft()); pt = tb->ScreenToClient(pt); tb->PopupMenu(&add_menu, pt); tb->SetToolSticky(evt.GetId(), false); tb->Refresh(); } , whID_CATALOG_SELECT); mModeToolBar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigMode(1); }, whID_CATALOG_PATH); mModeToolBar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigMode(0); }, whID_CATALOG_TYPE); mModeToolBar->Realize(); wxAuiPaneInfo bcb_pi; bcb_pi.Name(wxT("PathToolBar")).Top().CaptionVisible(false)//.Dock() .PaneBorder(false).Resizable(false); path_panel->mAuiMgr.AddPane(mModeToolBar, bcb_pi); // path mViewPathBrowser = std::make_shared<ViewPathBrowser>(path_panel); const auto path_bs = mViewPathBrowser->GetWnd()->GetBestSize(); wxAuiPaneInfo path_pi; path_pi.Name(wxT("PathBrowser")).Top().CaptionVisible(false).Dock().PaneBorder(false) .Resizable().MinSize(path_bs).MaxSize(-1,path_bs.GetHeight()); path_pi.dock_proportion = 7; path_panel->mAuiMgr.AddPane(mViewPathBrowser->GetWnd(), path_pi); // search mCtrlFind = new wxSearchCtrl(path_panel, wxID_ANY); mCtrlFind->ShowSearchButton(true); mCtrlFind->ShowCancelButton(true); mCtrlFind->SetDescriptiveText("ะ‘ั‹ัั‚ั€ั‹ะน ะฟะพะธัะบ"); const auto search_bs = mCtrlFind->GetBestSize(); wxAuiPaneInfo search_pi; search_pi.Name(wxT("SearchCtrl")).Top().CaptionVisible(false).Dock().PaneBorder(false) .MinSize(search_bs).MaxSize(-1, search_bs.GetHeight()); search_pi.dock_proportion = 3; path_panel->mAuiMgr.AddPane(mCtrlFind, search_pi); // path_panel---> panel panel->mAuiMgr.AddPane(path_panel, wxAuiPaneInfo().Name("Splitter").Top().Row(1).CaptionVisible(false).Dock().PaneBorder(false) .Fixed().MinSize(-1, search_bs.GetHeight()).MaxSize(-1, search_bs.GetHeight())); path_panel->mAuiMgr.Update(); // table mViewTableBrowser = std::make_shared<ViewTableBrowser>(panel); panel->mAuiMgr.AddPane(mViewTableBrowser->GetWnd(), wxAuiPaneInfo().Name(wxT("TableBrowser")) .Center().CaptionVisible(false).Dock().CentrePane().PaneBorder(false) ); //mViewTableBrowser->GetWnd()->SetFocus(); panel->mAuiMgr.Update(); mCtrlFind->Bind(wxEVT_SEARCH, &ViewBrowserPage::OnCmd_Find, this); mCtrlFind->Bind(wxEVT_SEARCH_CANCEL , [this](wxCommandEvent& event) { sigFind(wxEmptyString); }); panel->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) { sigClosePage(); }, wxID_CLOSE); } //----------------------------------------------------------------------------- void ViewBrowserPage::OnCmd_Find(wxCommandEvent& evt) { auto obj = evt.GetEventObject(); wxString ss; wxTextCtrl* txtCtrl = wxDynamicCast(obj, wxTextCtrl); if (txtCtrl) ss = txtCtrl->GetValue(); else { wxSearchCtrl* txtCtrl = wxDynamicCast(obj, wxSearchCtrl); if (txtCtrl) ss = txtCtrl->GetValue(); } sigFind(ss); } //----------------------------------------------------------------------------- //virtual std::shared_ptr<IViewToolbarBrowser> ViewBrowserPage::GetViewToolbarBrowser()const// override; { return mViewToolbarBrowser; } //----------------------------------------------------------------------------- //virtual std::shared_ptr<IViewPathBrowser> ViewBrowserPage::GetViewPathBrowser()const// override; { return mViewPathBrowser; } //----------------------------------------------------------------------------- //virtual std::shared_ptr<IViewTableBrowser> ViewBrowserPage::GetViewTableBrowser()const //override; { return mViewTableBrowser; } //----------------------------------------------------------------------------- //virtual void ViewBrowserPage::SetAfterRefreshCls(const std::vector<const IIdent64*>& vec , const IIdent64* root , const wxString& ss , bool , int mode ) //override; { mCtrlFind->SetValue(ss); sigUpdateTitle(); auto mgr = ResMgr::GetInstance(); if (0 == mode) { mModeTool->SetBitmap(mgr->m_ico_dir_cls16); mModeToolBar->Refresh(); } else if (1 == mode) { mModeTool->SetBitmap(mgr->m_ico_dir_obj16); mModeToolBar->Refresh(); } }
#include "hmi_message_publisher/const_vars.h" #include <vector> namespace HMI { namespace SL4 { namespace hmi_message { using VectorDataType = std::vector<unsigned char>; /* * Define hmi_sl4 Lane general info Message * If the input was outside of the range, it would store the min/max value instead */ class ObstacleGeneralInfo { public: ObstacleGeneralInfo(); ObstacleGeneralInfo(const int& num_obstacles); ObstacleGeneralInfo(const VectorDataType& data_vector); void setObstacleCount(const int& num_obstacles); bool getObstacleCount(); VectorDataType getVectorData() const { return _data_vec; } private: VectorDataType _data_vec; }; } } // namespace SL4 } // namespace HMI
#ifndef _SNOW_FILE #define _SNOW_FILE #include "comn.h" #include "SnowInfo.h" class SnowFile { std::map<std::string,SnowInfo> allRecords; public: SnowFile(){}; SnowFile(std::string filename) { InitFromFile(filename); }; bool InitFromFile(std::string filename) { std::ifstream fin(filename.c_str()); if(!fin.is_open()) { return false; } std::string timeStr,stationID, equleSign; double lon,lat,snowDepth,snowVolumn; fin>>timeStr; while(timeStr != "NNNN") { fin>>stationID>>lon>>lat>>snowDepth>>snowVolumn>>equleSign; allRecords[stationID] = SnowInfo(snowVolumn/10,snowDepth/10); fin>>timeStr; } return true; } SnowInfo GetStationSnow(const std::string& stationID) { if(allRecords.count(stationID) ) { return allRecords[stationID]; } return SnowInfo(); } }; #endif //_SNOW_FILE
#ifndef _EVENT_H_ #define _EVENT_H_ using namespace irr; using namespace core; using namespace gui; class CEvent : public IEventReceiver { public: typedef enum { LeftButton, MiddleButton, RightButton } EButton; CEvent(); virtual bool OnEvent(const SEvent&); bool isKeyDown(EKEY_CODE); bool isButtonDown(EButton, position2di &); f32 getLastWheelMovement(); bool mouseOver(rect<s32>); position2di getMousePosition(); private: bool KeyIsDown[KEY_KEY_CODES_COUNT]; bool ButtonIsDown[3]; position2di ButtonClickPosition[3]; f32 LastWheelMovement; position2di MousePosition; }; #endif
/** * Copyright (c) 2014, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file log_accel.cc */ #include <algorithm> #include "log_accel.hh" #include "config.h" const double log_accel::MIN_RANGE = 5.0; const double log_accel::THRESHOLD = 0.1; bool log_accel::add_point(int64_t point) { require(this->la_velocity_size < HISTORY_SIZE); if (this->la_last_point_set) { // TODO Reenable this when we find the bug that causes some older // timestamps to show up after more recent ones. // require(this->la_last_point >= point); // Compute the message velocity. this->la_velocity[this->la_velocity_size] = (this->la_last_point - point); // Find the range of velocities so we can normalize. this->la_min_velocity = std::min( this->la_min_velocity, this->la_velocity[this->la_velocity_size]); this->la_max_velocity = std::max( this->la_max_velocity, this->la_velocity[this->la_velocity_size]); this->la_velocity_size += 1; } this->la_last_point = point; this->la_last_point_set = true; return this->la_velocity_size < HISTORY_SIZE; } double log_accel::get_avg_accel() const { double avg_accel = 0, total_accel = 0; // Compute the range of values so we can normalize. double range = (double) (this->la_max_velocity - this->la_min_velocity); range = std::max(range, MIN_RANGE); for (int lpc = 0; lpc < (this->la_velocity_size - 1); lpc++) { double accel = (this->la_velocity[lpc] - this->la_velocity[lpc + 1]) / range; total_accel += accel; } if (this->la_velocity_size > 1) { avg_accel = total_accel / (double) (this->la_velocity_size - 1); } return avg_accel; } log_accel::direction_t log_accel::get_direction() const { double avg_accel = this->get_avg_accel(); direction_t retval; if (std::fabs(avg_accel) <= THRESHOLD) { retval = A_STEADY; } else if (avg_accel < 0.0) { retval = A_ACCEL; } else { retval = A_DECEL; } return retval; }
#include <climits> #include <cstdio> #include <string> #include <ostream> #include <sstream> #include <iomanip> #include "text_files.h" #include "linalg.h" #include "config.h" struct Result { vec2 current; vec2 current_std; double tau; double n_opt; double n_ac; }; double random_uniform(unsigned int & x1, unsigned int & y1, unsigned int & z1, unsigned int & w1); void runge(Point & p, double t); Point init_dist(unsigned int & x1, unsigned int & y1, unsigned int & z1, unsigned int & w1); double mean(double * arr, int count); double mean(unsigned int * arr, int count); double sd(double * arr, int count); void job_kernel(const Point & init_condition, unsigned int seed, vec2 & current, double & tau, unsigned int & n_ac, unsigned int & n_opt); Result result(); std::ostream & operator<<(std::ostream & os, const Result & res); std::string to_string(const Result & res);
/*==================================================================== Copyright(c) 2018 Adam Rankin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ====================================================================*/ // Local includes #include "pch.h" #include "AppView.h" #include "CameraResources.h" #include "Common.h" #include "RegistrationSystem.h" #include "StepTimer.h" // Registration types #include "CameraRegistration.h" #include "ModelAlignmentRegistration.h" #include "OpticalRegistration.h" #include "ToolBasedRegistration.h" // Rendering includes #include "ModelRenderer.h" #include "Model.h" // Spatial includes #include "SurfaceMesh.h" // Input includes #include "SpatialInput.h" // Physics includes #include "PhysicsAPI.h" // UI includes #include "Icons.h" // System includes #include "NotificationSystem.h" // Unnecessary, but removes Intellisense errors #include "Log.h" #include <WindowsNumerics.h> using namespace Concurrency; using namespace Windows::Data::Xml::Dom; using namespace Windows::Foundation::Collections; using namespace Windows::Foundation::Numerics; using namespace Windows::Graphics::Holographic; using namespace Windows::Media::SpeechRecognition; using namespace Windows::Perception::Spatial; using namespace Windows::Storage; using namespace Windows::UI::Input::Spatial; namespace HoloIntervention { namespace System { Platform::String^ RegistrationSystem::REGISTRATION_ANCHOR_NAME = ref new Platform::String(L"Registration"); const std::wstring RegistrationSystem::REGISTRATION_ANCHOR_MODEL_FILENAME = L"anchor"; std::array<std::wstring, REGISTRATIONTYPE_COUNT> RegistrationSystem::REGISTRATION_TYPE_NAMES = { L"None", L"ToolBased", L"Optical", L"Camera", L"ModelAlignment" }; //---------------------------------------------------------------------------- void RegistrationSystem::OnLocatabilityChanged(Windows::Perception::Spatial::SpatialLocatability locatability) { m_messageSent = false; m_locatability = locatability; } //---------------------------------------------------------------------------- float3 RegistrationSystem::GetStabilizedPosition(SpatialPointerPose^ pose) const { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_currentRegistrationMethod != nullptr && m_currentRegistrationMethod->IsStabilizationActive()) { return m_currentRegistrationMethod->GetStabilizedPosition(pose); } else { const float4x4& pose = m_regAnchorModel->GetCurrentPose(); return float3(pose.m41, pose.m42, pose.m43); } } //---------------------------------------------------------------------------- float3 RegistrationSystem::GetStabilizedVelocity() const { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_currentRegistrationMethod != nullptr && m_currentRegistrationMethod->IsStabilizationActive()) { return m_currentRegistrationMethod->GetStabilizedVelocity(); } else { return m_regAnchorModel->GetVelocity(); } } //---------------------------------------------------------------------------- float RegistrationSystem::GetStabilizePriority() const { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_currentRegistrationMethod != nullptr && m_currentRegistrationMethod->IsStabilizationActive()) { return m_currentRegistrationMethod->GetStabilizePriority(); } else if (m_regAnchorModel != nullptr && m_regAnchorModel->IsInFrustum()) { return PRIORITY_REGISTRATION; } else { return PRIORITY_NOT_ACTIVE; } } //---------------------------------------------------------------------------- task<bool> RegistrationSystem::WriteConfigurationAsync(XmlDocument^ document) { return create_task([this, document]() { if (document->SelectNodes(L"/HoloIntervention")->Length != 1) { return false; } auto rootNode = document->SelectNodes(L"/HoloIntervention")->Item(0); if (m_cachedReferenceToAnchor != float4x4::identity()) { auto repo = ref new UWPOpenIGTLink::TransformRepository(); auto trName = ref new UWPOpenIGTLink::TransformName(L"Reference", L"Anchor"); if (!repo->SetTransform(trName, m_cachedReferenceToAnchor, true)) { return false; } if (!repo->SetTransformPersistent(trName, true)) { return false; } bool result = repo->WriteConfiguration(document); if (!result) { LOG_ERROR("Unable to write repository configuration in RegistrationSystem::WriteConfigurationAsync"); return false; } } bool result = true; for (auto& pair : m_knownRegistrationMethods) { result &= pair.second->WriteConfigurationAsync(document).get(); } return result; }); } //---------------------------------------------------------------------------- task<bool> RegistrationSystem::ReadConfigurationAsync(XmlDocument^ document) { return create_task([this, document]() { auto repo = ref new UWPOpenIGTLink::TransformRepository(); auto trName = ref new UWPOpenIGTLink::TransformName(L"Reference", L"Anchor"); if (!repo->ReadConfiguration(document)) { return false; } IKeyValuePair<bool, float4x4>^ temp; temp = repo->GetTransform(trName); if (temp->Key) { m_cachedReferenceToAnchor = transpose(temp->Value); } // Test each known registration method ReadConfigurationAsync and store if known for (auto pair : { std::pair<std::wstring, std::shared_ptr<IRegistrationMethod>>(REGISTRATION_TYPE_NAMES[REGISTRATIONTYPE_OPTICAL], std::make_shared<OpticalRegistration>(IConfigurable::m_core, m_notificationSystem, m_networkSystem)), std::pair<std::wstring, std::shared_ptr<IRegistrationMethod>>(REGISTRATION_TYPE_NAMES[REGISTRATIONTYPE_MODELALIGNMENT], std::make_shared<ModelAlignmentRegistration>(IConfigurable::m_core, m_notificationSystem, m_networkSystem, m_modelRenderer, m_spatialInput, m_icons, m_debug, m_timer)), std::pair<std::wstring, std::shared_ptr<IRegistrationMethod>>(REGISTRATION_TYPE_NAMES[REGISTRATIONTYPE_CAMERA], std::make_shared<CameraRegistration>(IConfigurable::m_core, m_notificationSystem, m_networkSystem, m_modelRenderer)), std::pair<std::wstring, std::shared_ptr<IRegistrationMethod>>(REGISTRATION_TYPE_NAMES[REGISTRATIONTYPE_TOOLBASED], std::make_shared<ToolBasedRegistration>(IConfigurable::m_core, m_networkSystem)) }) { bool result = pair.second->ReadConfigurationAsync(document).get(); if (result) { m_knownRegistrationMethods[pair.first] = pair.second; } pair.second->RegisterTransformUpdatedCallback(std::bind(&RegistrationSystem::OnRegistrationComplete, this, std::placeholders::_1)); } m_configDocument = document; m_componentReady = true; return true; }); } //---------------------------------------------------------------------------- RegistrationSystem::RegistrationSystem(HoloInterventionCore& core, NetworkSystem& networkSystem, Physics::PhysicsAPI& physicsAPI, NotificationSystem& notificationSystem, Rendering::ModelRenderer& modelRenderer, Input::SpatialInput& spatialInput, UI::Icons& icons, Debug& debug, DX::StepTimer& timer) : ILocatable(core) , IConfigurable(core) , m_notificationSystem(notificationSystem) , m_networkSystem(networkSystem) , m_modelRenderer(modelRenderer) , m_physicsAPI(physicsAPI) , m_icons(icons) , m_debug(debug) , m_spatialInput(spatialInput) , m_currentRegistrationMethod(nullptr) , m_timer(timer) { m_modelRenderer.AddModelAsync(REGISTRATION_ANCHOR_MODEL_FILENAME).then([this](uint64 m_regAnchorModelId) { if (m_regAnchorModelId != INVALID_TOKEN) { m_regAnchorModel = m_modelRenderer.GetModel(m_regAnchorModelId); } if (m_regAnchorModel == nullptr) { m_notificationSystem.QueueMessage(L"Unable to retrieve anchor model."); return; } m_regAnchorModel->SetVisible(false); m_regAnchorModel->EnablePoseLerp(true); m_regAnchorModel->SetPoseLerpRate(4.f); }); } //---------------------------------------------------------------------------- RegistrationSystem::~RegistrationSystem() { m_regAnchorModel = nullptr; m_regAnchorModelId = 0; } //---------------------------------------------------------------------------- void RegistrationSystem::Update(SpatialCoordinateSystem^ coordinateSystem, SpatialPointerPose^ headPose, HolographicCameraPose^ cameraPose) { // Anchor placement logic if (m_regAnchorRequested) { if (m_locatability != SpatialLocatability::PositionalTrackingActive && !m_messageSent) { m_notificationSystem.QueueMessage(L"Positional tracking required for dropping an anchor."); m_messageSent = true; return; } if (m_physicsAPI.DropAnchorAtIntersectionHit(REGISTRATION_ANCHOR_NAME, coordinateSystem, headPose)) { if (m_regAnchorModel != nullptr) { m_regAnchorModel->SetVisible(true); m_regAnchor = m_physicsAPI.GetAnchor(REGISTRATION_ANCHOR_NAME); } m_notificationSystem.QueueMessage(L"Anchor created."); m_physicsAPI.SaveAppStateAsync(); } else { m_notificationSystem.QueueMessage(L"Unable to drop anchor."); } m_regAnchorRequested = false; } Platform::IBox<float4x4>^ transformContainer(nullptr); // Anchor model position update logic if (m_regAnchor != nullptr) { transformContainer = m_regAnchor->CoordinateSystem->TryGetTransformTo(coordinateSystem); if (transformContainer != nullptr) { m_regAnchorModel->SetVisible(true); if (m_forcePose) { m_regAnchorModel->SetCurrentPose(transformContainer->Value); m_forcePose = false; } else { m_regAnchorModel->SetDesiredPose(transformContainer->Value); } } else if (m_locatability != SpatialLocatability::PositionalTrackingActive) { // World locked content not available, head-locked only m_regAnchorModel->SetVisible(false); } } std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_currentRegistrationMethod != nullptr && m_currentRegistrationMethod->IsStarted() && transformContainer != nullptr) { m_currentRegistrationMethod->Update(headPose, coordinateSystem, transformContainer, cameraPose); } } //---------------------------------------------------------------------------- task<bool> RegistrationSystem::LoadAppStateAsync() { return create_task([this]() { if (m_physicsAPI.HasAnchor(REGISTRATION_ANCHOR_NAME)) { m_forcePose = true; m_regAnchor = m_physicsAPI.GetAnchor(REGISTRATION_ANCHOR_NAME); if (m_regAnchor != nullptr) { { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_currentRegistrationMethod != nullptr) { m_currentRegistrationMethod->SetWorldAnchor(m_regAnchor); } } while (m_regAnchorModel == nullptr) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } m_regAnchorModel->SetVisible(true); } else { LOG_ERROR("Anchor exists by name but is nullptr."); return false; } } return true; }); } //---------------------------------------------------------------------------- bool RegistrationSystem::IsCameraActive() const { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); auto camReg = dynamic_cast<CameraRegistration*>(m_currentRegistrationMethod.get()); return camReg != nullptr && camReg->IsCameraActive(); } //---------------------------------------------------------------------------- void RegistrationSystem::RegisterVoiceCallbacks(Input::VoiceInputCallbackMap& callbackMap) { for (auto& method : m_knownRegistrationMethods) { method.second->RegisterVoiceCallbacks(callbackMap); } callbackMap[L"debug registration"] = [this](SpeechRecognitionResult ^ result) { m_cachedReferenceToAnchor = float4x4::identity(); m_cachedReferenceToAnchor.m41 = 0.01f; }; callbackMap[L"drop anchor"] = [this](SpeechRecognitionResult ^ result) { m_regAnchorRequested = true; }; callbackMap[L"remove anchor"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); m_currentRegistrationMethod->StopAsync().then([this](bool result) { if (m_regAnchorModel) { m_regAnchorModel->SetVisible(false); } if (m_physicsAPI.RemoveAnchor(REGISTRATION_ANCHOR_NAME) == 1) { m_notificationSystem.QueueMessage(L"Anchor \"" + REGISTRATION_ANCHOR_NAME + "\" removed."); } }); }; callbackMap[L"start camera registration"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (dynamic_cast<CameraRegistration*>(m_currentRegistrationMethod.get()) != nullptr && m_currentRegistrationMethod->IsStarted()) { m_notificationSystem.QueueMessage(L"Registration already running."); return; } if (m_regAnchor == nullptr) { m_notificationSystem.QueueMessage(L"Anchor required. Please place an anchor with 'drop anchor'."); return; } if (m_knownRegistrationMethods.find(REGISTRATION_TYPE_NAMES[REGISTRATIONTYPE_CAMERA]) == m_knownRegistrationMethods.end()) { m_notificationSystem.QueueMessage(L"No camera configuration defined. Please add the necessary information to the configuration file and try again."); return; } m_currentRegistrationMethod = m_knownRegistrationMethods[REGISTRATION_TYPE_NAMES[REGISTRATIONTYPE_CAMERA]]; m_currentRegistrationMethod->SetWorldAnchor(m_regAnchor); m_currentRegistrationMethod->StartAsync().then([this](bool result) { if (!result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); m_currentRegistrationMethod = nullptr; m_notificationSystem.QueueMessage(L"Unable to start camera registration."); } }); }; callbackMap[L"start optical registration"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (dynamic_cast<OpticalRegistration*>(m_currentRegistrationMethod.get()) != nullptr && m_currentRegistrationMethod->IsStarted()) { m_notificationSystem.QueueMessage(L"Registration already running."); return; } if (m_regAnchor == nullptr) { m_notificationSystem.QueueMessage(L"Anchor required. Please place an anchor with 'drop anchor'."); return; } if (m_knownRegistrationMethods.find(REGISTRATION_TYPE_NAMES[REGISTRATIONTYPE_OPTICAL]) == m_knownRegistrationMethods.end()) { m_notificationSystem.QueueMessage(L"No optical configuration defined. Please add the necessary information to the configuration file and try again."); return; } m_currentRegistrationMethod = m_knownRegistrationMethods[REGISTRATION_TYPE_NAMES[REGISTRATIONTYPE_OPTICAL]]; m_currentRegistrationMethod->SetWorldAnchor(m_regAnchor); m_currentRegistrationMethod->StartAsync().then([this](bool result) { if (!result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); m_currentRegistrationMethod = nullptr; m_notificationSystem.QueueMessage(L"Unable to start optical registration."); } }); }; callbackMap[L"start alignment registration"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (dynamic_cast<ModelAlignmentRegistration*>(m_currentRegistrationMethod.get()) != nullptr && m_currentRegistrationMethod->IsStarted()) { m_notificationSystem.QueueMessage(L"Registration already running."); return; } if (m_regAnchor == nullptr) { m_notificationSystem.QueueMessage(L"Anchor required. Please place an anchor with 'drop anchor'."); return; } if (m_knownRegistrationMethods.find(REGISTRATION_TYPE_NAMES[REGISTRATIONTYPE_MODELALIGNMENT]) == m_knownRegistrationMethods.end()) { m_notificationSystem.QueueMessage(L"No alignment configuration defined. Please add the necessary information to the configuration file and try again."); return; } m_currentRegistrationMethod = m_knownRegistrationMethods[REGISTRATION_TYPE_NAMES[REGISTRATIONTYPE_MODELALIGNMENT]]; m_currentRegistrationMethod->SetWorldAnchor(m_regAnchor); m_currentRegistrationMethod->StartAsync().then([this](bool result) { if (!result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); m_currentRegistrationMethod = nullptr; m_notificationSystem.QueueMessage(L"Unable to start alignment registration."); } }); }; callbackMap[L"start tool registration"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (dynamic_cast<ToolBasedRegistration*>(m_currentRegistrationMethod.get()) != nullptr && m_currentRegistrationMethod->IsStarted()) { m_notificationSystem.QueueMessage(L"Registration already running."); return; } if (m_regAnchor == nullptr) { m_notificationSystem.QueueMessage(L"Anchor required. Please place an anchor with 'drop anchor'."); return; } if (m_knownRegistrationMethods.find(REGISTRATION_TYPE_NAMES[REGISTRATIONTYPE_TOOLBASED]) == m_knownRegistrationMethods.end()) { m_notificationSystem.QueueMessage(L"No alignment configuration defined. Please add the necessary information to the configuration file and try again."); return; } m_currentRegistrationMethod = m_knownRegistrationMethods[REGISTRATION_TYPE_NAMES[REGISTRATIONTYPE_TOOLBASED]]; m_currentRegistrationMethod->SetWorldAnchor(m_regAnchor); m_currentRegistrationMethod->StartAsync().then([this](bool result) { if (!result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); m_currentRegistrationMethod = nullptr; m_notificationSystem.QueueMessage(L"Unable to start tool based registration."); } }); }; callbackMap[L"stop registration"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_currentRegistrationMethod == nullptr) { m_notificationSystem.QueueMessage(L"Registration not running."); return; } m_currentRegistrationMethod->StopAsync().then([this](bool result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); m_currentRegistrationMethod = nullptr; }); }; callbackMap[L"reset registration"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_currentRegistrationMethod != nullptr) { m_currentRegistrationMethod->ResetRegistration(); } }; callbackMap[L"enable registration viz"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_currentRegistrationMethod != nullptr) { m_currentRegistrationMethod->EnableVisualization(true); m_notificationSystem.QueueMessage(L"Visualization enabled."); } }; callbackMap[L"disable registration viz"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_currentRegistrationMethod != nullptr) { m_currentRegistrationMethod->EnableVisualization(false); m_notificationSystem.QueueMessage(L"Visualization disabled."); } }; callbackMap[L"anchor up"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_regAnchor == nullptr) { return; } auto anchor = m_regAnchor->TryCreateRelativeTo(m_regAnchor->CoordinateSystem, float3(0.f, 0.005f, 0.f)); // 5 mm in Y if (anchor != nullptr) { m_regAnchor = nullptr; m_physicsAPI.RemoveAnchor(REGISTRATION_ANCHOR_NAME); m_physicsAPI.AddOrUpdateAnchor(anchor, REGISTRATION_ANCHOR_NAME); m_regAnchor = anchor; m_physicsAPI.SaveAppStateAsync(); } }; callbackMap[L"anchor big up"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_regAnchor == nullptr) { return; } auto anchor = m_regAnchor->TryCreateRelativeTo(m_regAnchor->CoordinateSystem, float3(0.f, 0.01f, 0.f)); // 1 cm in Y if (anchor != nullptr) { m_regAnchor = nullptr; m_physicsAPI.RemoveAnchor(REGISTRATION_ANCHOR_NAME); m_physicsAPI.AddOrUpdateAnchor(anchor, REGISTRATION_ANCHOR_NAME); m_regAnchor = anchor; m_physicsAPI.SaveAppStateAsync(); } }; callbackMap[L"anchor down"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_regAnchor == nullptr) { return; } auto anchor = m_regAnchor->TryCreateRelativeTo(m_regAnchor->CoordinateSystem, float3(0.f, -0.005f, 0.f)); // 5 mm in -Y if (anchor != nullptr) { m_regAnchor = nullptr; m_physicsAPI.RemoveAnchor(REGISTRATION_ANCHOR_NAME); m_physicsAPI.AddOrUpdateAnchor(anchor, REGISTRATION_ANCHOR_NAME); m_regAnchor = anchor; m_physicsAPI.SaveAppStateAsync(); } }; callbackMap[L"anchor big down"] = [this](SpeechRecognitionResult ^ result) { std::lock_guard<std::mutex> guard(m_registrationMethodMutex); if (m_regAnchor == nullptr) { return; } auto anchor = m_regAnchor->TryCreateRelativeTo(m_regAnchor->CoordinateSystem, float3(0.f, -0.01f, 0.f)); // 1 cm in -Y if (anchor != nullptr) { m_regAnchor = nullptr; m_physicsAPI.RemoveAnchor(REGISTRATION_ANCHOR_NAME); m_physicsAPI.AddOrUpdateAnchor(anchor, REGISTRATION_ANCHOR_NAME); m_regAnchor = anchor; m_physicsAPI.SaveAppStateAsync(); } }; } //---------------------------------------------------------------------------- bool RegistrationSystem::GetReferenceToCoordinateSystemTransformation(SpatialCoordinateSystem^ requestedCoordinateSystem, float4x4& outTransform) { if (m_cachedReferenceToAnchor == float4x4::identity()) { return false; } if (m_regAnchor == nullptr) { return false; } try { Platform::IBox<float4x4>^ anchorToRequestedBox = m_regAnchor->CoordinateSystem->TryGetTransformTo(requestedCoordinateSystem); if (anchorToRequestedBox == nullptr) { return false; } outTransform = m_cachedReferenceToAnchor * anchorToRequestedBox->Value; return true; } catch (Platform::Exception^ e) { return false; } return false; } //---------------------------------------------------------------------------- void RegistrationSystem::OnRegistrationComplete(float4x4 registrationTransformation) { if (!CheckRegistrationValidity(registrationTransformation)) { // Remove any scaling, for now, assume 1:1 (mm to mm) float3 scaling; quaternion rotation; float3 translation; decompose(registrationTransformation, &scaling, &rotation, &translation); auto unscaledMatrix = make_float4x4_from_quaternion(rotation); unscaledMatrix.m41 = translation.x; unscaledMatrix.m42 = translation.y; unscaledMatrix.m43 = translation.z; LOG(LogLevelType::LOG_LEVEL_INFO, L"Registration matrix scaling: " + scaling.x.ToString() + L", " + scaling.y.ToString() + L", " + scaling.z.ToString()); m_cachedReferenceToAnchor = unscaledMatrix; } else { m_cachedReferenceToAnchor = registrationTransformation; } } //---------------------------------------------------------------------------- bool RegistrationSystem::CheckRegistrationValidity(float4x4 registrationTransformation) { // Check orthogonality of basis vectors float3 xAxis = normalize(float3(registrationTransformation.m11, registrationTransformation.m21, registrationTransformation.m31)); float3 yAxis = normalize(float3(registrationTransformation.m12, registrationTransformation.m22, registrationTransformation.m32)); float3 zAxis = normalize(float3(registrationTransformation.m13, registrationTransformation.m23, registrationTransformation.m33)); if (!IsFloatEqual(dot(xAxis, yAxis), 0.f) || !IsFloatEqual(dot(xAxis, zAxis), 0.f) || !IsFloatEqual(dot(yAxis, zAxis), 0.f)) { // Not orthogonal! return false; } // Check to see if scale is 1 // TODO : this is currently hardcoded as tracker is expected to produce units in mm, eventually this assumption will be removed // the scale is currently not 1, this is a bug float3 scale; quaternion rot; float3 translation; if (!decompose(registrationTransformation, &scale, &rot, &translation)) { return false; } LOG(LogLevelType::LOG_LEVEL_DEBUG, "scale: " + scale.x.ToString() + L" " + scale.y.ToString() + L" " + scale.z.ToString()); if (!IsFloatEqual(scale.x, 1.f) || !IsFloatEqual(scale.y, 1.f) || !IsFloatEqual(scale.z, 1.f)) { return false; } return true; } } }
#include "Voter.h" class VoterDB { public: VoterDB(); VoterDB(int v); void populate(ifstream &infile); int user_exists(string userid); Voter& get_voter(int i); float sum_donations() const; bool is_full(); void add_user(string last_name, string first_name, string userid, string password, string age, string street_number, string street_name, string town, string zip); void save(ofstream &outfile); friend ostream& operator<<(ostream& os, const VoterDB& db); private: Voter* voters; int max_size; int size; };
// Example 5.1 : scope, memory management unique_ptr // Created by Oleksiy Grechnyev 2017, 2020 // Class Tjej is used a lot here, it logs Ctors and Dtors #include <iostream> #include <string> #include <memory> #include "Tjej.h" using namespace std; // Global variable Tjej glob("Globula Statika"); //============================== // Factory (source) function example 1 unique_ptr<Tjej> factory1(const string & name){ return make_unique<Tjej>(name); // No need for explicit move here } //============================== // Factory (source) function example 2 : the same unique_ptr<Tjej> factory2(const string & name){ unique_ptr<Tjej> upT = make_unique<Tjej>(name); return upT; // Will work without move also } //============================== // Sink (consumer) example which destroys a unique_ptr<Tjej> object // Note the parameter BY VALUE unique_uupTr<Tjej> uupT void sink(unique_ptr<Tjej> upT){ // By value !!! NO ref ! MOVED here ! cout << "Sink: name = " << upT->getName() << endl; // Now upT and the managed object are destroyed as they go out of scope ! } //============================== int main(){ { cout << "\nLocal and temp objects : \n\n"; Tjej *pT = new Tjej("Heap Tjej"); Tjej t1("Local Tjej"); Tjej("Temp Tjej"); delete pT; } { cout << "\nunique_ptr example 1: \n\n"; unique_ptr<Tjej> upT1 = make_unique<Tjej>("Maria Traydor"); // Create a new heap object owned by a unique upTR unique_ptr<Tjej> upT2(new Tjej("Tynave")); // This is also OK cout << "sizeof(unique_ptr<Tjej>) = " << sizeof(unique_ptr<Tjej>) << endl; cout << "name1 = " << upT1->getName() << endl; // You can access members like this cout << "name2 = " << (*upT2).getName() << endl; // Or like this // Let's create some more unique_ptr<Tjej> upT3 = move(upT1); // Move is OK, copy is not unique_ptr<Tjej> upT4 = make_unique<Tjej>("Sophia Esteed"); auto upT5 = make_unique<Tjej>("Nel Zelpher"); // We can use auto like this ! auto upT6 = make_unique<Tjej>("Clair Lasbard"); auto upT7 = make_unique<Tjej>("Mirage Koas"); auto upT8 = make_unique<Tjej>("Blair Lansfeld"); cout << "Deleting some objects by hand :" << endl; upT4.reset(); // Force delete upT5 = nullptr; // Same effect ! Tjej * pT6 = upT6.get(); // Get raw pointer. OK, but don't delete it ! Tjej * pT7 = upT7.release(); // Release ownership and get the raw pointer delete pT7; // Now we have to delete it by hand !!!! // Release ownership and give a regular pointer cout << "About to clean up automatically :" << endl; // Here all managed objects get destroyed by the unique_ptr destructor } { cout << "\nunique_ptr example 2: Source (factory) and sink (consumer). \n\n"; // Create a new heap object owned by a unique_ptr unique_ptr<Tjej> upT = factory2("Souce of all magic"); // We can use the managed object cout << "name = " << upT->getName() << endl; // Now we move upT to sink(), where it is destroyed sink(move(upT)); cout << "After sink" << endl; } return 0; }
/* * File: Waypoint.cpp * Author: mohammedheader * * Created on November 24, 2014, 2:22 PM */ #include "HelloWorldScene.h" #include "Waypoint.h" USING_NS_CC; Waypoint* Waypoint::create(HelloWorld* game, cocos2d::Vec2 location) { Waypoint *wayPoint = new (std::nothrow) Waypoint(); if (wayPoint && wayPoint->init(game,location)) { wayPoint->autorelease(); return wayPoint; } CC_SAFE_DELETE(wayPoint); return nullptr; } Waypoint* Waypoint::init(HelloWorld* game, cocos2d::Vec2 location) { myGame = game; myPosition = location; game->addChild(this); return this; } void Waypoint::draw(Renderer* renderer, const cocos2d::Mat4& transform, unsigned int flags) { _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Waypoint::onDrawPrimitives, this, transform); renderer->addCommand(&_customCommand); } void Waypoint::onDrawPrimitives(const Mat4& transform) { kmGLPushMatrix(); kmGLLoadMatrix(&transform); DrawPrimitives::setDrawColor4B(0, 255, 2, 255); DrawPrimitives::drawCircle(getMyPosition(), 6, 360, 30, false); DrawPrimitives::drawCircle(getMyPosition(), 2, 360, 30, false); if(nextWayPoint){ DrawPrimitives::drawLine(getMyPosition(), nextWayPoint->getMyPosition()); } } void Waypoint::setNextWayPoint(Waypoint* wayPoint){ nextWayPoint = wayPoint; } Waypoint* Waypoint::getNextWayPoint() { return nextWayPoint; } Vec2 Waypoint::getMyPosition(){ return myPosition; }
#include<iostream> #include<vector> #include<algorithm> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; void Init_ListNode(ListNode* head, vector<int> vec) { if (vec.size() == 0) { head = NULL; return; } ListNode* p; p = head; p->val = vec[0]; for (int i = 1; i < vec.size(); i++) { ListNode* q = new ListNode(vec[i]); p->next = q; p = p->next; } } class Solution { public: ListNode* deleteDuplicates(ListNode* head) { //ๅŸบๆœฌๆ€ๆƒณ๏ผšๅ•้“พ่กจๆ“ไฝœ๏ผŒpๆŒ‡ๅ‘ๅฝ“ๅ‰่Š‚็‚น๏ผŒqๆŒ‡ๅ‘pไน‹ๅŽ่Š‚็‚น๏ผŒpreๆŒ‡ๅ‘pไน‹ๅ‰่Š‚็‚น //ๅฆ‚ๆžœp็š„ๅ€ผไธŽq็š„ๅ€ผ็›ธ็ญ‰๏ผŒๅŽป้™ค้‡ๅค่Š‚็‚น๏ผŒpไธ€็›ดๅพ€ๅŽ็งปๅŠจๅˆฐๆ–ฐๅ€ผ๏ผŒ็„ถๅŽpre->next=p ListNode* p, * q, * start; ListNode* pre = new ListNode(0); start = pre; pre->next = head; if (head == NULL) return head; p = pre->next; q = p->next; //ๅพช็Žฏ้ๅކ้“พ่กจๆฏไธ€ไธช่Š‚็‚น while (q != NULL) { //ๅฆ‚ๆžœp็š„ๅ€ผไธŽq็š„ๅ€ผไธ็›ธ็ญ‰๏ผŒpๅพ€ๅŽ็งปๅŠจไธ€ๆฌก if (p->val != q->val) { pre = p; p = q; q = q->next; } //ๅฆ‚ๆžœp็š„ๅ€ผไธŽq็š„ๅ€ผ็›ธ็ญ‰๏ผŒๅŽป้™ค้‡ๅค่Š‚็‚น๏ผŒpไธ€็›ดๅพ€ๅŽ็งปๅŠจๅˆฐๆ–ฐๅ€ผ๏ผŒ็„ถๅŽpre->next=p else { while (p != NULL && p->val == q->val) { p = p->next; } pre->next = p; if (p != NULL) q = p->next; else q = p; } } return start->next; } }; int main() { Solution solute; ListNode* head = new ListNode(0); vector<int> vec = { 1,2,3,3,4,4,5 }; //ๅˆๅง‹ๅŒ–้“พ่กจ Init_ListNode(head, vec); ListNode* p; p = solute.deleteDuplicates(head); while (p != NULL) { cout << p->val << " "; p = p->next; } cout << endl; return 0; }
#ifndef WINDOWSSVGFONT_H #define WINDOWSSVGFONT_H #ifdef SVG_SUPPORT #include "modules/svg/src/SVGFont.h" #include "modules/svg/src/SVGTransform.h" class OpFont; class WindowsSVGFont : public SVGSystemFont { private: static const int buffer_size; SVGTransform m_text_transform; SVGnumber m_size; public: WindowsSVGFont(OpFont* font); virtual ~WindowsSVGFont() { } virtual OpBpath* GetGlyphOutline(uni_char uc); virtual SVGnumber GetGlyphAdvance(uni_char uc); virtual void SetSize(SVGnumber size); virtual void SetWeight(SVGFontWeight weight); virtual BOOL HasGlyph(uni_char uc); virtual SVGnumber GetStringWidth(const uni_char* text, INT32 len = -1); virtual SVGTransform* GetTextTransform(); }; #endif // SVG_SUPPORT #endif // WINDOWSSVGFONT_H
#pragma once #include "myBook.h" class Gossip : public myBook{ private : int m_nMonth; public : Gossip() : m_nMonth(0) {}; Gossip(string title, string author, string company, int price, int month) : myBook(title, author, company, price), m_nMonth(month){ } Gossip(const char* title, const char* author, const char* company, int price, int month): myBook(title, author, company, price), m_nMonth(month) { }; void view() { myBook::view(); cout << m_nMonth << "ยฟรน รˆยฃ" << endl; } };
#pragma once #include <string> #include <fstream> using namespace std; class Config { public: Config(void); ~Config(void); static string strPPIFileName; static string strSequenceFileName; static string strGoldensetFileName; static string strPeptideProphetResult; static char cSplitChar; static int iRunTimes; static string strOutResultFileName; static void ReadPara() { ifstream config_file("../para.ini"); string strFromPara; while(config_file>>strFromPara) { if(strFromPara=="strPPIFileName") config_file>>strPPIFileName; else if(strFromPara=="strSequenceFileName") config_file>>strSequenceFileName; else if(strFromPara=="strGoldensetFileName") config_file>>strGoldensetFileName; else if(strFromPara=="strPeptideProphetResult") config_file>>strPeptideProphetResult; else if(strFromPara=="cSplitChar") config_file>>cSplitChar; else if(strFromPara=="iRunTimes") config_file>>iRunTimes; else if(strFromPara=="strOutResultFileName") config_file>>strOutResultFileName; } } };
// // main.cpp // baekjoon // // Created by ์ตœํฌ์—ฐ on 2021/05/03. // #include <iostream> using namespace std; int main(int argc, const char * argv[]) { // insert code here... int n, x; cin >> n >> x; for(int i=0;i<n;i++) { int a; cin >> a; if(a<x) cout<<a<<" "; } cout << endl; }
// // NetException.cpp // // $Id: //poco/1.4/Net/src/NetException.cpp#4 $ // // Library: Net // Package: NetCore // Module: NetException // // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "_Net/NetException.h" #include <typeinfo> using _::IOException; namespace _Net { ___IMPLEMENT_EXCEPTION(NetException, IOException, "Net Exception") ___IMPLEMENT_EXCEPTION(InvalidAddressException, NetException, "Invalid address") ___IMPLEMENT_EXCEPTION(InvalidSocketException, NetException, "Invalid socket") ___IMPLEMENT_EXCEPTION(ServiceNotFoundException, NetException, "Service not found") ___IMPLEMENT_EXCEPTION(ConnectionAbortedException, NetException, "Software caused connection abort") ___IMPLEMENT_EXCEPTION(ConnectionResetException, NetException, "Connection reset by peer") ___IMPLEMENT_EXCEPTION(ConnectionRefusedException, NetException, "Connection refused") ___IMPLEMENT_EXCEPTION(DNSException, NetException, "DNS error") ___IMPLEMENT_EXCEPTION(HostNotFoundException, DNSException, "Host not found") ___IMPLEMENT_EXCEPTION(NoAddressFoundException, DNSException, "No address found") ___IMPLEMENT_EXCEPTION(InterfaceNotFoundException, NetException, "Interface not found") ___IMPLEMENT_EXCEPTION(NoMessageException, NetException, "No message received") ___IMPLEMENT_EXCEPTION(MessageException, NetException, "Malformed message") ___IMPLEMENT_EXCEPTION(MultipartException, MessageException, "Malformed multipart message") ___IMPLEMENT_EXCEPTION(HTTPException, NetException, "HTTP Exception") ___IMPLEMENT_EXCEPTION(NotAuthenticatedException, HTTPException, "No authentication information found") ___IMPLEMENT_EXCEPTION(UnsupportedRedirectException, HTTPException, "Unsupported HTTP redirect (protocol change)") ___IMPLEMENT_EXCEPTION(FTPException, NetException, "FTP Exception") ___IMPLEMENT_EXCEPTION(SMTPException, NetException, "SMTP Exception") ___IMPLEMENT_EXCEPTION(POP3Exception, NetException, "POP3 Exception") ___IMPLEMENT_EXCEPTION(ICMPException, NetException, "ICMP Exception") ___IMPLEMENT_EXCEPTION(NTPException, NetException, "NTP Exception") ___IMPLEMENT_EXCEPTION(HTMLFormException, NetException, "HTML Form Exception") ___IMPLEMENT_EXCEPTION(WebSocketException, NetException, "WebSocket Exception") ___IMPLEMENT_EXCEPTION(UnsupportedFamilyException, NetException, "Unknown or unsupported socket family.") } //< namespace _Net
#include <iostream> #include "servant/Application.h" #include "FightData.h" using namespace taf; using namespace std; taf::CommunicatorPtr g_connPtr; void doTest(bool bCout) { ServerEngine::FightDataPrx fightPrx = g_connPtr->stringToProxy<ServerEngine::FightDataPrx>("ServerEngine.FightDataServer.FightDataObj@tcp -h 127.0.0.1 -p 22728 -t 120000"); for(int i = 0; i <10000; i++) { stringstream ss; ss<<"TTWout"<<i; ServerEngine::PKFight fightKey; fightKey.iWorldID = 0; fightKey.u64LowUUID = i; fightKey.u64HighUUID = i; std::string strValue = ss.str(); { int iRet = fightPrx->saveFightData(fightKey, strValue); if(bCout) { cout<<"doTest SaveFightData|"<<iRet<<endl; } } { string strGetData; int iRet = fightPrx->getFightData(fightKey, strGetData); if(bCout) { cout<<"doTest getFight|"<<strGetData<<"|"<<iRet<<endl; } } { int iRet = fightPrx->delFightData(fightKey); if(bCout) { cout<<"doTest DelFight|"<<iRet<<endl; } } } } void testFightData(bool bCout) { ServerEngine::FightDataPrx fightDataPrx = g_connPtr->stringToProxy<ServerEngine::FightDataPrx>("ServerEngine.FightDataServer.FightDataObj@tcp -h 127.0.0.1 -p 22728 -t 120000"); for(int i = 0; i <10000; i++) { ServerEngine::PKFight fightKey; fightKey.iWorldID = 0; fightKey.u64LowUUID = i; fightKey.u64HighUUID = i; { string strData; int iRet = fightDataPrx->getFightData(fightKey, strData); if(bCout) { cout<<"testFightData getDataServer|"<<i<<"|"<<strData<<"|"<<iRet<<endl; } } } } int main(int argc, char** argv) { g_connPtr = new Communicator(); unsigned int begin = time(0); doTest(true); //testFightData(true); unsigned int end = time(0); cout<<"cosy:"<<(end-begin)<<endl; g_connPtr = NULL; return 0; };
#include "../include/CoinScoreManager.h" namespace gnGame { CoinScoreManager* CoinScoreManager::getIns() { static CoinScoreManager Instance; return &Instance; } void gnGame::CoinScoreManager::addScore() { ++coinScore.score; } void gnGame::CoinScoreManager::resetScore() { coinScore.score = 0; } int gnGame::CoinScoreManager::getScore() const { return coinScore.score; } }
#include <iostream> void numTo(unsigned number, unsigned& sys) { if (number < sys) { std :: cout << number; return; } numTo(number / sys, sys); if (number % sys < 10) { std :: cout << number % sys; } else { std :: cout << char('A' + number % sys - 10); } } void input(unsigned& number, unsigned& sys) { std :: cout << "Input number and numeric system(Numberic system will be bigger than 0) : "; std :: cin >> number >> sys; while (!std :: cin || sys < 0 || number < 0) { std :: cin.clear(); std :: cin.ignore(); std :: cout << "Please input correct : "; std :: cin >> number >> sys; } } int main() { unsigned number = 0; unsigned system = 0; input(number, system); numTo(number, system); std :: cout << std :: endl; return 0; }
// StringFileReader // // A class for reading a file // // Last modified 2009-02-17 by Willi #ifndef TextReader_H #define TextReader_H #include <string> #include <iostream> #include <vector> #include <sstream> #include "CLArguments.h" ///Stuff from the "C++ AG" at school namespace cppag { ///A class for reading \b one text file class TextReader { public: /** * * \brief Constructor - creates a Text Reader * * \param loc the filename, either relative or absolute * **/ TextReader(const std::string& loc); ///reads the content of the file bool Read (); /** * \brief returns the content of the file * * Don't forget to read() it first! * * \return content of the file * **/ std::string GetContent () const; virtual ~TextReader(); protected: ///Which file to read std::string mLocation; ///The content of the file, saved as a vector of lines. std::vector<std::string> mContent; //Zeilenweise gespeicherter Inhalt }; } #endif // TextReader_H
template <typename T> inline Matrix<T,4,4>::Matrix() : data{ Vector<T,4>(1,0,0,0), Vector<T,4>(0,1,0,0), Vector<T,4>(0,0,1,0), Vector<T,4>(0,0,0,1)} { } template <typename T> inline Matrix<T,4,4>::Matrix(T m00, T m01, T m02, T m03, T m10, T m11, T m12, T m13, T m20, T m21, T m22, T m23, T m30, T m31, T m32, T m33) : data{ Vector<T,4>(m00,m01,m02,m03), Vector<T,4>(m10,m11,m12,m13), Vector<T,4>(m20,m21,m22,m23), Vector<T,4>(m30,m31,m32,m33) } { } template <typename T> inline Matrix<T,4,4>::Matrix(std::initializer_list<T> l) { assert(l.size() == 16 && "Matrix 4x4 must have 16 values\n"); data[0][0] = l.begin()[0]; data[0][1] = l.begin()[1]; data[0][2] = l.begin()[2]; data[0][3] = l.begin()[3]; data[1][0] = l.begin()[4]; data[1][1] = l.begin()[5]; data[1][2] = l.begin()[6]; data[1][3] = l.begin()[7]; data[2][0] = l.begin()[8]; data[2][1] = l.begin()[9]; data[2][2] = l.begin()[10]; data[2][3] = l.begin()[11]; data[3][0] = l.begin()[12]; data[3][1] = l.begin()[13]; data[3][2] = l.begin()[14]; data[3][3] = l.begin()[15]; } template <typename T> inline Matrix<T,4,4>::Matrix(T v) : data{ Vector<T,4>(v,0,0,0), Vector<T,4>(0,v,0,0), Vector<T,4>(0,0,v,0), Vector<T,4>(0,0,0,v) } { } template <typename T> inline Matrix<T,4,4>::Matrix(const Vector<T,4>& u, const Vector<T,4>& v, const Vector<T,4>& w, const Vector<T,4>& k) : data{u, v, w, k} { } template <typename T> template <typename U> inline Matrix<T,4,4>::Matrix(const Matrix<U,4,4> &m) : data{ m.data[0], m.data[1], m.data[2], m.data[3] } { } template <typename T> inline Matrix<T,4,4>::Matrix(const Matrix<T,2,2> &m) : data{ Vector<T,4>(m[0][0],m[0][1],0,0), Vector<T,4>(m[1][0],m[1][1],0,0), Vector<T,3>(0,0,1,0), Vector<T,4>(0,0,0,1) } { } template <typename T> inline Matrix<T,4,4>::Matrix(const Matrix<T,2,3> &m) : data{ Vector<T,4>(m[0][0],m[0][1],m[0][2],0), Vector<T,4>(m[1][0],m[1][1],m[1][2],0), Vector<T,4>(0,0,1,0), Vector<T,4>(0,0,0,1) } { } template <typename T> inline Matrix<T,4,4>::Matrix(const Matrix<T,2,4> &m) : data{ m[0], m[1], Vector<T,4>(0,0,1,0), Vector<T,4>(0,0,0,1) } { } template <typename T> inline Matrix<T,4,4>::Matrix(const Matrix<T,3,2> &m) : data{Vector<T,4>(m[0][0],m[0][1],0,0), Vector<T,4>(m[1][0],m[1][1],0,0), Vector<T,4>(m[2][0],m[2][1],1,0), Vector<T,4>(0,0,0,1) } { } template <typename T> inline Matrix<T,4,4>::Matrix(const Matrix<T,3,3> &m) : data{ Vector<T,4>(m[0][0],m[0][1],m[0][2],0), Vector<T,4>(m[1][0],m[1][1],m[1][2],0), Vector<T,4>(m[2][0],m[2][1],m[2][2],0), Vector<T,4>(0,0,0,1) } { } template <typename T> inline Matrix<T,4,4>::Matrix(const Matrix<T,3,4> &m) : data{ m[0], m[1], m[2], Vector<T,4>(0,0,0,1) } { } template <typename T> inline Matrix<T,4,4>::Matrix(const Matrix<T,4,2> &m) : data{ Vector<T,4>(m[0][0],m[0][1],0,0), Vector<T,4>(m[1][0],m[1][1],0,0), Vector<T,4>(m[2][0],m[2][1],1,0), Vector<T,4>(m[3][0],m[3][1],0,1) } { } template <typename T> inline Matrix<T,4,4>::Matrix(const Matrix<T,4,3> &m) : data{ Vector<T,4>(m[0][0],m[0][1],m[0][2],0), Vector<T,4>(m[1][0],m[1][1],m[1][2],0), Vector<T,4>(m[2][0],m[2][1],m[2][2],0), Vector<T,4>(m[3][0],m[3][1],m[3][2],1) } { } template <typename T> inline Matrix<T,4,4>::~Matrix() { } template <typename T> inline Matrix<T,4,4>& Matrix<T,4,4>::operator = (const Matrix<T,4,4>& m) { this->data[0] = m.data[0]; this->data[1] = m.data[1]; this->data[2] = m.data[2]; this->data[3] = m.data[3]; return *this; } template <typename T> inline Vector<T,4>& Matrix<T,4,4>::operator[](UI32 i) { assert(i < 4 && "Array Index out of bounds\n"); return this->data[i]; } template <typename T> inline const Vector<T,4>& Matrix<T,4,4>::operator[](UI32 i) const { assert(i < 4 && "Array Index out of bounds\n"); return this->data[i]; } template <typename T> inline T determinant(const Matrix<T,4,4>& m) { T SubFactor00 = m[2][2] * m[3][3] - m[3][2] * m[2][3]; T SubFactor01 = m[2][1] * m[3][3] - m[3][1] * m[2][3]; T SubFactor02 = m[2][1] * m[3][2] - m[3][1] * m[2][2]; T SubFactor03 = m[2][0] * m[3][3] - m[3][0] * m[2][3]; T SubFactor04 = m[2][0] * m[3][2] - m[3][0] * m[2][2]; T SubFactor05 = m[2][0] * m[3][1] - m[3][0] * m[2][1]; return ( m[0][0] * ( (m[1][1] * SubFactor00 - m[1][2] * SubFactor01 + m[1][3] * SubFactor02)) + m[0][1] * (-(m[1][0] * SubFactor00 - m[1][2] * SubFactor03 + m[1][3] * SubFactor04)) + m[0][2] * ( (m[1][0] * SubFactor01 - m[1][1] * SubFactor03 + m[1][3] * SubFactor05)) + m[0][3] * (-(m[1][0] * SubFactor02 - m[1][1] * SubFactor04 + m[1][2] * SubFactor05))); } template <typename T> inline Matrix<T,4,4> inverse(const Matrix<T,4,4>& m) { Matrix<T,4,4> res; // matrix to store result T tmp[12]; // temporary array for pairs Matrix<T,4,4> transp; // matrix of transposed source matrix T det; // determinant // transpose matrix transp = transpose(m); // calculate pairs for first 8 elements (cofactors) tmp[0] = transp[2][2] * transp[3][3]; tmp[1] = transp[2][3] * transp[3][2]; tmp[2] = transp[2][1] * transp[3][3]; tmp[3] = transp[2][3] * transp[3][1]; tmp[4] = transp[2][1] * transp[3][2]; tmp[5] = transp[2][2] * transp[3][1]; tmp[6] = transp[2][0] * transp[3][3]; tmp[7] = transp[2][3] * transp[3][0]; tmp[8] = transp[2][0] * transp[3][2]; tmp[9] = transp[2][2] * transp[3][0]; tmp[10] = transp[2][0] * transp[3][1]; tmp[11] = transp[2][1] * transp[3][0]; // calculate first 8 elements (cofactors) res[0][0] = tmp[0] * transp[1][1] + tmp[3] * transp[1][2] + tmp[4] * transp[1][3]; res[0][0] -= tmp[1] * transp[1][1] + tmp[2] * transp[1][2] + tmp[5] * transp[1][3]; res[0][1] = tmp[1] * transp[1][0] + tmp[6] * transp[1][2] + tmp[9] * transp[1][3]; res[0][1] -= tmp[0] * transp[1][0] + tmp[7] * transp[1][2] + tmp[8] * transp[1][3]; res[0][2] = tmp[2] * transp[1][0] + tmp[7] * transp[1][1] + tmp[10] * transp[1][3]; res[0][2] -= tmp[3] * transp[1][0] + tmp[6] * transp[1][1] + tmp[11] * transp[1][3]; res[0][3] = tmp[5] * transp[1][0] + tmp[8] * transp[1][1] + tmp[11] * transp[1][2]; res[0][3] -= tmp[4] * transp[1][0] + tmp[9] * transp[1][1] + tmp[10] * transp[1][2]; res[1][0] = tmp[1] * transp[0][1] + tmp[2] * transp[0][2] + tmp[5] * transp[0][3]; res[1][0] -= tmp[0] * transp[0][1] + tmp[3] * transp[0][2] + tmp[4] * transp[0][3]; res[1][1] = tmp[0] * transp[0][0] + tmp[7] * transp[0][2] + tmp[8] * transp[0][3]; res[1][1] -= tmp[1] * transp[0][0] + tmp[6] * transp[0][2] + tmp[9] * transp[0][3]; res[1][2] = tmp[3] * transp[0][0] + tmp[6] * transp[0][1] + tmp[11] * transp[0][3]; res[1][2] -= tmp[2] * transp[0][0] + tmp[7] * transp[0][1] + tmp[10] * transp[0][3]; res[1][3] = tmp[4] * transp[0][0] + tmp[9] * transp[0][1] + tmp[10] * transp[0][2]; res[1][3] -= tmp[5] * transp[0][0] + tmp[8] * transp[0][1] + tmp[11] * transp[0][2]; // calculate pairs for second 8 elements (cofactors) tmp[0] = transp[0][2] * transp[1][3]; tmp[1] = transp[0][3] * transp[1][2]; tmp[2] = transp[0][1] * transp[1][3]; tmp[3] = transp[0][3] * transp[1][1]; tmp[4] = transp[0][1] * transp[1][2]; tmp[5] = transp[0][2] * transp[1][1]; tmp[6] = transp[0][0] * transp[1][3]; tmp[7] = transp[0][3] * transp[1][0]; tmp[8] = transp[0][0] * transp[1][2]; tmp[9] = transp[0][2] * transp[1][0]; tmp[10] = transp[0][0] * transp[1][1]; tmp[11] = transp[0][1] * transp[1][0]; // calculate second 8 elements (cofactors) res[2][0] = tmp[0] * transp[3][1] + tmp[3] * transp[3][2] + tmp[4] * transp[3][3]; res[2][0] -= tmp[1] * transp[3][1] + tmp[2] * transp[3][2] + tmp[5] * transp[3][3]; res[2][1] = tmp[1] * transp[3][0] + tmp[6] * transp[3][2] + tmp[9] * transp[3][3]; res[2][1] -= tmp[0] * transp[3][0] + tmp[7] * transp[3][2] + tmp[8] * transp[3][3]; res[2][2] = tmp[2] * transp[3][0] + tmp[7] * transp[3][1] + tmp[10] * transp[3][3]; res[2][2] -= tmp[3] * transp[3][0] + tmp[6] * transp[3][1] + tmp[11] * transp[3][3]; res[2][3] = tmp[5] * transp[3][0] + tmp[8] * transp[3][1] + tmp[11] * transp[3][2]; res[2][3] -= tmp[4] * transp[3][0] + tmp[9] * transp[3][1] + tmp[10] * transp[3][2]; res[3][0] = tmp[2] * transp[2][2] + tmp[5] * transp[2][3] + tmp[1] * transp[2][1]; res[3][0] -= tmp[4] * transp[2][3] + tmp[0] * transp[2][1] + tmp[3] * transp[2][2]; res[3][1] = tmp[8] * transp[2][3] + tmp[0] * transp[2][0] + tmp[7] * transp[2][2]; res[3][1] -= tmp[6] * transp[2][2] + tmp[9] * transp[2][3] + tmp[1] * transp[2][0]; res[3][2] = tmp[6] * transp[2][1] + tmp[11] * transp[2][3] + tmp[3] * transp[2][0]; res[3][2] -= tmp[10] * transp[2][3] + tmp[2] * transp[2][0] + tmp[7] * transp[2][1]; res[3][3] = tmp[10] * transp[2][2] + tmp[4] * transp[2][0] + tmp[9] * transp[2][1]; res[3][3] -= tmp[8] * transp[2][1] + tmp[11] * transp[2][2] + tmp[5] * transp[2][0]; // calculate determinant det = transp[0][0] * res[0][0] + transp[0][1] * res[0][1] + transp[0][2] * res[0][2] + transp[0][3] * res[0][3]; assert(det != 0 && "Cannot invert Matrix: Determinant is zero\n"); // calculate matrix inverse T invDeterminant = 1/det; res *= invDeterminant; return res; } template <typename T> inline Matrix<T,4,4> operator / (const Matrix<T,4,4>& left, const Matrix<T,4,4>& right) { Matrix<T,4,4> tmp = left * inverse(right); return tmp; } template <typename T> inline Matrix<T,4,4>& operator /= (Matrix<T,4,4>& left, const Matrix<T,4,4>& right) { return (left = left / right); }
#include "switch.h" #include <iostream> Switch::Switch():Life() { Life::image.load("button.png"); //loads image Life::rect = image.rect(); //assigns image } Switch::~Switch() { std::cout << ("Switch deleted\n"); }
#ifndef CPVS_H #define CPVS_H #include <cassert> #include <string> #include <vector> #include <unordered_map> #include <memory> #include <exception> #include <cmath> #include <GL/glew.h> #include <GLFW/glfw3.h> using std::string; using std::vector; using std::shared_ptr; using std::unique_ptr; using std::array; using std::unordered_map; using uint = unsigned int; using uint64 = uint64_t; #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> using mat3 = glm::mat3; using mat4 = glm::mat4; using vec2 = glm::vec2; using vec3 = glm::vec3; using vec4 = glm::vec4; using ivec2 = glm::ivec2; using ivec3 = glm::ivec3; using ivec4 = glm::ivec4; /* Some common functions and macros */ #define CPVS_SAFE_DELETE(ptr) { if (ptr != NULL) delete ptr; } #ifndef NDEBUG #define GL_CHECK_ERROR(X) checkGLErrors(X) #else #define GL_CHECK_ERROR(X) #endif #define GL_ASSERT_NO_ERROR() assert(glGetError() == GL_NO_ERROR); // Counts the number of set bits. // Builtin exists for clang and gcc #define POPCOUNT(x) __builtin_popcount(x) /** Checks for OpenGL errors and outputs an error string */ extern void checkGLErrors(const std::string &str); /** Returns true if the parameter is a power of two */ inline constexpr bool isPowerOfTwo(int x) { return !(x & (x - 1)); } /** Computes the log of base 2 */ inline double log2(double x) { return log(x) * 1.44269504088896340736; //log(x) * log2(e) } inline double log8(double x) { return log(x) / 2.07944154167983592825; //log(x) / log(8) } /* Some exception types */ class FileNotFound : std::exception { public: FileNotFound(const char *msg) noexcept : m_msg(msg) { } FileNotFound() noexcept : m_msg("File not found\n") { } virtual const char* what() const noexcept override { return m_msg; } private: const char *m_msg; }; class LoadFileException : std::exception { public: LoadFileException(const char *str) noexcept : m_msg(str) { } LoadFileException() noexcept : m_msg("Could not load/parse file\n") { } virtual const char* what() const noexcept override { return m_msg; } private: const char *m_msg; }; #endif
#include<iostream> #include<vector> #include<list> using namespace std; class Graph{ int Vertices; list<int> *adj; void DFSUtil(int u,bool visited[]); public: Graph(int V); void addEdge(int u,int v); int countTree(); }; Graph::Graph(int V){ this->Vertices=V; this->adj=new list<int> [V]; } void Graph::addEdge(int u,int v ){ adj[u].push_back(v); adj[v].push_back(u); } int Graph::countTree(){ int count=0; bool *visited=new bool[Vertices]; for(int i=0;i<Vertices;i++){ visited[i]=false; } for(int i=0;i<Vertices;i++){ if(!visited[i]){ count++; DFSUtil(i,visited); } } return count; } void Graph::DFSUtil(int u,bool visited[]){ if(visited[u]){ return; } visited[u]=true; list<int>::iterator i; for(i=adj[u].begin();i!=adj[u].end();++i){ if(!visited[*i]){ DFSUtil(*i,visited); } } } int main() { int V = 10; //vector<int> adj[V]; Graph obj(V); obj.addEdge( 0, 1); obj.addEdge(0, 2); obj.addEdge( 3, 4); obj.addEdge( 4, 5); obj.addEdge(4, 6); obj.addEdge( 7, 8); cout << obj.countTree(); return 0; }
#include<stdio.h> #include<string.h> char ar1[1000000],ar2[1000000]; int main(int argc, char const *argv[]) { int len1, len2; int sum; scanf("%s%s",&ar1,&ar2); len1 = strlen(ar1); len2 = strlen(ar2); for (int i = 1; i <=3; ++i) { sum = (int)ar1[i]+(int)ar2[i]; printf("%d\n",sum); } return 0; }
// Copyright (c) 2007-2016 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <pika/executors/thread_pool_executor.hpp> namespace pika::parallel::execution { using current_executor = parallel::execution::thread_pool_executor; } // namespace pika::parallel::execution namespace pika::threads { /// Returns a reference to the executor which was used to create /// the given thread. /// /// \throws If <code>&ec != &throws</code>, never throws, but will set \a ec /// to an appropriate value when an error occurs. Otherwise, this /// function will throw an \a pika#exception with an error code of /// \a pika#yield_aborted if it is signaled with \a wait_aborted. /// If called outside of a pika-thread, this function will throw /// an \a pika#exception with an error code of \a pika::null_thread_id. /// If this function is called while the thread-manager is not /// running, it will throw an \a pika#exception with an error code of /// \a pika#invalid_status. /// PIKA_EXPORT parallel::execution::current_executor get_executor( detail::thread_id_type const& id, error_code& ec = throws); } // namespace pika::threads namespace pika::this_thread { /// Returns a reference to the executor which was used to create the current /// thread. /// /// \throws If <code>&ec != &throws</code>, never throws, but will set \a ec /// to an appropriate value when an error occurs. Otherwise, this /// function will throw an \a pika#exception with an error code of /// \a pika#yield_aborted if it is signaled with \a wait_aborted. /// If called outside of a pika-thread, this function will throw /// an \a pika#exception with an error code of \a pika::null_thread_id. /// If this function is called while the thread-manager is not /// running, it will throw an \a pika#exception with an error code of /// \a pika#invalid_status. /// PIKA_EXPORT parallel::execution::current_executor get_executor(error_code& ec = throws); } // namespace pika::this_thread
#include<iostream> #include<vector> #include<queue> #include<set> using namespace std; const int d[]={2,3,5}; set<long long> s; priority_queue<long long,vector<long long>,greater<long long> > line; int main() { s.insert(1); line.push(1); for (int i = 1;; i++) {long long x=line.top();line.pop(); if (i == 1500) {cout << "The 1500'th ugly number is " << x << endl; break; } for (int j = 0;j < 3;j++) {long long x1=x*d[j]; if (!s.count(x1)) {s.insert(x1); line.push(x1); } } } return 0; }
#include<string> #include<iostream> #include<vector> using namespace std; class Solution { public: ListNode* swapPairs(ListNode* head) { if (head == nullptr || head->next == nullptr) { return head; } ListNode* newHead = head->next; head->next = swapPairs(newHead->next); newHead->next = head; return newHead; } };
#pragma once #include <stdexcept> namespace dot_pp { namespace lexer { class TokenInfo; enum class TokenizerState; }} namespace dot_pp { namespace parser { enum class ParserState; }} namespace dot_pp { class ParserError : public std::runtime_error { public: ParserError(const std::string& reason); }; class TokenizerError : public std::runtime_error { public: TokenizerError(const std::string& reason); }; class UnknownTokenizerState : public TokenizerError { public: UnknownTokenizerState(const lexer::TokenizerState state); }; class SyntaxError : public ParserError { public: SyntaxError(const std::string& error, const lexer::TokenInfo& token); }; class UnknownParserState : public ParserError { public: UnknownParserState(const parser::ParserState state); }; }
#include<stdio.h> #include<stdlib.h> #include<conio.h> struct node { int data; struct node *prev; struct node *next; }; int countnodes(struct node *head); struct node *DLLtoBST(struct node **ptr,int n); void insert(struct node **ptr,int a) { struct node *newnode; if((*ptr) == NULL) { (*ptr) = (struct node*)malloc(sizeof(struct node)); (*ptr)->data = a; (*ptr)->prev = (*ptr)->next = NULL; return; } newnode = (struct node*)malloc(sizeof(struct node)); newnode->data = a; struct node *temp = *ptr; while(temp->next!=NULL) { temp = temp->next; } temp->next = newnode; newnode->prev = temp; newnode->next = NULL; } void print_list(struct node *head) { while(head!=NULL) { printf("%d \t",head->data); head = head->next; } } struct node* DLL2BST(struct node *ptr) { int count = countnodes(ptr); return DLLtoBST(&ptr,count); } struct node *DLLtoBST(struct node **ptr,int n) { if(n<=0) return NULL; struct node *left = DLLtoBST(ptr,n/2); struct node *root = *ptr; root->prev = left; (*ptr) = (*ptr)->next; root->next = DLLtoBST(ptr,n-n/2-1); return root; } void preorder(struct node *head) { if(head==NULL) return; printf("%d",head->data); preorder(head->prev); preorder(head->next); } int countnodes(struct node *head) { int count=0; struct node *temp = head; while(temp!=NULL) { temp=temp->next; count++; } return count; } int main() { struct node *ptr = NULL; for(int i=1;i<8;i++) insert(&ptr,i); print_list(ptr); struct node *root = DLL2BST(ptr); preorder(root); getch(); }
/**************************************************************** File Name: recyqueue.C Author: Tian Zhang, CS Dept., Univ. of Wisconsin-Madison, 1995 Copyright(c) 1995 by Tian Zhang All Rights Reserved Permission to use, copy and modify this software must be granted by the author and provided that the above copyright notice appear in all relevant copies and that both that copyright notice and this permission notice appear in all relevant supporting documentations. Comments and additions may be sent the author at zhang@cs.wisc.edu. ******************************************************************/ #include "global.h" #include "util.h" #include "vector.h" #include "rectangle.h" #include "parameter.h" #include "status.h" #include "cfentry.h" #include "cutil.h" #include "recyqueue.h" UnitQueue::UnitQueue(Stat *Stats) { queue=new Entry[UNIT_SIZE]; for (int i=0; i<UNIT_SIZE; i++) queue[i].Init(Stats->Dimension); next = NULL; } UnitQueue::~UnitQueue() { delete [] queue; } RecyQueueClass::RecyQueueClass(Stat *Stats) { size=Stats->QueueSize*Stats->PageSize/Stats->EntrySize(); head = tail = new UnitQueue(Stats); actsize = start = end = 0; } RecyQueueClass::~RecyQueueClass() { UnitQueue *ptr; while (head!=tail) { ptr=head; head=head->next; delete ptr; } delete tail; } void RecyQueueClass::CF(Entry& tmpcf) const { UnitQueue *ptr=head; tmpcf.Reset(); for (int i=0; i<actsize; i++) { tmpcf += ptr->queue[(start+i)%UNIT_SIZE]; if ((start+i+1)%UNIT_SIZE==0) ptr=ptr->next; } } int RecyQueueClass::Size() const {return size;} short RecyQueueClass::Full() const {return actsize>size;} short RecyQueueClass::Empty() const {return actsize==0;} int RecyQueueClass::CountEntry() const {return actsize;} int RecyQueueClass::CountTuple() const { UnitQueue *ptr=head; int tmpcnt=0; for (int i=0; i<actsize; i++) { tmpcnt += ptr->queue[(start+i)%UNIT_SIZE].n; if ((start+i+1)%UNIT_SIZE==0) ptr=ptr->next; } return tmpcnt; } void RecyQueueClass::AddEnt(Entry &ent,Stat* Stats) { UnitQueue *ptr; tail->queue[end]=ent; end++; actsize++; if (end==UNIT_SIZE) { end=0; ptr=new UnitQueue(Stats); tail->next=ptr; tail=tail->next; } } void RecyQueueClass::DeleteEnt(Entry &ent) { UnitQueue *ptr; ent=head->queue[start]; start++; actsize--; if (start==UNIT_SIZE) { start=0; ptr=head; head=head->next; delete ptr; } } std::ostream& operator<<(std::ostream &fo, RecyQueueClass *Queue) { fo << "Size: " << Queue->Size() << std::endl; fo << "Entry: " << Queue->CountEntry() << std::endl; fo << "Tuple: " << Queue->CountTuple() << std::endl; return fo; } std::ofstream& operator<<(std::ofstream &fo, RecyQueueClass *Queue) { fo << "Size: " << Queue->Size() << std::endl; fo << "Entry: " << Queue->CountEntry() << std::endl; fo << "Tuple: " << Queue->CountTuple() << std::endl; return fo; }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ShrubberyCreationForm.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kwillum <kwillum@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/16 16:28:58 by kwillum #+# #+# */ /* Updated: 2021/01/22 18:14:33 by kwillum ### ########.fr */ /* */ /* ************************************************************************** */ #include "ShrubberyCreationForm.hpp" const std::string ShrubberyCreationForm::_tree = " v\n" " >X<\n" " A\n" " d$b\n" " .d\\$$b.\n" " .d$i$$\\$$b.\n" " d$$@b\n" " d\\$$$ib\n" " .d$$$\\$$$b\n" " .d$$@$$$$\\$$ib.\n" " d$$i$$b\n" " d\\$$$$@$b\n" " .d$@$$\\$$$$$@b.\n" ".d$$$$i$$$\\$$$$$$b.\n" " ###\n" " ###\n" " ### mh"; ShrubberyCreationForm::ShrubberyCreationForm() : Form("Shrubbery Creation", 145, 137), _target("Deault_target") { } ShrubberyCreationForm::~ShrubberyCreationForm() { } ShrubberyCreationForm::ShrubberyCreationForm(const ShrubberyCreationForm &toCopy) : Form(toCopy), _target(toCopy.getTartget()) { } ShrubberyCreationForm::ShrubberyCreationForm(const std::string &target) : Form("Shrubbery Creation", 145, 137), _target(target) { } const std::string &ShrubberyCreationForm::getTartget() const { return (_target); } void ShrubberyCreationForm::execute(const Bureaucrat &b) const { Form::execute(b); std::ofstream outputFile((_target + "_shrubbery").c_str(), std::ios::trunc); if (!outputFile.is_open() || outputFile.fail()) throw ShrubberyFormFileOpenException(); outputFile << _tree; if (outputFile.bad()) { outputFile << std::endl; outputFile.close(); throw ShrubberyFormWriteErrorException(); } outputFile << std::endl; outputFile.close(); } ShrubberyCreationForm &ShrubberyCreationForm::operator=(const ShrubberyCreationForm &toCopy) { (void)toCopy; return (*this); } const char *ShrubberyCreationForm::ShrubberyFormFileOpenException::what() const throw() { return ("ShrubberyCreationForm::Exception error with open file!"); } const char *ShrubberyCreationForm::ShrubberyFormWriteErrorException::what() const throw() { return ("ShrubberyCreationForm::Exception error writing in file!"); } Form *ShrubberyCreationForm::formCreator(std::string const &target) { Form *newForm = NULL; try { newForm = new ShrubberyCreationForm(target); } catch(const std::bad_alloc& e) { throw Form::FormBadAllocException(); } return (newForm); }
// This file is triangularView of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" template<typename MatrixType> void bandmatrix(const MatrixType& _m) { typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrixType; Index rows = _m.rows(); Index cols = _m.cols(); Index supers = _m.supers(); Index subs = _m.subs(); MatrixType m(rows,cols,supers,subs); DenseMatrixType dm1(rows,cols); dm1.setZero(); m.diagonal().setConstant(123); dm1.diagonal().setConstant(123); for (int i=1; i<=m.supers();++i) { m.diagonal(i).setConstant(static_cast<RealScalar>(i)); dm1.diagonal(i).setConstant(static_cast<RealScalar>(i)); } for (int i=1; i<=m.subs();++i) { m.diagonal(-i).setConstant(-static_cast<RealScalar>(i)); dm1.diagonal(-i).setConstant(-static_cast<RealScalar>(i)); } //std::cerr << m.m_data << "\n\n" << m.toDense() << "\n\n" << dm1 << "\n\n\n\n"; VERIFY_IS_APPROX(dm1,m.toDenseMatrix()); for (int i=0; i<cols; ++i) { m.col(i).setConstant(static_cast<RealScalar>(i+1)); dm1.col(i).setConstant(static_cast<RealScalar>(i+1)); } Index d = std::min(rows,cols); Index a = std::max<Index>(0,cols-d-supers); Index b = std::max<Index>(0,rows-d-subs); if(a>0) dm1.block(0,d+supers,rows,a).setZero(); dm1.block(0,supers+1,cols-supers-1-a,cols-supers-1-a).template triangularView<Upper>().setZero(); dm1.block(subs+1,0,rows-subs-1-b,rows-subs-1-b).template triangularView<Lower>().setZero(); if(b>0) dm1.block(d+subs,0,b,cols).setZero(); //std::cerr << m.m_data << "\n\n" << m.toDense() << "\n\n" << dm1 << "\n\n"; VERIFY_IS_APPROX(dm1,m.toDenseMatrix()); } void test_bandmatrix() { typedef BandMatrix<float>::Index Index; for(int i = 0; i < 10*g_repeat ; i++) { Index rows = ei_random<Index>(1,10); Index cols = ei_random<Index>(1,10); Index sups = ei_random<Index>(0,cols-1); Index subs = ei_random<Index>(0,rows-1); CALL_SUBTEST(bandmatrix(BandMatrix<float>(rows,cols,sups,subs)) ); } }
#pragma once #include "..\Common\Pch.h" #include "..\Graphic\Direct3D.h" class Material { public: Material(); ~Material(); void Initialize(); void SetMaterial(D3DXVECTOR4 ambient, D3DXVECTOR4 diffuse, D3DXVECTOR4 specular, FLOAT specularPower); void SetBuffer(RB_Type materialType); private: struct BufferData { D3DXVECTOR4 Ambient; D3DXVECTOR4 Diffuse; D3DXVECTOR4 Specular; FLOAT SpecularPower; D3DXVECTOR3 Pad; }; ID3D11Buffer* mBuffer; D3DXVECTOR4 mAmbient; D3DXVECTOR4 mDiffuse; D3DXVECTOR4 mSpecular; FLOAT mSpecularPower; };
#include <bits/stdc++.h> using namespace std; string s; vector<int> mx1,mx2,mn1,mn2; int sum_1,sum_2; int main(){ cin>>s; for(int i=0;i<3;++i){ sum_1+=s[i]-'0'; mx1.emplace_back(9-(s[i]-'0')); mn1.emplace_back(s[i]-'0'); } for(int i=3;i<6;++i){ sum_2+=s[i]-'0'; mx2.emplace_back(9-(s[i]-'0')); mn2.emplace_back(s[i]-'0'); } sort(mx1.begin(),mx1.end(),greater<int>()); sort(mx2.begin(),mx2.end(),greater<int>()); sort(mn1.begin(),mn1.end(),greater<int>()); sort(mn2.begin(),mn2.end(),greater<int>()); if(sum_1==sum_2){ cout<<0<<endl; }else if(sum_1>sum_2){ int num=sum_1-sum_2; vector<int> v; for(int i=0;i<3;i++){ v.emplace_back(mn1[i]); v.emplace_back(mx2[i]); } sort(v.begin(),v.end(),greater<int>()); int ans=0,cnt=0; for(int i=0;i<6;++i){ ++ans; cnt+=v[i]; if(cnt>=num) break; } cout<<ans<<endl; }else{ int num=sum_2-sum_1; vector<int> v; for(int i=0;i<3;i++){ v.emplace_back(mx1[i]); v.emplace_back(mn2[i]); } sort(v.begin(),v.end(),greater<int>()); int ans=0,cnt=0; for(int i=0;i<6;++i){ ++ans; cnt+=v[i]; if(cnt>=num) break; } cout<<ans<<endl; } return 0; }
// // include: rawdata.h // // last update: '18.xx.xx // author: matchey // // memo: // #ifndef PERFECT_VELODYNE_RAWDATA_H #define PERFECT_VELODYNE_RAWDATA_H #include <errno.h> #include <stdint.h> #include <string> #include <boost/format.hpp> #include <math.h> #include <ros/ros.h> #include <pcl_ros/point_cloud.h> #include <velodyne_msgs/VelodyneScan.h> #include <velodyne_pointcloud/calibration.h> #include "perfect_velodyne/point_types.h" namespace perfect_velodyne { // Shorthand typedefs for point cloud representations // typedef pcl::PointXYZINormal pXYZINormal; // typedef pcl::PointCloud<pXYZINormal> pcXYZINormal; typedef PointXYZIRNormal VPointNormal; typedef pcl::PointCloud<VPointNormal> VPointCloudNormal; static const int SIZE_BLOCK = 100; static const int RAW_SCAN_SIZE = 3; static const int SCANS_PER_BLOCK = 32; static const int BLOCK_DATA_SIZE = (SCANS_PER_BLOCK * RAW_SCAN_SIZE); static const float ROTATION_RESOLUTION = 0.01f; // [deg] static const uint16_t ROTATION_MAX_UNITS = 36000u; // [deg/100] static const float DISTANCE_RESOLUTION = 0.002f; // [m] /** @todo make this work for both big and little-endian machines */ static const uint16_t UPPER_BANK = 0xeeff; static const uint16_t LOWER_BANK = 0xddff; typedef struct raw_block { uint16_t header; ///< UPPER_BANK or LOWER_BANK uint16_t rotation; ///< 0-35999, divide by 100 to get degrees uint8_t data[BLOCK_DATA_SIZE]; } raw_block_t; /** used for unpacking the first two data bytes in a block * * They are packed into the actual data stream misaligned. I doubt * this works on big endian machines. */ union two_bytes { uint16_t uint; uint8_t bytes[2]; }; static const int PACKET_SIZE = 1206; static const int BLOCKS_PER_PACKET = 12; static const int PACKET_STATUS_SIZE = 4; static const int SCANS_PER_PACKET = (SCANS_PER_BLOCK * BLOCKS_PER_PACKET); /** \brief Raw Velodyne packet. * * revolution is described in the device manual as incrementing * (mod 65536) for each physical turn of the device. Our device * seems to alternate between two different values every third * packet. One value increases, the other decreases. * * \todo figure out if revolution is only present for one of the * two types of status fields * * status has either a temperature encoding or the microcode level */ typedef struct raw_packet { raw_block_t blocks[BLOCKS_PER_PACKET]; uint16_t revolution; uint8_t status[PACKET_STATUS_SIZE]; } raw_packet_t; class RawDataWithNormal { /** configuration parameters */ typedef struct { std::string calibrationFile; ///< calibration file name double max_range; ///< maximum range to publish double min_range; ///< minimum range to publish int min_angle; ///< minimum angle to publish int max_angle; ///< maximum angle to publish double tmp_min_angle; double tmp_max_angle; } Config; Config config_; /** * Calibration file */ velodyne_pointcloud::Calibration calibration_; float sin_rot_table_[ROTATION_MAX_UNITS]; float cos_rot_table_[ROTATION_MAX_UNITS]; /** in-line test whether a point is in range */ bool pointInRange(float range) { return (range >= config_.min_range && range <= config_.max_range); // return true; } public: RawDataWithNormal(); ~RawDataWithNormal() {} void unpack(const velodyne_msgs::VelodynePacket &pkt, VPointCloudNormal &pc); int setup(ros::NodeHandle private_nh); int setupOffline(std::string calibration_file, double max_range_, double min_range_); void setParameters(double min_range, double max_range, double view_direction, double view_width); }; } // namespace perfect_velodyne #endif
#include<bits/stdc++.h> using namespace std; main() { int m, s, i, t; string x, y; cin>>m>>s; if(s==0) { cout<<(m==1 ? "0 0":"-1 -1"); return 0; } for(i=0; i<m; i++) { t = min(s, 9); y += t+'0'; s -= t; } if(s>0) { cout<<"-1 -1"; return 0; } for(i=m-1; i>=0; i--) x += y[i]; /* for(i=0; x[i]=='0'; i++); x[i]--, x[0]++; cout<<x<<" "<<y;*/ cout<<x<<endl; return 0; }
#ifndef CREATECOMMITMENT_H #define CREATECOMMITMENT_H #include <Interval.h> #include <QCheckBox> #include <QDateEdit> #include <QIntValidator> #include <QLineEdit> #include <QWidget> #define WRITING_STRING "Writing" #define MUSIC_STRING "Compose Music" #define CUSTOM_STRING "Custom" namespace Ui { class CreateCommitmentQWidget; } /** * @brief The CreateCommitmentQWidget class */ class CreateCommitmentQWidget : public QWidget { Q_OBJECT public: explicit CreateCommitmentQWidget(QWidget *parent = nullptr); ~CreateCommitmentQWidget(); QCheckBox *getKeyboardCheckBox(); QCheckBox *getAudioCheckBox(); Ui::CreateCommitmentQWidget *getUI(); QIntValidator validator{ (0, 999, this) }; QString getCommitmentName(); QDate getStartDate(); QDate getEndDate(); util::Interval getInterval(); private slots: void dropDownTaskSlot(const QString &); void createCommitmentButtonSlot(); void backButtonSlot(); void on_createCommitmentQFrame_destroyed(); private: Ui::CreateCommitmentQWidget *ui; }; #endif // CREATECOMMITMENT_H
/* Erronious GPL licence text and copyright removed. * See lth's comment to https://cvs.intern.opera.no/viewcvs/viewcvs.cgi/Opera/lib/Mail/liboe.cpp?hideattic=0&r1=2.6&r2=2.7 * "Removed an incorrect copyright notice at the instruction of VPE." */ #include "core/pch.h" #ifdef M2_SUPPORT # if !defined(_UNIX_DESKTOP_) && !defined(_MACINTOSH_) # include "adjunct/desktop_util/opfile/desktop_opfile.h" # include "modules/util/opfile/opfile.h" /* The use of fpos_t here where one assumes it to be some int type * is not portable. A suggestion for increased portability would be * off_t or long int and using ftell/ftello and fseek rfz 20040702 */ # include <stdio.h> # include <stdlib.h> # include <string.h> # include <sys/stat.h> # define OE_CANNOTREAD 1 # define OE_NOTOEBOX 2 # define OE_POSITION 3 # define OE_NOBODY 4 # define OE_PANIC 5 /* #define DEBUG -- uncomment to get some DEBUG output to stdout */ /* TABLE STRUCTURES -- tables store pointers to message headers and other tables also containing pointers to message headers and other tables -- */ struct oe_table_header { /* At the beginning of each table */ int self, /* Pointer to self (filepos) */ unknown1, /* Unknown */ list, /* Pointer to list */ next, /* Pointer to next */ unknown3, /* Unknown */ unknown4; /* Unknown */ }; typedef struct oe_table_header oe_table_header; struct oe_table_node { /* Actual table entries */ int message, /* Pointer to message | 0 */ list, /* Pointer to another table | 0 */ unknown; /* Unknown */ }; typedef struct oe_table_node oe_table_node; struct oe_list { /* Internal use only */ fpos_t pos; struct oe_list *next; }; typedef struct oe_list oe_list; /* MESSAGE STRUCTURES -- OE uses 16-byte segment headers inside the actual messages. These are meaningful, as described below, but were not very easy to hack correctly -- note that a message may be composed of segments located anywhere in the mailbox file, some times far from each other. */ struct oe_msg_segmentheader { int self, /* Pointer to self (filepos) */ increase, /* Increase to next segment header (not in msg, in file!) */ include, /* Number of bytes to include from this segment */ next, /* Pointer to next message segment (in msg) (filepos) */ usenet; /* Only used with usenet posts */ }; typedef struct oe_msg_segmentheader oe_msg_segmentheader; /* INTERAL STRUCTURES */ struct oe_internaldata{ void (*oput)(char*); FILE *oe; oe_list *used; int success, justheaders, failure; int errcode; int msgcount; struct stat *stat; }; typedef struct oe_internaldata oe_data; /* LIST OF USED TABLES */ void oe_posused(oe_data *data, fpos_t pos) { oe_list *n = OP_NEW(oe_list, ()); n->pos = pos; n->next = data->used; data->used = n; } int oe_isposused(oe_data *data, fpos_t pos) { oe_list *n = data->used; while (n!=NULL) { if (pos==n->pos) return 1; n = n->next; } return 0; } void oe_freeposused(oe_data *data) { oe_list *n; while (data->used!=NULL) {n=data->used->next; OP_DELETE(data->used); data->used=n;} } /* ACTUAL MESSAGE PARSER */ int oe_readmessage(oe_data *data, fpos_t pos, int newsarticle) { int segheadsize = sizeof(oe_msg_segmentheader)-4; /*+(newsarticle<<2);*/ oe_msg_segmentheader sgm; char buff[65]; int endofsegment, headerwritten = 0; // fsetpos(data->oe,&pos); while (1) { fsetpos(data->oe,&pos); fread(&sgm,4,4,data->oe); if (pos!=sgm.self) { // No body found #ifdef DEBUG printf("- Fail reported at %.8x (%.8x)\n",pos,sgm.self); #endif data->failure++; return OE_NOBODY; } pos+=segheadsize; endofsegment = ((int)pos)+sgm.include; if (!headerwritten) { #ifdef DEBUG printf("%.8x : \n",pos-segheadsize); #endif data->oput("From importer@localhost Fri Oct 25 12:00:00 2002\n"); headerwritten = 1; } while (pos<endofsegment) { int rLen = endofsegment - (int)pos; if (rLen>64) rLen=64; rLen = fread(&buff,1,rLen,data->oe); if (!rLen) break; buff[rLen] = 0; data->oput(buff); pos += rLen; } pos = sgm.next; if (pos==0) break; fsetpos(data->oe, &pos); } data->oput("\n"); data->success++; return 0; } /* PARSES MESSAGE HEADERS */ int oe_readmessageheader(oe_data *data, fpos_t pos) { int segheadsize = sizeof(oe_msg_segmentheader)-4; oe_msg_segmentheader *sgm; int self=1, msgpos = 0, newsarticle = 0; if (oe_isposused(data,pos)) return 0; else oe_posused(data,pos); fsetpos(data->oe,&pos); sgm = OP_NEW(oe_msg_segmentheader, ()); fread(sgm,segheadsize,1,data->oe); if (pos!=sgm->self) { OP_DELETE(sgm); return OE_POSITION; /* ERROR */ } OP_DELETE(sgm); fread(&self,4,1,data->oe); self=1; while ((self & 0x7F)>0) { fread(&self,4,1,data->oe); if ((self & 0xFF) == 0x84) /* 0x80 = Set, 04 = Index */ if (msgpos==0) msgpos = self >> 8; if ((self & 0xFF) == 0x83) /* 0x80 = Set, 03 = News */ newsarticle = 1; } if (msgpos) { data->msgcount++; oe_readmessage(data,msgpos,newsarticle); } else { fread(&self,4,1,data->oe); fread(&msgpos,4,1,data->oe); if (oe_readmessage(data,msgpos,newsarticle)) { if (newsarticle) { data->justheaders++; data->failure--; } } } return 0; } /* PARSES MAILBOX TABLES */ int oe_readtable(oe_data *data, fpos_t pos) { oe_table_header thead; oe_table_node tnode; int quit = 0; if (oe_isposused(data,pos)) return 0; fsetpos(data->oe,&pos); fread(&thead,sizeof(oe_table_header),1,data->oe); if (thead.self != pos) return OE_POSITION; oe_posused(data,pos); pos+=sizeof(oe_table_header); oe_readtable(data,thead.next); oe_readtable(data,thead.list); fsetpos(data->oe,&pos); while (!quit) { //int tmp = fread(&tnode,sizeof(oe_table_node),1,data->oe); int sizTableNode = sizeof(oe_table_node); pos+=sizTableNode; if ( (tnode.message > data->stat->st_size) && (tnode.list > data->stat->st_size) ) return 0xF0; /* PANIC */ if ( (tnode.message == tnode.list) && (tnode.message == 0) ) /* Neither message nor list==quit */ { quit = 1; } else { oe_readmessageheader(data,tnode.message); oe_readtable(data,tnode.list); } fsetpos(data->oe,&pos); } return 0; } void oe_readdamaged(oe_data *data) { /* If nothing else works (needed this to get some mailboxes that even OE couldn't read to work. Should generally not be needed, but is nice to have in here */ fpos_t pos = 0x7C; int i,check, lastID; #ifdef DEBUG printf(" Trying to construct internal mailbox structure\n"); #endif fsetpos(data->oe,&pos); fread(&pos,sizeof(int),1,data->oe); if (pos==0) return; /* No, sorry, didn't work */ fsetpos(data->oe,&pos); fread(&i,sizeof(int),1,data->oe); if (i!=pos) return; /* Sorry */ fread(&pos,sizeof(int),1,data->oe); i+=((int)(pos))+8; pos = i+4; fsetpos(data->oe,&pos); #ifdef DEBUG printf(" Searching for %.8x\n",i); #endif lastID=0; while (pos<data->stat->st_size) { /* Read through file, notice markers, look for message (gen. 2BD4)*/ fread(&check,sizeof(int),1,data->oe); if (check==pos) lastID=((int)(pos)); pos+=4; if ((check==i) && (lastID)) { #ifdef DEBUG printf("Trying possible table at %.8x\n",lastID); #endif oe_readtable(data,lastID); fsetpos(data->oe,&pos); } } } void oe_readbox_oe4(oe_data *data) { fpos_t pos = 0x54, endpos=0, i; oe_msg_segmentheader header; char *cb = OP_NEWA(char, 4), *sfull = OP_NEWA(char, 65536), *s = sfull; fsetpos(data->oe,&pos); while (pos<data->stat->st_size) { fsetpos(data->oe,&pos); fread(&header,16,1,data->oe); data->oput("From importer@localhost Sat Jun 17 01:08:25 2000\n"); endpos = pos + header.include; if (endpos>data->stat->st_size) endpos=data->stat->st_size; pos+=4; while (pos<endpos) { fread(cb,1,4,data->oe); for (i=0;i<4;i++,pos++) if (*(cb+i)!=0x0d) { *s++ = *(cb+i); if (*(cb+i) == 0x0a) { *s = '\0'; data->oput(sfull); s = sfull; } } } data->success++; if (s!=sfull) { *s='\0'; data->oput(sfull); s=sfull; } data->oput("\n"); pos=endpos; } OP_DELETEA(sfull); OP_DELETEA(cb); } /* CALL THIS ONE */ oe_data* oe_readbox(const uni_char* filename,void (*oput)(char*)) { UINT32 signature[4]; fpos_t i; oe_data *data = OP_NEW(oe_data, ()); data->success=data->failure=data->justheaders=data->errcode=data->msgcount=0; data->used = NULL; data->oput = oput; /* FIXME: this was replaced by windows specific code temporarily, to be able to remove the old uni_fopen. It should be rewritten using OpFile. */ data->oe = _wfopen(filename, UNI_L("rb")); if (data->oe==NULL) { data->errcode = OE_CANNOTREAD; return data; } /* SECURITY (Yes, we need this, just in case) */ data->stat = OP_NEW(struct stat, ()); OpFile box_file; box_file.Construct(filename); DesktopOpFileUtils::Stat(&box_file, data->stat); /* SIGNATURE */ fread(&signature,16,1,data->oe); if ((signature[0]!=0xFE12ADCF) || /* OE 5 & OE 5 BETA SIGNATURE */ (signature[1]!=0x6F74FDC5) || (signature[2]!=0x11D1E366) || (signature[3]!=0xC0004E9A)) { if ((signature[0]==0x36464D4A) && (signature[1]==0x00010003)) /* OE4 SIGNATURE */ { oe_readbox_oe4(data); fclose(data->oe); OP_DELETE(data->stat); return data; } fclose(data->oe); OP_DELETE(data->stat); data->errcode = OE_NOTOEBOX; return data; } /* ACTUAL WORK */ i = 0x30; if( fsetpos(data->oe, &i) != 0) { data->errcode=errno; data->errcode=OE_PANIC; //not able to set file position!!! } else { fread(&i,4,1,data->oe); if (!i) i=0x1e254; i = oe_readtable(data,i); /* Reads the box */ if (i & 0xF0) { oe_readdamaged(data); data->errcode=OE_PANIC; } oe_freeposused(data); } /* CLOSE DOWN */ fclose(data->oe); OP_DELETE(data->stat); return data; } #endif // !_UNIX_DESKTOP_ && !_MACINTOSH_ #endif //M2_SUPPORT
#pragma once #include "Camera.h" #include <GLFW/glfw3.h> #include <iostream> #include <functional> #include "GUIWrapper.h" using namespace HW; using namespace std; class CameraSpeed { public: float speed_base = 0.0005; int level = 3; int MinLevel = 1; int MaxLevel = 10; float speed=1.0; CameraSpeed() { CalcSpeed(); } void Dec(int d) { level -= d; if (level <= MinLevel) level = MinLevel; CalcSpeed(); } void Inc(int d) { level += d; if (level >=MaxLevel) level = MaxLevel; CalcSpeed(); } void CalcSpeed() { speed=speed_base*level*level*level; } }; class CameraRotate { public: //for camera rotate bool EnterRotateMode=false; bool firstMove=true; float lastx; float lasty; int w, h; float RotateSpeed=100; void process_mouse_button(int button, int action) { if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) { EnterRotateMode = true; firstMove = true; } if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_RELEASE) { EnterRotateMode = false; } } void process_mouse_move(double x,double y,Camera* camera) { if (!EnterRotateMode) return; if (firstMove) { lastx = x; lasty = y; firstMove = false; return; } float dx = (x - lastx) / w*RotateSpeed; float dy = (y - lasty) / h*RotateSpeed; lastx = x; lasty = y; camera->RotatePitchYaw(-dy, dx); camera->setUp(Vector3(0, 1, 0)); } }; class CameraMove { public: CameraSpeed MoveSpeed; double LastTime; void move_func(GLFWwindow* window,Camera* camera) { double CurrentTime = glfwGetTime(); auto DeltaTime = CurrentTime - LastTime; LastTime = CurrentTime; float d = MoveSpeed.speed; if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) { camera->MoveUp(d); } if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) { camera->MoveDown(d); } if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera->MoveForward(d); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera->MoveBack(d); } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera->MoveLeft(d); } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera->MoveRight(d); } } void move_speed_change(int key ,int action) { if (key == GLFW_KEY_UP && action == GLFW_PRESS) MoveSpeed.Inc(1); if (key == GLFW_KEY_DOWN && action == GLFW_PRESS) MoveSpeed.Dec(1); } }; class InteractionControler { public: static Camera* camera; static GLFWwindow* window; static CameraRotate cameraRotate; static CameraMove cameraMove; static vector<function<void(int, int)>> KeyCallBacks; static GUI* gui; static void SetCamera(Camera* cam) { camera = cam; } static void SetWindow(GLFWwindow* win) { window = win; glfwGetWindowSize(win, &cameraRotate.w, &cameraRotate.h); } static void key_func() { cameraMove.move_func(window, camera); } static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { cameraMove.move_speed_change(key, action); gui->MouseKeyCallBack(window, key, scancode, action, mode); for (auto& f : KeyCallBacks) { f(key, action); } } static void mouse_button_callback(GLFWwindow* window, int button, int action,int mod) { cameraRotate.process_mouse_button(button, action); gui->MouseButtonCallBack(window, button, action, mod); } static void mouse_move_callback(GLFWwindow* window, double x, double y) { cameraRotate.process_mouse_move(x, y,camera); } static void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { gui->MouseScrollCallBack(window, xoffset, yoffset); cout << "scroll" << xoffset << " "<<yoffset << endl; } static void char_callback(GLFWwindow* window, unsigned ch) { gui->MouseCharCallBack(window, ch); } static void iconify_callback(GLFWwindow* window, int f) { cout << "iconify "<<f<<endl; } static void focus_callback(GLFWwindow* window, int f) { cout <<"focus "<< f << endl; //if(f==1) } };
#include <iostream> #include <cstring> #include <queue> #include <vector> #include <algorithm> #define MAX 5001 #define INF 1e12 typedef long long ll; int n, q; std::vector<std::pair<int, ll>> USADO[MAX]; int find(int idx, ll v) { std::queue<std::pair<int, ll>> q; bool visited[n + 1]; int ret = 0; std::memset(visited, 0, sizeof(visited)); visited[idx] = 1; for(auto [nidx, usado] : USADO[idx]) { visited[nidx] = 1; q.push({nidx, usado}); } while(!q.empty()) { auto [now, W] = q.front(); q.pop(); if(W >= v) { ret++; } for(auto [nidx, usado] : USADO[now]) { if(!visited[nidx]) { visited[nidx] = 1; q.push({nidx, std::min(W, usado)}); } } } return ret; } int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); std::cin >> n >> q; for(int i = 0; i < n - 1; i++) { int P, Q; ll R; std::cin >> P >> Q >> R; USADO[P].push_back({Q, R}); USADO[Q].push_back({P, R}); } while(q--) { int k; ll v, ans = 0; std::cin >> k >> v; std::cout << find(v, k) << '\n'; } return 0; }
#include "LazyTermBuilders.h" #include <cassert> /** * LazyTermBuilder */ LazyTermBuilder *LazyTermBuilder::from(term_t term) { switch (PL_term_type(term)) { case PL_ATOM: return LazyAtomBuilder::from(term); case PL_STRING: return LazyStringBuilder::from(term); case PL_TERM: if (!PL_is_list(term)) { return LazyFunctorBuilder::from(term); } return LazyListBuilder::from(term); default: assert(false && "No know lazy building functionality for term"); } } /** * LazyAtomBuilder */ LazyAtomBuilder::LazyAtomBuilder(std::string name) : name_(name) { } PrologTerm LazyAtomBuilder::build() const { return PrologAtom(name_); } LazyAtomBuilder *LazyAtomBuilder::from(term_t term) { char *s; assert(PL_get_chars(term, &s, CVT_ATOM)); return new LazyAtomBuilder(s); } /** * LazyStringBuilder */ LazyStringBuilder::LazyStringBuilder(std::string string) : string_(string) { } PrologTerm LazyStringBuilder::build() const { return PrologString(string_); } LazyStringBuilder *LazyStringBuilder::from(term_t term) { char *s; assert(PL_get_chars(term, &s, CVT_STRING)); return new LazyStringBuilder(s); } /** * LazyListBuilder */ LazyListBuilder::LazyListBuilder(std::vector<LazyTermBuilder*> elements) : elements_(elements) { } PrologTerm LazyListBuilder::build() const { std::vector<PrologTerm> elements; for (auto &element : elements_) { elements.push_back(element->build()); } return PrologList(elements); } LazyListBuilder *LazyListBuilder::from(term_t term) { term_t list = PL_copy_term_ref(term); term_t head = PL_new_term_ref(); std::vector<LazyTermBuilder*> elements; while (!PL_unify_nil(list) && PL_unify_list(list, head, list)) { elements.push_back(LazyTermBuilder::from(head)); } return new LazyListBuilder(elements); } /** * LazyFunctorBuilder */ LazyFunctorBuilder::LazyFunctorBuilder( std::string name, std::vector<LazyTermBuilder*> args) : name_(name), args_(args) { } PrologTerm LazyFunctorBuilder::build() const { std::vector<PrologTerm> args; for (auto &element : args_) { args.push_back(element->build()); } return PrologFunctor(name_, PrologTermVector(args)); } LazyFunctorBuilder *LazyFunctorBuilder::from(term_t term) { term_t tmp = PL_new_term_ref(); atom_t name; int arity; assert(PL_get_name_arity(term, &name, &arity)); std::vector<LazyTermBuilder*> args; for (unsigned i = 1; i <= arity; ++i) { assert(PL_get_arg(i, term, tmp)); args.push_back(LazyTermBuilder::from(tmp)); } return new LazyFunctorBuilder(PL_atom_chars(name), args); }
๏ปฟ #include <iostream> #include <cmath> using namespace std; int main() { setlocale(LC_ALL, "Russian"); int* a; int n, i, c, w; cout << "ะ’ะฒะตะดะธั‚ะต ั€ะฐะทะผะตั€ะฝะพัั‚ัŒ ะผะฐััะธะฒะฐ "; cin >> n; a = new int[n]; for (i = 0; i < n; i++) a[i] = rand() % 20 - 10; cout << "---------- ะ˜ัั…ะพะดะฝั‹ะน ะผะฐััะธะฒ ------------" << endl; for (i = 0; i < n; i++) cout << a[i] << " "; w = 0; for (i = 0; i < n; i++) if (abs(a[i]) < 5) w += a[i]; cout << "\nะกัƒะผะผะฐ ัะปะธะผะตะฝั‚ะพะฒ ะผะฐััะธะฒะฐ, ะฐะฑัะพะปัŽั‚ะฝั‹ะต ะทะฝะฐั‡ะตะฝะธั ะบะพั‚ะพั€ั‹ั… ะผะตะฝัŒัˆะต 5: " << w << endl; c = 0; i = 0; w = 0; while (a[i]%2 == 0) { i++; } c = i; while (a[i+1]%2 == 0) { i++; w++; } cout << "\nะšะพะปะธั‡ะตัั‚ะฒะพ ัะปะตะผะตะฝั‚ะพะฒ, ั€ะฐัะฟะพะปะพะถะตะฝะฝั‹ั… ะผะตะถะดัƒ ะฟะตั€ะฒั‹ะผ ะธ ะฒั‚ะพั€ั‹ะผ ะฝะตั‡ะตั‚ะฝั‹ะผ ัะปะตะผะตะฝั‚ะฐะผะธ: " << w << endl; }
// // Created by ้’Ÿๅฅ‡้พ™ on 2019-05-21. // #include <iostream> #include <string> #include <vector> using namespace std; string manacherString(string str){ int targetLength = 2 * str.size() + 1; string manacher = ""; for(int i=0; i<targetLength; ++i){ if(i % 2 == 0){ manacher.push_back('#'); }else{ manacher.push_back(str[(i-1)/2]); } } return manacher; } /* * ๅŽŸ้—ฎ้ข˜ */ int maxLcpsLength(string str){ if(str.size() == 0) return 0; string manacher = manacherString(str); vector<int> pArr(manacher.size()); int index = -1; int pR = -1; int maxLength = INT_MIN; for(int i=0; i<manacher.size(); ++i){ pArr[i] = pR > i ? min(pArr[index-(i-index)],pR-1 - i + 1):1; while(i+pArr[i] < manacher.size() && i-pArr[i] >= 0){ if(manacher[i+pArr[i]] == manacher[i-pArr[i]]){ pArr[i]++; }else{ break; } } if(i+pArr[i] > pR){ pR = i+pArr[i]; index = i; } maxLength = max(maxLength,pArr[i]); } return maxLength - 1; } /* * ่ฟ›้˜ถ้—ฎ้ข˜ */ string shortestLcpString(string str){ if(str.size() == 0) return 0; string manacher = manacherString(str); vector<int> pArr(manacher.size()); int index = -1; int pR = -1; int maxContainsLength = -1; for(int i=0; i<manacher.size(); ++i){ pArr[i] = pR > i ? min(pArr[index - (i-index)],pR-1 - i + 1) : 1; while(i + pArr[i] < manacher.size() && i - pArr[i] >= 0){ if(manacher[i+pArr[i]] == manacher[i-pArr[i]]){ pArr[i]++; }else{ break; } } if(i+pArr[i] > pR){ pR = i + pArr[i]; index = i; } if(pR == manacher.size()){ maxContainsLength = pArr[i]-1; break; } } string res = ""; for(int i=str.size()-maxContainsLength-1; i>=0; --i){ res.push_back(str[i]); } return res; } int main(){ cout<<maxLcpsLength("abc1234321ab")<<endl; cout<<shortestLcpString("abc1234321ab")<<endl; cout<<shortestLcpString("abcd123321")<<endl; return 0; }
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "GameFramework/GameModeBase.h" #include "Surviving_GroundsGameMode.generated.h" UCLASS(minimalapi) class ASurviving_GroundsGameMode : public AGameModeBase { GENERATED_BODY() public: ASurviving_GroundsGameMode(); };
#include<bits/stdc++.h> using namespace std; class node{ public: int data; node* left; node* right; node(int d){ this->data = d; this->left = NULL; this->right = NULL; } }; node* buildTree(node* root){ int data; cin>>data; if(data == -1) return NULL; root = new node(data); root->left = buildTree(root->left); root->right = buildTree(root->right); return root; } int height(node* root){ if(root == NULL){ return 0; } return (max(height(root->left),height(root->right))+1); } int main(){ node* root = NULL; root = buildTree(root); cout<<height(root)<<endl; return 0; }
// // Player.h // // Created by Yajun Shi // // The user-controlled actor, has abilities of moving and shooting. // #include "stdafx.h" #ifndef __ClientGame__Player__ #define __ClientGame__Player__ class Player : public PhysicsActor { public: Player(); virtual void Update(float dt); virtual void ReceiveMessage(Message *message); void Explode(); void Reset(); private: float _bulletCooldown; int _bulletMode; float _bulletduration; AngelSampleHandle _bulletSound; AngelSampleHandle _explodeSound; }; #endif /* defined(__ClientGame__Player__) */
#ifndef MATH_RANDOM_HEX_HPP #define MATH_RANDOM_HEX_HPP #include <string> #include <sstream> #include <random> namespace Math { static std::string randomHexColor() { static const std::string chArr = "1234567890abcdef"; std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dist(0, 15); std::stringstream ss; ss << '#'; for (size_t i = 0; i < 6; i++) ss << chArr[(dist(gen))]; return ss.str(); } } // namespace Math #endif /* end of include guard : MATH_RANDOM_HEX_HPP */
#include <iostream> #include <vector> #include <queue> #include <algorithm> using namespace std; /* โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ */ #define int long long int #define ld long double #define F first #define S second #define P pair<int,int> #define pb push_back #define endl '\n' /* โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ */ const int N = 1e3 + 5; vector <int> Graph[N]; vector <P> ans, topo; vector <int> indeg; int n, m; typedef vector <int> vi; void kahn(int n) { priority_queue <P, vector<P>, greater<P>> q; for (int i = 0; i < n; i++) { if (indeg[i] == 0) q.push({i, 1}); } while (!q.empty()) { P cur = q.top(); q.pop(); int level = cur.S; int node = cur.F; topo.pb(cur); for (auto to : Graph[node]) { indeg[to]--; if (indeg[to] == 0) q.push({to, level + 1}); } } } void solve() { ans.clear(); indeg = vi(N, 0); topo.clear(); cin >> n >> m; for (int i = 0; i < n; i++) Graph[i].clear(); while (m--) { int u, v; cin >> u >> v; Graph[v].pb(u); indeg[u]++; } kahn(n); for (auto x : topo) ans.pb({x.S, x.F}); sort(ans.begin(), ans.end()); for (auto x : ans) cout << x.F << " " << x.S << endl; return ; } int32_t main() { /* โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ */ ios_base:: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif /* โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ โ†’ */ int t, tc; cin >> t; tc = t; while (t--) { cout << "Scenario #" << tc - t << ":" << endl; solve(); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <sstream> #include <fstream> #include <string.h> #include <algorithm> #include <math.h> #include <map> #include <vector> #include "ResultsReader.h" using namespace std; int main(int argc,char** argv){ if(argc != 9){ cout<<"\nUsage: ./generate_statistics results_base n_threads n_stats n_params target_file percentage distributions_file final_results\n"; cout<<"\n"; return 0; } string results_base = argv[1]; unsigned int n_threads = atoi(argv[2]); unsigned int n_stats = atoi(argv[3]); unsigned int n_params = atoi(argv[4]); string target_file = argv[5]; float percentage = atof(argv[6]); string distributions_file = argv[7]; string final_results = argv[8]; cout << "Statistics - Inicio (n_stats: " << n_stats << ", n_params: " << n_params << ", percentage: " << percentage << ")\n"; ResultsReader reader; // Agrega los datos de TODOS los n_threads resultados parciales reader.readThreadsData(results_base, n_threads, n_stats, n_params); // Agrega el target reader.setTarget(target_file); // Normaliza tanto los datos como el target reader.normalize(); // Calcula la distancia de cada dato normalizado al target reader.computeDistances(); // Ordena por distancia y selecciona los mejores resultados para el training reader.selectBestResults(percentage); // Retorna pares <mean, stddev> de cada parametro calculado de los datos seleccionados vector< pair<double, double> > dist_post = reader.getPosteriori(); fstream writer(distributions_file, fstream::out | fstream::trunc); // En la primera linea pongo las distancias writer << "Distances\t"; writer << reader.getMinDistance() << "\t"; writer << reader.getMaxDistance() << "\t"; writer << reader.getCutDistance() << "\t"; writer << "\n"; // En la primera linea pongo las distancias writer << "DistancesNorm\t"; writer << (reader.getMinDistance() / reader.getMaxDistance()) << "\t"; writer << (reader.getMaxDistance() / reader.getMaxDistance()) << "\t"; writer << (reader.getCutDistance() / reader.getMaxDistance()) << "\t"; writer << "\n"; // Siguen las distribuciones for(unsigned int i = 0; i < dist_post.size(); ++i){ double mean = dist_post[i].first; double stddev = dist_post[i].second; cout << "Posteriori[" << i << "]\t" << mean << "\t" << stddev << "\n"; writer << "Posteriori[" << i << "]\t" << mean << "\t" << stddev << "\n"; } writer.close(); vector< pair<double, unsigned int> > distancias = reader.getDistances(); writer.open(final_results, fstream::out | fstream::trunc); for(unsigned int i = 0; i < distancias.size(); ++i){ double d = distancias[i].first; unsigned pos = distancias[i].second; writer << d << "\t"; // vector<double> res_stats = reader.getStats(pos); // for(unsigned int j = 0; j < n_stats; ++j){ // writer << res_stats[j] << "\t"; // } vector<double> res_params = reader.getParams(pos); for(unsigned int j = 0; j < n_params; ++j){ writer << res_params[j] << "\t"; } writer << "\n"; } writer.close(); cout << "Statistics - Fin\n"; return 0; }
#pragma once #include <LogListenerInterface.h> #include <StringHelper.h> #include <list> #include <memory> namespace breakout { class LogManager { public: static LogManager& Get(); void Init(); void AddListener(std::shared_ptr<ILogListener> listener); void Log(const ILogMessage& message) const; void Log(const ELogLevel& level, const ELogChannel& channel, const std::string& str) const; template<typename... Targs> void Log(const ELogLevel& level, const ELogChannel& channel, const std::string& fstr, const Targs& ... args) const; template<typename... Targs> void Log(const std::string& fstr, const Targs& ... args) const; private: LogManager(); ~LogManager(); LogManager(LogManager&) = delete; LogManager(LogManager&&) = delete; void operator=(LogManager&) = delete; void operator=(LogManager&&) = delete; std::list<std::shared_ptr<ILogListener>> m_listenersList; }; template<typename... Targs> void LogManager::Log(const ELogLevel& level, const ELogChannel& channel, const std::string& fstr, const Targs& ... args) const { Log(level, channel, StringHelper::Format(fstr, args...)); } template<typename... Targs> void LogManager::Log(const std::string& fstr, const Targs& ... args) const { Log(ELogLevel::DEBUG, ELogChannel::MAIN, fstr, args...); } }
#pragma once class CMyClass { public: CMyClass(void); ~CMyClass(void); // speak int Say(void); // eat void eat(void); };
/* Author: Visar Shehu Email: v.shehu@seeu.edu.mk File created: 19.10.2016 Last revision: 19.10.2016 */ #include <iostream> #include <string> using namespace std; struct ADRESA { int housenumber; string streetname; string zipcode; }; int main() { ADRESA a1, a2, a3; ADRESA a[3]; for (int i = 0; i < 3; i++) { cout << "Regjistro vlerat per adresen e pare:" << endl << "Rruga?: "; cin >> a[i].streetname; cout << endl << "Numri: "; cin >> a[i].housenumber; cout << endl << "ZIP Kodi: "; cin >> a[i].zipcode; } cout << "Adresat e regjistruara jane: " << endl; for (int i = 0; i < 3; i ++ ) { //Checking if house number is even if (a[i].housenumber % 2 == 0) { cout << a[i].streetname << " " << a[i].housenumber << " " << a[i].zipcode << endl; } } }
// -*- coding:utf8 -*- // -*- ะบะพะดะธั€ะพะฒะบะฐ:utf8 -*- #include <iostream> #include <libledmatrix/ledmatrix.h> #include <yqnet/yqlib.h> #include <unistd.h> #include "config.h" #include <string> const char * IP = "192.168.0.199"; const uint16_t PORT = 80; const char * LOGIN = "guest"; void test1() { struct LEDDevice * device = leddevice_new(IP, PORT, LOGIN); if (device) { struct LEDProgram * program = ledprogram_new(device, "program 1"); led_program_add_text(program, "mytest", 0, 0, 30, 20, 100); ledprogram_send_to_player(program); sleep(1); ledprogram_free(program); leddevice_free(device); }; //int err = check_time(IP, PORT, LOGIN, LOGIN); //std::cout <<"error "<<err<<std::endl; /* char* ip = "192.168.89.156"; int port = 80; LPCWSTR str = L"guest"; err = check_time(ip, port, str, str); cout<<"check_time:"<<err<<endl; Program_cleardynamic(ip, port, str); Program_bmp(ip, port, str); Program_dynamic_small(ip, port, str); Sleep(5000); Program_dynamic_uint_small(ip, port, str); err=release_sdk(); */ } void test2() { std::string file = std::string(PROJECT_DATADIR) + "/" + "1.bmp"; struct LEDDevice * device = leddevice_new(IP, PORT, LOGIN); if (device) { struct LEDProgram * program = ledprogram_new(device, "program 5"); led_program_clear(program); //led_program_add_dynamics(program, "Hi ะ’ะฐัั asdgg!", 0, 0, 64, 32, 100); led_program_add_dynamics_picture(program, file.c_str(), 0, 0, 128, 96, 100); led_program_send(program); ledprogram_free(program); leddevice_free(device); }; } int main(int argc, char **argv) { test2(); return 0; }
/** *** Copyright (c) 1995, 1996, 1997, 1998, 1999, 2000 by *** The Board of Trustees of the University of Illinois. *** All rights reserved. **/ #include <stdlib.h> #include <math.h> #include "PmeKSpace.h" static void dftmod(double *bsp_mod, double *bsp_arr, int nfft) { int j, k; double twopi, arg, sum1, sum2; double infft = 1.0/nfft; /* Computes the modulus of the discrete fourier transform of bsp_arr, */ /* storing it into bsp_mod */ twopi = 2.0 * M_PI; for (k = 0; k <nfft; ++k) { sum1 = 0.; sum2 = 0.; for (j = 0; j < nfft; ++j) { arg = twopi * k * j * infft; sum1 += bsp_arr[j] * cos(arg); sum2 += bsp_arr[j] * sin(arg); } bsp_mod[k] = sum1*sum1 + sum2*sum2; } } static void compute_b_moduli(double *bm, int K, int order) { int i; double fr[3]; double *M = new double[3*order]; double *dM = new double[3*order]; double *scratch = new double[K]; fr[0]=fr[1]=fr[2]=0.0; compute_b_spline(fr,M,dM,order); for (i=0; i<order; i++) bm[i] = M[i]; for (i=order; i<K; i++) bm[i] = 0.0; dftmod(scratch, bm, K); for (i=0; i<K; i++) bm[i] = 1.0/scratch[i]; delete [] scratch; delete [] dM; delete [] M; } PmeKSpace::PmeKSpace(PmeGrid grid, int K2_start, int K2_end) : myGrid(grid), k2_start(K2_start), k2_end(K2_end) { int K1, K2, K3, order; K1=myGrid.K1; K2=myGrid.K2, K3=myGrid.K3; order=myGrid.order; bm1 = new double[K1]; bm2 = new double[K2]; bm3 = new double[K3]; exp1 = new double[K1/2 + 1]; exp2 = new double[K2/2 + 1]; exp3 = new double[K3/2 + 1]; compute_b_moduli(bm1, K1, order); compute_b_moduli(bm2, K2, order); compute_b_moduli(bm3, K3, order); } PmeKSpace::~PmeKSpace() { delete [] bm1; delete [] bm2; delete [] bm3; delete [] exp1; delete [] exp2; delete [] exp3; } double PmeKSpace::compute_energy(double *q_arr, Lattice lattice, double ewald, double *virial) { double energy = 0.0; int pad2, pad3, n; int k1, k2, k3, ind; int K1, K2, K3; K1=myGrid.K1; K2=myGrid.K2; K3=myGrid.K3; pad2 = 0; pad3 = myGrid.dim3-K3-(K3 & 1 ? 1 : 2); i_pi_volume = 1.0/(M_PI * lattice_volume(&lattice)); piob = M_PI/ewald; piob *= piob; for (n=0; n<6; virial[n++] = 0.0); if ( lattice_is_orthogonal(&lattice) ) { double recipx = lattice.b1.x; double recipy = lattice.b2.y; double recipz = lattice.b3.z; init_exp(exp1, K1, recipx); init_exp(exp2, K2, recipy); init_exp(exp3, K3, recipz); ind = 0; for ( k1=0; k1<K1; ++k1 ) { double m1, m11, b1, xp1; b1 = bm1[k1]; int k1_s = k1<=K1/2 ? k1 : k1-K1; m1 = k1_s*recipx; m11 = m1*m1; xp1 = i_pi_volume*exp1[abs(k1_s)]; for ( k2=k2_start; k2<k2_end; ++k2 ) { double m2, m22, b1b2, xp2; b1b2 = b1*bm2[k2]; int k2_s = k2<=K2/2 ? k2 : k2-K2; m2 = k2_s*recipy; m22 = m2*m2; xp2 = exp2[abs(k2_s)]*xp1; if ( k1==0 && k2==0 ) { q_arr[ind++] = 0.0; q_arr[ind++] = 0.0; k3 = 1; } else { k3 = 0; } for ( ; k3<=K3/2; ++k3 ) { double m3, m33, xp3, msq, imsq, vir, fac; double theta3, theta, q2, qr, qc, C; theta3 = bm3[k3] *b1b2; m3 = k3*recipz; m33 = m3*m3; xp3 = exp3[k3]; qr = q_arr[ind]; qc=q_arr[ind+1]; q2 = 2*(qr*qr + qc*qc)*theta3; if ( (k3 == 0) || ( k3 == K3/2 && ! (K3 & 1) ) ) q2 *= 0.5; msq = m11 + m22 + m33; imsq = 1.0/msq; C = xp2*xp3*imsq; theta = theta3*C; q_arr[ind] *= theta; q_arr[ind+1] *= theta; vir = -2*(piob+imsq); fac = q2*C; energy += fac; virial[0] += fac*(1.0+vir*m11); virial[1] += fac*vir*m1*m2; virial[2] += fac*vir*m1*m3; virial[3] += fac*(1.0+vir*m22); virial[4] += fac*vir*m2*m3; virial[5] += fac*(1.0+vir*m33); ind += 2; } ind += pad3; } ind += pad2; } } else if ( cross(lattice.a1,lattice.a2).unit() == lattice.a3.unit() ) { Vector recip1 = lattice.b1; Vector recip2 = lattice.b2; Vector recip3 = lattice.b3; double recip3_x = recip3.x; double recip3_y = recip3.y; double recip3_z = recip3.z; init_exp(exp3, K3, recip3.length()); ind = 0; for ( k1=0; k1<K1; ++k1 ) { double b1; Vector m1; b1 = bm1[k1]; int k1_s = k1<=K1/2 ? k1 : k1-K1; m1 = k1_s*recip1; // xp1 = i_pi_volume*exp1[abs(k1_s)]; for ( k2=k2_start; k2<k2_end; ++k2 ) { double xp2, b1b2, m2_x, m2_y, m2_z; b1b2 = b1*bm2[k2]; int k2_s = k2<=K2/2 ? k2 : k2-K2; m2_x = m1.x + k2_s*recip2.x; m2_y = m1.y + k2_s*recip2.y; m2_z = m1.z + k2_s*recip2.z; // xp2 = exp2[abs(k2_s)]*xp1; xp2 = i_pi_volume*exp(-piob*(m2_x*m2_x+m2_y*m2_y+m2_z*m2_z)); if ( k1==0 && k2==0 ) { q_arr[ind++] = 0.0; q_arr[ind++] = 0.0; k3 = 1; } else { k3 = 0; } for ( ; k3<=K3/2; ++k3 ) { double xp3, msq, imsq, vir, fac; double theta3, theta, q2, qr, qc, C; double m_x, m_y, m_z; theta3 = bm3[k3] *b1b2; m_x = m2_x + k3*recip3_x; m_y = m2_y + k3*recip3_y; m_z = m2_z + k3*recip3_z; msq = m_x*m_x + m_y*m_y + m_z*m_z; xp3 = exp3[k3]; qr = q_arr[ind]; qc=q_arr[ind+1]; q2 = 2*(qr*qr + qc*qc)*theta3; if ( (k3 == 0) || ( k3 == K3/2 && ! (K3 & 1) ) ) q2 *= 0.5; imsq = 1.0/msq; C = xp2*xp3*imsq; theta = theta3*C; q_arr[ind] *= theta; q_arr[ind+1] *= theta; vir = -2*(piob+imsq); fac = q2*C; energy += fac; virial[0] += fac*(1.0+vir*m_x*m_x); virial[1] += fac*vir*m_x*m_y; virial[2] += fac*vir*m_x*m_z; virial[3] += fac*(1.0+vir*m_y*m_y); virial[4] += fac*vir*m_y*m_z; virial[5] += fac*(1.0+vir*m_z*m_z); ind += 2; } ind += pad3; } ind += pad2; } } else { Vector recip1 = lattice.b1; Vector recip2 = lattice.b2; Vector recip3 = lattice.b3; double recip3_x = recip3.x; double recip3_y = recip3.y; double recip3_z = recip3.z; ind = 0; for ( k1=0; k1<K1; ++k1 ) { double b1; Vector m1; b1 = bm1[k1]; int k1_s = k1<=K1/2 ? k1 : k1-K1; m1 = k1_s*recip1; // xp1 = i_pi_volume*exp1[abs(k1_s)]; for ( k2=k2_start; k2<k2_end; ++k2 ) { double b1b2, m2_x, m2_y, m2_z; b1b2 = b1*bm2[k2]; int k2_s = k2<=K2/2 ? k2 : k2-K2; m2_x = m1.x + k2_s*recip2.x; m2_y = m1.y + k2_s*recip2.y; m2_z = m1.z + k2_s*recip2.z; // xp2 = exp2[abs(k2_s)]*xp1; if ( k1==0 && k2==0 ) { q_arr[ind++] = 0.0; q_arr[ind++] = 0.0; k3 = 1; } else { k3 = 0; } for ( ; k3<=K3/2; ++k3 ) { double xp3, msq, imsq, vir, fac; double theta3, theta, q2, qr, qc, C; double m_x, m_y, m_z; theta3 = bm3[k3] *b1b2; m_x = m2_x + k3*recip3_x; m_y = m2_y + k3*recip3_y; m_z = m2_z + k3*recip3_z; msq = m_x*m_x + m_y*m_y + m_z*m_z; // xp3 = exp3[k3]; xp3 = i_pi_volume*exp(-piob*msq); qr = q_arr[ind]; qc=q_arr[ind+1]; q2 = 2*(qr*qr + qc*qc)*theta3; if ( (k3 == 0) || ( k3 == K3/2 && ! (K3 & 1) ) ) q2 *= 0.5; imsq = 1.0/msq; C = xp3*imsq; theta = theta3*C; q_arr[ind] *= theta; q_arr[ind+1] *= theta; vir = -2*(piob+imsq); fac = q2*C; energy += fac; virial[0] += fac*(1.0+vir*m_x*m_x); virial[1] += fac*vir*m_x*m_y; virial[2] += fac*vir*m_x*m_z; virial[3] += fac*(1.0+vir*m_y*m_y); virial[4] += fac*vir*m_y*m_z; virial[5] += fac*(1.0+vir*m_z*m_z); ind += 2; } ind += pad3; } ind += pad2; } } for (n=0; n<6; ++n) virial[n] *= 0.5; return 0.5*energy; } void PmeKSpace::init_exp(double *xp, int K, double recip) { int i; double fac; fac = -piob*recip*recip; for (i=0; i<= K/2; i++) xp[i] = exp(fac*i*i); }