text
stringlengths
8
6.88M
#include <iostream> using namespace std; int main(){ int t; int n1, n2, n3; cin >> t; for(int i = 1; i <= t; i++){ cout << "Case " << i << ": "; cin >> n1 >> n2 >> n3; if(n1 > 20 || n2 > 20 || n3 > 20){ cout << "bad" << endl; }else{ cout << "good" << endl; } } return 0; }
#include<conio.h> #include<iostream.h> void main (){ int num[]={1,20,3,2,1}; int search; int b=1; clrscr(); for(int i=0; i<=4;i++){ cout<<"Num["<<i<<"]="<<num[i]<<endl; }//end loop cout<<"Enter Element For Search Loction:"; cin>>search; for( i=0; i<=4;i++){ if(num[i]==search){ cout<<endl<<"Your Element :"<<search<<":Found Array Location:"<<i<<endl; b=0; } }//end outer if(b) cout<<endl<<"Your Element :"<<search<<" Not :Found In Array"; getch(); }
// Connection Manager Functions // // Copyright (C) 2008 // Center for Perceptual Systems // University of Texas at Austin // // jsp Thu Jul 10 10:24:37 CDT 2008 #ifndef CONNECTION_MANAGER_H #define CONNECTION_MANAGER_H #include "connection.h" #include <QIcon> //#include <QMap> #include <QHash> #include <QObject> #include <QTcpSocket> #include <cassert> namespace flying_dragon { /// @brief Manage a list of connections class ConnectionManager : public QObject { Q_OBJECT signals: /// @brief A connection has been added /// @param connection The added connection void Added (const Connection *connection); /// @brief A connection has been removed /// @param id The removed connection's id void Removed (unsigned id); public: /// @brief Constructor ConnectionManager () : current_connection_id_ (0) { } /// @brief Get a new connection ID /// @return The ID /// /// A new ID is generated each time you call this /// function. unsigned GetNewID () { return current_connection_id_++; } /// @brief Create a new connection to a server /// @param server Name of the server /// @param port The socket port number void ConnectToServer (const QString &server, int port) { ClientConnection *connection = new ClientConnection (this, GetNewID (), server); connection->ConnectToServer (server, port); Add (connection); } /// @brief Accept a connection from a client /// @param socket_descriptor Descriptor of new socket void AcceptConnection (int socket_descriptor) { ServerConnection *connection = new ServerConnection (this, GetNewID (), socket_descriptor); Add (connection); } /// @brief Add a connection /// @param connection The connection to add void Add (Connection *connection) { assert (connection); connections_[connection->GetID ()] = connection; emit Added (connection); } /// @brief Remove a connection /// @param connection The connection to add /// @param id The id of the connection to remove void Remove (unsigned id) { qDebug() << "removing " << id; Connection *connection = connections_[id]; assert (connection); disconnect (connection, 0, 0, 0); connection->deleteLater (); connections_.remove (id); emit Removed (id); } /// @brief Get the total number of connections int Total () const { return connections_.size (); } /// @brief Find a connection given an id /// @param id Connection id Connection *Find (unsigned id) { Connection *connection = connections_[id]; assert (connection); return connection; } public slots: /// @brief A new icon is ready to send void NewIcon (const QImage &icon) { Connection *c; foreach (c, connections_) if (c->GetState () == Connection::StateConnected) c->SendIcon (icon); } /// @brief A new frame is ready to send void NewFrame (const QImage &frame) { Connection *c; foreach (c, connections_) if (c->GetState () == Connection::StateConnected && c->GetStreaming ()) c->SendFrame (frame); } private: QHash<unsigned, Connection *> connections_; unsigned current_connection_id_; }; } // namespace flying_dragon #endif // CONNECTION_MANAGER_H
// Copyright (c) 2021 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 _NCollection_AliasedArray_HeaderFile #define _NCollection_AliasedArray_HeaderFile #include <Standard_DimensionMismatch.hxx> #include <Standard_OutOfMemory.hxx> #include <Standard_OutOfRange.hxx> #include <Standard_TypeMismatch.hxx> #include <Standard_Macro.hxx> //! Defines an array of values of configurable size. //! For instance, this class allows defining an array of 32-bit or 64-bit integer values with bitness determined in runtime. //! The element size in bytes (stride) should be specified at construction time. //! Indexation starts from 0 index. //! As actual type of element varies at runtime, element accessors are defined as templates. //! Memory for array is allocated with the given alignment (template parameter). template<int MyAlignSize = 16> class NCollection_AliasedArray { public: DEFINE_STANDARD_ALLOC public: //! Empty constructor. NCollection_AliasedArray (Standard_Integer theStride) : myData (NULL), myStride (theStride), mySize (0), myDeletable (false) { if (theStride <= 0) { throw Standard_RangeError ("NCollection_AliasedArray, stride should be positive"); } } //! Constructor NCollection_AliasedArray (Standard_Integer theStride, Standard_Integer theLength) : myData (NULL), myStride (theStride), mySize (theLength), myDeletable (true) { if (theLength <= 0 || myStride <= 0) { throw Standard_RangeError ("NCollection_AliasedArray, stride and length should be positive"); } myData = (Standard_Byte* )Standard::AllocateAligned (SizeBytes(), MyAlignSize); if (myData == NULL) { throw Standard_OutOfMemory ("NCollection_AliasedArray, allocation failed"); } } //! Copy constructor NCollection_AliasedArray (const NCollection_AliasedArray& theOther) : myData (NULL), myStride (theOther.myStride), mySize (theOther.mySize), myDeletable (false) { if (mySize != 0) { myDeletable = true; myData = (Standard_Byte* )Standard::AllocateAligned (SizeBytes(), MyAlignSize); if (myData == NULL) { throw Standard_OutOfMemory ("NCollection_AliasedArray, allocation failed"); } Assign (theOther); } } //! Move constructor NCollection_AliasedArray (NCollection_AliasedArray&& theOther) Standard_Noexcept : myData (theOther.myData), myStride (theOther.myStride), mySize (theOther.mySize), myDeletable (theOther.myDeletable) { theOther.myDeletable = false; } //! Constructor wrapping pre-allocated C-array of values without copying them. template<typename Type_t> NCollection_AliasedArray (const Type_t& theBegin, Standard_Integer theLength) : myData ((Standard_Byte* )&theBegin), myStride ((int )sizeof(Type_t)), mySize (theLength), myDeletable (false) { if (theLength <= 0) { throw Standard_RangeError ("NCollection_AliasedArray, length should be positive"); } } //! Returns an element size in bytes. Standard_Integer Stride() const { return myStride; } //! Size query Standard_Integer Size() const { return mySize; } //! Length query (the same as Size()) Standard_Integer Length() const { return mySize; } //! Return TRUE if array has zero length. Standard_Boolean IsEmpty() const { return mySize == 0; } //! Lower bound Standard_Integer Lower() const { return 0; } //! Upper bound Standard_Integer Upper() const { return mySize - 1; } //! myDeletable flag Standard_Boolean IsDeletable() const { return myDeletable; } //! IsAllocated flag - for naming compatibility Standard_Boolean IsAllocated() const { return myDeletable; } //! Return buffer size in bytes. Standard_Size SizeBytes() const { return size_t(myStride) * size_t(mySize); } //! Copies data of theOther array to this. //! This array should be pre-allocated and have the same length as theOther; //! otherwise exception Standard_DimensionMismatch is thrown. NCollection_AliasedArray& Assign (const NCollection_AliasedArray& theOther) { if (&theOther != this) { if (myStride != theOther.myStride || mySize != theOther.mySize) { throw Standard_DimensionMismatch ("NCollection_AliasedArray::Assign(), arrays have different size"); } if (myData != NULL) { memcpy (myData, theOther.myData, SizeBytes()); } } return *this; } //! Move assignment. //! This array will borrow all the data from theOther. //! The moved object will keep pointer to the memory buffer and //! range, but it will not free the buffer on destruction. NCollection_AliasedArray& Move (NCollection_AliasedArray& theOther) { if (&theOther != this) { if (myDeletable) { Standard::FreeAligned (myData); } myStride = theOther.myStride; mySize = theOther.mySize; myDeletable = theOther.myDeletable; myData = theOther.myData; theOther.myDeletable = false; } return *this; } //! Assignment operator; @sa Assign() NCollection_AliasedArray& operator= (const NCollection_AliasedArray& theOther) { return Assign (theOther); } //! Move assignment operator; @sa Move() NCollection_AliasedArray& operator= (NCollection_AliasedArray&& theOther) { return Move (theOther); } //! Resizes the array to specified bounds. //! No re-allocation will be done if length of array does not change, //! but existing values will not be discarded if theToCopyData set to FALSE. //! @param theLength new length of array //! @param theToCopyData flag to copy existing data into new array void Resize (Standard_Integer theLength, Standard_Boolean theToCopyData) { if (theLength <= 0) { throw Standard_RangeError ("NCollection_AliasedArray::Resize, length should be positive"); } if (mySize == theLength) { return; } const Standard_Integer anOldLen = mySize; const Standard_Byte* anOldData = myData; mySize = theLength; if (!theToCopyData && myDeletable) { Standard::FreeAligned (myData); } myData = (Standard_Byte* )Standard::AllocateAligned (SizeBytes(), MyAlignSize); if (myData == NULL) { throw Standard_OutOfMemory ("NCollection_AliasedArray, allocation failed"); } if (!theToCopyData) { myDeletable = true; return; } const size_t aLenCopy = size_t(Min (anOldLen, theLength)) * size_t(myStride); memcpy (myData, anOldData, aLenCopy); if (myDeletable) { Standard::FreeAligned (anOldData); } myDeletable = true; } //! Destructor - releases the memory ~NCollection_AliasedArray() { if (myDeletable) { Standard::FreeAligned (myData); } } public: //! Access raw bytes of specified element. const Standard_Byte* value (Standard_Integer theIndex) const { Standard_OutOfRange_Raise_if (theIndex < 0 || theIndex >= mySize, "NCollection_AliasedArray::value(), out of range index"); return myData + size_t(myStride) * size_t(theIndex); } //! Access raw bytes of specified element. Standard_Byte* changeValue (Standard_Integer theIndex) { Standard_OutOfRange_Raise_if (theIndex < 0 || theIndex >= mySize, "NCollection_AliasedArray::changeValue(), out of range index"); return myData + size_t(myStride) * size_t(theIndex); } //! Initialize the items with theValue template<typename Type_t> void Init (const Type_t& theValue) { for (Standard_Integer anIter = 0; anIter < mySize; ++anIter) { ChangeValue<Type_t> (anIter) = theValue; } } //! Access element with specified position and type. //! This method requires size of a type matching stride value. template<typename Type_t> const Type_t& Value (Standard_Integer theIndex) const { Standard_TypeMismatch_Raise_if(size_t(myStride) != sizeof(Type_t), "NCollection_AliasedArray::Value(), wrong type"); return *reinterpret_cast<const Type_t*>(value (theIndex)); } //! Access element with specified position and type. //! This method requires size of a type matching stride value. template<typename Type_t> void Value (Standard_Integer theIndex, Type_t& theValue) const { Standard_TypeMismatch_Raise_if(size_t(myStride) != sizeof(Type_t), "NCollection_AliasedArray::Value(), wrong type"); theValue = *reinterpret_cast<const Type_t*>(value (theIndex)); } //! Access element with specified position and type. //! This method requires size of a type matching stride value. template<typename Type_t> Type_t& ChangeValue (Standard_Integer theIndex) { Standard_TypeMismatch_Raise_if(size_t(myStride) != sizeof(Type_t), "NCollection_AliasedArray::ChangeValue(), wrong type"); return *reinterpret_cast<Type_t* >(changeValue (theIndex)); } //! Access element with specified position and type. //! This method allows wrapping element into smaller type (e.g. to alias 2-components within 3-component vector). template<typename Type_t> const Type_t& Value2 (Standard_Integer theIndex) const { Standard_TypeMismatch_Raise_if(size_t(myStride) < sizeof(Type_t), "NCollection_AliasedArray::Value2(), wrong type"); return *reinterpret_cast<const Type_t*>(value (theIndex)); } //! Access element with specified position and type. //! This method allows wrapping element into smaller type (e.g. to alias 2-components within 3-component vector). template<typename Type_t> void Value2 (Standard_Integer theIndex, Type_t& theValue) const { Standard_TypeMismatch_Raise_if(size_t(myStride) < sizeof(Type_t), "NCollection_AliasedArray::Value2(), wrong type"); theValue = *reinterpret_cast<const Type_t*>(value (theIndex)); } //! Access element with specified position and type. //! This method allows wrapping element into smaller type (e.g. to alias 2-components within 3-component vector). template<typename Type_t> Type_t& ChangeValue2 (Standard_Integer theIndex) { Standard_TypeMismatch_Raise_if(size_t(myStride) < sizeof(Type_t), "NCollection_AliasedArray::ChangeValue2(), wrong type"); return *reinterpret_cast<Type_t* >(changeValue (theIndex)); } //! Return first element template<typename Type_t> const Type_t& First() const { return Value<Type_t> (0); } //! Return first element template<typename Type_t> Type_t& ChangeFirst() { return ChangeValue<Type_t> (0); } //! Return last element template<typename Type_t> const Type_t& Last() const { return Value<Type_t> (mySize - 1); } //! Return last element template<typename Type_t> Type_t& ChangeLast() { return Value<Type_t> (mySize - 1); } protected: Standard_Byte* myData; //!< data pointer Standard_Integer myStride; //!< element size Standard_Integer mySize; //!< number of elements Standard_Boolean myDeletable; //!< flag showing who allocated the array }; #endif // _NCollection_AliasedArray_HeaderFile
// // Task.h // Lab1Progr // // Created by Дмитрий Богомолов on 12.09.14. // Copyright (c) 2014 Дмитрий Богомолов. All rights reserved. // #ifndef Lab1Progr_Task_h #define Lab1Progr_Task_h #include <iostream> #include <time.h> #include <xlocale.h> #include <ctime> #include <stdio.h> #include <ctype.h> using namespace std; class Task { char *value; int length; char *time_buf = new char[50]; static char* sampleStatic; public: Task(char*); Task() { value[0] = 0;} ~Task(); void Print(); char* GetValue(); void changeString(); void changeString(char*); int acrossIntoString(char *,char*); char* ToUpper(char*); char* ToUpper(); char* ToLower(); char* ToLower(char*); /* Lab 2*/ long operator+(Task b); friend long operator-(Task a,Task b); friend long operator++(Task a); friend long operator++(Task a,int); operator char* () { return value; } // возможна модификация объекта через результат приведения operator const char* () const { return value; } operator string() { return string(value); } long operator=(Task a); }; #endif
//: C10:Initializer.h // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt // Technika inicjalizacji obiektow statycznych #ifndef INITIALIZER_H #define INITIALIZER_H #include <iostream> extern int x; // Deklaracje, a nie definicje extern int y; class Initializer { static int initCount; public: Initializer() { std::cout << "Initializer()" << std::endl; // Inicjalizacja tylko za pierwszym razem if(initCount++ == 0) { std::cout << "inicjalizacja" << std::endl; x = 100; y = 200; } } ~Initializer() { std::cout << "~Initializer()" << std::endl; // Sprzatanie tylko za ostatnim razem if(--initCount == 0) { std::cout << "sprzatanie" << std::endl; // Wszelkie niezbedne czynnosci zwiazane ze sprzataniem } } }; // Ponizsza definicja tworzy obiekt, // w kazdym pliku, do ktorego jest dolaczony // plik Initializer.h, ale obiekt ten jest widoczny // tylko w obrebie biezacego pliku: static Initializer init; #endif // INITIALIZER_H ///:~
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-1999 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef _JS11_SCREEN_ #define _JS11_SCREEN_ #include "modules/ecmascript/ecmascript.h" #include "modules/dom/src/domobj.h" class JS_Screen : public DOM_Object { public: virtual ES_GetState GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime); virtual ES_PutState PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime); }; #endif /* _JS11_WINDOW_ */
#ifndef MODELS_H #define MODELS_H #include "data.hpp" #include "interp.hpp" #include "integrate.hpp" #include <vector> #include <cmath> #include <sstream> #include <string> #include <iostream> #include <fstream> using namespace std; class SingletDM_RD { private: Data data; public: SingletDM_RD (){} // defualt constructor SingletDM_RD(Data _data) { data=_data; } //constructor double gamma_h(double x); double Dh2(double s); double sigma_v_VV(double s); double sigma_v_ff(double s); double sigma_v_hh(double s); double cs_integral(double s, double T); double sigma_v(double s); double quick_cs(double T){return 1e-8;}//(1e-12)*(1e-28)*(3e10)*(10*10);}; Data set_dm_mass(Data data){data.M_dm=data.M_s;return data;}; }; class SingletDMZ3_RD { private: Data data; public: SingletDMZ3_RD (){} // defualt constructor SingletDMZ3_RD(Data _data) { data=_data; } //constructor double gamma_h(double x); double Dh2(double s); double sigma_v_VV(double s); double sigma_v_ff(double s); double sigma_v_hh(double s); double cs_integral(double s, double T); double sigma_v(double s); double quick_cs(double T){return (1e-12)*(1e-28)*(3e8);}; Data set_dm_mass(Data data){data.M_dm=data.M_s;return data;}; }; class MDM_RD { private: Data data; public: MDM_RD (){} // defualt constructor MDM_RD(Data _data) { data=_data; } //constructor double quick_cs(double T); double cs_integral(double s, double T); Data set_dm_mass(Data data){data.M_dm=data.M_chi;return data;}; }; template <class M> struct cs_func { cs_func(double T, Data data) : T(T) , data(data) {} double operator()(double x) const { M cs(data);double val; try{ val = cs.cs_integral(x,T); return val; } catch (const char* msg) { cout << "catch 3" << endl; throw "invalid_pt"; return 0; } }//cs_integral(x,T);} private: double T; Data data; }; #endif
#ifndef COMMON_SRC_PATHAPPENDER_H #define COMMON_SRC_PATHAPPENDER_H #include <QString> namespace common { namespace util { /*! * \brief The PathAppender class is a helper utility to concatenate path strings. */ class PathAppender { public: /*! * \brief Combines two path string to generate a valid path string. * \param path1 The first path that gets appended. * \param path2 The second path that is appended to first one. * \return A \c QString containing the two paths combined. */ static QString combine(const QString& path1, const QString& path2); /*! * \brief PathAppender constructor. * \param path The initial path string the object will hold. */ explicit PathAppender(const QString& path); /*! * \overload * \param path1 The first path that gets appended. * \param path2 The second path that is appended to first one. */ PathAppender(const QString& path1, const QString path2); /*! * \brief Convenient operator to append multiple path strings. * \param path The path string to append. * \return The instance of \c PathAppender where the pats are being appende to. */ PathAppender& operator<<(const QString& path); /*! * \brief Returns the full path string the object is holding. * \return The \c QString path. */ QString toString() const { return path_; } /*! * \brief Implicit conversion to \c QString. */ operator QString() const { return path_; } private: QString path_; //!< Path string. }; } } #endif // COMMON_SRC_PATHAPPENDER_H
#include <iostream> #include "common.hh" #include "server_metrics.hh" #include "server_utils.hh" #include "DIET_server.h" #include "scheduler/est_internal.hh" #include <fstream> #include <cmath> #include <stdio.h> #include <iostream> #include <fstream> #include <istream> #include <cstdlib> #include <string> #include "server.hh" using namespace std; const char *configuration_file = "/root/dietg/cfgs/server.cfg"; const char *current_job_file = "/root/dietg/log/current.jobs"; const char *total_job_file = "/root/dietg/log/total.jobs"; MetricsAggregator metrics; void start_job(){ puts( "start_job" ); my_lock(); ofstream current; current.open (current_job_file, ios::app); current << "busy\n"; current.close(); ofstream total; total.open (total_job_file,ofstream::app); //total.seekg (0, ios::end); total << "another task\n"; total.close(); my_unlock(); } void end_job(){ my_lock(); puts( "end_job" ); int number_of_lines = 0; string line; ifstream myfile(current_job_file); while (getline(myfile, line)) { number_of_lines += 1; } myfile.close(); // erase the file if( remove(current_job_file) != 0 ) perror( "Error deleting jobs" ); else puts( "File successfully deleted" ); // reduce it ofstream current; current.open (current_job_file, ios::app); int i = 0; while (i < number_of_lines-1){ current << "busy\n"; i += 1; } std::cout << "end_job : I just wrote / number of lines = " << number_of_lines-1 << " for file " << current_job_file << std::endl; current.close(); my_unlock(); } int handler_myserv(diet_profile_t *p) { start_job(); uint64_t start_t = utime(); double *duration; int *num_processes; double *result; diet_scalar_get(diet_parameter(p, 0), &duration, NULL); diet_scalar_get(diet_parameter(p, 1), &num_processes, NULL); diet_scalar_get(diet_parameter(p, 2), &result, NULL); std::cout << "in: " << *duration << ", " << *num_processes << std::endl; stress(*duration, *num_processes); *result = 0.0; metrics.record(start_t, utime()); end_job(); return 1; } void myperfmetric(diet_profile_t *profile, estVector_t estvec) { diet_est_set_internal(estvec, EST_CPUIDLE, metrics.get_avg_cpu_idle()); diet_est_set_internal(estvec, EST_CONSO, metrics.get_avg_pdu()); diet_est_set_internal(estvec, EST_NODEFLOPS, metrics.get_node_flops()); diet_est_set_internal(estvec, EST_COREFLOPS, metrics.get_core_flops()); diet_est_set_internal(estvec, EST_NUMCORES, double(metrics.get_num_cores())); diet_est_set_internal(estvec, EST_CURRENTJOBS, double(metrics.get_current_jobs())); diet_est_set_internal(estvec, EST_CONSOJOB, double(metrics.get_bench_conso())); } int solve_matmut(diet_profile_t *pb){ start_job(); std::cout << "Solve Matmut: " << std::endl; float MIN_RAND = 1.0; float MAX_RAND = 999.0; float *C = NULL; long i,j; // loop index unsigned long k; int a = 0; size_t mA, nA, mB, nB; // size of matrix // Lecture taille matrice double * size_mat; diet_scalar_get(diet_parameter(pb, 0), &size_mat, NULL); //std::cout << "size of matrices: " << *size_mat std::endl; // Allocation matrice long row=16384*(*size_mat); long col=16384*(*size_mat); //long taille_matrice = row*col/1048576; /* C = (float*)malloc(row * col * sizeof(float)); if (C == NULL){ std::cout << "Allocation of memory failed for matrix " << std::endl; exit(0); } std::cout << "Allocation of the matrix is done! " << std::endl; // Intitialisation for (i = 0; i < (col * row); i++) { //std::cout << "%.0f (%.0f) / %.0f (%.0f) \n",i,log10(fabs(i)),col*row,log10(fabs(col*row))); C[i] = random() * ((MAX_RAND - MIN_RAND) / RAND_MAX) + MIN_RAND; //std::cout << "INIT : Current " << i << " Total "<< (int)(col*row) << " || Value = " << C[i] << std::endl; } std::cout << "Initialisation of the matrix is done! " << std::endl; // Calcul for (i=0; i< (col * row); i++){ C[i] = C[i] * C[(col*row)-1-i]; //std::cout << "Compute : Current " << i << " Opposite "<< (int)(col*row)-1-i << " || Value = " << C[i] << std::endl; } std::cout << "Computation of the matrix is done! " << std::endl; */ for (k=0; k < (unsigned long)*size_mat ; k++){ //at least 9 a = ( a + k ) % 1000; } std::cout << "Iterative Additions until " << k << std::endl; /*// Résultat attendu bool check = true; for (i=0; i<col*row; i++){ if (C[i] != A[i] * B[i]){ check = false; } } if (check == true) std::cout << "Multiplication succeed on " << col*row << " items" << std::endl; else std::cout << "Multiplication failed " << std::endl; free(C); */ /* Send the hostname as a result */ int size_hostname = 64; char * hostname = (char *) malloc(64 * sizeof(char)); //hostname[63] = '\0'; gethostname(hostname, 63); //size_hostname = hostname.length(); std::cout << "Host = " << hostname << std::endl; diet_string_set(diet_parameter(pb, 1),hostname, DIET_VOLATILE); end_job(); return 0; } int main(int argc, char **argv) { metrics.init(argc > 1 ? argv[1] : ""); if( remove(total_job_file) != 0 ) perror( "Error deleting total job file" ); else puts( "Total job file successfully deleted" ); if( remove(current_job_file) != 0 ) perror( "Error deleting current job file" ); else puts( "Current job file successfully deleted" ); diet_profile_desc_t *profile; diet_profile_desc_t *profile_matmut; diet_aggregator_desc_t *agg; diet_aggregator_desc_t *agg2; diet_service_table_init(1); profile = diet_profile_desc_alloc("myserv", 1, 1, 2); diet_generic_desc_set(diet_param_desc(profile, 0), DIET_SCALAR, DIET_DOUBLE); diet_generic_desc_set(diet_param_desc(profile, 1), DIET_SCALAR, DIET_INT); diet_generic_desc_set(diet_param_desc(profile, 2), DIET_SCALAR, DIET_DOUBLE); agg = diet_profile_desc_aggregator(profile); diet_aggregator_set_type(agg, DIET_AGG_USER); diet_service_use_perfmetric(myperfmetric); /* for this service, use a developper defined scheduler */ //diet_aggregator_set_type(agg, DIET_AGG_PRIORITY); // diet_aggregator_priority_min(agg, EST_CONSO); // diet_aggregator_priority_max(agg, EST_TIMESINCELASTSOLVE); diet_service_table_add(profile, NULL, handler_myserv); diet_profile_desc_free(profile); /* Matrix multiplication */ profile_matmut = diet_profile_desc_alloc("matmut", 0, 0, 1); diet_generic_desc_set(diet_param_desc(profile_matmut, 0), DIET_SCALAR, DIET_DOUBLE); diet_generic_desc_set(diet_param_desc(profile_matmut, 1), DIET_STRING, DIET_CHAR); agg2 = diet_profile_desc_aggregator(profile_matmut); diet_aggregator_set_type(agg2, DIET_AGG_USER); diet_service_use_perfmetric(myperfmetric); diet_service_table_add(profile_matmut, NULL, solve_matmut); diet_print_service_table(); diet_SeD(configuration_file, argc, argv); return 0; }
#include "SDL.h" #include "SDL_image.h" #include "SDL_ttf.h" #include "Window.h" SDL_Window * WINDOW_WINDOW = nullptr; SDL_Renderer * WINDOW_RENDERER = nullptr; SDL_Texture * Render::createTextureFromSurface(SDL_Surface * surface) { SDL_Texture * t = SDL_CreateTextureFromSurface(WINDOW_RENDERER, surface); SDL_SetTextureBlendMode(t, SDL_BLENDMODE_BLEND); return t; } void Render::blit(SDL_Texture * tex, SDL_Rect dest) { SDL_RenderCopy(WINDOW_RENDERER, tex, nullptr, &dest); } void Render::blitEx(SDL_Texture * tex, SDL_Rect dest, double angle, SDL_Point spincenter) { SDL_RenderCopyEx(WINDOW_RENDERER, tex, nullptr, &dest, angle, &spincenter, SDL_FLIP_NONE); } void Window::init() { SDL_Init(SDL_INIT_EVERYTHING); IMG_Init(IMG_INIT_PNG | IMG_INIT_JPG); TTF_Init(); WINDOW_WINDOW = SDL_CreateWindow(WINDOWNAME, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, NULL); WINDOW_RENDERER = SDL_CreateRenderer(WINDOW_WINDOW, -1, SDL_RENDERER_ACCELERATED); //SDL_SetRenderDrawBlendMode(WINDOW_RENDERER, SDL_BLENDMODE_BLEND); } void Window::destroy() { SDL_DestroyWindow(WINDOW_WINDOW); SDL_DestroyRenderer(WINDOW_RENDERER); } void Window::update() { SDL_RenderPresent(WINDOW_RENDERER); SDL_SetRenderDrawColor(WINDOW_RENDERER, 255, 255, 255, 255);; SDL_RenderClear(WINDOW_RENDERER); }
#include <iostream> #include <sstream> #include <cstdlib> #include <cstdio> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <ctime> #include <cmath> #include <string> #include <cctype> #include <cstring> #include <algorithm> #include<climits> using namespace std; #define maxn 10005 typedef struct edge { int to; int length; }edge; int N,K; vector<edge> G[maxn]; bool centroid[maxn]; int subtree_size[maxn]; int ans; int compute_subtree_size(int v,int p){ int c=1; int sz=G[v].size(); for(int i=0;i<sz;i++){ int w=G[v][i].to; if(w==p||centroid[w]) continue; c+=compute_subtree_size(G[v][i].to,v); } subtree_size[v]=c; return c; } pair<int,int> search_centroid(int v,int p,int t){ pair<int,int> res=make_pair(INT_MAX,-1); int s=1,m=0; int sz=G[v].size(); for(int i=0;i<sz;i++){ int w=G[v][i].to; if(w==p||centroid[w]) continue; res=min(res,search_centroid(w,v,t)); m=max(m,subtree_size[w]); s+=subtree_size[w]; } m=max(m,t-s); res=min(res,make_pair(m,v)); return res; } void enumerate_paths(int v,int p,int d,vector<int> &ds){ ds.push_back(d); int sz=G[v].size(); for(int i=0;i<sz;i++){ int w=G[v][i].to; if(w==p||centroid[w]) continue; enumerate_paths(w,v,d+G[v][i].length,ds); } } int count_pairs(vector<int> &ds){ int res=0; sort(ds.begin(),ds.end()); int j=ds.size(); for(int i=0;i<ds.size();i++){ while(j>0&&ds[i]+ds[j-1]>K) --j; res+=j-(j>i?1:0); } return res/2; } void solve_subproblem(int v){ compute_subtree_size(v,-1); int s=search_centroid(v,-1,subtree_size[v]).second; centroid[s]=true; for(int i=0;i<G[s].size();i++){ if(centroid[G[s][i].to]) continue; solve_subproblem(G[s][i].to); } vector<int> ds; ds.push_back(0); for(int i=0;i<G[s].size();i++){ if(centroid[G[s][i].to]) continue; vector<int> tds; enumerate_paths(G[s][i].to,s,G[s][i].length,tds); ans-=count_pairs(tds); ds.insert(ds.end(),tds.begin(),tds.end()); } ans+=count_pairs(ds); centroid[s]=false; } void solve(){ ans=0; solve_subproblem(0); printf("%d\n",ans); } int main(){ while(scanf("%d%d",&N,&K)&&(N!=0||K!=0)){ int a,b,c; for(int i=0;i<N;i++) G[i].clear(); for(int i=0;i<N-1;i++){ scanf("%d%d%d",&a,&b,&c); a--; b--; edge e; e.to=b; e.length=c; G[a].push_back(e); e.to=a; e.length=c; G[b].push_back(e); } solve(); } }
int aPin = 5; //DT Pin int bPin = 6; //CLK Pin int buttonPin = 7; //SW Pin int temp; int temprotation = 100; int rotation; void setup() { pinMode(aPin, INPUT); pinMode(bPin, INPUT); pinMode(buttonPin, INPUT); Serial.begin(9600); } void loop(){ int change = getEncoderTurn(); if(change!=temp){ rotation = rotation+change; if(rotation != temprotation){ Serial.println(rotation); } temprotation = rotation; } temp = change; delay(1); } int getEncoderTurn(){ //return -1, 0, or +1 static int oldA = LOW; static int oldB = LOW; int result = 0; int newA = digitalRead(aPin); int newB = digitalRead(bPin); if(newA != oldA || newB != oldB){ if(oldA == LOW && newA == HIGH){ result = -(oldB*2 -1); } } oldA = newA; oldB = newB; return result; }
#include "AudioMarkupNavigatorDialog.h" #include "ui_AudioMarkupNavigatorDialog.h" #include <QShowEvent> AudioMarkupNavigatorDialog::AudioMarkupNavigatorDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AudioMarkupNavigatorDialog) { ui->setupUi(this); } AudioMarkupNavigatorDialog::~AudioMarkupNavigatorDialog() { delete ui; } void AudioMarkupNavigatorDialog::showEvent(QShowEvent*) { ui->lineEditMarkerId->setFocus(); } int AudioMarkupNavigatorDialog::markerId() const { bool parseIntOp; int markerId = ui->lineEditMarkerId->text().toInt(&parseIntOp); return parseIntOp ? markerId : -1; }
#include <SPI.h> #define NTAB 32 volatile uint16_t sine_table[NTAB]; #define DAC_CS 2 SPISettings dac_spi_settings(100000, MSBFIRST, SPI_MODE0); auto& ser= Serial; void init_timer2(unsigned int f) { static const unsigned int scales[] = {1, 8, 32, 64, 128, 256, 1024}; cli();//stop interrupts TCCR2A = 0; TCNT2 = 0; TCCR2A |= (1 << WGM21); // turn on CTC mode TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt // calculate prescaler and Match Register Comparison unsigned int p; for (p = 0; p < 8; p++) if (scales[p] >= 62500 / f) break; OCR2A = (62500 / scales[p]) * 256 / f; // Set Compare Match Register TCCR2B = ++p; // the prescaler sei();//allow interrupts } void dac_write(uint16_t value) { if(value>4095) value = 4095; //value &= 0b0000111111111111; value |= 0b0011000000000000; SPI.beginTransaction(dac_spi_settings); digitalWrite(DAC_CS, LOW); SPI.transfer16(value); digitalWrite(DAC_CS, HIGH); SPI.endTransaction(); } volatile int idx=0; /* ISR(TIMER2_COMPA_vect) { dac_write(sine_table[idx++]); if(idx>=NTAB) idx = 0; //dac_write(4096); } */ void setup() { // put your setup code here, to run once: ser.begin(115200); for(int i=0; i<NTAB; ++i) { float f = 2.0 * PI * i / NTAB; float s = (1.0+sin(f))*4096/2; int si = (int)s; //if(si == 4096) s=4095; //si = si >> 1; sine_table[i] = si; char str[30]; //sprintf(str, "%d %d", i, s); //ser.println(str); ser.print(i); ser.print(" "); ser.println(si); } pinMode(DAC_CS, OUTPUT); digitalWrite(DAC_CS, HIGH); //init_timer2(44 * TAB); dac_write(4095); } void loop() { // put your main code here, to run repeatedly: }
// // Created by Brady Bodily on 4/19/17. // #ifndef ITAK_CONFIG_HPP #define ITAK_CONFIG_HPP #include "UserIPList.hpp" #include "KeyValue.hpp" #include <string> #include <vector> #include <iostream> using namespace std; class Config { public: string GetType(); int GetValue(); Config(string type, int value); private: string Type; int Value; }; #endif //ITAK_CONFIG_HPP
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef OP_UNDOABLE_OPERATION_H #define OP_UNDOABLE_OPERATION_H #include "modules/util/simset.h" /** * Represents one of the undoable, atomic operations comprising an * OpTransaction. * * Please make sure only generic OpUndoableOperation implementations reside * in @c desktop_util/transactions. Anything specific to the task at hand is * best kept close the task itself. * * @author Wojciech Dzierzanowski (wdzierzanowski) * @see OpTransaction::Continue */ class OpUndoableOperation : public ListElement<OpUndoableOperation> { public: /** * Executes the operation. * * @return status used by OpTransaction to determine subsequent course of * action */ virtual OP_STATUS Do() = 0; /** * Reverses the effects of Do(). No return value, because when we're here, * we're already rolling back, so there's nothing more we can do to respond * to errors. */ virtual void Undo() = 0; }; #endif // OP_UNDOABLE_OPERATION_H
// Created on: 1995-03-02 // Created by: Jean-Louis Frenkel // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Aspect_RectangularGrid_HeaderFile #define _Aspect_RectangularGrid_HeaderFile #include <Standard.hxx> #include <Aspect_Grid.hxx> class Aspect_RectangularGrid : public Aspect_Grid { DEFINE_STANDARD_RTTIEXT(Aspect_RectangularGrid, Aspect_Grid) public: //! creates a new grid. By default this grid is not //! active. //! The first angle is given relatively to the horizontal. //! The second angle is given relatively to the vertical. Standard_EXPORT Aspect_RectangularGrid(const Standard_Real aXStep, const Standard_Real aYStep, const Standard_Real anXOrigin = 0, const Standard_Real anYOrigin = 0, const Standard_Real aFirstAngle = 0, const Standard_Real aSecondAngle = 0, const Standard_Real aRotationAngle = 0); //! defines the x step of the grid. Standard_EXPORT void SetXStep (const Standard_Real aStep); //! defines the y step of the grid. Standard_EXPORT void SetYStep (const Standard_Real aStep); //! defines the angle of the second network //! the fist angle is given relatively to the horizontal. //! the second angle is given relatively to the vertical. Standard_EXPORT void SetAngle (const Standard_Real anAngle1, const Standard_Real anAngle2); Standard_EXPORT void SetGridValues (const Standard_Real XOrigin, const Standard_Real YOrigin, const Standard_Real XStep, const Standard_Real YStep, const Standard_Real RotationAngle); //! returns the point of the grid the closest to the point X,Y Standard_EXPORT virtual void Compute (const Standard_Real X, const Standard_Real Y, Standard_Real& gridX, Standard_Real& gridY) const Standard_OVERRIDE; //! returns the x step of the grid. Standard_EXPORT Standard_Real XStep() const; //! returns the x step of the grid. Standard_EXPORT Standard_Real YStep() const; //! returns the x Angle of the grid, relatively to the horizontal. Standard_EXPORT Standard_Real FirstAngle() const; //! returns the y Angle of the grid, relatively to the vertical. Standard_EXPORT Standard_Real SecondAngle() const; Standard_EXPORT virtual void Init() Standard_OVERRIDE; //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE; private: Standard_EXPORT Standard_Boolean CheckAngle (const Standard_Real alpha, const Standard_Real beta) const; private: Standard_Real myXStep; Standard_Real myYStep; Standard_Real myFirstAngle; Standard_Real mySecondAngle; Standard_Real a1; Standard_Real b1; Standard_Real c1; Standard_Real a2; Standard_Real b2; Standard_Real c2; }; DEFINE_STANDARD_HANDLE(Aspect_RectangularGrid, Aspect_Grid) #endif // _Aspect_RectangularGrid_HeaderFile
#include <time.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/file.h> #include <netinet/in.h> #include "netdb.h" #include "stdio.h" #include "stdlib.h" #include "sys/socket.h" #include "unistd.h" #include "arpa/inet.h" #include "string.h" #include "memory.h" #include "signal.h" #include "time.h" #include <string> #include <sys/stat.h> #include <stdio.h> #include <string.h> #define DBUG(format, ...) fprintf(stdout, format, __VA_ARGS__) #define ACK1 "ACK1" #define ACK2 "ACK2" #define CPU "CPU" #define MEM "MEM" #define DISK "DISK" #define USER "USER" #define SYS "SYS" #define COM 5 int socket_create(int port); int socket_connect(int port,char *host); int get_conf_value(char* pathname, char* key_name, char *value); int GetConfig(); int socket_connect(int port,char *host){ int sockfd; struct sockaddr_in dest_addr; if ((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0){ perror("socket error"); return 1; } memset(&dest_addr,0,sizeof(dest_addr)); dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(port); dest_addr.sin_addr.s_addr = inet_addr(host); fflush(stdout); if (connect(sockfd,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0){ perror("connect error "); return -1; } return sockfd; } int socket_create(int port){ int sockfd; int yes = 1; struct sockaddr_in sock_addr; //创建套接字 if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket() error\n"); return -1; } //设置本地套接字地址 sock_addr.sin_family = AF_INET; sock_addr.sin_port = htons(port); //转化为网络字节序 sock_addr.sin_addr.s_addr = htonl(INADDR_ANY); //0.0.0.0 //设置本地套接字 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { close(sockfd); perror("setsockopt() error\n"); return -1; } //绑定本地套接字到套接字 if (bind(sockfd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0) { close(sockfd); perror("bind() error\n"); return -1; } //将套接字设置为监听状态 if (listen(sockfd, 20) < 0) { close(sockfd); perror("listen() error"); return -1; } /* struct sockaddr_in client_add; socklen_t l = sizeof(sock_addr); int listen_soc = accept(sockfd,(struct sockaddr*) &client_add, &l); if (listen_soc < 0){ printf("accept ERROR\n"); }else { printf("accept OK\n"); }*/ return sockfd; } int socket_accept(int listen_sock){ struct sockaddr_in client_add; int accept_sock; //socklen_t l = sizeof(sock_addr); int accept_soc = accept(listen_sock,(struct sockaddr*)NULL, NULL); if (accept_soc < 0){ printf("accept ERROR\n"); }else { printf("accept OK\n"); } return accept_sock; } int get_conf_value(char* pathname, char* key_name, char *value) { FILE *fp = NULL; char *line = NULL, *substr = NULL; size_t len = 0, tmplen = 0; ssize_t read; //memset(value, 0, sizeof(char)*MAX_SIZE); if ( key_name == NULL || value == NULL) { // DBG("paramer is invaild!n"); exit(-1); } fp = fopen(pathname,"r"); if (fp == NULL) { // DBG("Open config file error!\n"); exit(-1); } while (( read = getline(&line, &len,fp)) != -1) { substr = strstr(line, key_name); if (substr == NULL) continue; else { tmplen = strlen(key_name); if (line[tmplen] == '=') { strncpy(value, &line[tmplen + 1], (int)read - tmplen + 1); tmplen = strlen(value); *(value + tmplen - 1) = ' '; break; } else { // DBG("Maybe there is something wrong with config file!n"); continue; } } } if (substr == NULL) { // DBG("%s not found in config file!n", key_name); fclose(fp); exit(-1); } //DBG("%s=%sn", key_name, value); free(line); fclose(fp); return 0; } int NUM; int CTRL_PORT; int DATA_PORT; int WARN_PORT; char str[50]; char MASTER_IP[100]; char Client_Ip[50][50]; int a = GetConfig(); int GetConfig(){ printf(" ------------------------------------------\n"); get_conf_value("master.conf","num",str); NUM = atoi(str); printf("NUM : %d \n",NUM); get_conf_value("master.conf","MASTER_IP",MASTER_IP); printf("MASTER_IP: %s \n",MASTER_IP); get_conf_value("master.conf","ctrl_port",str); CTRL_PORT = atoi(str); printf("CTRL_PORT: %d \n",CTRL_PORT); get_conf_value("master.conf","data_port",str); DATA_PORT = atoi(str); printf("DATA_PORT: %d \n",DATA_PORT); get_conf_value("master.conf","warn_port",str); WARN_PORT = atoi(str); printf("WARN_PORT: %d \n",WARN_PORT); for(int i = 0; i < NUM; i++){ char key[50]; sprintf(key,"CLIENTIP%i",i); //printf("key :%s \n",key); get_conf_value("master.conf",key,Client_Ip[i]); printf("Client_Ip[%d] :%s \n",i,Client_Ip[i]); } printf(" ------------------------------------------\n"); return 1; }
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 100 #define INF 0x3f3f3f3f #define DEVIATION 0.00000005 int main(int argc, char const *argv[]) { int table[10]; string str; while( getline(cin,str) ){ stringstream ss(str); int idx = 8; while( ss >> table[idx--] ); bool first = true; for(int i = 8 ; i >= 0 ; i-- ){ if( table[i] == 0 ) continue; if( !first ){ if( table[i] < 0 ) printf(" - "); else printf(" + "); table[i] = abs(table[i]); } if( table[i] == -1 && i != 0 ) printf("-"); else if ( table[i] != 1 || i == 0 ) printf("%d", table[i]); if( i > 0 ) printf("x"); if( i > 1 ) printf("^%d",i); first = false; } if( first ) printf("0"); printf("\n"); } return 0; }
#include "RateControl.h" /** * \brief 获取VRLS_param中的Tile mapping方式等信息,创建rateControl线程,线程suspend * \param rateControl 线程NULL指针 * \param VRLS_param 编码配置信息 * \param pfvlist 输入帧链表 * \param pmlist 输出码控信息到链表 * \param privateSpace 线程私有空间 * \return int -1失败 0成功 */ int init_rateControl( HANDLE *rateControl, VRLSParam *VRLS_param,AVFrameList *pfvlist,MessageList *pmlist, void *privateSpace ) { return 0; } /** * \brief 线程从挂起状态唤醒 * \param rateControl rateControl线程句柄 * \param privateSpace 线程私有空间 * \param pfvlist 输入帧链表 * \param pmlist 输出码控信息到链表 * \return int -1失败 0成功 */ int activate_rateControl( HANDLE *rateControl, void *privateSpace, AVFrameList *pfvlist, MessageList *pmlist ) { return 0; } /** * \brief 线程销毁,释放私有空间 * \param rateControl rateControl线程句柄 * \param privateSpace 线程私有空间 * \return int -1失败 0成功 */ int destroy_rateControl( HANDLE *rateControl, void *privateSpace ) { return 0; }
#pragma once #include <API/Code/Graphics/Framebuffer/Framebuffer.h> #include <API/Code/Graphics/Framebuffer/FramebufferSprite.h> #include <API/Code/Graphics/Material/Material.h> #include <API/Code/Graphics/Texture/Texture2D.h> #include <API/Code/Graphics/Shader/Shader.h> /// <summary>Process the jump flooding algorithm on the GPU.</summary> class JumpFlooding { public: /// <summary>Initializa the jump flooding pass.</summary> /// <param name="_TextureSize">The pingpong framebuffer size (and the distance texture).</param> /// <param name="_PenetrationTexture">The penetrationg texture resulting of previous step.</param> JumpFlooding( Uint32 _TextureSize, ae::Texture& _PenetrationTexture ); /// <summary>Destructor.</summary> ~JumpFlooding(); /// <summary>Run the jump flooding algorithm from the penetration texture given in the constructor.</summary> void Run(); /// <summary>Retrieve the result of the jump flooding algorithm (distance field).</summary> /// <returns>The jump flooding result.</returns> ae::Texture& GetDistanceTexture(); /// <summary>Resize the framebuffer (thus the distance texture).</summary> /// <param name="_TextureSize">The size to apply.</param> void Resize( Uint32 _TextureSize ); /// <summary>Expose properties to the editor panel.</summary> void ToEditor(); private: /// <summary>Shader for the first step of the algorithm to initialize a first time a ping pong texture.</summary> ae::Shader m_InitShader; /// <summary>Material for the first step shader.</summary> ae::Material m_InitMaterial; /// <summary>Shader for the flooding algorithm.</summary> ae::Shader m_FloodingShader; /// <summary>Material for the flooding algorithm.</summary> ae::Material m_FloodingMaterial; /// <summary>Parameter for the ping pong texture to read from.</summary> ae::ShaderParameterTexture* m_FloodingTextureParameter; /// <summary>Parameter for the flooding range.</summary> ae::ShaderParameterInt* m_FloodingRangeParameter; /// <summary>Parameter for the time (used to feed random function).</summary> ae::ShaderParameterFloat* m_FloodingTimeParameter; /// <summary>Ping-pong framebuffer.</summary> ae::Framebuffer* m_PingPongFBO[2]; /// <summary>Fullscreen quad.</summary> ae::FramebufferSprite m_FullscreenSprite; /// <summary>Maximum possible range.</summary> Uint32 m_MaxFloodingRange; /// <summary>Size of the texture.</summary> Uint32 m_TextureSize; /// <summary>Index of the last ping pong texture written.</summary> Uint32 m_CurrentPingPongIndex; };
#include <iostream> #include <set> using namespace std; using ll = long long; ll calc(ll n, ll k) { ll m = n / k; return m + m * (m - 1) / 2 * k; } int main() { ll N; cin >> N; set<ll> ans; for (ll i = 1; i * i <= N; ++i) { if (N % i > 0) continue; ans.insert(calc(N, i)); ans.insert(calc(N, N / i)); } for (ll f : ans) cout << f << " "; cout << endl; return 0; }
/* replay Software Library Copyright (c) 2010-2019 Marius Elvert 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. */ #ifndef replay_vector3_hpp #define replay_vector3_hpp #include <iosfwd> #include <replay/common.hpp> #include <replay/vector2.hpp> namespace replay { /** 3-dimensional vector. \note The element type is supposed to be a mathematical group. \ingroup Math */ template <class type> class vector3 { public: /** Element type. */ typedef type value_type; /** Get a pointer to the internal array. */ inline type* ptr() { return data; } /** Get a pointer to the internal array. */ inline const type* ptr() const { return data; } /** Index access operator. */ template <class index_type> constexpr value_type& operator[](const index_type i) { return data[i]; } /** Index access operator. */ template <class index_type> constexpr const value_type operator[](const index_type i) const { return data[i]; } // Access constexpr vector3<type>& reset(value_type x, value_type y, value_type z); constexpr vector3<type>& reset(value_type value = value_type(0)); // Linear Algebra vector3<type> operator-() const; // Negation /** Create a new vector. This constructor will leave all values uninitialized. */ explicit vector3(uninitialized_tag) { } /** Constructor for user-defined conversions. \see convertible_tag */ template <class source_type> vector3(const source_type& other, typename convertible_tag<source_type, vector3>::type empty = 0) { *this = convert(other); } /** Create a vector with all elements the same value. */ constexpr explicit vector3(value_type value = value_type(0)) : data{ value, value, value } { } /** Create a new vector from seperate values. \param xy The first two components. \param z The third component. */ constexpr vector3(vector2<value_type> const& xy, value_type z) : data{ xy[0], xy[1], z } { } /** Create a new vector from seperate values. \param x The first component. \param y The second component. \param z The third component. */ constexpr vector3(value_type x, value_type y, value_type z) : data{x, y, z} { } vector3<type>& operator+=(vector3<type> const& operand); vector3<type>& operator-=(vector3<type> const& operand); vector3<type>& operator*=(const type& operand); vector3<type>& operator/=(const type& operand); bool operator==(vector3<type> const& operand) const; bool operator!=(vector3<type> const& operand) const; /** In-place negate. Negates each element of this vector. */ vector3<type>& negate(); value_type squared() const; value_type sum() const; /** Static element wise type cast. This can be used on all indexable array-like types. */ template <class array_type> constexpr inline static vector3<type> cast(array_type const& src) { return vector3<type>(static_cast<type>(src[0]), static_cast<type>(src[1]), static_cast<type>(src[2])); } private: /** the actual data. */ type data[3]; }; /** Cross product. Also referred to as vector-product, this operator returns a vector that is perpendicular to both input vectors. The length of this vector is equal to the area of the parallelogram spanned by the two input vectors. \relates vector3 \ingroup Math */ template <class type> inline vector3<type> cross(vector3<type> const& lhs, vector3<type> const& rhs); /** Dot product of two 3D vectors. \relates vector3 \ingroup Math */ template <class type> inline type dot(vector3<type> const& lhs, vector3<type> const& rhs); /** Component wise product of two 3D vectors. \relates vector3 \ingroup Math */ template <class type> inline vector3<type> comp(vector3<type> const& lhs, vector3<type> const& rhs); /** Addition. \relates vector3 \ingroup Math */ template <class type> inline vector3<type> operator+(vector3<type> lhs, vector3<type> const& rhs) { return lhs += rhs; } /** Subtraction. \relates vector3 \ingroup Math */ template <class type> inline vector3<type> operator-(vector3<type> lhs, vector3<type> const& rhs) { return lhs -= rhs; } /** Scalar product. \relates vector3 \ingroup Math */ template <class type> inline vector3<type> operator*(vector3<type> lhs, type rhs) { return lhs *= rhs; } /** Scalar product. \relates vector3 \ingroup Math */ template <class type> inline vector3<type> operator*(type lhs, vector3<type> rhs) { return rhs *= lhs; } /** Scalar division. \relates vector3 \ingroup Math */ template <class type> inline vector3<type> operator/(vector3<type> lhs, type rhs) { return lhs /= rhs; } /** Scalar division. \relates vector3 \ingroup Math */ template <class type> inline vector3<type> operator/(type lhs, vector3<type> const& rhs) { return vector3<type>(lhs / rhs[0], lhs / rhs[1], lhs / rhs[2]); } /** A convenience typedef for a 3d floating-point vector. \relates vector3 \ingroup Math */ typedef vector3<float> vector3f; /** A convenience typedef for a 3d double-precision floating-point vector. \relates vector3 \ingroup Math */ typedef vector3<double> vector3d; /** Shorthandle for all 3d vectors \relates vector2 \ingroup Math */ template <class T> using v3 = vector3<T>; } // namespace replay #include "vector3.inl" #endif // replay_vector3_hpp
/* * ulcd_component.cpp * * * */ #include "ulcd_component.h" /* * private defines * */ /* * private variables * */ /* * constructor * */ ulcd_component::ulcd_component() : rect() { } ulcd_component::~ulcd_component() { } /* * private functions * */ /* * public functions * */
/* Class intent: We want to be able to measure an arbitrary metric, and then adjust an arbitrary output variable to attempt to find a maximal resultant input. This is is probably over-generic, and shouldn't be, but let's find out what happens. Input */ #include <deque> #include "Accelerometer.h" Accelerometer::append_val(int val) { max_inputs.push_back } Accelerometer::balance_load() { // Primary maintenance loop for load balancer // this should be run in it's own thread / process /* : while (true): { // get load // get load_acceleration // } }
#include <bits/stdc++.h> using namespace std; #define endl '\n' typedef pair<int, int> pii; typedef long double ld; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; const int maxn = 400005; const int INF = 0x3f3f3f3f; const double pi = acos(-1.0); const double eps = 1e-9; template<class T> inline void read (T &x) { int c; for (c = getchar(); c < 32 && ~c; c = getchar()); for (x = 0; c > 32; x = x * 10 + c - '0', c = getchar()); } template<class T> struct Segtree { #define ls (o<<1) #define rs (o<<1)|1 T data1[maxn << 2]; T data2[maxn << 2]; T lazy1[maxn << 2]; T lazy2[maxn << 2]; void pushup (int o) { data1[o] = min(data1[ls], data1[rs]); data2[o] = max(data2[ls], data2[rs]); } void setlazy1 (int o, T v) { if (v == 2) { lazy1[o] = 2; data1[o] = 0; data2[o] = 0; lazy2[o] = 0; return; } lazy1[o] = v; data1[o] = v; data2[o] = v; lazy2[o] = 0; } void setlazy2 (int o, T v) { lazy2[o] ^= 1; int t1 = 1, t2 = 0; if (data1[o] == 0) { t2 = 1; } if (data2[o] == 1) { t1 = 0; } data1[o] = t1; data2[o] = t2; } void pushdown (int o) { if (lazy1[o]) { setlazy1(ls, lazy1[o]); setlazy1(rs, lazy1[o]); lazy1[o] = 0; } if (lazy2[o]) { setlazy2(ls, lazy2[o]); setlazy2(rs, lazy2[o]); lazy2[o] = 0; } } void build (int o, int l, int r) { lazy1[o] = 0; lazy2[o] = 0; if (l == r) { data1[o] = 0; data2[o] = 0; return; } int mid = (l + r) >> 1; build(ls, l, mid); build(rs, mid + 1, r); pushup(o); } void update1 (int o, int l, int r, int x, int y, T v) { if (l >= x && r <= y) { setlazy1(o, v); return; } pushdown(o); int mid = (l + r) >> 1; if (x <= mid) update1(ls, l, mid, x, y, v); if (y > mid) update1(rs, mid + 1, r, x, y, v); pushup(o); } void update2 (int o, int l, int r, int x, int y, T v) { if (l >= x && r <= y) { setlazy2(o, v); return; } pushdown(o); int mid = (l + r) >> 1; if (x <= mid) update2(ls, l, mid, x, y, v); if (y > mid) update2(rs, mid + 1, r, x, y, v); pushup(o); } T query (int o, int l, int r, int x, int y) { if (l >= x && r <= y) { return data1[o]; } pushdown(o); int mid = (l + r) >> 1; if (y <= mid) return query(ls, l, mid, x, y); if (x > mid) return query(rs, mid + 1, r, x, y); return min(query(ls, l, mid, x, y), query(rs, mid + 1, r, x, y)); } int query1 (int o, int l, int r) { if (l==r) { return l; } pushdown(o); int mid = (l + r) >> 1; // cout<<data1[ls]<<endl; if(data1[ls]==1) return query1(rs,mid+1,r); return query1(ls,l,mid); } }; Segtree<ll> tree; struct node{ int o; ll x,y; node(){} node(int a,ll b,ll c):o(a),x(b),y(c){} }; vector<node>v; vector<ll>num; int getid(ll x){ return 1+distance(num.begin(),lower_bound(num.begin(),num.end(),x)); } int n; //ll query[100005][4]; //set<ll> st; //ll hash1[400005]; //map<ll, int> mp; int main () { // freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); read(n); for (int i = 0; i < n; i++) { // read(query[i][0]); // read(query[i][1]); // read(query[i][2]); // st.insert(query[i][1]); // st.insert(query[i][2]); ll op,x,y; read(op),read(x),read(y); v.emplace_back(op,x,y); num.emplace_back(x); num.emplace_back(y); num.emplace_back(y+1); } num.emplace_back(1); sort(num.begin(), num.end()); num.erase(unique(num.begin(), num.end()),num.end()); int ind=num.size(); tree.build(1, 1, ind); for (const auto &t:v) { int type=t.o; // int l = mp[query[i][1]]; // int r = mp[query[i][2]]; // ll type = query[i][0]; ll l=getid(t.x),r=getid(t.y); if (type == 1) { tree.update1(1, 1, ind, l, r, 1); } else if (type == 2) { tree.update1(1, 1, ind, l, r, 2); } else if (type == 3) tree.update2(1, 1, ind, l, r, 1); // int _l = 1, _r = ind; // while (_r - _l > 3) { // int mid = (_l + _r) >> 1; // if (tree.query(1, 1, ind, _l, mid) == 0) { // _r = mid; // } else if (tree.query(1, 1, ind, mid, _r) == 0) { // _l = mid; // } else // break; // } // int tans = _l; // for (; tans <= _r; tans++) { // if (tree.query(1, 1, ind, tans, tans) == 0) { // break; // } // } // printf("%I64d\n", hash1[tans]); ll tans=tree.query1(1, 1, ind); // printf("tans=%d\n",tans); printf("%I64d\n",num[tans-1]); } return 0; }
// Created on: 2016-07-07 // Copyright (c) 2016 OPEN CASCADE SAS // Created by: Oleg AGASHIN // // 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 _BRepMesh_BaseMeshAlgo_HeaderFile #define _BRepMesh_BaseMeshAlgo_HeaderFile #include <IMeshTools_MeshAlgo.hxx> #include <NCollection_Shared.hxx> #include <IMeshTools_Parameters.hxx> #include <BRepMesh_DegreeOfFreedom.hxx> #include <Poly_Triangulation.hxx> class BRepMesh_DataStructureOfDelaun; //! Class provides base functionality for algorithms building face triangulation. //! Performs initialization of BRepMesh_DataStructureOfDelaun and nodes map structures. class BRepMesh_BaseMeshAlgo : public IMeshTools_MeshAlgo { public: typedef NCollection_Shared<NCollection_Vector<gp_Pnt> > VectorOfPnt; //! Constructor. Standard_EXPORT BRepMesh_BaseMeshAlgo(); //! Destructor. Standard_EXPORT virtual ~BRepMesh_BaseMeshAlgo(); //! Performs processing of the given face. Standard_EXPORT virtual void Perform( const IMeshData::IFaceHandle& theDFace, const IMeshTools_Parameters& theParameters, const Message_ProgressRange& theRange = Message_ProgressRange()) Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(BRepMesh_BaseMeshAlgo, IMeshTools_MeshAlgo) protected: //! Gets discrete face. const IMeshData::IFaceHandle& getDFace() const { return myDFace; } //! Gets meshing parameters. const IMeshTools_Parameters& getParameters() const { return myParameters; } //! Gets common allocator. const Handle(NCollection_IncAllocator)& getAllocator() const { return myAllocator; } //! Gets mesh structure. const Handle(BRepMesh_DataStructureOfDelaun)& getStructure() const { return myStructure; } //! Gets 3d nodes map. const Handle(VectorOfPnt)& getNodesMap() const { return myNodesMap; } protected: //! Registers the given point in vertex map and adds 2d point to mesh data structure. //! Returns index of node in the structure. Standard_EXPORT virtual Standard_Integer registerNode( const gp_Pnt& thePoint, const gp_Pnt2d& thePoint2d, const BRepMesh_DegreeOfFreedom theMovability, const Standard_Boolean isForceAdd); //! Adds the given 2d point to mesh data structure. //! Returns index of node in the structure. Standard_EXPORT virtual Standard_Integer addNodeToStructure( const gp_Pnt2d& thePoint, const Standard_Integer theLocation3d, const BRepMesh_DegreeOfFreedom theMovability, const Standard_Boolean isForceAdd); //! Returns 2d point associated to the given vertex. Standard_EXPORT virtual gp_Pnt2d getNodePoint2d(const BRepMesh_Vertex& theVertex) const; //! Performs initialization of data structure using existing model data. Standard_EXPORT virtual Standard_Boolean initDataStructure(); //! Generates mesh for the contour stored in data structure. Standard_EXPORT virtual void generateMesh(const Message_ProgressRange& theRange) = 0; private: //! If the given edge has another pcurve for current face coinciding with specified one, //! returns TopAbs_INTERNAL flag. Elsewhere returns orientation of specified pcurve. TopAbs_Orientation fixSeamEdgeOrientation( const IMeshData::IEdgeHandle& theDEdge, const IMeshData::IPCurveHandle& thePCurve) const; //! Adds new link to the mesh data structure. //! Movability of the link and order of nodes depend on orientation parameter. Standard_Integer addLinkToMesh( const Standard_Integer theFirstNodeId, const Standard_Integer theLastNodeId, const TopAbs_Orientation theOrientation); //! Commits generated triangulation to TopoDS face. void commitSurfaceTriangulation(); //! Collects triangles to output data. Handle(Poly_Triangulation) collectTriangles(); //! Collects nodes to output data. void collectNodes(const Handle(Poly_Triangulation)& theTriangulation); private: typedef NCollection_Shared<NCollection_DataMap<Standard_Integer, Standard_Integer> > DMapOfIntegerInteger; IMeshData::IFaceHandle myDFace; IMeshTools_Parameters myParameters; Handle(NCollection_IncAllocator) myAllocator; Handle(BRepMesh_DataStructureOfDelaun) myStructure; Handle(VectorOfPnt) myNodesMap; Handle(DMapOfIntegerInteger) myUsedNodes; }; #endif
#ifndef __LINKEDLIST_H__ #define __LINKEDLIST_H__ #include "Node.h" class LinkedList { private: Node *head; Node *tail; int length; public: LinkedList(); ~LinkedList(); void Insert(std::string name, int id); bool Remove(std::string name, int id); int Hashfunction(std::string name); bool Find(std::string name); void Remove(); void Print(); }; #endif // __LINKEDLIST_H__
#include <iostream> #include <vector> using namespace std; bool char_to_bool(char c) { return (c != '0'); } bool bool_and(bool left, bool right) { return left & right; } bool bool_or(bool left, bool right) { return left | right; } bool bool_xor(bool left, bool right) { return left ^ right; } vector<bool> eval(string str) { if ((str.length() % 2) == 0) { cout << str.length() << endl; throw "string length should never be even"; } if (str.length() == 1) { return {char_to_bool(str.at(0))}; } else { vector<bool> result {}; for (int i = 1; i < str.length(); i += 2) { char oper = str.at(i); auto left = eval(str.substr(0,i)); auto right = eval(str.substr(i + 1)); bool (*pred)(bool, bool); switch(oper) { case '&': pred = bool_and; break; case '|': pred = bool_or; break; case '^': pred = bool_xor; break; default: cout << oper << endl; throw "Operation not supported"; } for (auto left_value : left) { for (auto right_value : right) { result.push_back(pred(left_value, right_value)); } } } return result; } } int count_eval(string str, bool desired_result) { int count = 0; auto results = eval(str); for (auto result : results) { if (result == desired_result) { ++count; } } return count; } int main() { cout << count_eval("1&1", true) << endl; cout << count_eval("1&0", true) << endl; cout << count_eval("1^0|1", true) << endl; cout << count_eval("1^0|0|1", false) << endl; cout << count_eval("0&0&0&1^1|0", true) << endl; }
#include <iostream> #include <deque> #include <string> typedef long long ll; std::string str; std::deque<ll> opd; std::deque<char> opt; void parse() { int str_len = (int)str.length(); int idx = 0; while(idx < str_len) { ll number = 0; bool MINUS = false; if(str[idx] == '-') { MINUS = true; idx++; } for(idx; idx < str_len; idx++) { if(str[idx] < '0' || str[idx] > '9') { break; } number = number * 10 + (str[idx] - '0'); } if(MINUS) { number *= -1; } opd.push_back(number); if(idx < str_len) { opt.push_back(str[idx]); idx++; } } } ll calc_front() { ll num1 = opd[0]; ll num2 = opd[1]; char opt1 = opt.front(); ll ret; switch(opt1){ case '+': ret = num1 + num2; break; case '-': ret = num1 - num2; break; case '*': ret = num1 * num2; break; case '/': ret = num1 / num2; break; } return ret; } ll calc_back() { int sz = (int)opd.size(); ll num1 = opd[sz - 2]; ll num2 = opd[sz - 1]; char opt1 = opt.back(); ll ret; switch(opt1){ case '+': ret = num1 + num2; break; case '-': ret = num1 - num2; break; case '*': ret = num1 * num2; break; case '/': ret = num1 / num2; break; } return ret; } int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); std::cin >> str; parse(); while(!opt.empty()) { int front_opt = (opt.front() == '*' || opt.front() == '/') ? 1 : 0; int back_opt = (opt.back() == '*' || opt.back() == '/') ? 1 : 0; if(front_opt == back_opt) { ll front = calc_front(); ll back = calc_back(); if(front >= back) { opd.pop_front(); opd.pop_front(); opt.pop_front(); opd.push_front(front); } else { opd.pop_back(); opd.pop_back(); opt.pop_back(); opd.push_back(back); } } else if(front_opt > back_opt) { ll front = calc_front(); opd.pop_front(); opd.pop_front(); opt.pop_front(); opd.push_front(front); } else { ll back = calc_back(); opd.pop_back(); opd.pop_back(); opt.pop_back(); opd.push_back(back); } } std::cout << opd.front() << '\n'; return 0; }
/* limit.h Represents a single limit price */ #ifndef limit_h #define limit_h #include <assert.h> #include "order.h" #include "book.h" //forward declaration class Order; class Book; class Limit { public: Limit( Order * order, Book * book ); void Insert(Order * order); Limit * Remove(); Limit * GetMin(); Limit * GetMax(); Limit * Succesor( ); Limit * Predecessor( ); Limit * parent; Limit * left; Limit * right; Order * head; Order * tail; Book * book; int volume; int price; }; #endif
#include "RenderTexture.h" #include "Debug.h" #include "Util.h" #include "Graphics.h" #include <vector> using namespace NoHope; RenderTexture::RenderTexture(): _bound(false) { init(); } RenderTexture::~RenderTexture() { glDeleteFramebuffers(1, &_frameBufferId); glDeleteRenderbuffers(1, &_depthBufferId); } void RenderTexture::init() { std::vector<GLfloat> data(24); //vertex positions data[0] = -1.0f; data[1] = 1.0f; data[2] = -1.0f; data[3] = -1.0f; data[4] = 1.0f; data[5] = 1.0f; data[6] = 1.0f; data[7] = 1.0f; data[8] = -1.0f; data[9] = -1.0f; data[10] = 1.0f; data[11] = -1.0f; //texture coordinates data[12] = 0.0f; data[13] = 1.0f; data[14] = 0.0f; data[15] = 0.0f; data[16] = 1.0f; data[17] = 1.0f; data[18] = 1.0f; data[19] = 1.0f; data[20] = 0.0f; data[21] = 0.0f; data[22] = 1.0f; data[23] = 0.0f; _vertexData = new VertexData(data); //Create color attachment glGenFramebuffers(1, &_frameBufferId); checkGlError("glGenFramebuffers"); _texture = new Texture(0, Graphics::screenWidth, Graphics::screenHeight, 32); glBindFramebuffer(GL_FRAMEBUFFER, _frameBufferId); checkGlError("glBindFramebuffer"); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture->getTextureObject(), 0); checkGlError("glFramebufferTexture2D"); //Create depth attachment glGenRenderbuffers(1, &_depthBufferId); checkGlError("glGenRenderBuffers"); glBindRenderbuffer(GL_RENDERBUFFER, _depthBufferId); checkGlError("glBindRenderbuffer"); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, Graphics::screenWidth, Graphics::screenHeight); checkGlError("glRenderbufferStorage"); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthBufferId); checkGlError("glFramebufferRenderbuffer"); ////Create stencil attachment //glGenRenderbuffers(1, &_stencilBufferId); //checkGlError("glGenRenderBuffers"); //glBindRenderbuffer(GL_RENDERBUFFER, _stencilBufferId); //checkGlError("glBindRenderbuffer"); //glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, Graphics::screenWidth, Graphics::screenHeight); //checkGlError("glRenderbufferStorage"); //glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _stencilBufferId); //checkGlError("glFramebufferRenderbuffer"); //Check for completeness GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(status != GL_FRAMEBUFFER_COMPLETE) writeLog("\nFramebuffer is not complete!"); else writeLog("\nFramebuffer is complete!"); _shader = new Shader(Util::resourcePath + "Shaders/postprocess.vert", Util::resourcePath + "Shaders/postprocessblank.frag"); clear(Color(0, 0, 0)); } void RenderTexture::draw(Entity& entity, Camera &_camera) { bind(); entity.draw(_camera); /*_data.insert(_data.end(), entity._vertexData->getData().begin(), entity._vertexData->getData().end()); _batchTexture = entity._texture; _batchShader = entity._shader;*/ } void RenderTexture::display() { //_batchTexture->bind(_batchShader); //glUseProgram(_batchShader->program()); //_batchData = new VertexData(_data); //static const int stride = sizeof(GLfloat)*8; //_batchData->bindBuffers(); //_batchData->setAttribute(glGetAttribLocation(_batchShader->program(), "position"), 2, stride, 0); //vertex positions //_batchData->setAttribute(glGetAttribLocation(_batchShader->program(), "color"), 4, stride, sizeof(GLfloat)*2); //color //_batchData->setAttribute(glGetAttribLocation(_batchShader->program(), "texCoords"), 2, stride, sizeof(GLfloat)*6); //texture coordinates //glDrawArrays(GL_TRIANGLE_STRIP, 0, 500); //delete _batchData; //_data.clear(); //_batchTexture = 0; //_batchShader = 0; unBind(); glUseProgram(_shader->program()); checkGlError("Glbaadadadad"); _shader->setUniform("time", Util::getTotalTime()); _texture->bind(_shader); _vertexData->bindBuffers(); _vertexData->setAttribute(glGetAttribLocation(_shader->program(), "position"), 2, 0, 0); _vertexData->setAttribute(glGetAttribLocation(_shader->program(), "texCoords"), 2, 0, sizeof(GLfloat)*12); glDrawArrays(GL_TRIANGLES, 0, 6); checkGlError("glDrawArraysframebuffer"); } void RenderTexture::clear(const Color& color) { bind(); glClearColor(color.red, color.green, color.blue, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); checkGlError("Framebuffer clear"); unBind(); } void RenderTexture::bind() { if(!_bound) { glBindFramebuffer(GL_FRAMEBUFFER, _frameBufferId); checkGlError("glBindFramebuffers"); _bound = true; } } void RenderTexture::unBind() { if(_bound) { glBindFramebuffer(GL_FRAMEBUFFER, 0); checkGlError("glBindFramebuffer"); _bound = false; } }
#ifndef SUDOKU_HPP #define SUDOKU_HPP #include <iostream> #include <list> #include <iterator> #include <stdexcept> #include <cmath> //#define DEBUGGING /** @file Sudoku.hpp @brief Sudoku template class declaration */ /** @brief out_of_range_input. Custom exception class that derives from std :: runtime_error It is thrown when you try to access indexes outside the sudoku table. */ class out_of_range_input : public std::runtime_error { public: /** Default constructor */ out_of_range_input() : std::runtime_error("Out of range input") {} }; /** @brief bad_input. Custom exception class that derives from std :: runtime_error It is thrown when you try to insert bad input inside the sudoku table. */ class bad_input : public std::runtime_error { public: /** Default constructor */ bad_input() : std::runtime_error("Bad input") {} }; /** @brief my_uninitialized_value Custom exception class that derives from std::runtime_error. It is generated when trying to access values not yet initialized. */ class my_uninitialized_value: public std::runtime_error { public: /** Default constructor */ my_uninitialized_value() : std::runtime_error("Value not inizializated") {} }; /** @brief Sudoku solver. Class that implements a Sudoku table. @param table A 9x9 matrix of Cell. (private). @param changed It tells us if there have been any changes since the last check. */ class Sudoku{ private: /** @brief Sudoku cell. Structure that implements a Sudoku table cell. @param flag [bool] If true we have found the number. @param value [int] Real value of the cell. If -1 we have not found the number. @param possible_values [std::list<int>*] Possible values in a cell. */ struct Cell { bool flag; int value; std::list<int>* possible_values; /** @brief Default constructor. Default constructor that instantiates an ampty Cell. 'flag' is set to false, 'value' is set to -1 and 'possible_values' has all the possible values. */ Cell(): flag(false), value(-1) { possible_values = new std::list<int>(); for(int i=0; i < 9; i++){ possible_values->push_back(i+1); } } /** @brief Constructor. Constructor that instantiates an depp copy Cell. */ Cell(const Cell &other) { this->flag = other.flag; this->value = other.value; delete this->possible_values; this->possible_values = new std::list<int> (); std::list<int>::iterator it; for (it = other.possible_values->begin(); it != other.possible_values->end(); ++it){ this->possible_values->push_back( *it ); } } /** @brief Constructor. Constructor that instantiates an depp copy Cell. */ Cell(const Cell *other) { this->flag = other->flag; this->value = other->value; delete this->possible_values; this->possible_values = new std::list<int> (); std::list<int>::iterator it; for (it = other->possible_values->begin(); it != other->possible_values->end(); ++it){ this->possible_values->push_back( *it ); } } /** @brief Constructor. Constructor that instantiates a Cell. 'flag' is set to true, 'value' is set to n and 'possible_values' is empty. @param n [int] Actual value of the Cell. */ explicit Cell(int n): flag(true), value(n) { possible_values = new std::list<int> (1, n); } /** @brief Destroyer. Removes the allocated memory from the Cell. */ ~Cell(){} /** @brief Assignment operator Redefine operator =. Allows copying between Cells. @param other Cell to copy */ Cell& operator=(const Cell &other){ this->flag = other.flag; this->value = other.value; if( !other.flag ){ delete this->possible_values; this->possible_values = new std::list<int> (); std::list<int>::iterator it; for (it = other.possible_values->begin(); it != other.possible_values->end(); ++it){ this->possible_values->push_back( *it ); } } return *this; } /** @brief Assignment operator Redefine operator =. Allows copying between Cells. @param other Cell to copy */ Cell& operator=(const Cell *other){ this->flag = other->flag; this->value = other->value; if( !other->flag ){ delete this->possible_values; this->possible_values = new std::list<int> (); std::list<int>::iterator it; for (it = other->possible_values->begin(); it != other->possible_values->end(); ++it){ this->possible_values->push_back( *it ); } } return *this; } /** @brief Assignment operator Redefine operator =. Allows copying between Cell and int. @param value Cell to copy */ Cell& operator=(int value){ this->flag = true; this->value = value; delete this->possible_values; this->possible_values = new std::list<int> (); return *this; } }; Cell table [9][9]; bool changed; /** @brief Check if value is possible in that column. If 'val' is in the (x,y) Cell return true. Else, check if 'val' can be a possible value looking only the column. @param val [int] Value to check, in [1,9]. @param x x-coordinate, in [1,9]. @param y y-coordinate, in [1,9]. */ bool check_col(int val, int x, int y){ if( this->get(x, y) == val ){ return true; } bool flag = true; for(int i=1; i <= 9; i++){ if( (this->get(x, i) == val) && (i != y) ){ return false; } } return true; } /** @brief Check if value is possible in that row. If 'val' is in the (x,y) Cell return true. Else, check if 'val' can be a possible value looking only the row. @param val [int] Value to check, in [1,9]. @param x x-coordinate, in [1,9]. @param y y-coordinate, in [1,9]. */ bool check_row(int val, int x, int y){ if( this->get(x, y) == val ){ return true; } bool flag = true; for(int i=1; i <= 9; i++){ if( ( this->get(i, y) == val) && (i != x) ){ return false; } } return true; } /** @brief Check if value is possible in that block. If 'val' is in the (x,y) Cell return true. Else, check if 'val' can be a possible value looking only the block. @param val [int] Value to check, in [1,9]. @param x x-coordinate, in [1,9]. @param y y-coordinate, in [1,9]. @throw bad_input. */ bool check_block(int val, int x, int y){ if( this->get(x, y) == val ){ return true; } x = x-1; y = y-1; int x_block = (int) floor(x / 3); int y_block = (int) floor(y / 3); int x_block_position = x_block * 3; //x_block_starting_position int y_block_position = y_block * 3; //y_block_starting_position for(int i=x_block_position; i <= ( x_block_position + 2 ); i++){ for(int j=y_block_position; j <= ( y_block_position + 2 ); j++){ if( ( table[i][j].value == val) && (i != x) && (j != y) ){ return false; } } } return true; } /** @brief Check if value is possible in that place. If 'val' is in the (x,y) Cell return true. Else, check if 'val' can be a possible value. @param val [int] Value to check, in [1,9]. @param x x-coordinate, in [1,9]. @param y y-coordinate, in [1,9]. */ bool is_Valid_place(int value, int x, int y){ bool flag_value = value >= 1 && value <= 9; if( !flag_value ){ #ifdef DEBUGGING std::cout << "Bad input from 'is_Valid_place()' " << std::endl; #endif //DEBUGGING throw bad_input(); } bool flag_x = x >= 1 && x <= 9; bool flag_y = y >= 1 && y <= 9; if( ! (flag_x && flag_y) ){ throw out_of_range_input(); } bool row = check_row( value, x, y); bool col = check_col( value, x, y); bool block = check_block( value, x, y); return ( row && col && block ); } /** @brief Check if a value is in a std::list. @param val [int] Value to check. @param cpp_list [std::list<int>] A C++ list. */ bool is_value_in_list(int value, std::list<int>* cpp_list){ for (std::list<int>::iterator it = cpp_list->begin(); it != cpp_list->end(); ++it){ if( *it == value ){ return true; } } return false; } /** @brief If 'value' in 'list' is removed and 'true' is returned. Else return 'false'. If 'x' or 'y' not in [1,9] throw out_of_range_input(). @param value Value to remove. @param list List in which to search. */ bool remove_if_exist(std::list<int> *list, int value){ bool flag_value = value >= 1 && value <= 9; if( !flag_value ){ return false; } size_t len = list->size(); list->remove(value); return len != list->size(); } /** @brief Simplify column 'col'. Remove the impossible value from column 'col' looking only that row. If 'col' not in [1,9] throw out_of_range_input. If a possible_value is removed return 'true'. @param col Column number, in [1,9]. @throw out_of_range_input */ bool simplify_col(int col){ //Scan to search real values std::list<int> real_values; std::list<int>::iterator it; bool flag_col = col >= 1 && col <= 9; if( !flag_col ){ throw out_of_range_input(); } col = col - 1; bool flag = false; bool flag_t = false; for(int i=0; i < 9; i++){ if( table[i][col].flag ) real_values.push_back( table[i][col].value ); } //Scan to remove possible values if in real values for(int i=0; i < 9; i++){ if( !table[i][col].flag ){ for (it = real_values.begin(); it != real_values.end(); ++it){ flag_t = remove_if_exist( table[i][col].possible_values, *it); if( flag_t ){ changed = true; } if( table[i][col].possible_values->size() == 1 ){ table[i][col].value = table[i][col].possible_values->front(); table[i][col].flag = true; } if( flag_t ){ flag = true; } } } } return flag; } /** @brief Simplify row 'row'. Remove the impossible value from row 'row' looking only that row. If 'row' not in [1,9] throw out_of_range_input. If a possible_value is removed return 'true'. @param row Row number, in [1,9]. @throw out_of_range_input */ bool simplify_row(int row){ //Scan to search real values std::list<int> real_values; std::list<int>::iterator it; bool flag_row = row >= 1 && row <= 9; if( !flag_row ){ throw out_of_range_input(); } row = row - 1; bool flag = false; bool flag_t = false; for(int i=0; i < 9; i++){ if( table[row][i].flag ) real_values.push_back( table[row][i].value ); } //Scan to remove possible values if in real values for(int i=0; i < 9; i++){ if( !table[row][i].flag ){ for (it = real_values.begin(); it != real_values.end(); ++it){ flag_t = remove_if_exist( table[row][i].possible_values, *it); if( flag_t ){ changed = true; } if( table[row][i].possible_values->size() == 1 ){ table[row][i].value = table[row][i].possible_values->front(); table[row][i].flag = true; } if( flag_t ){ flag = true; } } } } return flag; } /** @brief Simplify block 'block'. Remove the impossible value from block 'block' looking only that row. If 'block' not in [1,9] throw out_of_range_input. If a possible_value is removed return 'true'. @param x x-coordinate, in [1,9]. @param y y-coordinate, in [1,9]. @throw out_of_range_input */ bool simplify_block(int x, int y){ //Scan to search real values bool flag_x = x >= 1 && x <= 9; bool flag_y = y >= 1 && y <= 9; if( !(flag_x && flag_y) ){ throw out_of_range_input(); } std::list<int> real_values; std::list<int>::iterator it; bool flag = false; bool flag_t = false; int x_block = (int) floor(x / 3); int y_block = (int) floor(y / 3); int x_block_position = x_block * 3; //x_block_starting_position int y_block_position = y_block * 3; //y_block_starting_position for(int i=x_block_position; i <= ( x_block_position + 2 ); i++){ for(int j=y_block_position; j <= ( y_block_position + 2 ); j++){ if( table[i][j].flag ) real_values.push_back( table[i][j].value ); } } for(int i=x_block_position; i <= ( x_block_position + 2 ); i++){ for(int j=y_block_position; j <= ( y_block_position + 2 ); j++){ if( !table[i][j].flag ){ for (it = real_values.begin(); it != real_values.end(); ++it){ flag_t = remove_if_exist( table[i][j].possible_values, *it); if( flag_t ){ changed = true; } if( table[i][j].possible_values->size() == 1 ){ table[i][j].value = table[i][j].possible_values->front(); table[i][j].flag = true; } if( flag_t ){ flag = true; } } } } } return flag; } /** @brief Search for number that appear one time in the row. If a number is possible just in a cell so that cell is solved. @param row Row number, in [1,9]. @throw out_of_range_input */ bool one_possibility_row(int row){ int real_values[9]; std::list<int>::iterator it; bool flag_row = row >= 1 && row <= 9; if( !flag_row ){ throw out_of_range_input(); } row = row - 1; for(int i=0; i < 9; i++){ real_values[i] = 0; } //Scan to search real values for(int i=0; i < 9; i++){ if( !table[i][row].flag ){ for (it = table[i][row].possible_values->begin(); it != table[i][row].possible_values->end(); ++it){ real_values[(*it-1)]++; } } } //Scan to search one possibility std::list <int> values; for(int i=0; i < 9; i++){ if( real_values[i] == 1 ){ values.push_back( i + 1 ); } } //Set values. bool flag = false; for (it = values.begin(); it != values.end(); ++it){ for(int i=0; i < 9; i++){ if( !table[i][row].flag ){ if( is_value_in_list(*it, table[i][row].possible_values) ){ if( is_Valid_place(*it, row+1, i+1) ){ table[i][row] = *it; flag = true; changed = true; #ifdef DEBUGGING std::cout << "row " << row+1 << ", value " << *it << std::endl; #endif //DEBUGGING } } } } } return flag; } /** @brief Search for number that appear one time in the column. If a number is possible just in a cell so that cell is solved. @param col Column number, in [1,9]. @throw out_of_range_input */ bool one_possibility_col(int col){ int real_values[9]; std::list<int>::iterator it; bool flag_col = col >= 1 && col <= 9; if( !flag_col ){ throw out_of_range_input(); } col = col - 1; for(int i=0; i < 9; i++){ real_values[i] = 0; } //Scan to search real values for(int i=0; i < 9; i++){ if( !table[col][i].flag ){ for (it = table[col][i].possible_values->begin(); it != table[col][i].possible_values->end(); ++it){ real_values[(*it-1)]++; } } } //Scan to search one possibility std::list <int> values; for(int i=0; i < 9; i++){ if( real_values[i] == 1 ){ values.push_back( i + 1 ); } } //Set values. bool flag = false; for (it = values.begin(); it != values.end(); ++it){ for(int i=0; i < 9; i++){ if( !table[col][i].flag ){ if( is_value_in_list(*it, table[col][i].possible_values) ){ if( is_Valid_place(*it, i+1, col+1) ){ table[col][i] = *it; flag = true; changed = true; #ifdef DEBUGGING std::cout << "col " << col+1 << ", value " << *it << std::endl; #endif //DEBUGGING } } } } } return flag; } /** @brief Search for number that appear one time in the block. If a number is possible just in a cell so that cell is solved. @param x x-coordinate, in [1,9]. @param y y-coordinate, in [1,9]. @throw out_of_range_input */ bool one_possibility_block(int x, int y){ bool flag_x = x >= 1 && x <= 9; bool flag_y = y >= 1 && y <= 9; if( !(flag_x && flag_y) ){ throw out_of_range_input(); } int x_block = (int) floor(x / 3); int y_block = (int) floor(y / 3); int x_block_position = x_block * 3; //x_block_starting_position int y_block_position = y_block * 3; //y_block_starting_position int real_values[9]; std::list<int>::iterator it; for(int i=0; i < 9; i++){ real_values[i] = 0; } //Scan to search real values for(int i=x_block_position; i <= ( x_block_position + 2 ); i++){ for(int j=y_block_position; j <= ( y_block_position + 2 ); j++){ if( !table[i][j].flag ){ for (it = table[i][j].possible_values->begin(); it != table[i][j].possible_values->end(); ++it){ real_values[(*it-1)]++; } } } } //Scan to search one possibility std::list <int> values; for(int i=0; i < 9; i++){ if( real_values[i] == 1 ){ values.push_back( i + 1 ); } } //Set values. bool flag = false; for (it = values.begin(); it != values.end(); ++it){ for(int i=x_block_position; i <= ( x_block_position + 2 ); i++){ for(int j=y_block_position; j <= ( y_block_position + 2 ); j++){ if( !table[i][j].flag ){ if( is_value_in_list(*it, table[i][j].possible_values) ){ if( is_Valid_place(*it, i+1, j+1) ){ table[i][j] = *it; flag = true; changed = true; #ifdef DEBUGGING std::cout << "block " << i+1 <<","<< j+1 << ", value " << *it << std::endl; #endif //DEBUGGING } } } } } } return flag; } /** @brief Backtracking bruteforse algorithm. @param row row-coordinate, in [0,8]. @param col col-coordinate, in [0,8]. */ bool brute_force_temp(int row, int col){ // End if (row == 8 && col == 9) return true; // Move to the next row if (col == 9) { row++; col = 0; } if ( table[row][col].flag ) return brute_force_temp(row, col + 1); std::list<int>::iterator it; if( !table[row][col].flag ){ for (it = table[row][col].possible_values->begin(); it != table[row][col].possible_values->end(); ++it){ if( is_Valid_place(*it, row+1, col+1) ){ table[row][col].value = *it; table[row][col].flag = true; if ( brute_force_temp(row, col + 1) ) return true; } } // Removing the assigned value table[row][col].value = -1; table[row][col].flag = false; } return false; } public: /** @brief Default constructor. Default constructor that instantiates an empty Sudoku table. */ Sudoku(): changed(false) { } /** @brief Destroyer. Removes the allocated memory from the Sudoku table. */ ~Sudoku(){ for(int i=0; i<9; i++){ for(int j=0; j<9; j++){ delete table[i][j].possible_values; } } } /** @brief Default constructor. Default constructor that instantiates an empty Sudoku table. */ Sudoku(const Sudoku *s): changed(false) { if( s == nullptr ){ throw my_uninitialized_value(); } for(int i=0; i<9; i++){ for(int j=0; j<9; j++){ this->table[i][j] = s->table[i][j]; } } } /** @brief Default constructor. Default constructor that instantiates an empty Sudoku table. */ Sudoku(const Sudoku &s): changed(false) { for(int i=0; i<9; i++){ for(int j=0; j<9; j++){ this->table[i][j] = s.table[i][j]; } } } /** @brief Assignment operator Redefine operator =. Allows copying between Sudoku. @param other Sudoku to copy */ Sudoku& operator=(const Sudoku &other){ this->changed = other.changed; for(int i=0; i<9; i++){ for(int j=0; j<9; j++){ this->table[i][j] = other.table[i][j]; } } return *this; } /** @brief Assignment operator Redefine operator =. Allows copying between Sudoku. @param other Sudoku to copy */ Sudoku& operator=(const Sudoku *other){ if( other == nullptr ){ throw my_uninitialized_value(); } this->changed = other->changed; for(int i=0; i<9; i++){ for(int j=0; j<9; j++){ this->table[i][j] = other->table[i][j]; } } return *this; } /** @brief Set 'value' in Cell (x,y) if possible. If 'value', 'x' and 'y' are in [1,9], set 'value' in Cell (x,y). If 'x' or 'y' not in [1,9] throw out_of_range_input. If 'value' not in [1,9] throw bad_input. @param value [int] Value, in [1,9]. @param x x-coordinate, in [1,9]. @param y y-coordinate, in [1,9]. */ bool set(int value, int x, int y){ if( is_Valid_place(value, x, y) ){ table[x-1][y-1].value = value; table[x-1][y-1].flag = true; this->changed = true; //The possible values now are just 'value' delete table[x-1][y-1].possible_values; table[x-1][y-1].possible_values = new std::list <int> (1, value); return true; } else{ return false; } } /** @brief Check if the Sudoku table is changed. True if the Sudoku table was changed since the last check. */ bool is_changed(){ bool r = this->changed; if( this->changed ){ this->changed = false; } return r; } /** @brief Check if the Sudoku table is solved. True if the Sudoku table is solved, False otherwise. */ bool is_solved(){ for(int i=0; i<9; i++){ for(int j=0; j<9; j++){ if( !table[i][j].flag ){ return false; } } } return true; } /** @brief Get value in Cell (x,y) if possible. If 'x' or 'y' not in [1,9] throw out_of_range_input(). @param x x-coordinate, in [1,9]. @param y y-coordinate, in [1,9]. @throw out_of_range_input */ int get(int x, int y){ bool flag_x = x >= 1 && x <= 9; bool flag_y = y >= 1 && y <= 9; if( flag_x && flag_y ){ return table[x-1][y-1].value; } else{ throw out_of_range_input(); } } /** @brief Get flag in Cell (x,y) if possible. If 'x' or 'y' not in [1,9] throw out_of_range_input(). @param x x-coordinate, in [1,9]. @param y y-coordinate, in [1,9]. @throw out_of_range_input */ bool get_flag(int x, int y){ bool flag_x = x >= 1 && x <= 9; bool flag_y = y >= 1 && y <= 9; if( flag_x && flag_y ){ return table[x-1][y-1].flag; } else{ throw out_of_range_input(); } } /** @brief Get possible values in Cell (x,y) if possible. If 'x' or 'y' not in [1,9] throw out_of_range_input(). @param x x-coordinate, in [1,9]. @param y y-coordinate, in [1,9]. @throw out_of_range_input */ std::list<int> get_possible_values(int x, int y){ bool flag_x = x >= 1 && x <= 9; bool flag_y = y >= 1 && y <= 9; if( flag_x && flag_y ){ std::list<int> possible_values( *table[x-1][y-1].possible_values ); return possible_values; } else{ throw out_of_range_input(); } } /** @brief Simplify. Remove the impossible value from every Cells in the Sudoku table. If a possible_value is removed return 'true'. It can solve the simplest sudoku puzzles. */ bool simplify(){ bool flag_r = false; //To check if table is modified. bool flag = false; bool row = false; bool col = false; bool block = false; do{ flag = false; for(int i=1; i <= 9; i++){ row = simplify_row(i); col = simplify_col(i); if( row || col ){ flag = true; flag_r = true; } } for(int i=1; i <= 9; i+=3){ for(int j=1; j <= 9; j+=3){ block = simplify_block(i,j); if( block ){ flag = true; flag_r = true; } } } } while( flag ); return flag_r; } /** @brief Search for number that appear one time in the column, row or block. If a number is possible just in a cell so that cell is solved. */ bool one_possibility(){ bool flag_r = false; //To check if table is modified. bool flag = false; bool row = false; bool col = false; bool block = false; do{ flag = false; for(int i=1; i <= 9; i++){ row = one_possibility_row(i); col = one_possibility_col(i); if( row || col ){ flag = true; flag_r = true; } } for(int i=1; i <= 9; i+=3){ for(int j=1; j <= 9; j+=3){ block = one_possibility_block(i,j); if( block ){ flag = true; flag_r = true; } } } } while( flag ); return flag_r; } /** @brief Simplify the Sudoku. Sometimes, if the sudoku is simple it can solve it. If he modified the Sudoku table return 'true', else 'false'. */ bool pre_solver(){ if( this->is_solved() ){ return false; } bool flag = false; //To check if table is modified. bool flag_simplify = false; bool flag_one_possibility = false; size_t n_loop = 0; do{ simplify(); one_possibility(); n_loop++; } while( this->is_changed() ); if( n_loop > 1 ){ flag = true; } return flag; } /** @brief Backtracking bruteforse algorithm. Return 'true' if a solution is founded. */ bool brute_force(){ return brute_force_temp(0, 0); } /** @brief Solve the Sudoku. Return 'true' if it solve the sudoku. */ bool solve(){ if( this->is_solved() ){ return true; } this->pre_solver(); if( this->is_solved() ){ return true; } //Brute force brute_force(); return this->is_solved(); } /** @brief Print possible value of each Sudoku cell. */ void print_possible_values(){ for(int i=0; i< 9; i++){ for(int j=0; j< 9; j++){ if ( ! table[j][i].flag ){ std::cout << "(" ; for (auto const &i: *table[j][i].possible_values) { std::cout << i ; std::cout << "," ; } std::cout << ")|" ; } else{ std::cout << table[j][i].value; std::cout << "|" ; } if( (j+1) % 3 == 0 ){ std::cout << "|" ; } } if( (i+1) % 3 == 0 ){ std::cout << "\n"; std::cout << "--------------------" ; } std::cout << "\n"; } } }; /** @brief Print value of each Sudoku cell. If a cell is unknown a '?' is printed. Usefull to print with std::cout or std::ostream in general. */ std::ostream & operator << (std::ostream &out, Sudoku &srt) { for(int i=1; i<=9; i++){ for(int j=1; j<=9; j++){ if ( srt.get_flag(j,i) ){ out << srt.get(j,i); out << "|" ; } else{ out << "?|"; } if( j % 3 == 0 ){ out << " " ; } } if( i % 3 == 0 ){ out << "\n"; out << "--------------------" ; } out << "\n"; } return out; } /** @brief Print value of each Sudoku cell. If a cell is unknown a '?' is printed. Usefull to print with std::cout or std::ostream in general. */ std::ostream & operator << (std::ostream &out, Sudoku *srt) { for(int i=1; i<=9; i++){ for(int j=1; j<=9; j++){ if ( srt->get_flag(j,i) ){ out << srt->get(j,i); out << "|" ; } else{ out << "?|"; } if( j % 3 == 0 ){ out << " " ; } } if( i % 3 == 0 ){ out << "\n"; out << "--------------------" ; } out << "\n"; } return out; } #endif //SUDOKU_HPP
#ifndef CAPP_TESTS_H #define CAPP_TESTS_H #include <iostream> using namespace std; class Datas { private: int data; int datas[];//int datas[2][3]; must size for 2D array int* datas; public: Datas(){} //dup to Datas():data(1){} ?Datas():datas{1,2}{} works with size int datas[2]; Datas(int a):data(a){//the compiler will not create a default no-parameter constructor Datas():data(0){} //this->data=a;//data=a; //this->datas={0,1};//?assigning to an array from an initializer list } Datas(Datas&& other) { data=other.data;//move same as copy for int which has no move ctr other.data=0; cout << data <<"move ctr" << other.data << endl; } Datas& operator=(Datas&& other) { //if(this!=&other) //need to explicitly define != as well { data=other.data; other.data=0; cout << data <<"move assign" << other.data << endl; } return *this; } void proc(int* a){ return; }//no ; };//end with ; #endif //CAPP_TESTS_H
#include<stdio.h> #include<conio.h> #include<graphics.h> #include<dos.h> void floodfill4(int x,int y,int fillcolor,int oldcolor) { if(getpixel(x,y) == oldcolor) { setcolor(fillcolor); putpixel(x,y,fillcolor); delay(5); floodfill4(x+1,y,fillcolor,oldcolor); floodfill4(x-1,y,fillcolor,oldcolor); floodfill4(x,y+1,fillcolor,oldcolor); floodfill4(x,y-1,fillcolor,oldcolor); } } void draw_rectangle() { setcolor(15); rectangle(250,215,315,260); floodfill4(280,250,6,0); setcolor(RED); outtextxy(250,270,"RECTANGLE"); } void draw_triangle() { setcolor(15); line(140,250,90,310); line(140,250,200,310); line(90,310,200,310); floodfill4(140,290,5,0); setcolor(RED); outtextxy(110,320,"TRIANGLE"); } void draw_circle() { setcolor(15); circle(250,250,30); floodfill4(250,250,3,0); setcolor(RED); outtextxy(230,290,"CIRCLE"); } void main() { int gd=DETECT,gm,choice,run; do { initgraph(&gd,&gm,"C:\\TURBOC3\\BGI"); setcolor(YELLOW); outtextxy(250,20,"*** FLOOD FILL ALGORITHM ***"); printf(" \n\n\n\n"); printf("[1] TO FIIL A RECTANGLE\n"); printf("[2] TO FILL A CIRCLE\n"); printf("[3] TO FILL A TRIANGLE\n"); printf(" \n\n"); printf("ENTER YOUR CHOICE ==> "); scanf("%d",&choice); switch(choice) { case 1:draw_rectangle(); break; case 2:draw_triangle(); break; case 3:draw_circle(); break; default:printf(" \n\n\n SHAPE NOT AVAILABLE !!!"); break; } getch(); closegraph(); printf("PRESS [1] TO DRAW AGAIN OR [0] TO EXIT ==> "); scanf("%d",&run); }while(run == 1); }
/******************************************************************************* gaussianVolume.cpp - Shape-it Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, and the Shape-it contributors This file is part of Shape-it. 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. Shape-it can be linked against either OpenBabel version 3 or the RDKit. OpenBabel 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 version 2 of the License. ***********************************************************************/ #include <gaussianVolume.h> #ifndef USE_RDKIT // OpenBabel #include <openbabel/atom.h> #include <openbabel/data.h> #include <openbabel/elements.h> #include <openbabel/mol.h> #else #include <GraphMol/PeriodicTable.h> #include <GraphMol/ROMol.h> #endif // OpenBabel GaussianVolume::GaussianVolume() : volume(0.0), overlap(0.0), centroid(0.0, 0.0, 0.0), rotation(3, 3, 0.0), gaussians(), childOverlaps(), levels() {} GaussianVolume::~GaussianVolume() = default; double GAlpha(unsigned int an) { switch (an) { case 1: ///< H return 1.679158285; break; case 3: ///< Li return 0.729980658; break; case 5: ///< B return 0.604496983; break; case 6: ///< C return 0.836674025; break; case 7: ///< N return 1.006446589; break; case 8: ///< O return 1.046566798; break; case 9: ///< F return 1.118972618; break; case 11: ///< Na return 0.469247983; break; case 12: ///< Mg return 0.807908026; break; case 14: ///< Si return 0.548296583; break; case 15: ///< P return 0.746292571; break; case 16: ///< S return 0.746292571; break; case 17: ///< Cl return 0.789547080; break; case 19: ///< K return 0.319733941; break; case 20: ///< Ca return 0.604496983; break; case 26: ///< Fe return 1.998337133; break; case 29: ///< Cu return 1.233667312; break; case 30: ///< Zn return 1.251481772; break; case 35: ///< Br return 0.706497569; break; case 53: ///< I return 0.616770720; break; default: ///< * return 1.074661303; } return 1.074661303; }; namespace { #ifndef USE_RDKIT unsigned int initFromMol(const Molecule &mol, GaussianVolume &gv) { // Prepare the vector to store the atom and overlap volumes; unsigned int N = 0; for (unsigned int i = 1; i <= mol.NumAtoms(); ++i) { const OpenBabel::OBAtom *a = mol.GetAtom(i); if (a->GetAtomicNum() == 1) { continue; } else { ++N; } } gv.gaussians.resize(N); gv.childOverlaps.resize(N); gv.levels.push_back(N); // first level gv.volume = 0.0; gv.centroid.x = 0; gv.centroid.y = 0; gv.centroid.z = 0; int atomIndex = 0; // keeps track of the atoms processed so far int vecIndex = N; // keeps track of the last element added to the vectors for (unsigned int i = 1; i <= mol.NumAtoms(); ++i) { const OpenBabel::OBAtom *a = mol.GetAtom(i); // Skip hydrogens if (a->GetAtomicNum() == 1) { continue; } // First atom append self to the list // Store it at [index] gv.gaussians[atomIndex].center.x = a->GetX(); gv.gaussians[atomIndex].center.y = a->GetY(); gv.gaussians[atomIndex].center.z = a->GetZ(); gv.gaussians[atomIndex].alpha = GAlpha(a->GetAtomicNum()); gv.gaussians[atomIndex].C = GCI; double radius = OpenBabel::OBElements::GetVdwRad(a->GetAtomicNum()); gv.gaussians[atomIndex].volume = (4.0 * PI / 3.0) * radius * radius * radius; ++atomIndex; } return N; } #else unsigned int initFromMol(const Molecule &mol, GaussianVolume &gv) { // Prepare the vector to store the atom and overlap volumes; unsigned int N = 0; for (const auto a : mol.atoms()) { if (a->getAtomicNum() != 1) { ++N; } } gv.gaussians.resize(N); gv.childOverlaps.resize(N); gv.levels.push_back(N); // first level gv.volume = 0.0; gv.centroid.x = 0; gv.centroid.y = 0; gv.centroid.z = 0; int atomIndex = 0; // keeps track of the atoms processed so far int vecIndex = N; // keeps track of the last element added to the vectors const auto &conf = mol.getConformer(); for (const auto a : mol.atoms()) { // Skip hydrogens if (a->getAtomicNum() == 1) { continue; } // First atom append self to the list // Store it at [index] const auto &p = conf.getAtomPos(a->getIdx()); gv.gaussians[atomIndex].center.x = p.x; gv.gaussians[atomIndex].center.y = p.y; gv.gaussians[atomIndex].center.z = p.z; gv.gaussians[atomIndex].alpha = GAlpha(a->getAtomicNum()); gv.gaussians[atomIndex].C = GCI; // double radius = et.GetVdwRad(a->GetAtomicNum()); double radius = RDKit::PeriodicTable::getTable()->getRvdw(a->getAtomicNum()); gv.gaussians[atomIndex].volume = (4.0 * PI / 3.0) * radius * radius * radius; ++atomIndex; } return N; } #endif } // namespace void listAtomVolumes(const Molecule &mol, GaussianVolume &gv) { // Prepare the vector to store the atom and overlap volumes; unsigned int N = initFromMol(mol, gv); // Vector to keep track of parents of an overlap std::vector<std::pair<unsigned int, unsigned int>> parents(N); // Create a vector to keep track of the overlaps // Overlaps are stored as sets std::vector<std::set<unsigned int> *> overlaps(N); // Start by iterating over the single atoms and build map of overlaps int vecIndex = N; // keeps track of the last element added to the vectors for (unsigned int atomIndex = 0; atomIndex < N; ++atomIndex) { // Add empty child overlaps auto *vec = new std::vector<unsigned int>(); gv.childOverlaps[atomIndex] = vec; // Update volume and centroid gv.volume += gv.gaussians[atomIndex].volume; gv.centroid.x += gv.gaussians[atomIndex].volume * gv.gaussians[atomIndex].center.x; gv.centroid.y += gv.gaussians[atomIndex].volume * gv.gaussians[atomIndex].center.y; gv.centroid.z += gv.gaussians[atomIndex].volume * gv.gaussians[atomIndex].center.z; // Add new empty set of possible overlaps auto *tmp = new std::set<unsigned int>(); overlaps[atomIndex] = tmp; // Loop over the current list of processed atoms and add overlaps for (int i = 0; i < atomIndex; ++i) { // Create overlap gaussian AtomGaussian ga = atomIntersection(gv.gaussians[i], gv.gaussians[atomIndex]); // Check if the atom-atom overlap volume is large enough if (ga.volume / (gv.gaussians[i].volume + gv.gaussians[atomIndex].volume - ga.volume) < EPS) { continue; } // Add gaussian volume, and empty overlap set gv.gaussians.push_back(ga); auto *vec = new std::vector<unsigned int>(); gv.childOverlaps.push_back(vec); // Update local variables of parents and possible overlaps parents.emplace_back(i, atomIndex); auto *dummy = new std::set<unsigned int>(); overlaps.push_back(dummy); // Update volume and centroid (negative contribution of atom-atom overlap) gv.volume -= ga.volume; gv.centroid.x -= ga.volume * ga.center.x; gv.centroid.y -= ga.volume * ga.center.y; gv.centroid.z -= ga.volume * ga.center.z; // Update overlap information of the parent atom overlaps[i]->insert(atomIndex); gv.childOverlaps[i]->push_back(vecIndex); // Move to next index in vector ++vecIndex; } } // Position in list of gaussians where atom gaussians end unsigned int startLevel = N; unsigned int nextLevel = gv.gaussians.size(); // Update level information gv.levels.push_back(nextLevel); // Loop overall possible levels of overlaps from 2 to 6 for (unsigned int l = 2; l < LEVEL; ++l) { // List of atom-atom overlaps is made => gv.gaussians[startLevel .. // nextLevel-1]; Now update the overlap lists for each overlap in this level // Create the next overlap Gaussian // And add it to the vector of overlaps for (unsigned int i = startLevel; i < nextLevel; ++i) { // Parent indices unsigned int a1 = parents[i].first; unsigned int a2 = parents[i].second; // Append volume to end of overlap vector // Add new empty set std::set<unsigned int> *tmp = overlaps[i]; std::set_intersection( overlaps[a1]->begin(), overlaps[a1]->end(), overlaps[a2]->begin(), overlaps[a2]->end(), std::insert_iterator<std::set<unsigned int>>(*tmp, tmp->begin())); // Check if the overlap list is empty if (overlaps[i]->empty()) { continue; } // Get the possible overlaps from the parent gaussians // and create the new overlap volume for (auto overlapIdx : *overlaps[i]) { if (overlapIdx <= a2) { continue; } // Create a new overlap gaussian AtomGaussian ga = atomIntersection(gv.gaussians[i], gv.gaussians[overlapIdx]); // Check if the volume is large enough if (ga.volume / (gv.gaussians[i].volume + gv.gaussians[overlapIdx].volume - ga.volume) < EPS) { continue; } gv.gaussians.push_back(ga); auto *vec = new std::vector<unsigned int>(); gv.childOverlaps.push_back(vec); // Update local variables parents.emplace_back(i, overlapIdx); auto *tmp = new std::set<unsigned int>(); overlaps.push_back(tmp); // Update volume, centroid and moments // Overlaps consisting of an even number of atoms have a negative // contribution if ((ga.nbr % 2) == 0) { // Update volume and centroid gv.volume -= ga.volume; gv.centroid.x -= ga.volume * ga.center.x; gv.centroid.y -= ga.volume * ga.center.y; gv.centroid.z -= ga.volume * ga.center.z; } else { // Update volume and centroid gv.volume += ga.volume; gv.centroid.x += ga.volume * ga.center.x; gv.centroid.y += ga.volume * ga.center.y; gv.centroid.z += ga.volume * ga.center.z; } // Update child list of the first gv.childOverlaps[i]->push_back(vecIndex); // Move to next index in vector ++vecIndex; } } // Update levels startLevel = nextLevel; nextLevel = gv.gaussians.size(); // Update level information gv.levels.push_back(nextLevel); } // cleanup current set of computed overlaps for (auto &overlap : overlaps) { delete overlap; overlap = nullptr; } parents.clear(); // Update self-overlap gv.overlap = atomOverlap(gv, gv); return; } void initOrientation(GaussianVolume &gv) { double x(0.0), y(0.0), z(0.0); // Scale centroid and moments with self volume gv.centroid.x /= gv.volume; gv.centroid.y /= gv.volume; gv.centroid.z /= gv.volume; // Compute moments of inertia from mass matrix SiMath::Matrix mass(3, 3, 0.0); // Loop over all gaussians for (auto &g : gv.gaussians) { // Translate to center g.center.x -= gv.centroid.x; g.center.y -= gv.centroid.y; g.center.z -= gv.centroid.z; x = g.center.x; y = g.center.y; z = g.center.z; if ((g.nbr % 2) == 0) { // Update upper triangle mass[0][0] -= g.volume * x * x; mass[0][1] -= g.volume * x * y; mass[0][2] -= g.volume * x * z; mass[1][1] -= g.volume * y * y; mass[1][2] -= g.volume * y * z; mass[2][2] -= g.volume * z * z; } else { // Update upper triangle mass[0][0] += g.volume * x * x; mass[0][1] += g.volume * x * y; mass[0][2] += g.volume * x * z; mass[1][1] += g.volume * y * y; mass[1][2] += g.volume * y * z; mass[2][2] += g.volume * z * z; } } // Set lower triangle mass[1][0] = mass[0][1]; mass[2][0] = mass[0][2]; mass[2][1] = mass[1][2]; // Normalize mass matrix mass /= gv.volume; // Compute SVD of the mass matrix SiMath::SVD svd(mass, true, true); gv.rotation = svd.getU(); double det = gv.rotation[0][0] * gv.rotation[1][1] * gv.rotation[2][2] + gv.rotation[2][1] * gv.rotation[1][0] * gv.rotation[0][2] + gv.rotation[0][1] * gv.rotation[1][2] * gv.rotation[2][0] - gv.rotation[0][0] * gv.rotation[1][2] * gv.rotation[2][1] - gv.rotation[1][1] * gv.rotation[2][0] * gv.rotation[0][2] - gv.rotation[2][2] * gv.rotation[0][1] * gv.rotation[1][0]; // Check if it is a rotation matrix and not a mirroring if (det < 0) { // Switch sign of third column gv.rotation[0][2] = -gv.rotation[0][2]; gv.rotation[1][2] = -gv.rotation[1][2]; gv.rotation[2][2] = -gv.rotation[2][2]; } // Rotate all gaussians for (auto &g : gv.gaussians) { x = g.center.x; y = g.center.y; z = g.center.z; g.center.x = gv.rotation[0][0] * x + gv.rotation[1][0] * y + gv.rotation[2][0] * z; g.center.y = gv.rotation[0][1] * x + gv.rotation[1][1] * y + gv.rotation[2][1] * z; g.center.z = gv.rotation[0][2] * x + gv.rotation[1][2] * y + gv.rotation[2][2] * z; } return; } double atomOverlap(const GaussianVolume &gRef, const GaussianVolume &gDb) { // Create a queue to hold the pairs to process std::queue<std::pair<unsigned int, unsigned int>> processQueue; // loop over the single atom volumes of both molecules and make the // combinations unsigned int N1(gRef.levels[0]); unsigned int N2(gDb.levels[0]); double Cij(0.0), Vij(0.0); double dx(0.0), dy(0.0), dz(0.0); std::vector<unsigned int> *d1(nullptr), *d2(nullptr); std::vector<unsigned int>::iterator it1; // Overlap volume double overlapVol(0.0); // First compute atom-atom overlaps for (unsigned int i(0); i < N1; ++i) { for (unsigned int j(0); j < N2; ++j) { // Scaling constant Cij = gRef.gaussians[i].alpha * gDb.gaussians[j].alpha / (gRef.gaussians[i].alpha + gDb.gaussians[j].alpha); // Variables to store sum and difference of components dx = (gRef.gaussians[i].center.x - gDb.gaussians[j].center.x); dx *= dx; dy = (gRef.gaussians[i].center.y - gDb.gaussians[j].center.y); dy *= dy; dz = (gRef.gaussians[i].center.z - gDb.gaussians[j].center.z); dz *= dz; // Compute overlap volume Vij = gRef.gaussians[i].C * gDb.gaussians[j].C * pow(PI / (gRef.gaussians[i].alpha + gDb.gaussians[j].alpha), 1.5) * exp(-Cij * (dx + dy + dz)); // Check if overlap is sufficient enough if (Vij / (gRef.gaussians[i].volume + gDb.gaussians[j].volume - Vij) < EPS) { continue; } // Add to overlap volume overlapVol += Vij; // Loop over child nodes and add to queue d1 = gRef.childOverlaps[i]; d2 = gDb.childOverlaps[j]; // First add (i,child(j)) if (d2 != nullptr) { for (it1 = d2->begin(); it1 != d2->end(); ++it1) { processQueue.push(std::make_pair(i, *it1)); } } // Second add (child(i,j)) if (d1 != nullptr) { for (it1 = d1->begin(); it1 != d1->end(); ++it1) { // add (child(i),j) processQueue.push(std::make_pair(*it1, j)); } } } } while (!processQueue.empty()) { // Get next element from queue std::pair<unsigned int, unsigned int> nextPair = processQueue.front(); processQueue.pop(); unsigned int i = nextPair.first; unsigned int j = nextPair.second; // Scaling constant Cij = gRef.gaussians[i].alpha * gDb.gaussians[j].alpha / (gRef.gaussians[i].alpha + gDb.gaussians[j].alpha); // Variables to store sum and difference of components dx = (gRef.gaussians[i].center.x - gDb.gaussians[j].center.x); dx *= dx; dy = (gRef.gaussians[i].center.y - gDb.gaussians[j].center.y); dy *= dy; dz = (gRef.gaussians[i].center.z - gDb.gaussians[j].center.z); dz *= dz; // Compute overlap volume Vij = gRef.gaussians[i].C * gDb.gaussians[j].C * pow(PI / (gRef.gaussians[i].alpha + gDb.gaussians[j].alpha), 1.5) * exp(-Cij * (dx + dy + dz)); // Check if overlap is sufficient enough if (Vij / (gRef.gaussians[i].volume + gDb.gaussians[j].volume - Vij) < EPS) { continue; } // Even number of overlap atoms => addition to volume // Odd number => substraction if ((gRef.gaussians[i].nbr + gDb.gaussians[j].nbr) % 2 == 0) { overlapVol += Vij; } else { overlapVol -= Vij; } // Loop over child nodes and add to queue d1 = gRef.childOverlaps[i]; d2 = gDb.childOverlaps[j]; if (d1 != nullptr && gRef.gaussians[i].nbr > gDb.gaussians[j].nbr) { for (it1 = d1->begin(); it1 != d1->end(); ++it1) { // Add (child(i),j) processQueue.push(std::make_pair(*it1, j)); } } else { // First add (i,child(j)) if (d2 != nullptr) { for (it1 = d2->begin(); it1 != d2->end(); ++it1) { processQueue.push(std::make_pair(i, *it1)); } } if (d1 != nullptr && gDb.gaussians[j].nbr - gRef.gaussians[i].nbr < 2) { for (it1 = d1->begin(); it1 != d1->end(); ++it1) { // add (child(i),j) processQueue.push(std::make_pair(*it1, j)); } } } } return overlapVol; } double getScore(const std::string &id, double Voa, double Vra, double Vda) { // set the score by which molecules are being compared if (id == tanimoto) { return Voa / (Vra + Vda - Voa); } else if (id == tversky_ref) { return Voa / (0.95 * Vra + 0.05 * Vda); } else if (id == tversky_db) { return Voa / (0.05 * Vra + 0.95 * Vda); } return 0.0; } void checkVolumes(const GaussianVolume &gRef, const GaussianVolume &gDb, AlignmentInfo &res) { if (res.overlap > gRef.overlap) { res.overlap = gRef.overlap; } if (res.overlap > gDb.overlap) { res.overlap = gDb.overlap; } return; }
#pragma once #ifndef IMAGIO_GL_PROGRAM_H #define IMAGIO_GL_PROGRAM_H #include <GL/gl3w.h> #include <GL/gl.h> #include <stddef.h> #include <string> #include <vector> namespace wimgui { namespace gl_program { class gl_program { private: GLuint vertex_shader_id; std::string vertex_shader; GLuint fragment_shader_id; std::string fragment_shader; GLuint program_id; public: gl_program() { set_vertex_shader_code( std::string(R"glsl( #version 330 core layout(location=0) in vec3 position; layout(location=1) in vec3 normal; out vec4 fragment_color; out vec3 fragment_position; out vec3 fragment_normal; uniform mat4 view_matrix; void main() { gl_Position = view_matrix * vec4(position, 1.0); fragment_color = vec4(0.4, 0.3, 0.6, 1.0); fragment_position = vec3(gl_Position); fragment_normal = vec3(view_matrix * vec4(normal, 1.0)); } )glsl") ); set_fragment_shader_code( std::string(R"gsls( #version 330 core in vec4 fragment_color; in vec3 fragment_position; in vec3 fragment_normal; uniform mat4 view_matrix; out vec4 out_color; uniform struct Light { vec3 position; vec3 color; }; void main() { if (gl_FrontFacing == false) { return; } Light light = Light(vec3(0.0, 0.0, -2.0), vec3(1.0, 1.0, 1.0)); float ambient_strength = 0.5; vec3 ambient = ambient_strength * light.color; vec3 normal = normalize(fragment_normal); vec3 light_direction = normalize(light.position - fragment_position); float diff = max(dot(normal, light_direction), 0); vec3 diffuse = diff * light.color; out_color = vec4((ambient + diffuse) * vec3(fragment_color), fragment_color[3]); // out_color = vec4(diffuse * vec3(fragment_color), fragment_color[3]); } )gsls") ); } GLuint get_id() { return program_id; } std::string load_shader(std::string& path) { std::ifstream input_stream(path); std::string result( (std::istreambuf_iterator<char>(input_stream)), std::istreambuf_iterator<char>() ); return result; } std::string get_vertex_shader_code() { return vertex_shader; } void set_vertex_shader_code(const std::string& new_vertex_shader) { vertex_shader = new_vertex_shader; } void load_vertex_shader(std::string& path) { vertex_shader = load_shader(path); } std::string get_fragment_shader_code() { return fragment_shader; } void set_fragment_shader_code(const std::string& new_fragment_shader) { fragment_shader = new_fragment_shader; } void load_fragment_shader(std::string& path) { vertex_shader = load_shader(path); } GLuint compile() { GLint compilation_result = GL_FALSE; int compilation_result_length; vertex_shader_id = glCreateShader(GL_VERTEX_SHADER); const char * vertex_shader_pointer = vertex_shader.c_str(); glShaderSource(vertex_shader_id, 1, &vertex_shader_pointer, NULL); glCompileShader(vertex_shader_id); glGetShaderiv(vertex_shader_id, GL_COMPILE_STATUS, &compilation_result); glGetShaderiv(vertex_shader_id, GL_INFO_LOG_LENGTH, &compilation_result_length); if(compilation_result_length > 0) { std::vector<char> error_message(compilation_result_length + 1); glGetShaderInfoLog(vertex_shader_id, compilation_result_length, NULL, &error_message[0]); printf("%s\n", &error_message[0]); } fragment_shader_id = glCreateShader(GL_FRAGMENT_SHADER); const char * fragment_shader_pointer = fragment_shader.c_str(); glShaderSource(fragment_shader_id, 1, &fragment_shader_pointer, NULL); glCompileShader(fragment_shader_id); glGetShaderiv(fragment_shader_id, GL_COMPILE_STATUS, &compilation_result); glGetShaderiv(fragment_shader_id, GL_INFO_LOG_LENGTH, &compilation_result_length); if(compilation_result_length > 0) { std::vector<char> error_message(compilation_result_length + 1); glGetShaderInfoLog(fragment_shader_id, compilation_result_length, NULL, &error_message[0]); printf("%s\n", &error_message[0]); } program_id = glCreateProgram(); glAttachShader(program_id, vertex_shader_id); glAttachShader(program_id, fragment_shader_id); glLinkProgram(program_id); glGetProgramiv(program_id, GL_LINK_STATUS, &compilation_result); glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &compilation_result_length); if(compilation_result_length > 0) { std::vector<char> error_message(compilation_result_length + 1); glGetProgramInfoLog(program_id, compilation_result_length, NULL, &error_message[0]); printf("%s\n", &error_message[0]); } glDetachShader(program_id, vertex_shader_id); glDetachShader(program_id, fragment_shader_id); glDeleteShader(vertex_shader_id); glDeleteShader(fragment_shader_id); return program_id; } void use() { glUseProgram(program_id); } GLuint get_attribute_location(const char* attribute_name) { return glGetAttribLocation(program_id, attribute_name); } void set_attribute_float_pointer(const char* attribute_name, int size=3, GLsizei stride=0, const GLvoid* offset=0) { set_attribute_float_pointer(get_attribute_location(attribute_name), size, stride, offset); } void set_attribute_float_pointer(GLuint attribute_position, int size=3, GLsizei stride=0, const GLvoid* offset=0) { glVertexAttribPointer(attribute_position, size, GL_FLOAT, GL_FALSE, stride, offset); } GLuint get_uniform_location(const char* uniform_name) { return glGetUniformLocation(program_id, uniform_name); } void set_uniform(const char* uniform_name, glm::mat4& value) { set_uniform(get_uniform_location(uniform_name), value); } void set_uniform(GLuint uniform_location, glm::mat4& value) { glUniformMatrix4fv(uniform_location, 1, GL_FALSE, glm::value_ptr(value)); } void set_uniform(const char* uniform_name, glm::vec4& value) { set_uniform(get_uniform_location(uniform_name), value); } void set_uniform(GLuint uniform_location, glm::vec4& value) { glUniform4fv(uniform_location, 1, glm::value_ptr(value)); } void enable_attribute_array(GLuint attribute_position) { glEnableVertexAttribArray(attribute_position); } void disable_attribute_array(GLuint attribute_position) { glDisableVertexAttribArray(attribute_position); } }; class state { private: GLint program; GLint texture; GLint active_texture; GLint array_buffer; GLint element_array_buffer; GLint vertex_array; GLint blend_src; GLint blend_dst; GLint blend_equation_rgb; GLint blend_equation_alpha; GLint viewport[4]; GLint scissor_box[4]; GLboolean enable_blend; GLboolean enable_cull_face; GLboolean enable_depth_test; GLboolean enable_scissor_test; public: void save_current_state() { glGetIntegerv(GL_CURRENT_PROGRAM, &program); glGetIntegerv(GL_TEXTURE_BINDING_2D, &texture); glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &array_buffer); glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &element_array_buffer); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &vertex_array); glGetIntegerv(GL_BLEND_SRC, &blend_src); glGetIntegerv(GL_BLEND_DST, &blend_dst); glGetIntegerv(GL_BLEND_EQUATION_RGB, &blend_equation_rgb); glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &blend_equation_alpha); glGetIntegerv(GL_VIEWPORT, viewport); glGetIntegerv(GL_SCISSOR_BOX, scissor_box); enable_blend = glIsEnabled(GL_BLEND); enable_cull_face = glIsEnabled(GL_CULL_FACE); enable_depth_test = glIsEnabled(GL_DEPTH_TEST); enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); } void restore() { glUseProgram(program); glActiveTexture(active_texture); glBindTexture(GL_TEXTURE_2D, texture); glBindVertexArray(vertex_array); glBindBuffer(GL_ARRAY_BUFFER, array_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_array_buffer); glBlendEquationSeparate(blend_equation_rgb, blend_equation_alpha); glBlendFunc(blend_src, blend_dst); if(enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND); if(enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); if(enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); if(enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); glViewport(viewport[0], viewport[1], (GLsizei)viewport[2], (GLsizei)viewport[3]); glScissor(scissor_box[0], scissor_box[1], (GLsizei)scissor_box[2], (GLsizei)scissor_box[3]); } void activate_imgui_defaults() { glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); glEnable(GL_ALPHA); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } }; }; }; #endif
#include <map> #include <string> #include <cstdio> #include "ErrorMsg.h" #include "IniFile.h" static ErrorMsg* instance = NULL; static std::map<int, std::string> err_code_msg ; static const char* no_err_msg_find="error msg"; ErrorMsg::ErrorMsg() { } ErrorMsg::~ErrorMsg() { } ErrorMsg* ErrorMsg::getInstance() { if(instance==NULL) { instance = new ErrorMsg(); instance->init(); } return instance; } const char* ErrorMsg::getErrMsg(int code) { std::map<int , std::string>::iterator it = err_code_msg.find(code); if(it == err_code_msg.end()) return no_err_msg_find; else return it->second.c_str(); } void ErrorMsg::init(const char* file) { IniFile iniFile(file); if(!iniFile.IsOpen()) { printf("Open IniFile Error:[%s]\n",file); return ; } //日志 err_code_msg[0] = iniFile.ReadString("Error", "0", ""); err_code_msg[-1] = iniFile.ReadString("Error","-1","") ; err_code_msg[-2] = iniFile.ReadString("Error","-2",""); err_code_msg[-3] = iniFile.ReadString("Error","-3",""); err_code_msg[-4] = iniFile.ReadString("Error","-4",""); err_code_msg[-5] = iniFile.ReadString("Error","-5",""); err_code_msg[-6] = iniFile.ReadString("Error","-6",""); err_code_msg[-7] = iniFile.ReadString("Error","-7",""); err_code_msg[-8] = iniFile.ReadString("Error","-8",""); err_code_msg[-9] = iniFile.ReadString("Error","-9",""); err_code_msg[-10] = iniFile.ReadString("Error","-10",""); err_code_msg[-11] = iniFile.ReadString("Error","-11",""); err_code_msg[-12] = iniFile.ReadString("Error","-12",""); err_code_msg[-13] = iniFile.ReadString("Error","-13",""); err_code_msg[-14] = iniFile.ReadString("Error","-14",""); err_code_msg[-15] = iniFile.ReadString("Error","-15",""); err_code_msg[-16] = iniFile.ReadString("Error","-16",""); err_code_msg[-17] = iniFile.ReadString("Error","-17",""); err_code_msg[-18] = iniFile.ReadString("Error","-18",""); err_code_msg[-19] = iniFile.ReadString("Error","-19",""); err_code_msg[-20] = iniFile.ReadString("Error","-20",""); err_code_msg[-21] = iniFile.ReadString("Error","-21",""); err_code_msg[-22] = iniFile.ReadString("Error","-22",""); err_code_msg[-23] = iniFile.ReadString("Error","-23",""); err_code_msg[-24] = iniFile.ReadString("Error","-24",""); err_code_msg[-25] = iniFile.ReadString("Error","-25",""); err_code_msg[-26] = iniFile.ReadString("Error","-26",""); err_code_msg[-27] = iniFile.ReadString("Error","-27",""); err_code_msg[-28] = iniFile.ReadString("Error","-28",""); err_code_msg[-29] = iniFile.ReadString("Error","-29",""); err_code_msg[-30] = iniFile.ReadString("Error","-30",""); err_code_msg[-31] = iniFile.ReadString("Error", "-31", ""); err_code_msg[-32] = iniFile.ReadString("Error", "-32", ""); err_code_msg[-33] = iniFile.ReadString("Error", "-33", ""); err_code_msg[-34] = iniFile.ReadString("Error", "-34", ""); err_code_msg[-35] = iniFile.ReadString("Error", "-35", ""); err_code_msg[-36] = iniFile.ReadString("Error", "-36", ""); err_code_msg[-37] = iniFile.ReadString("Error", "-37", ""); err_code_msg[-38] = iniFile.ReadString("Error", "-38", ""); err_code_msg[-39] = iniFile.ReadString("Error", "-39", ""); err_code_msg[1] = iniFile.ReadString("Error","1","") ; err_code_msg[2] = iniFile.ReadString("Error","2",""); err_code_msg[3] = iniFile.ReadString("Error","3",""); err_code_msg[4] = iniFile.ReadString("Error","4",""); err_code_msg[5] = iniFile.ReadString("Error","5",""); err_code_msg[6] = iniFile.ReadString("Error","6",""); err_code_msg[7] = iniFile.ReadString("Error","7",""); err_code_msg[8] = iniFile.ReadString("Error","8",""); err_code_msg[9] = iniFile.ReadString("Error","9",""); err_code_msg[10] = iniFile.ReadString("Error","10",""); } void ErrorMsg::initFromBuf(const char *pErrMsg) { IniFile iniFile; if (!iniFile.ParseBuffer(pErrMsg)) { printf("Parse Ini Buffer Error\n"); return; } //日志 err_code_msg[0] = iniFile.ReadString("Error", "0", ""); err_code_msg[-1] = iniFile.ReadString("Error", "-1", ""); err_code_msg[-2] = iniFile.ReadString("Error", "-2", ""); err_code_msg[-3] = iniFile.ReadString("Error", "-3", ""); err_code_msg[-4] = iniFile.ReadString("Error", "-4", ""); err_code_msg[-5] = iniFile.ReadString("Error", "-5", ""); err_code_msg[-6] = iniFile.ReadString("Error", "-6", ""); err_code_msg[-7] = iniFile.ReadString("Error", "-7", ""); err_code_msg[-8] = iniFile.ReadString("Error", "-8", ""); err_code_msg[-9] = iniFile.ReadString("Error", "-9", ""); err_code_msg[-10] = iniFile.ReadString("Error", "-10", ""); err_code_msg[-11] = iniFile.ReadString("Error", "-11", ""); err_code_msg[-12] = iniFile.ReadString("Error", "-12", ""); err_code_msg[-13] = iniFile.ReadString("Error", "-13", ""); err_code_msg[-14] = iniFile.ReadString("Error", "-14", ""); err_code_msg[-15] = iniFile.ReadString("Error", "-15", ""); err_code_msg[-16] = iniFile.ReadString("Error", "-16", ""); err_code_msg[-17] = iniFile.ReadString("Error", "-17", ""); err_code_msg[-18] = iniFile.ReadString("Error", "-18", ""); err_code_msg[-19] = iniFile.ReadString("Error", "-19", ""); err_code_msg[-20] = iniFile.ReadString("Error", "-20", ""); err_code_msg[-21] = iniFile.ReadString("Error", "-21", ""); err_code_msg[-22] = iniFile.ReadString("Error", "-22", ""); err_code_msg[-23] = iniFile.ReadString("Error", "-23", ""); err_code_msg[-24] = iniFile.ReadString("Error", "-24", ""); err_code_msg[-25] = iniFile.ReadString("Error", "-25", ""); err_code_msg[-26] = iniFile.ReadString("Error", "-26", ""); err_code_msg[-27] = iniFile.ReadString("Error", "-27", ""); err_code_msg[-28] = iniFile.ReadString("Error", "-28", ""); err_code_msg[-29] = iniFile.ReadString("Error", "-29", ""); err_code_msg[-30] = iniFile.ReadString("Error", "-30", ""); err_code_msg[-31] = iniFile.ReadString("Error", "-31", ""); err_code_msg[-32] = iniFile.ReadString("Error", "-32", ""); err_code_msg[-33] = iniFile.ReadString("Error", "-33", ""); err_code_msg[-34] = iniFile.ReadString("Error", "-34", ""); err_code_msg[-35] = iniFile.ReadString("Error", "-35", ""); err_code_msg[-36] = iniFile.ReadString("Error", "-36", ""); err_code_msg[-37] = iniFile.ReadString("Error", "-37", ""); err_code_msg[-38] = iniFile.ReadString("Error", "-38", ""); err_code_msg[-39] = iniFile.ReadString("Error", "-39", ""); err_code_msg[1] = iniFile.ReadString("Error", "1", ""); err_code_msg[2] = iniFile.ReadString("Error", "2", ""); err_code_msg[3] = iniFile.ReadString("Error", "3", ""); err_code_msg[4] = iniFile.ReadString("Error", "4", ""); err_code_msg[5] = iniFile.ReadString("Error", "5", ""); err_code_msg[6] = iniFile.ReadString("Error", "6", ""); err_code_msg[7] = iniFile.ReadString("Error", "7", ""); err_code_msg[8] = iniFile.ReadString("Error", "8", ""); err_code_msg[9] = iniFile.ReadString("Error", "9", ""); err_code_msg[10] = iniFile.ReadString("Error", "10", ""); }
#include "EnemyTank.h" #include "cocostudio/CocoStudio.h" #include "GameManager.h" using namespace cocos2d; EnemyTank* EnemyTank::create() { EnemyTank* myNode = new EnemyTank(); if (myNode->init()) { myNode->autorelease(); return myNode; } else { CC_SAFE_DELETE(myNode); return nullptr; } return myNode; } bool EnemyTank::init() { if (!Node::init()) { return false; } //Load this object in from cocos studio. auto rootNode = CSLoader::createNode("res/EnemyTank.csb"); addChild(rootNode); auto winSize = Director::getInstance()->getVisibleSize(); this->setAnchorPoint(Vec2(1.0f, 0.0f)); this->setPosition(Vec2(0.0f, winSize.height*0.25)); this->scheduleUpdate(); Enemy_Tank = (Sprite*)rootNode->getChildByName("enemyTank"); startXPosition = 1190.0f; startYPosition = Enemy_Tank->getPositionY(); Enemy_Tank->setPosition(startXPosition, startYPosition); currentSpeed = 814.0f; return true; } EnemyTank::EnemyTank() { } EnemyTank::~EnemyTank() { } void EnemyTank::update(float deltaTime) { if (GameManager::sharedGameManager()->isGameLive) { //Get the window size. auto winSize = Director::getInstance()->getVisibleSize(); //Move the pipes to the left. Vec2 currentTankPos = Enemy_Tank->getPosition(); Enemy_Tank->setPosition(currentTankPos.x - currentSpeed*deltaTime, currentTankPos.y); //Did the x position (incorporating the sprite width) go off screen. if (currentTankPos.x < -Enemy_Tank->getBoundingBox().size.width*0.5f) { //Set the new positionings. Enemy_Tank->setPosition(startXPosition, startYPosition); } } } bool EnemyTank::hasCollidedWithAEnemyTank(Rect collisionBoxToCheck) { Rect modifiedEnemyTank; modifiedEnemyTank.size = Enemy_Tank->getBoundingBox().size; modifiedEnemyTank.origin = convertToWorldSpaceAR(Enemy_Tank->getBoundingBox().origin); if (modifiedEnemyTank.intersectsRect(collisionBoxToCheck)) { return true; } return false; } void EnemyTank::reset() { Enemy_Tank->setPosition(startXPosition, startYPosition); }
/* XMRig * Copyright (c) 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright (c) 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef XMRIG_IJSONREADER_H #define XMRIG_IJSONREADER_H #include "3rdparty/rapidjson/fwd.h" #include "base/tools/Object.h" #include "base/tools/String.h" namespace xmrig { class IJsonReader { public: XMRIG_DISABLE_COPY_MOVE(IJsonReader) IJsonReader() = default; virtual ~IJsonReader() = default; virtual bool getBool(const char *key, bool defaultValue = false) const = 0; virtual bool isEmpty() const = 0; virtual const char *getString(const char *key, const char *defaultValue = nullptr) const = 0; virtual const rapidjson::Value &getArray(const char *key) const = 0; virtual const rapidjson::Value &getObject(const char *key) const = 0; virtual const rapidjson::Value &getValue(const char *key) const = 0; virtual const rapidjson::Value &object() const = 0; virtual double getDouble(const char *key, double defaultValue = 0) const = 0; virtual int getInt(const char *key, int defaultValue = 0) const = 0; virtual int64_t getInt64(const char *key, int64_t defaultValue = 0) const = 0; virtual String getString(const char *key, size_t maxSize) const = 0; virtual uint64_t getUint64(const char *key, uint64_t defaultValue = 0) const = 0; virtual unsigned getUint(const char *key, unsigned defaultValue = 0) const = 0; }; } /* namespace xmrig */ #endif // XMRIG_IJSONREADER_H
#include<bits/stdc++.h> using namespace std; int main(){ int candies[5]={2,3,5,1,3}; int extra =3; int max =0; for(int i=0;i<5;i++){ if(candies[i]>max) max=candies[i]; } for(int j=0;j<5;j++){ if((candies[j]+extra)>=max){ cout<<"TRUE,"; } else{ cout<<"FALSE,"; } } return 0; }
#include<cstdio> #include<cstring> #include<algorithm> #include<vector> #define fe(e,x) for(__typeof(x.begin()) e=x.begin(); e!=x.end(); e++) using namespace std; const int maxn=111111, inf=~0U>>1; vector<int> E[maxn]; int n, l, f[maxn][2], fa[maxn], now_alpha, own[maxn][26], leaf[maxn]; void dfs(int x) {fe(e,E[x]) if(*e!=fa[x]) fa[*e]=x, dfs(*e); } void DP(int x) { if(leaf[x]) return; fe(e,E[x]) { if(*e==fa[x]) continue; DP(*e); if(leaf[*e]) { f[x][0] += (own[*e][now_alpha]==0); f[x][1] += (own[*e][now_alpha]==1); } else { f[x][0] += min(f[*e][0], f[*e][1] + 1); f[x][1] += min(f[*e][1], f[*e][0] + 1); } } } int main(){ scanf("%d %d",&n, &l); for(int i=1; i<n; i++) { int u,v; scanf("%d %d", &u, &v); E[u].push_back(v); E[v].push_back(u); } int x; char s[50]; for(int i=1; i<=l; i++) { scanf("%d %s", &x, s); leaf[x]=1; for(int j=0; j<strlen(s); j++) if(s[j]!='$') own[x][s[j]-'A']=1; } int ans=0; if(n==2) { for(int i=0; i<26; i++) ans+=( own[1][i]^own[2][i]); printf("%d\n", ans); return 0; } int rt=1; while(leaf[rt]) rt++; dfs(rt); for(int i=0; i<26; i++) { memset(f,0,sizeof f); now_alpha=i, DP(rt); ans+= min(f[rt][0], f[rt][1]); } printf("%d\n", ans); return 0; }
/* 这部分内存池实现来自于https://github.com/cacay/MemoryPool/blob/master/C-11/MemoryPool.h * 此处是拿来分析 */ #ifndef __SRC_UTILS_MEMPOLL_H__ #define __SRC_UTILS_MEMPOLL_H__ #include <climits> #include <cstddef> template <typename T, size_t BlockSize = 4096> class MemoryPool { public: /* Member types */ typedef T value_type; typedef T *pointer; typedef T &reference; typedef const T *const_pointer; typedef const T &const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef std::false_type propagate_on_container_copy_assignment; typedef std::true_type propagate_on_container_move_assignment; typedef std::true_type propagate_on_container_swap; template <typename U> struct rebind { typedef MemoryPool<U> other; }; public: MemoryPool() noexcept; MemoryPool(const MemoryPool &memoryPool) noexcept; MemoryPool(MemoryPool &&memoryPool) noexcept; template <class U> MemoryPool(const MemoryPool<U> &memoryPool) noexcept; ~MemoryPool() noexcept; MemoryPool &operator=(const MemoryPool &memoryPool) = delete; MemoryPool &operator=(MemoryPool &&memoryPool) noexcept; pointer address(reference x) const noexcept; const_pointer address(const_reference x) const noexcept; pointer allocate(size_type n = 1, const_pointer hint = 0); void deallocate(pointer p, size_type n = 1); size_type max_size() const noexcept; template <class U, class... Args> void construct(U *p, Args &&... args); template <class U> void destroy(U *p); template <class... Args> pointer newElement(Args &&... args); void deleteElement(pointer p); private: union Slot_ { value_type element; Slot_ * next; }; typedef char * data_pointer_; typedef Slot_ slot_type_; typedef Slot_ * slot_pointer_; slot_pointer_ currentBlock_; slot_pointer_ currentSlot_; slot_pointer_ lastSlot_; slot_pointer_ freeSlots_; size_type padPointer(data_pointer_ p, size_type align) const noexcept; void allocateBlock(); static_assert(BlockSize >= 2 * sizeof(slot_type_), "BlockSize too small."); }; #include "mempool.cc" #endif
#pragma once #include "view.hpp" #include <vector> using std::vector; struct ViewStack : View { virtual void render(Graphics& g, render_box const& pos) override; virtual void handle_keypress(KeyboardKey ks) override; void push(View*); void pop(); void reset(); vector<View*> vstack; };
#include<bits/stdc++.h> #include<iostream> #include<vector> #include<cmath> using namespace std; bitset<16>used; int n; vector<int>output; int isprime(int i) { int j; int s=sqrt(i); for(j=2;j<=s;j++) if(i%j==0)break; if(j==s+1)return 1; else return 0; } void backtrack (int i) { if((used==((1<<n)-1))&&output[n-1]%2==0) { if(isprime(output[n-1]+1)){ cout<<output[0]<<" "; for(int k=1;k<n;k++) {cout<<output[k];if(k!=n-1)cout<<" ";} cout<<endl; } } for(int j=1;j<=n;j++) { if(i+j%2!=0&&used[j-1]==0) if(isprime(i+j)) { used[j-1]=1; output.push_back(j); backtrack(j); used[j-1]=0; output.pop_back(); } } } int main() { int t=0; while(cin>>n) { if(t)cout<<endl; t++;used.reset();output.clear(); printf("Case %d:\n",t); output.push_back(1); used[0]=1; backtrack(1); } return 0; }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { if(nums.empty()) return NULL; return generate(nums,0,nums.size()-1); } TreeNode* generate(vector<int> &nums,int left,int right){ if(left > right) return NULL; int mid = left + (right-left)/2; TreeNode *root = new TreeNode(nums[mid]); root->left = generate(nums,left,mid-1); root->right = generate(nums,mid+1,right); return root; } };
#ifndef ASSETMANAGER_H #define ASSETMANAGER_H #include <android/asset_manager.h> namespace gg { class AssetManager { public: static AAssetManager* manager; }; } #endif
#include <iostream> #include <cstdlib> #include <cstring> #include "player.hpp" using namespace std; int main(int argc, char *argv[]) { // Read in side the player is on. if (argc != 2) { cerr << "usage: " << argv[0] << " side" << endl; exit(-1); } Side side = (!strcmp(argv[1], "Black")) ? BLACK : WHITE; // Initialize player. Player *player = new Player(side); // Tell java wrapper that we are done initializing. cout << "Init done" << endl; cout.flush(); int moveX, moveY, msLeft; // Get opponent's move and time left for player each turn. while (cin >> moveX >> moveY >> msLeft) { Move *opponentsMove = nullptr; if (moveX >= 0 && moveY >= 0) { opponentsMove = new Move(moveX, moveY); } // Get player's move and output to java wrapper. Move *playersMove = player->doMove(opponentsMove, msLeft); if (playersMove) { cout << playersMove->x << " " << playersMove->y << endl; } else { cout << "-1 -1" << endl; } cout.flush(); cerr.flush(); // Delete move objects. if (opponentsMove) delete opponentsMove; if (playersMove) delete playersMove; } return 0; }
// Copyright (c) 2019, tlblanc <tlblanc1490 at gmail dot com> #include "aio.h" #include <errno.h> #include <fcntl.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <signal.h> #include <stdio.h> #ifdef __APPLE__ #include <sys/event.h> int aio_create() { return kqueue(); } int aio_close(int sockfd) { return close(sockfd); } int aio_wait(int queue, struct kevent *events, size_t len, int64_t timeout_ms) { if (timeout_ms > -1) { struct timespec t_spec = { .tv_sec = timeout_ms / 1000, .tv_nsec = (timeout_ms % 1000) * 1000000 }; return kevent(queue, NULL, 0, events, len, &t_spec); } else { return kevent(queue, NULL, 0, events, len, NULL); } } int aio_rmonit(int queue, int fd, int id, bool edge) { int opts = edge ? EV_CLEAR : 0; int flags = EV_ADD | EV_ENABLE | opts; struct kevent event[1]; memset(event, 0, sizeof(struct kevent)); void* data = reinterpret_cast<void*>(static_cast<intptr_t>(id)); EV_SET(&event[0], fd, EVFILT_READ, flags, 0, 0, data); return kevent(queue, event, 1, NULL, 0, 0); } int aio_wmonit(int queue, int fd, int id, bool edge) { int opts = edge ? EV_CLEAR : 0; int flags = EV_ADD | EV_ENABLE | opts; struct kevent event[1]; memset(event, 0, sizeof(struct kevent)); void* data = reinterpret_cast<void*>(static_cast<intptr_t>(id)); EV_SET(&event[0], fd, EVFILT_WRITE, flags, 0, 0, data); return kevent(queue, event, 1, NULL, 0, 0); } int aio_monit(int queue, int fd, int id, bool edge) { int opts = edge ? EV_CLEAR : 0; int flags = EV_ADD | EV_ENABLE | opts; struct kevent event[2]; memset(event, 0, 2*sizeof(struct kevent)); void* data = reinterpret_cast<void*>(static_cast<intptr_t>(id)); EV_SET(&event[0], fd, EVFILT_READ, flags, 0, 0, data); EV_SET(&event[1], fd, EVFILT_WRITE, flags, 0, 0, data); return kevent(queue, event, 2, NULL, 0, 0); } int aio_unmonit(int queue, int fd) { struct kevent event[2]; memset(event, 0, 2*sizeof(struct kevent)); EV_SET(&event[0], fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr); EV_SET(&event[1], fd, EVFILT_WRITE, EV_DELETE, 0, 0, nullptr); return kevent(queue, event, 2, nullptr, 0, 0); } int aio_runmonit(int queue, int fd) { struct kevent event[1]; memset(event, 0, 1*sizeof(struct kevent)); EV_SET(&event[0], fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr); return kevent(queue, event, 1, nullptr, 0, 0); } int aio_wunmonit(int queue, int fd) { struct kevent event[1]; memset(event, 0, sizeof(struct kevent)); EV_SET(&event[0], fd, EVFILT_WRITE, EV_DELETE, 0, 0, nullptr); return kevent(queue, event, 1, nullptr, 0, 0); } int aio_getid(const struct kevent *event) { return static_cast<int>(reinterpret_cast<intptr_t>(event->udata)); } int aio_isclosed(const struct kevent *event) { return (event->flags & EV_EOF); } int aio_ispeer_closed(const struct kevent *event) { return (event->flags & EV_EOF); } int aio_iserror(const struct kevent *event) { return (event->flags & EV_ERROR); } int aio_isread(const struct kevent *event) { return event->filter == EVFILT_READ; } int aio_iswrite(const struct kevent *event) { return event->filter == EVFILT_WRITE; } #elif __linux__ #include <sys/epoll.h> int aio_create() { return epoll_create(1); } int aio_close(int queue) { return close(queue); } int aio_wait(int queue, struct epoll_event *events, size_t len, int64_t timeout_ms) { return epoll_wait(queue, events, len, timeout_ms); } int aio_rmonit(int queue, int fd, int id, bool edge) { struct epoll_event event; memset(&event, 0, sizeof(struct epoll_event)); int flags = edge ? EPOLLET : 0; event.events = EPOLLIN | EPOLLRDHUP | flags; event.data.u32 = static_cast<uint32_t>(id); return epoll_ctl(queue, EPOLL_CTL_ADD, fd, &event); } int aio_wmonit(int queue, int fd, int id, bool edge) { struct epoll_event event; memset(&event, 0, sizeof(struct epoll_event)); int flags = edge ? EPOLLET : 0; event.events = EPOLLOUT | EPOLLRDHUP | flags; event.data.u32 = static_cast<uint32_t>(id); return epoll_ctl(queue, EPOLL_CTL_ADD, fd, &event); } int aio_monit(int queue, int fd, int id, bool edge) { struct epoll_event event; memset(&event, 0, sizeof(struct epoll_event)); int flags = edge ? EPOLLET : 0; event.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP | flags; event.data.u32 = static_cast<uint32_t>(id); return epoll_ctl(queue, EPOLL_CTL_ADD, fd, &event); } int aio_unmonit(int queue, int fd) { struct epoll_event event; memset(&event, 0, sizeof(struct epoll_event)); return epoll_ctl(queue, EPOLL_CTL_DEL, fd, &event); } int aio_runmonit(int queue, int fd) { return aio_unmonit(queue, fd); } int aio_wunmonit(int queue, int fd) { return aio_unmonit(queue, fd); } int aio_getid(const struct epoll_event *event) { return event->data.u32; } int aio_isclosed(const struct epoll_event *event) { return (event->events & EPOLLHUP); } int aio_ispeer_closed(const struct epoll_event *event) { return (event->events & EPOLLRDHUP); } int aio_iserror(const struct epoll_event *event) { return (event->events & EPOLLERR); } int aio_isread(const struct epoll_event *event) { return (event->events & EPOLLIN); } int aio_iswrite(const struct epoll_event *event) { return (event->events & EPOLLOUT); } #else #error "platform not implemented" #endif #define RECOVER_ON_ERROR(action, recover) \ if ((action) == -1) { \ int tmp_errno = errno; \ do { \ recover \ } while (0); \ errno = tmp_errno; \ return -1; \ } static int ___ignore_sigpipe(void) { struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = SIG_IGN; act.sa_flags = SA_RESTART; return sigaction(SIGPIPE, &act, NULL); } static inline int __make_fd_async(int fd) { int current_flags = fcntl(fd, F_GETFL, 0); if (current_flags == -1) { return -1; } int new_flags = current_flags | O_NONBLOCK; if (fcntl(fd, F_SETFL, new_flags) == -1) { return -1; } return 0; } int aio_shutdownrd(int sockfd) { return shutdown(sockfd, SHUT_RD); } int aio_shutdownwd(int sockfd) { return shutdown(sockfd, SHUT_WR); } int aio_pipe(int fd[2]) { if (pipe(fd) == -1) { return -1; } RECOVER_ON_ERROR(__make_fd_async(fd[0]), { close(fd[0]); close(fd[1]); }); RECOVER_ON_ERROR(__make_fd_async(fd[1]), { close(fd[0]); close(fd[1]); }); return 0; } int aio_socket(int domain, int type, int protocol) { int sockfd = socket(domain, type, protocol); if (sockfd == -1) { return -1; } RECOVER_ON_ERROR(__make_fd_async(sockfd), { close(sockfd); }); return sockfd; } int aio_accept(int serverfd, struct sockaddr *addr, socklen_t *addrlen) { int sockfd = accept(serverfd, (struct sockaddr*)addr, addrlen); if (sockfd == -1) { return -1; } RECOVER_ON_ERROR(__make_fd_async(sockfd), { close(sockfd); }); return sockfd; } int aio_bind(int sockfd, const struct sockaddr* addr, socklen_t addrlen) { int arr[] = {1}; if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, arr, sizeof(int)) == -1 || bind(sockfd, addr, addrlen) == -1) { return -1; } return 0; } int aio_listen(int sockfd, int backlog) { if (listen(sockfd, backlog) == -1) { return -1; } else { return 0; } } int aio_connect(int sockfd, const struct sockaddr* addr, socklen_t addrlen) { return connect(sockfd, addr, addrlen) == -1 && errno != EINPROGRESS ? -1 : 0; } int aio_handle_signals(void) { return ___ignore_sigpipe(); }
/* Copyright (c) 2015, Vlad Mesco 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "blocks_interpreter.h" #include "log.h" template struct InstanceInterpreter<Constant>; template struct InstanceInterpreter<Generator>; template struct InstanceInterpreter<Filter>; template struct InstanceInterpreter<Input>; template struct InstanceInterpreter<Delay>; template struct InstanceInterpreter<Noise>; template struct InstanceInterpreter<Output>; std::shared_ptr<IInstanceInterpreter> GetInterpreter(std::string instanceType, std::string name) { #define INSTANCE_DECLARATION_START() if(0) #define DECLARE_INSTANCE(TYPE) } else if(instanceType.compare(#TYPE) == 0) {\ do{ return std::dynamic_pointer_cast<IInstanceInterpreter>(std::make_shared<InstanceInterpreter<TYPE>>(name)); }while(0) #define INSTANCE_DECLARATION_END() else {\ throw std::invalid_argument(std::string("Unknown instance type ") + instanceType);\ }do{}while(0) INSTANCE_DECLARATION_START() { DECLARE_INSTANCE(Constant); DECLARE_INSTANCE(Generator); DECLARE_INSTANCE(Input); DECLARE_INSTANCE(Filter); DECLARE_INSTANCE(Delay); DECLARE_INSTANCE(Noise); DECLARE_INSTANCE(Output); } INSTANCE_DECLARATION_END(); #undef INSTANCE_DECLARATION_START #undef DECLARE_INSTANCE #undef INSTANCE_DECLARATION_END } template<> DelayedLookup_fn InstanceInterpreter<Constant>::AcceptParameter( std::string paramName, PpValue value) { if(paramName.compare("Value") != 0) throw std::invalid_argument("paramName: Expecing Value"); switch(value.type) { case PpValue::PpNUMBER: thing_->value_ = (double)value.num / 999.0; return nullptr; default: throw std::invalid_argument("value: Expecting a NUMBER"); } } template<> DelayedLookup_fn InstanceInterpreter<Generator>::AcceptParameter( std::string paramName, PpValue value) { if(paramName.compare("WT") == 0) { switch(value.type) { case PpValue::PpLIST: { for(PpValueList* p = value.list; p; p = p->next) { PpValue v = p->value; switch(v.type) { case PpValue::PpNUMBER: thing_->WT.table_.push_back((double)v.num / 999.0); break; default: throw std::invalid_argument("WT: value: Expecing a LIST of NUMBERs"); } } return nullptr; } default: throw std::invalid_argument("WT: value: Expecing a LIST of NUMBERs"); } } else if(paramName.compare("GlideOnRest") == 0) { switch(value.type) { case PpValue::PpNUMBER: if(value.num == 0 || value.num == 1) { thing_->GlideOnRest = (value.num != 0); return nullptr; } else { /*FALLTHROUGH*/ } default: throw std::invalid_argument("WT: GlideOnRest: expecting 0 or 1"); } } else if(paramName.compare("RST") == 0) { switch(value.type) { case PpValue::PpSTRING: { std::string s; s.assign(value.str); auto thing = thing_; return [thing, s](LookupMap_t const& map) { thing->ResetBy = map.at(s); }; } default: throw std::invalid_argument("WT: RST: expecting a block name"); } } else if(paramName.compare("Interpolation") == 0) { switch(value.type) { case PpValue::PpSTRING: { std::string s; s.assign(value.str); if(s.compare("Cosine") == 0) { thing_->WT.interpolationMethod_ = WaveTable::COSINE; return nullptr; } else if(s.compare("Linear") == 0) { thing_->WT.interpolationMethod_ = WaveTable::LINEAR; return nullptr; } else if(s.compare("Trunc") == 0) { thing_->WT.interpolationMethod_ = WaveTable::TRUNCATE; return nullptr; } else { /*FALLTHROUGH*/ } } default: throw std::invalid_argument("WT: interpolation: Expecting Cosine, Trunc, Linear"); } } else if(paramName.compare("Glide") == 0) { switch(value.type) { case PpValue::PpSTRING: { std::string name; name.assign(value.str); thing_sp thing = thing_; return [thing, name](LookupMap_t const& map) { thing->TGlide = map.at(name); }; } break; case PpValue::PpNUMBER: { std::shared_ptr<Constant> k(new Constant); k->value_ = (double)value.num / 999.0; // FIXME thing_->TGlide = std::dynamic_pointer_cast<ABlock>(k); k->Tick3(); return nullptr; } default: throw std::invalid_argument("Generator: Glide: expecinting a NUMBER or a STRING"); } } else if(paramName.compare("IN") == 0) { switch(value.type) { case PpValue::PpLIST: { thing_->Inputs().clear(); std::deque<DelayedLookup_fn> fns; for(PpValueList* p = value.list; p; p = p->next) { PpValue v = p->value; switch(v.type) { case PpValue::PpSTRING: { std::string name; name.assign(v.str); thing_sp thing = thing_; fns.push_back([thing, name](LookupMap_t const& map) { thing->Inputs().push_back(map.at(name)); }); } break; default: throw std::invalid_argument("value: expected STRING or LIST of STRINGs or NUMBER"); } } return [fns](LookupMap_t const& map) { for(auto&& fn : fns) fn(map); }; } break; case PpValue::PpSTRING: { thing_->Inputs().clear(); std::string name; name.assign(value.str); std::shared_ptr<thing_t> thing = thing_; return [thing, name](LookupMap_t const& map) { thing->Inputs().push_back(map.at(name)); }; } case PpValue::PpNUMBER: { thing_->Inputs().clear(); std::shared_ptr<Constant> k(new Constant); k->value_ = (double)value.num / 22050.0; // FIXME k->Tick3(); thing_->Inputs().push_back(std::dynamic_pointer_cast<ABlock>(k)); return nullptr; } default: throw std::invalid_argument("IN: value: expecting LIST of STRINGs or STRING"); } } else { throw std::invalid_argument("paramName: Expecting WT, Interpolation, Glide, IN"); } } template<> DelayedLookup_fn InstanceInterpreter<Filter>::AcceptParameter(std::string paramName, PpValue value) { #define NUMBER_OR_INPUT(PARAM, SCALE) do{\ switch(value.type) {\ case PpValue::PpNUMBER:\ {\ std::shared_ptr<Constant> c(new Constant);\ c->value_ = (double)value.num / SCALE;\ LOGF(LOG_INTERPRETER, "%s = %f", #PARAM, c->value_); \ thing_->PARAM = std::dynamic_pointer_cast<ABlock>(c);\ c->Tick3(); /* force buffer transfer */\ return nullptr;\ }\ case PpValue::PpSTRING:\ {\ std::string name;\ name.assign(value.str);\ auto thing = thing_;\ LOGF(LOG_INTERPRETER, "%s = {%s}", #PARAM, value.str); \ return [thing, name](LookupMap_t const& map) {\ thing->PARAM = map.at(name);\ };\ }\ default:\ throw std::invalid_argument("Filter: " #PARAM ": expecting STRING or NUMBER");\ }\ }while(0) if(paramName.compare("A") == 0) { NUMBER_OR_INPUT(A, 999.0); } else if(paramName.compare("D") == 0) { NUMBER_OR_INPUT(D, 999.0); } else if(paramName.compare("S") == 0) { NUMBER_OR_INPUT(S, 999.0); } else if(paramName.compare("R") == 0) { NUMBER_OR_INPUT(R, 999.0); } else if(paramName.compare("ResetADSR") == 0) { switch(value.type) { case PpValue::PpNUMBER: if(value.num > 1) throw std::invalid_argument("Filter: ResetADSR: expecting 1 or 0"); thing_->ResetADSR = value.num != 0; return nullptr; default: throw std::invalid_argument("Filter: ResetADSR expecting NUMBER"); } } else if(paramName.compare("InvertADSR") == 0) { switch(value.type) { case PpValue::PpNUMBER: if(value.num > 1) throw std::invalid_argument("Filter: InvertADSR: expecting 1 or 0"); thing_->InvertADSR = value.num != 0; return nullptr; default: throw std::invalid_argument("Filter: InvertADSR: expecting NUMBER"); } } else if(paramName.compare("Mixing") == 0) { switch(value.type) { case PpValue::PpSTRING: { std::string s; s.assign(value.str); if(s.compare("Cut") == 0) { thing_->mixing_ = Filter::Cut; } else if(s.compare("Flatten") == 0) { thing_->mixing_ = Filter::Flatten; } else { throw std::invalid_argument("Filter: Mixing: expecting Cut or Flatten"); } } return nullptr; default: throw std::invalid_argument("Filter: Mixing: expecting a STRING"); } } else if(paramName.compare("Low") == 0) { NUMBER_OR_INPUT(Lo, 22050.0); } else if(paramName.compare("High") == 0) { NUMBER_OR_INPUT(Hi, 22050.0); } else if(paramName.compare("K") == 0) { NUMBER_OR_INPUT(K, 999.0); } else if(paramName.compare("RST") == 0) { switch(value.type) { case PpValue::PpSTRING: { std::string s; s.assign(value.str); auto thing = thing_; return [thing, s](LookupMap_t const& map) { thing->ResetBy = map.at(s); }; } default: throw std::invalid_argument("WT: RST: expecting a block name"); } } else if(paramName.compare("IN") == 0) { // TODO this bit of code is common for everyone // refactor into template<enum> ? switch(value.type) { case PpValue::PpLIST: { thing_->Inputs().clear(); std::deque<DelayedLookup_fn> fns; for(PpValueList* p = value.list; p; p = p->next) { PpValue v = p->value; switch(v.type) { case PpValue::PpSTRING: { std::string name; name.assign(v.str); thing_sp thing = thing_; fns.push_back([thing, name](LookupMap_t const& map) { thing->Inputs().push_back(map.at(name)); }); } break; default: throw std::invalid_argument("value: expected STRING or LIST of STRINGs or NUMBER"); } } return [fns](LookupMap_t const& map) { for(auto&& fn : fns) fn(map); }; } break; case PpValue::PpSTRING: { thing_->Inputs().clear(); std::string name; name.assign(value.str); std::shared_ptr<thing_t> thing = thing_; return [thing, name](LookupMap_t const& map) { thing->Inputs().push_back(map.at(name)); }; } case PpValue::PpNUMBER: { thing_->Inputs().clear(); std::shared_ptr<Constant> k(new Constant); k->value_ = (double)value.num / 999.0; // FIXME k->Tick3(); thing_->Inputs().push_back(std::dynamic_pointer_cast<ABlock>(k)); return nullptr; } default: throw std::invalid_argument("IN: value: expecting LIST of STRINGs or STRING"); } } throw std::invalid_argument("Filter: paramName: expecting A,D,S,R,ResetADSR,Low,High,K,InvertADSR,Mixing,IN"); } template<> DelayedLookup_fn InstanceInterpreter<Input>::AcceptParameter(std::string paramName, PpValue value) { if(paramName.compare("OnRest") == 0) { switch(value.type) { case PpValue::PpSTRING: { std::string s; s.assign(value.str); if(s.compare("RetainValue") == 0) { thing_->OnRest = Input::RetainValue; return nullptr; } else if(s.compare("Zero") == 0) { thing_->OnRest = Input::Zero; return nullptr; } else{ /*FALLTHROUGH*/ } } default: throw std::invalid_argument("Input: OnRest: expecting RetainValue or Zero"); } } throw std::invalid_argument("Input: paramName: expecing OnRest"); } template<> DelayedLookup_fn InstanceInterpreter<Delay>::AcceptParameter(std::string paramName, PpValue value) { if(paramName.compare("Amount") == 0) { switch(value.type) { case PpValue::PpNUMBER: { if(//value.num > 999 || value.num < 0) throw std::invalid_argument("Delay: Amount: should be between 0 and 999"); std::shared_ptr<Constant> k(new Constant); k->value_ = (double)value.num / 999.0; // FIXME k->Tick3(); thing_->delay_ = k; return nullptr; } case PpValue::PpSTRING: { std::string name; name.assign(value.str); thing_sp thing = thing_; return [thing, name](LookupMap_t const& map) { thing->delay_ = map.at(name); }; } default: throw std::invalid_argument("Delay: Amount: expecting a NUMBER or a STRING"); } } else if(paramName.compare("RST") == 0) { switch(value.type) { case PpValue::PpSTRING: { std::string s; s.assign(value.str); auto thing = thing_; return [thing, s](LookupMap_t const& map) { thing->ResetBy = map.at(s); }; } default: throw std::invalid_argument("WT: RST: expecting a block name"); } } else if(paramName.compare("IN") == 0) { switch(value.type) { case PpValue::PpLIST: { thing_->Inputs().clear(); std::deque<DelayedLookup_fn> fns; for(PpValueList* p = value.list; p; p = p->next) { PpValue v = p->value; switch(v.type) { case PpValue::PpSTRING: { std::string name; name.assign(v.str); thing_sp thing = thing_; fns.push_back([thing, name](LookupMap_t const& map) { thing->Inputs().push_back(map.at(name)); }); } break; default: throw std::invalid_argument("value: expected STRING or LIST of STRINGs or NUMBER"); } } return [fns](LookupMap_t const& map) { for(auto&& fn : fns) fn(map); }; } break; case PpValue::PpSTRING: { thing_->Inputs().clear(); std::string name; name.assign(value.str); std::shared_ptr<thing_t> thing = thing_; return [thing, name](LookupMap_t const& map) { thing->Inputs().push_back(map.at(name)); }; } default: throw std::invalid_argument("IN: value: expecting LIST of STRINGs or STRING"); } } else { throw std::invalid_argument("Delay: unknown param; expecting IN, Amount"); } } template<> DelayedLookup_fn InstanceInterpreter<Noise>::AcceptParameter(std::string paramName, PpValue value) { if(paramName.compare("Type") == 0) { switch(value.type) { case PpValue::PpNUMBER: switch(value.num) { case 0: thing_->type_ = Noise::EIGHT; return nullptr; case 1: thing_->type_ = Noise::SIXTEEN; return nullptr; default: throw std::invalid_argument("Noise: Type: expecting 0 or 1"); } break; default: throw std::invalid_argument("Noise: Type: expecting a NUMBER"); } } else if(paramName.compare("RST") == 0) { switch(value.type) { case PpValue::PpSTRING: { std::string s; s.assign(value.str); auto thing = thing_; return [thing, s](LookupMap_t const& map) { thing->ResetBy = map.at(s); }; } default: throw std::invalid_argument("WT: RST: expecting a block name"); } } else if(paramName.compare("IN") == 0) { // TODO this bit of code is common for everyone // refactor into template<enum> ? switch(value.type) { case PpValue::PpLIST: { thing_->Inputs().clear(); std::deque<DelayedLookup_fn> fns; for(PpValueList* p = value.list; p; p = p->next) { PpValue v = p->value; switch(v.type) { case PpValue::PpSTRING: { std::string name; name.assign(v.str); thing_sp thing = thing_; fns.push_back([thing, name](LookupMap_t const& map) { thing->Inputs().push_back(map.at(name)); }); } break; default: throw std::invalid_argument("value: expected STRING or LIST of STRINGs or NUMBER"); } } return [fns](LookupMap_t const& map) { for(auto&& fn : fns) fn(map); }; } break; case PpValue::PpSTRING: { thing_->Inputs().clear(); std::string name; name.assign(value.str); std::shared_ptr<thing_t> thing = thing_; return [thing, name](LookupMap_t const& map) { thing->Inputs().push_back(map.at(name)); }; } case PpValue::PpNUMBER: { thing_->Inputs().clear(); std::shared_ptr<Constant> k(new Constant); k->value_ = (double)value.num / 999; // FIXME k->Tick3(); thing_->Inputs().push_back(std::dynamic_pointer_cast<ABlock>(k)); return nullptr; } default: throw std::invalid_argument("IN: value: expecting LIST of STRINGs or STRING"); } } throw std::invalid_argument("Noise: paramName: expecting Type or IN"); } template<> DelayedLookup_fn InstanceInterpreter<Output>::AcceptParameter( std::string paramName, PpValue value) { if(paramName.compare("IN") == 0) { switch(value.type) { case PpValue::PpLIST: { thing_->Inputs().clear(); std::deque<DelayedLookup_fn> fns; for(PpValueList* p = value.list; p; p = p->next) { PpValue v = p->value; switch(v.type) { case PpValue::PpSTRING: { std::string name; name.assign(v.str); thing_sp thing = thing_; fns.push_back([thing, name](LookupMap_t const& map) { thing->Inputs().push_back(map.at(name)); }); } break; default: throw std::invalid_argument("value: expected STRING or LIST of STRINGs or NUMBER"); } } return [fns](LookupMap_t const& map) { for(auto&& fn : fns) fn(map); }; } break; case PpValue::PpSTRING: { thing_->Inputs().clear(); std::string name; name.assign(value.str); std::shared_ptr<thing_t> thing = thing_; return [thing, name](LookupMap_t const& map) { thing->Inputs().push_back(map.at(name)); }; } default: throw std::invalid_argument("IN: value: expecting LIST of STRINGs or STRING"); } } else if(paramName.compare("Mixing") == 0) { switch(value.type) { case PpValue::PpSTRING: { std::string s; s.assign(value.str); if(s.compare("Cut") == 0) { thing_->mixing_ = Output::Cut; } else if(s.compare("Flatten") == 0) { thing_->mixing_ = Output::Flatten; } else { throw std::invalid_argument("Output: Mixing: expecting Cut or Flatten"); } } return nullptr; default: throw std::invalid_argument("Output: Mixing: expecting a STRING"); } } else { throw std::invalid_argument("paramName: Expecting Mixing, IN"); } } LookupMap_t::mapped_type LookupMap_t::at(LookupMap_t::key_type name) const { auto&& found = std::find_if(data_.begin(), data_.end(), [name](value_type const& v) -> bool { return v->Name().compare(name) == 0; }); if(found == data_.end()) throw std::out_of_range(name + " not found."); return (*found)->Block(); } LookupMap_t::iterator LookupMap_t::find(LookupMap_t::key_type name) const { auto&& found = std::find_if(data_.begin(), data_.end(), [name](value_type const& v) -> bool { return v->Name().compare(name) == 0; }); return found; } template<> CannonicalStream& InstanceInterpreter<Input>::InputBuffer() { return thing_->stream_; } template<typename T> CannonicalStream& InstanceInterpreter<T>::InputBuffer() { throw std::invalid_argument("Block does not support NOTES input"); }
#ifndef ADDSECHEDULE_H #define ADDSECHEDULE_H #include <QDialog> #include "login.h" namespace Ui { class addsechedule; } class addsechedule : public QDialog { Q_OBJECT public: explicit addsechedule(QWidget *parent = 0); ~addsechedule(); void AddNewSechedule(); bool connOpen(); void connClose(); private slots: void on_pushButton_clicked(); private: Ui::addsechedule *ui; QSqlQuery* qry; QSqlDatabase mydb; }; #endif // ADDSECHEDULE_H
/* * File: Cara.cpp * Author: furia * * Created on 3 de diciembre de 2013, 18:05 */ #include "Cara.h" #include "Malla.h" Cara::Cara() { } Cara::Cara(int numVertices) { _numVertices = numVertices; _arrayVN = new VerticeNormal*[_numVertices]; /* Posible error*/ } Cara::Cara(int numVertices, VerticeNormal** vN) { _numVertices = numVertices; _arrayVN = vN; /* Posible error*/ } int Cara::getNumeroVertices() { return _numVertices; } int Cara::getIndiceNormalK(int posicion) { return _arrayVN[posicion]->getIndiceNormal(); } int Cara::getIndiceVerticeK(int posicion) { return _arrayVN[posicion]->getIndiceVertice(); } void Cara::addVerticeNormal(VerticeNormal *vn, int indx) { _arrayVN[indx] = vn; }
// // Created by manout on 17-3-29. // #include "common_use.h" /* * Given two words(start and ends), and a dictionary, find the length of shortest transformation * sequence from start to end * 分析: * 使用广度优先搜索 */ //定义节点类,表示当前的字符串信息和到start 的步数 struct state_t { int level; string word; state_t():level(0), word(){} state_t(int level, const string& word):level(level),word(word){} bool operator== (const state_t& state) { return this -> word == state.word; } }; //添加自定义类的hash函数 template<> struct hash<state_t> { public: size_t operator()(const state_t &state) { return str_hash(state.word); } private: std::hash<std::string> str_hash; }; int ladder_length(const string& start, const string& end, const unordered_map& dict) { queue<state_t> q; unordered_set<state_t> visited; //判断当前访问的状态是否可以加入到队列和已访问记录中 auto state_is_valid = [&](const state_t& s) { return dict.find(s.word) not_eq dict.end() or s.word == end }; //判断当前状态是不是终点 auto state_is_target = [&](const state_t& s) { return s.word == end; }; //从当前访问节点开始访问下一层,返回一个包含下一层元素的容器 auto state_extend = [&](const state_t& s) { unordered_set<state_t> result; for (int i = 0; i < s.word.length(); ++i) { state_t new_state = state_t(s.level + 1, s.word ); for (char c = 'a'; c < 'z'; ++c) { if(c == new_state.word[i])continue; swap(c, new_state.word[i]); if(state_is_valid(new_state) and visited.find(new_state) == visited.end()) { visited.insert(new_state); } swap(c, new_state.word[i]); } } return result }; state_t start_state(0,start); q.push(start_state); visited.insert(start_state); while(not q.empty()) { const auto state = q.front(); q.pop(); if(state_is_target(state)) { return start_state.level + 1; } const auto new_state = state_extend(state); for (const auto& s : new_state) { q.push(s); visited.insert(s); } } return 0; }
#include <iostream> using namespace std; typedef long long LL; LL a, b, mod; LL O1quick_mul(LL a, LL b, LL mod) { LL tmp = LL (a * (long double) b / mod); return ((a * b - tmp * mod) + mod) % mod; } int main() { while(1) { cin >> a >> b >> mod; cout << O1quick_mul(a, b, mod) << endl; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 2002-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Morten Stenshorne */ #ifndef X11_COLORMANAGER_TC16_H_ #define X11_COLORMANAGER_TC16_H_ #include "x11_colormanager.h" /** TrueColor 16 bit color manager. * Expected image format: 16 bits per pixel * Red mask:0xf800 Green mask:0x7e0 Blue mask:0x1f */ class X11TC16ColorManager : public X11ColorManager { private: bool swap_endianness; public: X11TC16ColorManager(bool swap) { swap_endianness = swap; } unsigned long GetPixelValue(int red, int green, int blue, int alfa, const XColor **color=0); void GetRGB(unsigned long pixel, int &red, int &green, int &blue, int &alpha); void PutLine(XImage *img, void *dest, const UINT32 *data, int line, int pixels, bool premultiply); void GetLine(XImage *img, const void *src, UINT32 *data, int line, int pixels, bool premultiply); void PutPixel(XImage *img, int x, int y, int r, int g, int b, int a); void GetPixel(XImage *img, int x, int y, int &r, int &g, int &b, int &a); void BlendLine( const void *src, void *dest, const UINT8 *srcalpha, UINT8 *destalpha, int pixels); OP_STATUS ScaleImage( XImage *src, XImage *dest, void *srcbuf, void *destbuf, int srcwidth, int srcheight, int srcbpl, int destwidth, int destheight, int destbpl, int xoffs, int yoffs, int dtotwidth, int dtotheight); }; #endif // X11_COLORMANAGER_TC16_H_
// Created on: 1995-04-20 // Created by: Tony GEORGIADES // 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 _Resource_Manager_HeaderFile #define _Resource_Manager_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TCollection_AsciiString.hxx> #include <Resource_DataMapOfAsciiStringAsciiString.hxx> #include <Resource_DataMapOfAsciiStringExtendedString.hxx> #include <Standard_Boolean.hxx> #include <Standard_Transient.hxx> #include <Standard_CString.hxx> #include <Standard_Integer.hxx> #include <Standard_Real.hxx> #include <Standard_ExtString.hxx> class Resource_Manager; DEFINE_STANDARD_HANDLE(Resource_Manager, Standard_Transient) //! Defines a resource structure and its management methods. class Resource_Manager : public Standard_Transient { DEFINE_STANDARD_RTTIEXT(Resource_Manager,Standard_Transient) public: //! Create a Resource manager. //! Attempts to find the two following files: //! $CSF_`aName`Defaults/aName //! $CSF_`aName`UserDefaults/aName //! and load them respectively into a reference and a user resource structure. //! //! If CSF_ResourceVerbose defined, seeked files will be printed. //! //! FILE SYNTAX //! The syntax of a resource file is a sequence of resource //! lines terminated by newline characters or end of file. The //! syntax of an individual resource line is: Standard_EXPORT Resource_Manager(const Standard_CString aName, const Standard_Boolean Verbose = Standard_False); //! Create an empty Resource manager Standard_EXPORT Resource_Manager(); //! Create a Resource manager. //! @param theName [in] description file name //! @param theDefaultsDirectory [in] default folder for looking description file //! @param theUserDefaultsDirectory [in] user folder for looking description file //! @param theIsVerbose [in] print verbose messages Standard_EXPORT Resource_Manager (const TCollection_AsciiString& theName, const TCollection_AsciiString& theDefaultsDirectory, const TCollection_AsciiString& theUserDefaultsDirectory, const Standard_Boolean theIsVerbose = Standard_False); //! Save the user resource structure in the specified file. //! Creates the file if it does not exist. Standard_EXPORT Standard_Boolean Save() const; //! returns True if the Resource does exist. Standard_EXPORT Standard_Boolean Find (const Standard_CString aResource) const; //! returns True if the Resource does exist. Standard_EXPORT Standard_Boolean Find (const TCollection_AsciiString& theResource, TCollection_AsciiString& theValue) const; //! Gets the value of an integer resource according to its //! instance and its type. Standard_EXPORT virtual Standard_Integer Integer (const Standard_CString aResourceName) const; //! Gets the value of a real resource according to its instance //! and its type. Standard_EXPORT virtual Standard_Real Real (const Standard_CString aResourceName) const; //! Gets the value of a CString resource according to its instance //! and its type. Standard_EXPORT virtual Standard_CString Value (const Standard_CString aResourceName) const; //! Gets the value of an ExtString resource according to its instance //! and its type. Standard_EXPORT virtual Standard_ExtString ExtValue (const Standard_CString aResourceName); //! Sets the new value of an integer resource. //! If the resource does not exist, it is created. Standard_EXPORT virtual void SetResource (const Standard_CString aResourceName, const Standard_Integer aValue); //! Sets the new value of a real resource. //! If the resource does not exist, it is created. Standard_EXPORT virtual void SetResource (const Standard_CString aResourceName, const Standard_Real aValue); //! Sets the new value of an CString resource. //! If the resource does not exist, it is created. Standard_EXPORT virtual void SetResource (const Standard_CString aResourceName, const Standard_CString aValue); //! Sets the new value of an ExtString resource. //! If the resource does not exist, it is created. Standard_EXPORT virtual void SetResource (const Standard_CString aResourceName, const Standard_ExtString aValue); //! Gets the resource file full path by its name. //! If corresponding environment variable is not set //! or file doesn't exist returns empty string. Standard_EXPORT static void GetResourcePath (TCollection_AsciiString& aPath, const Standard_CString aName, const Standard_Boolean isUserDefaults); //! Returns internal Ref or User map with parameters Standard_EXPORT Resource_DataMapOfAsciiStringAsciiString& GetMap(Standard_Boolean theRefMap = Standard_True); private: Standard_EXPORT void Load (const TCollection_AsciiString& thePath, Resource_DataMapOfAsciiStringAsciiString& aMap); private: TCollection_AsciiString myName; Resource_DataMapOfAsciiStringAsciiString myRefMap; Resource_DataMapOfAsciiStringAsciiString myUserMap; Resource_DataMapOfAsciiStringExtendedString myExtStrMap; Standard_Boolean myVerbose; }; #endif // _Resource_Manager_HeaderFile
#include <bits/stdc++.h> using namespace std; int main() { // only gravity will pull me down // Check if an array is sorted int t, n; cin >> t; while (t--) { cin >> n; vector<int> c(n); cin >> c[0]; int flg = 0; for(int i=1; i<n; i++) { cin >> c[i]; if (c[i] < c[i-1]) { flg = 1; break; } } if (flg) cout << 0 << endl; else cout << 1 << endl; } return 0; }
#include <contextual/Monad.hpp> int main(int, char**){ return 0; }
#ifndef _LIGHT_AERO_H_ #define _LIGHT_AERO_H_ #include "../../Toolbox/Toolbox.h" #include "../../Maths/Transform/Transform.h" #include "../Color/Color.h" #include "../../World/WorldObject/WorldObject.h" namespace ae { /// \ingroup graphics /// <summary> /// Basic class for lights. /// </summary> /// <seealso cref="Transform" /> /// <seealso cref="PointLight" /> /// <seealso cref="SpotLight" /> /// <seealso cref="DirectionalLight" /> class AERO_CORE_EXPORT Light : public Transform, public WorldObject { public: /// <summary>Enum listing the possible types of lights.</summary> enum class LightType : Uint8 { /// <summary>Point light.</summary> Point, /// <summary>Spotlight.</summary> Spot, /// <summary>Directional light.</summary> Directional, /// <summary>Other kind of light.</summary> Unknown }; public: /// <summary>Initialise a light.</summary> Light(); /// <summary>Light destructor (remove the light from the world).</summary> virtual ~Light(); /// <summary>Set the light color.</summary> /// <param name="_Color">The new color to apply.</param> void SetColor( const Color& _Color ); /// <summary>Get the light color.</summary> /// <returns>Color of the light.</returns> const Color& GetColor() const; /// <summary>Set the light intensity.</summary> /// <param name="_Intensity">The light intensity.</param> void SetIntensity( float _Intensity ); /// <summary>Get the light intensity.</summary> /// <returns>The current light intensity.</returns> float GetIntensity() const; /// <summary>Set shader uniform with light composant.</summary> /// <param name="_LightName">The light array name in the shader.</param> /// <param name="_LightIndex">The index in the array of the light.</param> /// <param name="_Shader">The shader to send the light to.</param> virtual void SendToShader( const std::string& _LightName, Uint32 _LightIndex, const class Shader& _Shader ) AE_IsVirtualPure; /// <summary>Get the light type.</summary> /// <returns>The light type.</returns> LightType GetLightType() const; /// <summary> /// Function called by the editor. /// It allows the class to expose some attributes for user editing. /// Think to call all inherited class function too when overloading. /// </summary> virtual void ToEditor() override; protected: /// <summary>Light color.</summary> Color m_Color; /// <summary>Intensity of the light.</summary> float m_Intensity; /// <summary>Type of the light.</summary> LightType m_Type; }; } // ae #endif // _LIGHT_AERO_H_
#ifndef ENDMENU_H #define ENDMENU_H #include <QGraphicsView> #include <QWidget> #include <QGraphicsScene> #include<QPushButton> #include<QObject> #include"score.h" class Endmenu: public QObject{ Q_OBJECT public: Endmenu(QObject *parent2=0); QGraphicsView *Eview = new QGraphicsView(); Score *score; private: //QGraphicsView * view; QGraphicsScene * scene; QPushButton *playagain; public slots: void pressedstart(bool); }; #endif // ENDMENU_H
#ifndef AOC_6_H #define AOC_6_H #include <map> #include <string> #include <vector> #include <tuple> namespace AoC_6 { std::map<std::string, std::string> MakeOrbitMap(std::vector<std::tuple<std::string, std::string>> orbits) { std::map<std::string, std::string> orbitMap = {}; for (auto& orbit : orbits) { orbitMap[std::get<1>(orbit)] = std::get<0>(orbit); } return orbitMap; } std::vector<std::string> GetOrbitPath(std::map<std::string, std::string> orbitMap, std::string node) { std::vector<std::string> orbitPath = {}; while (orbitMap.count(node) == 1) { orbitPath.push_back(node); node = orbitMap[node]; } return orbitPath; } int A(std::vector<std::tuple<std::string, std::string>> orbits) { std::map<std::string, std::string> orbitMap = MakeOrbitMap(orbits); return std::accumulate(orbitMap.begin(), orbitMap.end(), 0, [orbitMap](int acc, auto node) {return acc + GetOrbitPath(orbitMap, node.first).size(); }); } int B(std::vector<std::tuple<std::string, std::string>> orbits) { std::map<std::string, std::string> orbitMap = MakeOrbitMap(orbits); std::vector<std::string> SAN_path = GetOrbitPath(orbitMap, "SAN"); std::vector<std::string> YOU_path = GetOrbitPath(orbitMap, "YOU"); while (SAN_path.back() == YOU_path.back()) { SAN_path.pop_back(); YOU_path.pop_back(); } return SAN_path.size() + YOU_path.size() - 2; } } #endif
#pragma once #include <vector> #include <QString> #include <boost/utility/string_view.hpp> #include "PticaGovorunCore.h" #include <boost/filesystem.hpp> namespace PticaGovorun { PG_EXPORTS void appendTimeStampNow(std::string& strBuf); PG_EXPORTS void appendTimeStampNow(std::stringstream& str); PG_EXPORTS boost::wstring_view trim(boost::wstring_view text); PG_EXPORTS void utf8s2ws(boost::string_view strUtf8, std::wstring& target); PG_EXPORTS std::wstring utf8s2ws(boost::string_view str); PG_EXPORTS void toUtf8StdString(boost::wstring_view wstr, std::string& targetUtf8); PG_EXPORTS std::string toUtf8StdString(boost::wstring_view wstr); // Copyies string into buffer and returns reference to it. PG_EXPORTS boost::wstring_view toWStringRef(const QString& str, std::vector<wchar_t>& buff); PG_EXPORTS boost::wstring_view toWStringRef(const QStringRef& str, std::vector<wchar_t>& buff); PG_EXPORTS void toWStringRef(const QString& str, std::wstring& buff); PG_EXPORTS void toWStringRef(const QStringRef& str, std::wstring& buff); PG_EXPORTS QString utf8ToQString(boost::string_view text); PG_EXPORTS std::string toUtf8StdString(const QString& text); PG_EXPORTS std::string toUtf8StdString(const QStringRef& text); PG_EXPORTS std::string toStdString(boost::string_view text); PG_EXPORTS QString toQString(boost::wstring_view text); PG_EXPORTS std::wstring toStdWString(boost::wstring_view text); PG_EXPORTS void toStdWString(boost::wstring_view text, std::wstring& result); PG_EXPORTS QString toQStringBfs(const boost::filesystem::path& path); PG_EXPORTS boost::filesystem::path toBfs(const QString& path); }
// // main.cpp // 1193 // // Created by Pedro Neves Alvarez on 7/9/17. // Copyright © 2017 Pedro Neves Alvarez. All rights reserved. // #include <iostream> #include <iomanip> #include <cmath> #include <cstdlib> #include <string> using namespace std; char digit_hex (long x) { if (x >= 0 && x < 10) return x+'0'; else if (x < 16) return x-10+'a'; else return '!'; } string tobin (long x) { string aux; while (x > 0) { char c = x%2+'0'; aux = c + aux; x /= 2; } return aux; } string tohex (long x) { string aux; while (x > 0) { aux = digit_hex(x%16) + aux; x /= 16; } return aux; } int main () { char str[50]; string type; long x, n; cin >> n; for (int i = 0; i < n; i++) { cin >> str >> type; cout << "Case " << i+1 << ':' << endl; if (type == "bin") { x = strtol(str, 0, 2); long y = (long) x; cout << y << " dec" << endl; cout << tohex(y) << " hex" << endl; } else if (type == "dec") { x = strtol(str, 0, 10); cout << tohex(x) << " hex" << endl; cout << tobin(x) << " bin" << endl; } else { x = strtol(str, 0, 16); cout << x << " dec" << endl; cout << tobin(x) << " bin" << endl; } cout << endl; } return 0; }
#pragma once #include "piece.h" #include <iostream> using namespace std; class Pawn : public Piece { public : Pawn(int x, int y, bool pieceInfo); bool Move(int i, int j, Location** board); };
#pragma once #include <string> namespace ngn { void printHello(const std::string& name); } // namespace ngn
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // 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 Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// #ifndef INCLUDED_IMF_STANDARD_ATTRIBUTES_H #define INCLUDED_IMF_STANDARD_ATTRIBUTES_H //----------------------------------------------------------------------------- // // Optional Standard Attributes -- these attributes are "optional" // because not every image file header has them, but they define a // "standard" way to represent commonly used data in the file header. // // For each attribute, with name "foo", and type "T", the following // functions are automatically generated via macros: // // void addFoo (Header &header, const T &value); // bool hasFoo (const Header &header); // const TypedAttribute<T> & fooAttribute (const Header &header); // TypedAttribute<T> & fooAttribute (Header &header); // const T & foo (const Header &Header); // T & foo (Header &Header); // //----------------------------------------------------------------------------- #include <ImfHeader.h> #include <ImfChromaticitiesAttribute.h> #include <ImfEnvmapAttribute.h> #include <ImfFloatAttribute.h> #include <ImfKeyCodeAttribute.h> #include <ImfMatrixAttribute.h> #include <ImfRationalAttribute.h> #include <ImfStringAttribute.h> #include <ImfStringVectorAttribute.h> #include <ImfTimeCodeAttribute.h> #include <ImfVecAttribute.h> #define IMF_STD_ATTRIBUTE_DEF(name,suffix,type) \ \ void add##suffix (Header &header, const type &v); \ bool has##suffix (const Header &header); \ const TypedAttribute<type> & name##Attribute (const Header &header); \ TypedAttribute<type> & name##Attribute (Header &header); \ const type & name (const Header &header); \ type & name (Header &header); namespace Imf { // // chromaticities -- for RGB images, specifies the CIE (x,y) // chromaticities of the primaries and the white point // IMF_STD_ATTRIBUTE_DEF (chromaticities, Chromaticities, Chromaticities) // // whiteLuminance -- for RGB images, defines the luminance, in Nits // (candelas per square meter) of the RGB value (1.0, 1.0, 1.0). // // If the chromaticities and the whiteLuminance of an RGB image are // known, then it is possible to convert the image's pixels from RGB // to CIE XYZ tristimulus values (see function RGBtoXYZ() in header // file ImfChromaticities.h). // // IMF_STD_ATTRIBUTE_DEF (whiteLuminance, WhiteLuminance, float) // // adoptedNeutral -- specifies the CIE (x,y) coordinates that should // be considered neutral during color rendering. Pixels in the image // file whose (x,y) coordinates match the adoptedNeutral value should // be mapped to neutral values on the display. // IMF_STD_ATTRIBUTE_DEF (adoptedNeutral, AdoptedNeutral, Imath::V2f) // // renderingTransform, lookModTransform -- specify the names of the // CTL functions that implements the intended color rendering and look // modification transforms for this image. // IMF_STD_ATTRIBUTE_DEF (renderingTransform, RenderingTransform, std::string) IMF_STD_ATTRIBUTE_DEF (lookModTransform, LookModTransform, std::string) // // xDensity -- horizontal output density, in pixels per inch. // The image's vertical output density is xDensity * pixelAspectRatio. // IMF_STD_ATTRIBUTE_DEF (xDensity, XDensity, float) // // owner -- name of the owner of the image // IMF_STD_ATTRIBUTE_DEF (owner, Owner, std::string) // // comments -- additional image information in human-readable // form, for example a verbal description of the image // IMF_STD_ATTRIBUTE_DEF (comments, Comments, std::string) // // capDate -- the date when the image was created or captured, // in local time, and formatted as // // YYYY:MM:DD hh:mm:ss // // where YYYY is the year (4 digits, e.g. 2003), MM is the month // (2 digits, 01, 02, ... 12), DD is the day of the month (2 digits, // 01, 02, ... 31), hh is the hour (2 digits, 00, 01, ... 23), mm // is the minute, and ss is the second (2 digits, 00, 01, ... 59). // // IMF_STD_ATTRIBUTE_DEF (capDate, CapDate, std::string) // // utcOffset -- offset of local time at capDate from // Universal Coordinated Time (UTC), in seconds: // // UTC == local time + utcOffset // IMF_STD_ATTRIBUTE_DEF (utcOffset, UtcOffset, float) // // longitude, latitude, altitude -- for images of real objects, the // location where the image was recorded. Longitude and latitude are // in degrees east of Greenwich and north of the equator. Altitude // is in meters above sea level. For example, Kathmandu, Nepal is // at longitude 85.317, latitude 27.717, altitude 1305. // IMF_STD_ATTRIBUTE_DEF (longitude, Longitude, float) IMF_STD_ATTRIBUTE_DEF (latitude, Latitude, float) IMF_STD_ATTRIBUTE_DEF (altitude, Altitude, float) // // focus -- the camera's focus distance, in meters // IMF_STD_ATTRIBUTE_DEF (focus, Focus, float) // // exposure -- exposure time, in seconds // IMF_STD_ATTRIBUTE_DEF (expTime, ExpTime, float) // // aperture -- the camera's lens aperture, in f-stops (focal length // of the lens divided by the diameter of the iris opening) // IMF_STD_ATTRIBUTE_DEF (aperture, Aperture, float) // // isoSpeed -- the ISO speed of the film or image sensor // that was used to record the image // IMF_STD_ATTRIBUTE_DEF (isoSpeed, IsoSpeed, float) // // envmap -- if this attribute is present, the image represents // an environment map. The attribute's value defines how 3D // directions are mapped to 2D pixel locations. For details // see header file ImfEnvmap.h // IMF_STD_ATTRIBUTE_DEF (envmap, Envmap, Envmap) // // keyCode -- for motion picture film frames. Identifies film // manufacturer, film type, film roll and frame position within // the roll. // IMF_STD_ATTRIBUTE_DEF (keyCode, KeyCode, KeyCode) // // timeCode -- time and control code // IMF_STD_ATTRIBUTE_DEF (timeCode, TimeCode, TimeCode) // // wrapmodes -- determines how texture map images are extrapolated. // If an OpenEXR file is used as a texture map for 3D rendering, // texture coordinates (0.0, 0.0) and (1.0, 1.0) correspond to // the upper left and lower right corners of the data window. // If the image is mapped onto a surface with texture coordinates // outside the zero-to-one range, then the image must be extrapolated. // This attribute tells the renderer how to do this extrapolation. // The attribute contains either a pair of comma-separated keywords, // to specify separate extrapolation modes for the horizontal and // vertical directions; or a single keyword, to specify extrapolation // in both directions (e.g. "clamp,periodic" or "clamp"). Extra white // space surrounding the keywords is allowed, but should be ignored // by the renderer ("clamp, black " is equivalent to "clamp,black"). // The keywords listed below are predefined; some renderers may support // additional extrapolation modes: // // black pixels outside the zero-to-one range are black // // clamp texture coordinates less than 0.0 and greater // than 1.0 are clamped to 0.0 and 1.0 respectively // // periodic the texture image repeats periodically // // mirror the texture image repeats periodically, but // every other instance is mirrored // IMF_STD_ATTRIBUTE_DEF (wrapmodes, Wrapmodes, std::string) // // framesPerSecond -- defines the nominal playback frame rate for image // sequences, in frames per second. Every image in a sequence should // have a framesPerSecond attribute, and the attribute value should be // the same for all images in the sequence. If an image sequence has // no framesPerSecond attribute, playback software should assume that // the frame rate for the sequence is 24 frames per second. // // In order to allow exact representation of NTSC frame and field rates, // framesPerSecond is stored as a rational number. A rational number is // a pair of integers, n and d, that represents the value n/d. // // For the exact values of commonly used frame rates, please see header // file ImfFramesPerSecond.h. // IMF_STD_ATTRIBUTE_DEF (framesPerSecond, FramesPerSecond, Rational) // // multiView -- defines the view names for multi-view image files. // A multi-view image contains two or more views of the same scene, // as seen from different viewpoints, for example a left-eye and // a right-eye view for stereo displays. The multiView attribute // lists the names of the views in an image, and a naming convention // identifies the channels that belong to each view. // // For details, please see header file ImfMultiView.h // IMF_STD_ATTRIBUTE_DEF (multiView , MultiView, StringVector) // // worldToCamera -- for images generated by 3D computer graphics rendering, // a matrix that transforms 3D points from the world to the camera coordinate // space of the renderer. // // The camera coordinate space is left-handed. Its origin indicates the // location of the camera. The positive x and y axes correspond to the // "right" and "up" directions in the rendered image. The positive z // axis indicates the camera's viewing direction. (Objects in front of // the camera have positive z coordinates.) // // Camera coordinate space in OpenEXR is the same as in Pixar's Renderman. // IMF_STD_ATTRIBUTE_DEF (worldToCamera, WorldToCamera, Imath::M44f) // // worldToNDC -- for images generated by 3D computer graphics rendering, a // matrix that transforms 3D points from the world to the Normalized Device // Coordinate (NDC) space of the renderer. // // NDC is a 2D coordinate space that corresponds to the image plane, with // positive x and pointing to the right and y positive pointing down. The // coordinates (0, 0) and (1, 1) correspond to the upper left and lower right // corners of the OpenEXR display window. // // To transform a 3D point in word space into a 2D point in NDC space, // multiply the 3D point by the worldToNDC matrix and discard the z // coordinate. // // NDC space in OpenEXR is the same as in Pixar's Renderman. // IMF_STD_ATTRIBUTE_DEF (worldToNDC, WorldToNDC, Imath::M44f) } // namespace Imf #endif
#ifndef MOVE_H #define MOVE_H #include <QObject> #include <QString> class Monster; class Move : public QObject { Q_OBJECT public: explicit Move(QObject *parent = 0); int id; QString name; QString type; QString category; int power; int accuracy; int pp; int ppTot; QString statusAffected; bool rise; int amount; QString description; Q_INVOKABLE QString define(Monster &attack, Monster &defense ); Q_INVOKABLE QString physical(Monster &attack, Monster &defense ); Q_INVOKABLE QString special( Monster &attack, Monster &defense ); Q_INVOKABLE QString status( Monster &attack, Monster &defense ); Q_INVOKABLE QString effect( Monster &attack, Monster &defense ); Q_INVOKABLE QString struggle( Monster &attack, Monster &defense ); signals: void moveDone(); void toConsole(QString &string); public slots: }; #endif // MOVE_H
/* =========================================================================== Copyright (C) 2017 waYne (CAM) =========================================================================== */ #pragma once #ifndef ELYSIUM_DATA_QUERYING_JOINEXPRESSION #define ELYSIUM_DATA_QUERYING_JOINEXPRESSION #ifndef ELYSIUM_CORE_OBJECT #include "../../../Core/01-Shared/Elysium.Core/Object.hpp" #endif #ifndef ELYSIUM_DATA_QUERYING_JOINOPERATOR #include "JoinOperator.hpp" #endif #ifndef _XSTRING_ #include <string> #endif using namespace Elysium::Core; namespace Elysium { namespace Data { namespace Querying { /// <summary> /// /// /// https://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.query.linkentity.aspx /// </summary> class EXPORT JoinExpression : public Object { public: // constructors & destructor JoinExpression(); ~JoinExpression(); // fields JoinOperator JoinOperator = JoinOperator::Natural; std::string LinkFromTableName; std::string LinkFromAttributeName; std::string LinkToTableName; std::string LinkToAttributeName; /// <summary> /// /// </summary> void operator =(const JoinExpression& Source); }; } } } #endif
#include "loading.h" #include "index.h" #include "HelloWorldScene.h" #define COCOS_DEBUG_1 USING_NS_CC; using namespace cocos2d; Scene* loading::createScene() { auto scene = Scene::create(); auto layer = new (std::nothrow) loading(); scene->addChild(layer); return scene; } loading::loading() : numSprite(11), loadedSprite(0), timeAll(0), add(false) { Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); //set the color of the background is white whiteLayer = LayerColor::create(ccc4(255, 255, 255, 255)); this->addChild(whiteLayer, 1); /*loading*/ //borderForloading borderForload = Sprite::create("loading/borderForload.png"); Size borderForLoadingSize = borderForload->getContentSize(); borderForload->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2 - borderForLoadingSize.height)); float x = visibleSize.width / borderForLoadingSize.width / 2; borderForload->setScale(x, x); this->addChild(borderForload, 3); //timer auto progressContent = Sprite::create("loading/contentForload.jpg"); progressLoading = ProgressTimer::create(progressContent); progressLoading->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2 - borderForLoadingSize.height)); float xx = borderForload->getBoundingBox().size.width / progressContent->getContentSize().width; float yy = borderForload->getBoundingBox().size.height / progressContent->getContentSize().height; progressLoading->setScale(xx, yy); this->addChild(progressLoading, 2); progressLoading->setType(ProgressTimer::Type::BAR);//type of animation progressLoading->setBarChangeRate(Vec2(1, 0)); progressLoading->setMidpoint(Vec2(0, 0)); progressLoading->setPercentage(0.0f); //little girl girl = Sprite::create("index/stand.png"); float xxx = borderForload->getBoundingBox().size.width / girl->getContentSize().width / 8; girl->setAnchorPoint(Point(0.5, 0)); girl->setPosition(Vec2((visibleSize.width - borderForload->getBoundingBox().size.width) / 2, visibleSize.height / 2 - borderForLoadingSize.height + borderForload->getBoundingBox().size.height / 2)); girl->setScale(xxx,xxx); this->addChild(girl, 3); auto animation = Animation::create(); animation->addSpriteFrameWithFile("index/walk1.png"); animation->addSpriteFrameWithFile("index/walk2.png"); animation->addSpriteFrameWithFile("index/walk3.png"); animation->addSpriteFrameWithFile("index/walk4.png"); animation->setDelayPerUnit(0.2f); animation->setRestoreOriginalFrame(true); auto action = Animate::create(animation); girl->runAction(RepeatForever::create(action)); /*auto girlMove = MoveTo::create(4, ccp(visibleSize.width - (visibleSize.width - borderForload->getBoundingBox().size.width)/2, girl->getPosition().y)); girl->runAction(girlMove);*/ //loading Loading = Label::createWithTTF("Loading...", "fonts/impact.ttf", 42); Loading->setAnchorPoint(Point(0.5, 0.5)); Loading->setColor(Color3B(207, 138, 69)); Loading->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2 - borderForLoadingSize.height * 2)); this->addChild(Loading, 3); auto out = FadeOut::create(0.5); auto in = FadeIn::create(0.5); Loading->runAction(RepeatForever::create(Sequence::create(out, in, NULL))); schedule(schedule_selector(loading::update), 0.01f); //loading Director::getInstance()->getTextureCache()->addImageAsync("index/walk1.png", CC_CALLBACK_1(loading::loadingCallBack, this)); Director::getInstance()->getTextureCache()->addImageAsync("index/walk2.png", CC_CALLBACK_1(loading::loadingCallBack, this)); Director::getInstance()->getTextureCache()->addImageAsync("index/walk3.png", CC_CALLBACK_1(loading::loadingCallBack, this)); Director::getInstance()->getTextureCache()->addImageAsync("index/walk4.png", CC_CALLBACK_1(loading::loadingCallBack, this)); Director::getInstance()->getTextureCache()->addImageAsync("index/stand.png", CC_CALLBACK_1(loading::loadingCallBack, this)); Director::getInstance()->getTextureCache()->addImageAsync("index/background.png", CC_CALLBACK_1(loading::loadingCallBack, this)); Director::getInstance()->getTextureCache()->addImageAsync("index/exit.png", CC_CALLBACK_1(loading::loadingCallBack, this)); Director::getInstance()->getTextureCache()->addImageAsync("index/map.png", CC_CALLBACK_1(loading::loadingCallBack, this)); Director::getInstance()->getTextureCache()->addImageAsync("index/moon.png", CC_CALLBACK_1(loading::loadingCallBack, this)); Director::getInstance()->getTextureCache()->addImageAsync("index/parent.png", CC_CALLBACK_1(loading::loadingCallBack, this)); Director::getInstance()->getTextureCache()->addImageAsync("index/plane.png", CC_CALLBACK_1(loading::loadingCallBack, this)); //auto layer1 = new index(); //addChild(layer1); } void loading::update(float delta) { Size visibleSize = Director::getInstance()->getVisibleSize(); float origin = (visibleSize.width - borderForload->getBoundingBox().size.width) / 2; float interval = progressLoading->getPercentage() / 100 * borderForload->getBoundingBox().size.width; girl->setPosition(Vec2(origin + interval, girl->getPosition().y)); if (add == true) { auto time = ProgressFromTo::create(3.0f, progressLoading->getPercentage(), (float)(loadedSprite) * (100 / (float)(numSprite))); progressLoading->runAction(time); } add = false; if (loadedSprite == numSprite && progressLoading->getPercentage() >= 100) { if (timeAll >= 0.5) { this->gotoNewPage(); this->unschedule(schedule_selector(loading::update)); } else{ timeAll += delta; } } } void loading::loadingCallBack(cocos2d::Texture2D* texture) { loadedSprite++; add = true; } void loading::gotoNewPage(void) { this->stopAllActions(); /*this->removeChild(girl); this->removeChild(borderForload); this->removeChild(progressLoading); this->removeChild(whiteLayer); this->removeChild(Loading);*/ auto scene = HelloWorld::createScene(); CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(0.1, scene, Color3B::GRAY)); }
// AutoGetAwsFileDlg.cpp : 实现文件 // #include "stdafx.h" #include "AutoGetAwsFile.h" #include "AutoGetAwsFileDlg.h" #include <atlbase.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // CAutoGetAwsFileDlg 对话框 #define WM_SHOWTASK (WM_USER + 1000) CAutoGetAwsFileDlg::CAutoGetAwsFileDlg(CWnd* pParent /*=NULL*/) : CDialog(CAutoGetAwsFileDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); GetLastReadTime(); ProgramState = "程序将自动登陆FTP读取最新文件...\n"+last_time.Format("最近读取时次:%Y-%m-%d %H时"); } void CAutoGetAwsFileDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_PROGRAM_STATE, ProgramState); } BEGIN_MESSAGE_MAP(CAutoGetAwsFileDlg, CDialog) ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_WM_DESTROY() ON_WM_SYSCOMMAND() ON_MESSAGE(WM_SHOWTASK,OnShowTask) ON_WM_TIMER() END_MESSAGE_MAP() // CAutoGetAwsFileDlg 消息处理程序 BOOL CAutoGetAwsFileDlg::OnInitDialog() { CDialog::OnInitDialog(); // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 HideToTray(); //ShowWindow(SW_HIDE); AutoRunAfterStart(); SetTimer(1,5*1000,NULL);//程序运行后5秒后启动定时器 return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CAutoGetAwsFileDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 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; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CAutoGetAwsFileDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } // 隐藏到任务栏 void CAutoGetAwsFileDlg::HideToTray(void) { nid.cbSize=(DWORD)sizeof(NOTIFYICONDATA); nid.hWnd=this->m_hWnd; nid.uID=IDR_MAINFRAME; nid.uFlags=NIF_ICON|NIF_MESSAGE|NIF_TIP ; nid.uCallbackMessage=WM_SHOWTASK;//自定义的消息名称 nid.hIcon=LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDR_MAINFRAME)); strcpy_s(nid.szTip,"自动获取自动站资料"); //信息提示条为“计划任务提醒” Shell_NotifyIcon(NIM_ADD,&nid); //在托盘区添加图标 } void CAutoGetAwsFileDlg::OnDestroy() { Shell_NotifyIcon(NIM_DELETE, &nid); CDialog::OnDestroy(); // TODO: 在此处添加消息处理程序代码 } void CAutoGetAwsFileDlg::OnSysCommand(UINT nID, LPARAM lParam) { // TODO: 在此添加消息处理程序代码和/或调用默认值 if ( (nID == SC_MINIMIZE) || (nID == SC_CLOSE)) { HideToTray(); ShowWindow(SW_HIDE); //隐藏主窗口 } else { CDialog::OnSysCommand(nID, lParam); } } LRESULT CAutoGetAwsFileDlg::OnShowTask(WPARAM wParam,LPARAM lParam) //wParam接收的是图标的ID,而lParam接收的是鼠标的行为 { if(wParam!=IDR_MAINFRAME) return 1; switch(lParam) { case WM_RBUTTONUP://右键起来时弹出快捷菜单,这里只有一个“关闭” { LPPOINT lpoint=new tagPOINT; ::GetCursorPos(lpoint);//得到鼠标位置 CMenu menu; menu.CreatePopupMenu();//声明一个弹出式菜单 //增加菜单项“关闭”,点击则发送消息WM_DESTROY给主窗口(已 //隐藏),将程序结束。 menu.AppendMenu(MF_STRING,WM_DESTROY," 退出 "); //确定弹出式菜单的位置 menu.TrackPopupMenu(TPM_LEFTALIGN,lpoint->x,lpoint->y,this); //资源回收 HMENU hmenu=menu.Detach(); menu.DestroyMenu(); delete lpoint; } break; case WM_LBUTTONDBLCLK://双击左键的处理 { ShowWindow(SW_SHOWNORMAL);//简单的显示主窗口完事儿 } break; } return 0; } //bool GetFtpFile(CTime current_time); void InsertIntoMysql() { char buf[10]; GetPrivateProfileString("database","auto-insert-into-mysql","false",buf,10,"./setup.ini"); if(CString(buf).MakeLower() == "true") { char path_buf[1000], name_buf[1000]; GetPrivateProfileString("database","program-path",".\\",path_buf,1000,"./setup.ini"); GetPrivateProfileString("database","program-name","InsertIntoMysql.exe",name_buf,1000,"./setup.ini"); CString filepath = path_buf, filename = name_buf; //执行 PROCESS_INFORMATION proif; STARTUPINFO stif = {sizeof(stif)}; BOOL res = ::CreateProcess(NULL,(filepath+filename).GetBuffer(),NULL,NULL,FALSE,0,NULL,filepath,&stif,&proif); } } void CAutoGetAwsFileDlg::OnTimer(UINT_PTR nIDEvent) { // TODO: 在此添加消息处理程序代码和/或调用默认值 if(nIDEvent == 1) { KillTimer(nIDEvent); GetLastReadTime(); GetFtpFile(); //获取新文件 int cur_minute = CTime::GetCurrentTime().GetMinute(); if(cur_minute>9 && cur_minute<15) { InsertIntoMysql(); } SetLastReadTime(last_time); SetProgramState("程序将自动登陆FTP读取最新文件...\n"+last_time.Format("最近读取时次:%Y-%m-%d %H时")); SetTimer(1,3*1000*60,NULL);// 时间不能太短 否则函数SetLastReadTime()还没执行完毕 } CDialog::OnTimer(nIDEvent); } bool CAutoGetAwsFileDlg::GetFtpFile() { bool isdownload=false; try { CInternetSession sess("My FTP Session"); SetProgramState("正在登陆服务器..."); CFtpConnection* pConnect = sess.GetFtpConnection("172.18.172.155","lyqxt","lyqxt");//登录 SetProgramState("成功登陆,正在查找文件..."); pConnect->SetCurrentDirectory("/aws"); CFtpFileFind finder(pConnect); // start looping BOOL working = finder.FindFile("*"); while(working) { working = finder.FindNextFileA(); CString filename=finder.GetFileName(); CTime LastAccessTime,LastWriteTime,CreationTime; //finder.GetLastAccessTime(LastAccessTime); 不能读取 finder.GetLastWriteTime(LastWriteTime); //最后修改时间 //finder.GetCreationTime(CreationTime); 不能读取 CString TimeStr = LastAccessTime.Format("%Y-%m-%d %H:%M:%S")+LastWriteTime.Format("\n%Y-%m-%d %H:%M:%S")+CreationTime.Format("\n%Y-%m-%d %H:%M:%S"); //MessageBox(TimeStr); if(LastWriteTime > this->last_time) { SetProgramState("找到文件 "+filename+", 开始尝试下载"); if(pConnect->GetFile(filename,this->savepath+filename,FALSE)) { SetProgramState("下载文件 "+filename+ "成功!"); last_time = LastWriteTime; isdownload = true; } } } if (pConnect != NULL) { pConnect->Close(); delete pConnect; } //cout<<"本次监测结束 将在10分钟后重新登录Ftp服务器查看"<<endl; } catch (CInternetException* pEx) { char error[1025]; pEx->GetErrorMessage(error, 1024); SetProgramState("出现错误:"+CString(error)); //cout<<"ERROR!"<<error<<endl; pEx->Delete(); return false; } return isdownload ; } // 设置程序状态并刷新 void CAutoGetAwsFileDlg::SetProgramState(CString state) { ProgramState = state; UpdateData(FALSE); } // 从配置文件读取上次读取文件时间 void CAutoGetAwsFileDlg::GetLastReadTime(void) { char filepath[1024]; DWORD result = GetPrivateProfileString("file","savepath",NULL,filepath,1000,"./setup.ini"); if(result) { savepath = filepath; } else { CreateDirectory("aws-files",NULL); //此函数自动创建文件或者节名 WritePrivateProfileString("file","savepath","aws-files\\","./setup.ini"); } int year,month,day,hour,minute,second; year = GetPrivateProfileInt("lasttime","year",-1,"./setup.ini"); month= GetPrivateProfileInt("lasttime","month",-1,"./setup.ini"); day = GetPrivateProfileInt("lasttime","day",-1,"./setup.ini"); hour = GetPrivateProfileInt("lasttime","hour",-1,"./setup.ini"); minute=GetPrivateProfileInt("lasttime","minute",-1,"./setup.ini"); second=GetPrivateProfileInt("lasttime","second",-1,"./setup.ini"); if(year<0 || month<0 || day<0 || hour<0 || minute<0 || second<0) { last_time = CTime::GetCurrentTime()-CTimeSpan(2,10,0,0); SetLastReadTime(last_time); } else { last_time = CTime(year,month,day,hour,minute,second); } } // 设置读取时间 void CAutoGetAwsFileDlg::SetLastReadTime(CTime last_time) { WritePrivateProfileString("lasttime","year",last_time.Format("%Y"),"./setup.ini"); WritePrivateProfileString("lasttime","month",last_time.Format("%#m"),"./setup.ini"); WritePrivateProfileString("lasttime","day",last_time.Format("%#d"),"./setup.ini"); WritePrivateProfileString("lasttime","hour",last_time.Format("%#H"),"./setup.ini"); WritePrivateProfileString("lasttime","minute",last_time.Format("%#M"),"./setup.ini"); WritePrivateProfileString("lasttime","second",last_time.Format("%#S"),"./setup.ini"); } // 开机自动运行 void CAutoGetAwsFileDlg::AutoRunAfterStart(void) { char AppName[MAX_PATH]; GetModuleFileName(NULL,AppName,MAX_PATH); CString skey = "Software\\Microsoft\\Windows\\CurrentVersion\\Run"; CRegKey writevalue; writevalue.Create(HKEY_LOCAL_MACHINE,skey); int error = writevalue.SetStringValue("AGAFD",AppName); writevalue.Close(); }
#ifndef ORDEREDLINK_H #define ORDEREDLINK_H #include <iostream> #include <stdlib.h> #include "Link.h" using namespace std; template <typename _Type,bool AllowMultiply> class OrderedLink { public: Link<_Type> Data; OrderedLink() { } ~OrderedLink() { } Node<_Type>* GetHead() { return Data.Head; } void Copy(OrderedLink<_Type, AllowMultiply>& Object) { Data.Copy(Object.Data); } bool Add(const _Type& Object) { Node<_Type>* Temp=Data.Head; if (Temp) { while (Temp) { if (Object==Temp->Data) { if (AllowMultiply) { Data.AddPrev(Temp)->Data=Object; return true; } else return false; } else if (Object<Temp->Data) { Data.AddPrev(Temp)->Data=Object; return true; } Temp=Temp->Next; } } Data.AddLast()->Data=Object; return true; } Node<_Type>* Find(const _Type& Object) { return Data.Find(Object); }; bool Exists(const _Type& Object) { return Data.Find(Object)!=0; } void Delete(Node<_Type>* Object) { if (AllowMultiply) { Node<_Type>* Temp=Data.Head; while (Temp) { if (Temp->Data==Object->Data) { Node<_Type>* Temp_Delete=Temp; Temp=Temp->Next; Data.Delete(Temp_Delete); } else Temp=Temp->Next; } } else { Node<_Type>* Temp=Data.Find(Object->Data); if (Temp) Data.Delete(Temp); } } bool operator==(const OrderedLink<_Type, AllowMultiply>& Object) { Node<_Type>* Temp=Data.Head; Node<_Type>* Temp_Object=Object.Data.Head; while (true) { if (Temp && Temp_Object) { if (Temp->Data!=Temp_Object->Data) return false; Temp=Temp->Next; Temp_Object=Temp_Object->Next; } else if (!Temp && !Temp_Object) return true; else return false; } } void Zero() { Data.Zero(); } }; #endif
#include <iostream> #include <vector> using namespace std; void swapInt(int *a, int *b) { int temp = *a; *a = *b; *b = temp; return; } int runningTime(vector<int> &arr) { int shift = 0; for(int i = 1; i < arr.size(); i++) { for(int j = i; j > 0; j--) { if (arr[j] < arr[j-1]) { swap(arr[j], arr[j-1]); shift++; } } } return shift; } int main() { vector<int> mArray = {2, 1, 3, 1, 2,6,4,8}; cout << runningTime(mArray); return 0; }
#include <iostream> using namespace std; int c; void Soma() { int a, b; a = 5; b = 7; c = a + b; } int main() { c = 15; Soma(); cout<<(c); }
#include "edlines.h" #include "utils.h" #include <ctime> #include "triangle.h" #include "RandomSeeds.h" #include "ColorLab.h" //// The following struct represents a unsigned int precision 2D point. ////struct Pixel { //// unsigned int x;//X coordinate //// unsigned int y;//Y coordinate ////}; //typedef vector<Pixel> EdgeChain; //typedef vector<vector<Pixel> > VecEdgeChains; // //int EdgeChainsToVecEdgeChains(VecEdgeChains &vedges, const EdgeChains edges) { // // Pixel dot; // vedges.resize(edges.numOfEdges); // unsigned int index = 0; // for (int i = 0; i < edges.numOfEdges; i++) { // for (int k = 0; k < (edges.sId[i+1] - edges.sId[i]) && index < edges.xCors.size(); k++) { // dot.x = edges.xCors[index]; // dot.y = edges.yCors[index]; // vedges[i].push_back(dot); // index++; // } // } // return 1; // //} #define yita 0.02; //float MINLength; int main() { ImgSet Set; Set.InitImg = GetInitImg("img1.png"); Set.GrayImg = GetGrayImg(Set.InitImg); Set.FilterImg = GetFilterImg(Set.GrayImg); uint xsize = Getxsize(Set.FilterImg); uint ysize = Getysize(Set.FilterImg); uchar *data = GetImgData(Set.FilterImg); EdgeChains edges = GetEdgeChains(data, xsize, ysize); DeviationMetric DistanceDeviationMetric = &perpendicularDistance; //DeviationMetric DistanceToSegmentDeviationMetric = &shortestDistanceToSegment; float MINLength = (xsize + ysize) * yita; VecEdgeChains vedges; EdgeChainsToVecEdgeChains(vedges, edges); VecEdgeChainsToEdgeChains(edges, vedges); //重新转为edges,目的是减去尾部的(0,0) for (int i = 0; i < vedges.size(); i++) { DVector2D *segment = EDToPath(vedges[i]); unsigned int upointsincurrentpath = vedges[i].size(); compactPath(segment, upointsincurrentpath, segment, &upointsincurrentpath, 1, DistanceDeviationMetric); vedges[i] = PathToED(segment, upointsincurrentpath); delete segment; } EdgeChains edgesPathCompact; VecEdgeChainsToEdgeChains(edgesPathCompact, vedges); //clock_t begin = clock(); //clock_t end = clock(); //double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; //cout << elapsed_secs << endl; //EdgeChain JFASeeds; //EdgeChainsToJFASeeds(JFASeeds, edges); //是利用所有的edges点连成的线,慢一点,感觉正确一点 EdgeChain JFASeeds; JFASeeds.resize(edges.xCors.size()); for (uint i = 0; i < edges.xCors.size(); i++) { JFASeeds[i].x = edges.xCors[i]; JFASeeds[i].y = edges.yCors[i]; } //这一部分可以写成一个函数 //EdgeChainsToJFASeeds(Seeds, edgesPathCompact); //是利用简化后的edges点连成的线,快一点 //EdgeChain JFASeeds; //JFASeeds.resize(edgesPathCompact.xCors.size()); //for (uint i = 0; i < edgesPathCompact.xCors.size(); i++) { // JFASeeds[i].x = edgesPathCompact.xCors[i]; // JFASeeds[i].y = edgesPathCompact.yCors[i]; //} //这一部分可以写成一个函数 float* flowDisMap = (float*)malloc(sizeof(float) * xsize * ysize); ExecuteJumpFloodingDis(flowDisMap, JFASeeds, xsize, ysize); int optTimes = 15; int NumPoints = 250; Seeds RandomSeeds = creatRandomSeeds(xsize, ysize, NumPoints); Seeds optEdges = VertexOptimization(RandomSeeds, xsize, ysize, optTimes, flowDisMap); DrawLines(edges, xsize, ysize); DrawLines(edgesPathCompact, xsize, ysize); //DrawPlots(edges, xsize, ysize); EdgeChains optSeeds; optSeeds.xCors.resize(optEdges.size()); optSeeds.yCors.resize(optEdges.size()); for (size_t i = 0; i < optEdges.size(); i++) { optSeeds.xCors[i] = optEdges[i].x; optSeeds.yCors[i] = optEdges[i].y; } DrawPlots(optSeeds, xsize, ysize); cout << xsize << "\t" << ysize << endl; //合并 采样点 与 关键点 //绘制三角剖分模型 Size size = Set.InitImg.size(); Rect rect(0, 0, size.width, size.height); Subdiv2D subdiv(rect); for (int i = 0; i <optSeeds.xCors.size(); i++) { cv::Point2f p; p.x = optSeeds.xCors[i]; p.y = optSeeds.yCors[i]; subdiv.insert(p); } //三角剖分简化的关键点 for (int i = 0; i <edgesPathCompact.xCors.size(); i++) { cv::Point2f p; p.x = edgesPathCompact.xCors[i]; p.y = edgesPathCompact.yCors[i]; subdiv.insert(p); } subdiv.insert(cv::Point2f (0, 0)); subdiv.insert(cv::Point2f (0, ysize-1)); subdiv.insert(cv::Point2f (xsize - 1, 0)); subdiv.insert(cv::Point2f (xsize - 1, ysize - 1)); ////三角剖分可视化全部的关键点 //for (int i = 0; i <edges.xCors.size(); i++) { // cv::Point2f p; // p.x = edges.xCors[i]; // p.y = edges.yCors[i]; // subdiv.insert(p); //} Mat img(ysize, xsize, CV_8UC3, Vec3b(0, 0, 0)); Vec3b delaunay_color(255, 0, 255), points_color(0, 0, 255); draw_delaunay(img, subdiv, delaunay_color); imshow("Delaunay", img); waitKey(); vector<vector<Vec3f>> ColorMap(ysize); fill(ColorMap.begin(), ColorMap.end(), vector<Vec3f>(xsize, (0,0,0))); vector<vector<bool> > IsPointScanedMap(ysize); fill(IsPointScanedMap.begin(), IsPointScanedMap.end(), vector<bool>(xsize, false)); //ColorPointInTriangle(IsPointScanedMap, L_component, ColorMap, const Vec6f triangle) Mat LabMap(ysize, xsize, CV_8UC3, Vec3b(0, 0, 0)); Mat RGBMap(ysize, xsize, CV_8UC3, Vec3b(0, 0, 0)); cvtColor(Set.InitImg, LabMap, COLOR_RGB2Lab); ReadImgColorOnOpencv(LabMap, ColorMap); std::vector<Vec6f> triangleList; subdiv.getTriangleList(triangleList); //获得三角剖分的三角形 for (size_t i = 0; i < triangleList.size(); ++i) { ColorPointInTriangle(IsPointScanedMap, LabMap, ColorMap, triangleList[i]); } WriteImgColorOnOpencv(ColorMap, LabMap); cvtColor(LabMap, RGBMap, COLOR_Lab2RGB); imshow("Res", RGBMap); waitKey(); int a = 1; } /* 第一次采样较密,泊松点采样即可少; 第一次采样较稀,泊松点采样需要多,迭代次数? 多也不需要太多,看迭代次数? 加!号次数越多越不好 (对于edges不足) 加!号次数越多,泊松点越在edges附近 泊松采样是为了弥补edges点不足 初步判定不加!号好(对于edges不足) 初步判定泊松点多好(对于edges不足) 加!号次数越多,泊松点越在edges附近 为什么不加!号: 因为没有泊松点采样时,只有边界上的点,此时会有大量尖锐的三角形出现; 而加入泊松点采样,更加均匀的分布在非边界点的地方,降低了尖锐三角形效果 */
#include <iostream> #include <vector> #include <queue> #define MAX 32001 using namespace std; struct Problem{ int idx, indegree = 0; vector<int> next; }; Problem problem[MAX]; int main(){ ios_base::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; for(int i = 1; i <= n; i++){ problem[i].idx = i; } while(m--){ int a, b; cin >> a >> b; problem[a].next.push_back(b); problem[b].indegree++; } priority_queue<int, vector<int>, greater<int>> pq; for(int i = 1; i <= n; i++){ if(problem[i].indegree == 0){ pq.push(i); } } while(!pq.empty()){ int idx = pq.top(); cout << idx << " "; pq.pop(); for(int nIdx : problem[idx].next){ if(--problem[nIdx].indegree == 0){ pq.push(nIdx); } } } return 0; }
#include<iostream> using namespace std; int max(int a,int b){ return a>b?a:b; } int roofTop(int arr[],int n){ int temp=0,res=0; for(int i=1;i<n;i++){ if(arr[i]>arr[i-1]){ temp++; } else{ temp=0; } res=max(res,temp); } return res; }
#include <iostream> #include <fstream> #include <vector> #include <regex> using namespace std; struct Cs { int id; string name; int quantity; int quantityInWork; float efficiency; void Launch() { if (quantityInWork < quantity) quantityInWork++; else cout << "Все цехи включены" << endl; } void Stop() { if (quantityInWork > 0) quantityInWork--; else cout << "Все цехи выключены" << endl; } }; struct Tube { int id; float length; float diam; bool repaired = false; void Edit() { this->repaired = !this->repaired; } }; bool isPositiveFloat(const string& s) { const regex digit_regex("^[\+]?[0-9]+(\,[0-9])?[0-9]*$"); return regex_match(s, digit_regex); } bool isPositiveInteger(const string& s) { const regex digit_regex("^[\+]?[0-9]+$"); return regex_match(s, digit_regex); } float inputPositiveFloat(const string& msg) { char str[20]; bool first = true; do { if (!first) cout << "Некорректный ввод, введите еще раз >> "; cout << msg; cin >> str; first = false; } while (!isPositiveFloat(str)); return atof(str); } int inputPositiveInteger(const string& msg) { char str[20]; bool first = true; do { if (!first) cout << "Некорректный ввод, введите еще раз >> "; cout << msg; cin >> str; first = false; } while (!isPositiveInteger(str)); return atoi(str); } void AddTube(int &idTube, vector<Tube> &arrTube) { Tube tube1; tube1.id = idTube; tube1.length = inputPositiveFloat("Введите длину: "); tube1.diam = inputPositiveFloat("Введите диаметр: "); arrTube.push_back(tube1); idTube++; } void AddCs(int& idCs, vector<Cs>& arrCs) { Cs cs1; cs1.id = idCs; cout << "Введите наименование: "; cin >> cs1.name; cs1.quantity = inputPositiveInteger("Введите количество цехов: "); int cur = inputPositiveInteger("Введите количество цехов в работе: "); while (cur > cs1.quantity) { cout << "Введенное число больше количества цехов! "; cur = inputPositiveInteger("Введите количество цехов в работе: "); } cs1.quantityInWork = cur; cs1.efficiency = inputPositiveFloat("Введите показатель эффективности: "); cout << endl; arrCs.push_back(cs1); idCs++; } void View(vector<Tube>& arrTube, vector<Cs>& arrCs) { int idCs = 1; int idTube = 1; for (auto it : arrCs) { cout << "Компрессорная станция №: " << idCs++ << endl; cout << "Наименование: " << it.name << endl; cout << "Количество цехов: " << it.quantity << endl; cout << "Количество цехов в работе: " << it.quantityInWork << endl; cout << "Показатель эффективности: " << it.efficiency << endl << endl; } for (auto it : arrTube) { cout << "Труба №: " << idTube++ << endl; cout << "Длина: " << it.length << endl; cout << "Диаметр: " << it.diam << endl; if (!it.repaired) cout << "В ремонте: нет" << endl << endl; else cout << "В ремонте: да" << endl << endl; } } void EditTube(vector<Tube>& arrTube) { int id; id = inputPositiveInteger("Введите номер трубы: "); if (id > arrTube.size() || id < 1) { cout << "Такой трубы не существует! " << endl; } else { id = id - 1; arrTube[id].Edit(); } } void EditCs(vector<Cs>& arrCs) { int id; id = inputPositiveInteger("Введите номер КС: "); if (id > arrCs.size() || id < 1) { cout << "Такой станции не существует! " << endl; } else { int n; id = id - 1; n = inputPositiveInteger("Введите 1, чтобы запустить цех, или 2, чтобы остановить цех: "); while (n != 1 && n != 2) { cout << "Введенное число не равно 1 или 2! "; n = inputPositiveInteger("Введите номер команды: "); } if (n == 1) arrCs[id].Launch(); else arrCs[id].Stop(); } } void Save(vector<Tube>& arrTube, vector<Cs>& arrCs) { ofstream fout; fout.open("output.txt"); int idTube = 1; int idCs = 1; if (arrCs.size() == 0) fout << "Нет КС!"; for (auto& it : arrCs) { fout << "Компрессорная станция №: " << idCs++ << endl; fout << "Наименование: " << it.name << endl; fout << "Количество цехов: " << it.quantity << endl; fout << "Количество цехов в работе: " << it.quantityInWork << endl; fout << "Показатель эффективности: " << it.efficiency << endl << endl; } if (arrTube.size() == 0) fout << "Нет труб!"; for (auto& it : arrTube) { fout << "Труба №: " << idTube++ << endl; fout << "Длина: " << it.length << endl; fout << "Диаметр: " << it.diam << endl; fout << (it.repaired ? "В ремонте !" : "Не в ремонте!") << endl << endl; } cout << "Вывели трубы и КС в файл output.txt" << endl; fout.close(); } void Load(vector<Tube>& arrTube, vector<Cs>& arrCs) { ifstream fin("input.txt"); if (!fin.is_open()) cout << "Файл не может быть открыт!"; else { arrTube.clear(); arrCs.clear(); Tube tube1; Cs cs1; string buff; int idTube = 1; int idCs = 1; while (fin >> buff) { if (buff == "tube") { tube1.id = idTube++; fin >> tube1.length; fin >> tube1.diam; arrTube.push_back(tube1); } else { Cs cs1; cs1.id = idCs++; fin >> cs1.name; fin >> cs1.quantity; fin >> cs1.quantityInWork; fin >> cs1.efficiency; arrCs.push_back(cs1); } } } cout << "Ввели из файла данные" << endl; fin.close(); } int main() { setlocale(LC_ALL, "Russian"); vector<Cs> arrCs; vector<Tube> arrTube; int idCs = 1; int idTube = 1; for (;;) { int command; cout << "1. Добавить трубу" << endl << "2. Добавить КС" << endl << "3. Просмотр всех объектов" << endl << "4. Редактировать трубу" << endl << "5. Редактировать КС" << endl << "6. Сохранить" << endl << "7. Загрузить" << endl << "0. Выход" << endl; command = inputPositiveInteger("Введите номер команды: "); while (command > 7) { cout << "Введенное число больше 7! "; command = inputPositiveInteger("Введите номер команды: "); } switch (command) { case 1: { AddTube(idTube, arrTube); break; } case 2: { AddCs(idCs, arrCs); break; } case 3: { View(arrTube, arrCs); break; } case 4: { EditTube(arrTube); break; } case 5: { EditCs(arrCs); break; } case 6: { Save(arrTube, arrCs); break; } case 7: { Load(arrTube, arrCs); break; } case 0: return 0; } } }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<algorithm> #include<cmath> using namespace std; int a[1001000]; long long gcd(long long a,long long b) { while (b) { long long t = a;a = b;b = t%b; } return a; } long long pow2(int x) { long long ans = x; return ans*ans; } int main() { int t; a[1] = 1; long long x,y,k,ans; scanf("%I64d",&t); while (t--) { scanf("%I64d%I64d%I64d",&x,&y,&k); x = gcd(x,y); int s = 1,sum; for (int i = 2;pow2(i) <= x; i++) if (x%i == 0) a[++s] = i; sum = s+s; if (a[s]*a[s] == x) sum--; if (k > sum) ans = -1; else { if (k <= s) ans = x/a[k]; else ans = a[sum+1-k]; } printf("%I64d\n",ans); } return 0; }
/**************************************************************** File Name: hierarchy.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 <assert.h> #include "global.h" #include "util.h" #include "vector.h" #include "rectangle.h" #include "cfentry.h" #include "cutil.h" #include "parameter.h" #include "hierarchy.h" /* for MergeHierarchy use only */ static void Update_Distance(int n1, int n2, int CurI, int NextI, int n, int *checked, double *dist) { int i, j; double d1, d2; for (i=0; i<CurI; i++) { if (checked[i]!=0) { if (i!=NextI) { d1 = dist[i*n-i*(i+1)/2+CurI-i-1]; if (i<NextI) d2 = dist[i*n-i*(i+1)/2+NextI-i-1]; else d2 = dist[NextI*n-NextI*(NextI+1)/2+i-NextI-1]; dist[i*n-i*(i+1)/2+CurI-i-1] = (n1*d1+n2*d2)/(n1+n2); }}} for (j=CurI+1; j<n; j++) { if (checked[j]!=0) { if (j!=NextI) { d1 = dist[CurI*n-CurI*(CurI+1)/2+j-CurI-1]; if (j<NextI) d2 = dist[j*n-j*(j+1)/2+NextI-j-1]; else d2 = dist[NextI*n-NextI*(NextI+1)/2+j-NextI-1]; dist[CurI*n-CurI*(CurI+1)/2+j-CurI-1] = (n1*d1+n2*d2)/(n1+n2); }}} } /* for MergeHierarchy use only */ static int Pick_One_Unchecked(int n, int *checked) { int i,j = rand() % n; for (i=0;i<n;i++) if (checked[(i+j)%n]!=0) return (i+j)%n; return -1; } /* for MergeHierarchy use only */ static int Nearest_Neighbor(int CurI, int n, int *checked, double *dist) { int i, imin=0; double d, dmin = HUGE; for (i=0;i<CurI;i++) { if (checked[i]!=0){ d = dist[i*n-i*(i+1)/2+CurI-i-1]; if (d<dmin) { dmin=d; imin=i; } }} for (i=CurI+1;i<n;i++) { if (checked[i]!=0){ d = dist[CurI*n-CurI*(CurI+1)/2+i-CurI-1]; if (d<dmin) { dmin=d; imin=i; } }} if (dmin<HUGE) return imin; else return -1; } /* for SplitHierarchy use only */ static int Farthest_Merge(int chainptr, int *chain, double *dd) { if (chainptr<=0) return chainptr; double d, dmax = 0; int i, imax = -1; for (i=0; i<=chainptr; i++) { if (chain[i]<0) { d = dd[-chain[i]-1]; if (d>dmax) {imax = i; dmax = d;} }} return imax; } /* for SplitHierarchy use only */ static int Largest_Merge(int chainptr, int *chain, Entry *cf, short ftype, double ft) { for (int i=0; i<=chainptr; i++) { if (chain[i]<0) { if (cf[-chain[i]-1].Fitness(ftype)>ft) return i; }} return -1; } /********************************************************************* This is an O(n^2) algorithm, but works only for D2 and D4 due to the "REDUCIBILITY PROPERTY" that is given as below: if d(i,j) < p, d(i,k) > p, d(j,k) > p then d(i+j,k) > p. Algorithm: Part 1: MergeHierarchy: form the complete hierarchy in O(n^2) time step1: Pick any cluster i[1]. step2: Determine the chain i[2]=NN(i[1]), i[3]=NN(i[2]) ... until i[k]=NN(i[k-1]) and i[k-1]=NN(i[k]), where NN means nearest neighbor. step3: Merge clusters i[k-1] and i[k]. step4: If more than 1 clusters left, goto step using i[k-2] as start if (k-2>0), otherwise choose arbitrary i[1]. Part 2: SplitHierarchy: cut from the complete hierarchy in O(n^2) by number of clusters K, by the threshold Ft, by tree height H, ... *********************************************************************/ void Hierarchy::MergeHierarchy(short gdtype, // distance type int nentry, // number of entries Entry *entries) // array storing entries { if (gdtype!=D2 && gdtype!=D4) print_error("MergeHierarchy","only support distance D2 and D4"); int i,j,n1,n2; int CurI, PrevI, NextI; int uncheckcnt = nentry; int *checked = new int[nentry]; for (i=0;i<nentry;i++) checked[i]=i+1; // 0: invalid after being merged to other entries // positive 1..nentry+1 : original entries // negative -1..-(nentry-1) : merged entries // get initial distances double *dist=new double[nentry*(nentry-1)/2]; for (i=0; i<nentry-1; i++) for (j=i+1; j<nentry; j++) dist[i*nentry-i*(i+1)/2+j-i-1] = distance(gdtype,entries[i],entries[j]); CurI = rand() % nentry; // step1 chain[++chainptr]=CurI; while (uncheckcnt>1) { if (chainptr==-1) { // step4 chainptr++; chain[chainptr]=Pick_One_Unchecked(nentry,checked); } if (chainptr>0) PrevI=chain[chainptr-1]; else PrevI=-1; stopchain=FALSE; while (stopchain==FALSE) { // step2 CurI=chain[chainptr]; NextI = Nearest_Neighbor(CurI,nentry,checked,dist); // it is impossible NextI be -1 because uncheckcnt>1 if (NextI==PrevI) stopchain = TRUE; else { chain[++chainptr]=NextI; PrevI = CurI; } } // end of while for step 2 step++; ii[step] = checked[CurI]; // step3 jj[step] = checked[NextI]; if (CurI<NextI) dd[step] = dist[CurI*nentry-CurI*(CurI+1)/2+NextI-CurI-1]; else dd[step] = dist[NextI*nentry-NextI*(NextI+1)/2+CurI-NextI-1]; if (checked[CurI]>0) { n1 = entries[CurI].n; if (checked[NextI]>0) { n2 = entries[NextI].n; cf[step].Add(entries[CurI],entries[NextI]); } else { n2 = cf[-checked[NextI]-1].n; cf[step].Add(entries[CurI],cf[-checked[NextI]-1]); } } else { n1 = cf[-checked[CurI]-1].n; if (checked[NextI]>0) { n2 = entries[NextI].n; cf[step].Add(cf[-checked[CurI]-1],entries[NextI]); } else { n2 = cf[-checked[NextI]-1].n; cf[step].Add(cf[-checked[CurI]-1],cf[-checked[NextI]-1]); } } Update_Distance(n1,n2,CurI,NextI,nentry,checked,dist); uncheckcnt--; checked[CurI] = -(step+1); checked[NextI] = 0; chainptr--; chainptr--; } //end of while (uncheckcnt>1) if (checked) delete [] checked; if (dist) delete [] dist; // prepare for SplitHierarchy stopchain = FALSE; chainptr = 0; chain[chainptr] = -(step+1); } short Hierarchy::SplitHierarchy(short option,short ftype,double ft) { int i, j; switch (option) { case BY_THRESHOLD: if (stopchain==TRUE) return FALSE; i = Largest_Merge(chainptr,chain,cf,ftype,ft); if (i!=-1) {j = -chain[i]-1; chain[i] = ii[j]; chain[++chainptr]=jj[j]; return TRUE; } else {stopchain = TRUE; return FALSE;} break; case BY_KCLUSTERS: if (chainptr==size) return FALSE; i = Farthest_Merge(chainptr,chain,dd); if (i!=-1) {j = -chain[i]-1; chain[i]=ii[j]; chain[++chainptr]=jj[j]; return TRUE; } else return FALSE; break; } return FALSE; //dummy } double Hierarchy::MinFtMerged(short ftype) { int MinI; double tmpFt, MinFt=HUGE_DOUBLE; for (int i=0; i<=chainptr; i++) { if (chain[i]<0) { tmpFt=cf[-chain[i]-1].Fitness(ftype); if (tmpFt<MinFt) {MinFt=tmpFt; MinI=i;} } } // prepare for physically merging the MinI cluster stopchain=FALSE; chainptr=0; chain[0]=chain[MinI]; return MinFt; } double Hierarchy::DistortionEdge(Entry *entries) { double TotalDistort=0; for (int i=0; i<=chainptr; i++) { if (chain[i]<0) TotalDistort+=cf[-chain[i]-1].N()*cf[-chain[i]-1].Radius(); else TotalDistort+=entries[chain[i]-1].N()*entries[chain[i]-1].Radius(); } return TotalDistort; } double Hierarchy::NmaxFtMerged(short ftype) { double NmaxFt; int maxn; maxn = 0; NmaxFt=0; for (int i=0; i<=chainptr; i++) { if (chain[i]<0 && cf[-chain[i]-1].N()>maxn) { maxn = cf[-chain[i]-1].N(); NmaxFt = cf[-chain[i]-1].Fitness(ftype); } } return NmaxFt; } double Hierarchy::TotalFtDEdge(short ftype, short d, Entry *entries) { double TotalFtD=0; for (int i=0; i<=chainptr; i++) { if (chain[i]<0) TotalFtD+=pow(cf[-chain[i]-1].Fitness(ftype),1.0*d); else TotalFtD+=pow(entries[chain[i]-1].Fitness(ftype),1.0*d); } return TotalFtD; } /*********************************************************** This is an O(n^3) algorithm, but works fine for all 5 (D0,D1,D2,D3,D4) distance definitions. It is used to make sure Hierarchy1 and Hierarchy0 can produce the same results for debugging purpose. ************************************************************/ void Hierarchy0(int &n, // final number of clusters const int K, // final number of clusters Entry **entries, short GDtype, short Ftype, double Ft) { if (n<=1) return; int i, j, imin, jmin, done; short *checked = new short[n]; memset(checked,0,n*sizeof(short)); // 0: unchecked; // -1: exceeds the given threshold if merged with nearest neighbor; // -2: nonexistant after merging. double *dist = new double[n*(n-1)/2]; double d, dmin; Entry tmpent; tmpent.Init((*entries)[0].sx.dim); dmin = HUGE; // compute all initial distances and closest pair for (i=0; i<n-1; i++) for (j=i+1; j<n; j++) { d = distance(GDtype,(*entries)[i],(*entries)[j]); dist[i*n-i*(i+1)/2+j-i-1] = d; if (d<dmin) { dmin = d; imin = i; jmin = j; } } if (K==0) {// ****** case 1 ****** cluster by threshold ft done = FALSE; while (done==FALSE) { tmpent.Add((*entries)[imin],(*entries)[jmin]); if (tmpent.Fitness(Ftype) < Ft) { // within the threshold (*entries)[imin] += (*entries)[jmin]; checked[jmin] = -2; for (i=0; i<imin; i++) { if (checked[i]==0) { dist[i*n-i*(i+1)/2+imin-i-1] = distance(GDtype,(*entries)[i],(*entries)[imin]); }} for (j=imin+1; j<n; j++) { if (checked[j]==0) { dist[imin*n-imin*(imin+1)/2+j-imin-1] = distance(GDtype,(*entries)[imin],(*entries)[j]); }} } else { // exceeds the threshold checked[imin] = -1; checked[jmin] = -1; } done = TRUE; dmin = HUGE; for (i=0; i<n-1; i++) { if (checked[i]==0) { for (j=i+1; j<n; j++) { if (checked[j]==0) { d = dist[i*n-i*(i+1)/2+j-i-1]; if (d<dmin) { done = FALSE; dmin = d; imin = i; jmin = j; }}}}} } // end of while } // end of if else { // ***** case 2 ***** cluster by number k done = n; while (done > K) { (*entries)[imin] += (*entries)[jmin]; checked[jmin] = -2; done--; for (i=0; i<imin; i++) { if (checked[i]==0) { dist[i*n-i*(i+1)/2+imin-i-1] = distance(GDtype,(*entries)[i],(*entries)[imin]); }} for (j=imin+1; j<n; j++) { if (checked[j]==0) { dist[imin*n-imin*(imin+1)/2+j-imin-1] = distance(GDtype,(*entries)[imin],(*entries)[j]); }} dmin = HUGE; for (i=0; i<n-1; i++) { if (checked[i]==0) { for (j=i+1; j<n; j++) { if (checked[j]==0) { d = dist[i*n-i*(i+1)/2+j-i-1]; if (d<dmin) { dmin = d; imin = i; jmin = j; }}}}} } // end of while } // end of else j = 0; for (i=0; i<n; i++) if (checked[i]!=-2) { (*entries)[j]=(*entries)[i]; j++; } n=j; delete [] checked; delete [] dist; } /********************************************************************* This is an O(n^2) algorithm, but works only for D2 and D4 due to the "REDUCIBILITY PROPERTY" that is given as below: if d(i,j) < p, d(i,k) > p, d(j,k) > p then d(i+j,k) > p. Algorithm: Part 1: Form the complete hierarchy in O(n^2) time step1: Pick any cluster i[1]. step2: Determine the chain i[2]=NN(i[1]), i[3]=NN(i[2]) ... until i[k]=NN(i[k-1]) and i[k-1]=NN(i[k]), where NN means nearest neighbor. step3: Merge clusters i[k-1] and i[k]. step4: If more than 1 clusters left, goto step using i[k-2] as start if (k-2>0), otherwise choose arbitrary i[1]. Part 2: Split from the complete hierarchy in O(n^2) by number of clusters K, by the threshold Ft, by tree height H, ... *********************************************************************/ void Hierarchy1(int &n, // final number of clusters const int K, // final number of clusters Entry **entries,// array storing clusters short GDtype, short Ftype, double Ft) { if (GDtype!=D2 && GDtype!=D4) print_error("Hierarchy1","only support distance D2 and D4"); if (n<=1) return; if (n==K) return; // ****************** Part 1 ********************** Hierarchy *h = new Hierarchy(n-1,(*entries)[0].sx.dim); h->MergeHierarchy(GDtype,n,*entries); // ******************* Part 2 ********************* if (K==0) { // by the threshold while (h->SplitHierarchy(BY_THRESHOLD,Ftype,Ft)==TRUE); } else { // by the number of clusters while (h->chainptr+1<K && h->SplitHierarchy(BY_KCLUSTERS,Ftype,Ft)==TRUE); } // ******************* Part 3 ********************* int j; Entry *tmpentries = new Entry[h->chainptr+1]; for (j=0;j<=h->chainptr;j++) tmpentries[j].Init((*entries)[0].sx.dim); for (j=0;j<=h->chainptr;j++) { if (h->chain[j]<0) tmpentries[j] = h->cf[-h->chain[j]-1]; else tmpentries[j] = (*entries)[h->chain[j]-1]; } delete [] *entries; *entries = tmpentries; n=h->chainptr+1; delete h; }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> #include <deque> #include <random> const long long LINF = (1e18); const int INF = (1<<28); const int sINF = (1<<23); #define EPS 1e-6 const int MOD = 1000000007; using namespace std; class CollectingRiders { public: vector<string> b; const int dx[8] = {2, 1, -1, -2, -2, -1, 1, 2}; const int dy[8] = {1, 2 , 2, 1, -1, -2, -2, -1}; int search(int K, int cx, int cy, int gx, int gy) { int Y = (int)b.size(); int X = (int)b[0].size(); bool used[55][55]; memset(used, false, sizeof(used)); typedef pair<int, int> P; typedef pair<P, int> T; queue<T> que; que.push(T(P(cx,cy), 0)); while (!que.empty()) { T t = que.front(); que.pop(); P p = t.first; int px = p.first; int py = p.second; int c = t.second; if (px == gx && py == gy) return c/K + (c%K !=0 ? 1 : 0); for (int i=0; i<8; ++i) { int x = px + dx[i]; int y = py + dy[i]; if (0 <= x && x < X && 0 <= y && y < Y && !used[y][x]) { used[y][x] = true; que.push(T(P(x,y), c+1)); } } } return sINF; } int count(int gx, int gy) { int Y = (int)b.size(); int X = (int)b[0].size(); int res = 0; for (int x=0; x<X; ++x) { for (int y=0; y<Y; ++y) if (b[y][x] != '.') { res += search(b[y][x]-'0', x, y, gx, gy); } } return res; } int minimalMoves(vector <string> board) { this->b = board; int ans = sINF; int Y = (int)board.size(); int X = (int)board[0].size(); for (int x=0; x<X; ++x) { for (int y=0; y<Y; ++y) { ans = min(ans, count(x,y)); } } return ans == sINF ? -1 : ans; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"...1", "....", "2..."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(0, Arg1, minimalMoves(Arg0)); } void test_case_1() { string Arr0[] = {"........", ".1......", "........", "....3...", "........", "........", ".7......", "........"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(1, Arg1, minimalMoves(Arg0)); } void test_case_2() { string Arr0[] = {"..", "2.", ".."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; verify_case(2, Arg1, minimalMoves(Arg0)); } void test_case_3() { string Arr0[] = {".1....1."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = -1; verify_case(3, Arg1, minimalMoves(Arg0)); } void test_case_4() { string Arr0[] = {"9133632343", "5286698232", "8329333369", "5425579782", "4465864375", "8192124686", "3191624314", "5198496853", "1638163997", "6457337215"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 121; verify_case(4, Arg1, minimalMoves(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { CollectingRiders ___test; ___test.run_test(-1); } // END CUT HERE
/* filename: mos_ruleset.h author: Sherri Harms last modified: 7/23/01 description: Class mos_ruleset interface file for serial MINEPI REAR rules Values of this type are vectors of s_rules, where a mos_rule is a composite of an antecedent episode, and a consequent episode, with a confidence; ****************************************************************************** Local Data Structures: Local variables: ***************************************************************************** mos_ruleset operations include: input, output, constructors, relational operators, accessor functions and operations to adds rules, etc *******************************************************************************/ #ifndef mos_RULESET_H #define mos_RULESET_H #include "timestamp.h" #include "moserialrule.h" #include <vector> #include <algorithm> #include <iostream> using namespace std; typedef vector<mos_rule> mosrule_set; class mos_ruleset { public: void cleanup(); void clear(); //cleare the current mos_ruleset void insertrule(const mos_rule& in_rule); //add a mos_rule into the mos_ruleset mos_rule get_first_rule() const; //return the first mos_rule bool empty() const; //true if rear empty bool contain(const mos_rule& in_rule) const; //returns true if the mos_ruleset already contains this mos_rule string outputXML(char type) const; //Purpose: To add all of the rules generated by the algorithm to an // XML string for output //Author: Matt Culver //Last Modified: 7 July 2003 //type - The type of episode that the algorthm was looking for void output(ostream& outs, bool rar=false) const; // Dan Li, Oct 29 void output(ostream& outs, char type, bool rar=false) const; // friend bool operator ==(const mos_ruleset& r1, const mos_ruleset& r2); //Returns true if i1 and i2 represent the same mos_ruleset; //otherwise, returns false. // friend bool operator !=(const mos_ruleset& r1, const mos_ruleset& r2); //Returns true if i1 != i2 ; otherwise, returns false. mos_ruleset( ); //Constructor. int AccessCount() const; friend bool operator ==(const mos_ruleset& r1, const mos_ruleset& r2) //Returns true if i1 and i2 represent the same mos_ruleset; //otherwise, returns false. { return (r1.rs==r2.rs); } friend bool operator !=(const mos_ruleset& r1, const mos_ruleset& r2) //Returns true if i1 != i2 ; otherwise, returns false. { return !(r1.rs==r2.rs); } // friend istream& operator >>(istream& ins, mos_ruleset& the_object); //Overloads the >> operator for input values of type mos_ruleset. //Precondition: If ins is a file input stream, then ins has //already been connected to a file. // friend ostream& operator << (ostream& outs, const mos_ruleset& the_object); //Overloads the << operator for output values of type mos_ruleset. //Precondition: If outs is a file output stream, then outs as //already been connected to a file. private: mosrule_set rs; int count; }; #endif //ruleset_H
#ifndef FUNCTION_H #define FUNCTION_H #include <vector> #include <string> #include "../Term.h" #define NATIVE_FUNCTION 1 #define USER_FUNCTION 2 class Env; class Store; class Instr; class GenericFunction { public : virtual int getType() = 0; }; namespace function { class Function : public GenericFunction { public : Function(LTerm*); std::string getName(); int execute(Env*, Store*); unsigned int getNbVar(); unsigned int getArity(); std::string getVarName(int index); virtual int getType(); private : void analyse_arg(LTerm*); std::vector<Instr*> instr; std::string name; std::map<std::string, int> vars; std::map<int, std::string> vars_names; unsigned int arity; unsigned int nb_var; }; } #endif
#ifndef BALL_H #define BALL_H #include <vector> class Ball { public: Ball(float x, float y, float distance, float angle, double dt); void updateVisible(float x, float y, float distance, float angle, double dt); void updateInvisible(double dt); void markForRemoval(double afterSeconds); bool shouldBeRemoved(); int id; double createdTime; double updatedTime; double removeTime; float x; float y; float velocityX; float velocityY; float distance; float angle; float elasticity; float radius; bool visible; private: static int instances; void applyDrag(double dt); }; typedef std::vector<Ball*> BallList; #endif // BALL_H
#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; int main() { int t,n; scanf("%d",&t); for (int ca = 1;ca <= t; ca++) { scanf("%d",&n); int m = 0,sum = 0,k; for (int i = 1;i <= n; i++) { scanf("%d",&k); m = max(m,k); sum += k; } int d = sum/2,ans; if (m-d <= d/2) ans = d; else { ans = (sum-m)*2; if (d&1) ans++; } printf("Case #%d: %d\n",ca,ans); } return 0; }
#include<iostream> using namespace std; int main() { int salary; cout<<"please enter the salary : "; cin>>salary; if(salary<=600) cout<<"tax is equal to : "<<salary*0<<endl<<"and the net pay is : "<<salary; else if (salary<=1650) cout<<"tax is equal to : "<<salary*0.1-60<<endl<<endl<<"and the net pay is : "<<salary-(salary*0.1-60); else if (salary<=3200) cout<<"tax is equal to : "<<salary*0.15-142.5<<endl<<endl<<"and the net pay is : "<<salary-(salary*0.15-142.5); else if (salary<=5500) cout<<"tax is equal to : "<<salary*0.20-302.5<<endl<<endl<<"and the net pay is : "<<salary-(salary*0.20-302.5); else if (salary<=7800) cout<<"tax is equal to : "<<salary*0.25-565<<endl<<endl<<"and the net pay is : "<<salary-(salary*0.25-565); else if (salary<=10900) cout<<"tax is equal to : "<<salary*0.30-950<<endl<<endl<<"and the net pay is : "<<salary-(salary*0.30-950); else if (salary>10900) cout<<"tax is equal to : "<<salary*0.35-1500<<endl<<endl<<"and the net pay is : "<<salary-(salary*0.35-1500); return 0; }
#ifndef OPTIONS_H #define OPTIONS_H #include <time.h> #include <unistd.h> #include "Typedef.h" #include <string> class Options { public: static Options* instance() { static Options * options = NULL; if(options==NULL) options = new Options(); return options; } int parse_args(int argc, char *argv[]); int read_conf(const char file[256]); void printConf(); //*********************************************************** public: //***************监听Server************** //游戏监听Admin char listen_address[256]; short port; //连接大厅的ip和端口 char hall_ip[64]; short hall_port; char redis_ip[64]; short redis_port; //日志 int m_loglevel; std::string m_logRemoteIp; UINT16 m_logRemotePort; time_t lasttime; //扫描监控时间 short monitortime; //默认下注超时时间,可以再其上在加 short basebettime; //连续和用户玩的牌局数 short baseplayCount; //用户等待时间就开启机器人 short entertime; UINT16 m_robotId; //第几个机器人服务器 short level; //机器人明牌打等级 short konwcontrlLevel; int swtichWin1; int swtichWin2; int swtichWin3; int baseMoney1; int baseMoney2; int baseMoney3; int randMoney1; int randMoney2; int baseuid; int randuid; //验证服务器ip和端口 char verifyredis_ip1[64]; short verifyredis_port1; //验证服务器ip和端口 char verifyredis_ip2[64]; short verifyredis_port2; short getinredis; //头像链接 std::string m_headLink; private: Options(); }; #define _CFG_(key) Options::instance()->key #endif
#ifndef image_h #define image_h #include <tr1/array> #include "Color.h" #include "Constants.h" typedef std::tr1::array<std::tr1::array<Color,WIDTH>,HEIGHT> Image; typedef std::tr1::shared_ptr<Image> ImagePtr; #endif
#include "Material.hh" #include "G4UnitsTable.hh" #include "G4SystemOfUnits.hh" #include "G4PhysicalConstants.hh" using namespace CLHEP; Material* Material::instance = 0; Material::Material(void) { G4ElementName.push_back("Null"); G4ElementName.push_back("G4_H") ; G4ElementName.push_back("G4_He") ; G4ElementName.push_back("G4_Li"); G4ElementName.push_back("G4_Be"); G4ElementName.push_back("G4_B"); G4ElementName.push_back("G4_C"); G4ElementName.push_back("G4_N"); G4ElementName.push_back("G4_O"); G4ElementName.push_back("G4_F"); G4ElementName.push_back("G4_Ne"); G4ElementName.push_back("G4_Na"); G4ElementName.push_back("G4_Mg"); G4ElementName.push_back("G4_Al"); G4ElementName.push_back("G4_Si"); G4ElementName.push_back("G4_P"); G4ElementName.push_back("G4_S"); G4ElementName.push_back("G4_Cl"); G4ElementName.push_back("G4_Ar"); G4ElementName.push_back("G4_K"); G4ElementName.push_back("G4_Ca"); G4ElementName.push_back("G4_Sc"); G4ElementName.push_back("G4_Ti"); G4ElementName.push_back("G4_V"); G4ElementName.push_back("G4_Cr"); G4ElementName.push_back("G4_Mn"); G4ElementName.push_back("G4_Fe"); G4ElementName.push_back("G4_Co"); G4ElementName.push_back("G4_Ni"); G4ElementName.push_back("G4_Cu"); G4ElementName.push_back("G4_Zn"); G4ElementName.push_back("G4_Ga"); G4ElementName.push_back("G4_Ge"); G4ElementName.push_back("G4_As"); G4ElementName.push_back("G4_Se"); G4ElementName.push_back("G4_Br"); G4ElementName.push_back("G4_Kr"); G4ElementName.push_back("G4_Rb"); G4ElementName.push_back("G4_Sr"); G4ElementName.push_back("G4_Y"); G4ElementName.push_back("G4_Zr"); G4ElementName.push_back("G4_Nb"); G4ElementName.push_back("G4_Mo"); G4ElementName.push_back("G4_Tc"); G4ElementName.push_back("G4_Ru"); G4ElementName.push_back("G4_Rh"); G4ElementName.push_back("G4_Pd"); G4ElementName.push_back("G4_Ag"); G4ElementName.push_back("G4_Cd"); G4ElementName.push_back("G4_In"); G4ElementName.push_back("G4_Sn"); G4ElementName.push_back("G4_Sb"); G4ElementName.push_back("G4_Te"); G4ElementName.push_back("G4_I"); G4ElementName.push_back("G4_Xe"); G4ElementName.push_back("G4_Cs"); G4ElementName.push_back("G4_Ba"); G4ElementName.push_back("G4_La"); G4ElementName.push_back("G4_Ce"); G4ElementName.push_back("G4_Pr"); G4ElementName.push_back("G4_Nd"); G4ElementName.push_back("G4_Pm"); G4ElementName.push_back("G4_Sm"); G4ElementName.push_back("G4_Eu"); G4ElementName.push_back("G4_Gd"); G4ElementName.push_back("G4_Tb"); G4ElementName.push_back("G4_Dy"); G4ElementName.push_back("G4_Ho"); G4ElementName.push_back("G4_Er"); G4ElementName.push_back("G4_Tm"); G4ElementName.push_back("G4_Yb"); G4ElementName.push_back("G4_Lu"); G4ElementName.push_back("G4_Hf"); G4ElementName.push_back("G4_Ta"); G4ElementName.push_back("G4_W"); G4ElementName.push_back("G4_Re"); G4ElementName.push_back("G4_Os"); G4ElementName.push_back("G4_Ir"); G4ElementName.push_back("G4_Pt"); G4ElementName.push_back("G4_Au"); G4ElementName.push_back("G4_Hg"); G4ElementName.push_back("G4_Tl"); G4ElementName.push_back("G4_Pb"); G4ElementName.push_back("G4_Bi"); G4ElementName.push_back("G4_Po"); G4ElementName.push_back("G4_At"); G4ElementName.push_back("G4_Rn"); G4ElementName.push_back("G4_Fr"); G4ElementName.push_back("G4_Ra"); G4ElementName.push_back("G4_Ac"); G4ElementName.push_back("G4_Th"); G4ElementName.push_back("G4_Pa"); G4ElementName.push_back("G4_U"); G4ElementName.push_back("G4_Np"); G4ElementName.push_back("G4_Pu"); G4ElementName.push_back("G4_Am"); G4ElementName.push_back("G4_Cm"); G4ElementName.push_back("G4_Bk"); G4ElementName.push_back("G4_Cf"); CreateMaterials(); } G4Material * Material::GetMaterial(const G4String name) { G4Material* mat = nistMan->FindOrBuildMaterial(name); if( !mat ) mat = G4Material::GetMaterial(name); if( !mat ) { std::ostringstream o; o << "Material " << name << "NOT FOUND!" ; G4Exception("Materials::GetMaterial","",FatalException,o.str().c_str()); } return mat; } G4Material * Material::GetMaterial(int Z) { G4Material* mat = nistMan->FindOrBuildMaterial(G4ElementName[Z]); if( !mat ) { std::ostringstream o; o << "Material " << Z << "NOT FOUND!" ; G4Exception("Materials::GetMaterial","",FatalException,o.str().c_str()); } return mat; } G4Material * Material::CreateMaterials() { G4double density; //-------------------------------- // wood //-------------------------------- density = 0.9*g/cm3; Wood = new G4Material("Wood", density,3); Wood->AddElement(nistMan->FindOrBuildElement("H") , 4); Wood->AddElement(nistMan->FindOrBuildElement("O") , 1); Wood->AddElement(nistMan->FindOrBuildElement("C") , 2); //-------------------------------- // Cement //-------------------------------- density = 3.15*g/cm3; Cement = new G4Material("Cement", density ,9); Cement->AddElement(nistMan->FindOrBuildElement("O") , 35.63*perCent); Cement->AddElement(nistMan->FindOrBuildElement("Al") , 2.62*perCent); Cement->AddElement(nistMan->FindOrBuildElement("K") , 0.82*perCent); Cement->AddElement(nistMan->FindOrBuildElement("Na") , 0.16*perCent); Cement->AddElement(nistMan->FindOrBuildElement("Si") , 9.09*perCent); Cement->AddElement(nistMan->FindOrBuildElement("Ca") , 45.94*perCent); Cement->AddElement(nistMan->FindOrBuildElement("Mg") , 2.19*perCent); Cement->AddElement(nistMan->FindOrBuildElement("S") , 1.32*perCent); Cement->AddElement(nistMan->FindOrBuildElement("Fe") , 2.23*perCent); } Material * Material::Instance() { if (instance == 0) { instance = new Material(); } return instance; }
// // Created by manout on 17-8-8. // #include <string> #include <sstream> #include <vector> using std::string; using std::stringstream; string reverse_string(const string& sentence) { string buffer; stringstream string_split; std::vector<string> string_list; string ret; // stringstream 会使用空格和换行符作为分割字符串 while(string_split << sentence) { string_split >> buffer; string_list.push_back(buffer); } for (auto it = string_list.rbegin(); it not_eq string_list.rend() - 1; ++it) { ret += *it + ' '; } ret += *string_list.begin(); return ret; }
// seperate odd and even lists, then append the even list to the odd list. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* oddEvenList(ListNode* head) { if (!head || !head->next) return head; ListNode *p1 = head, *p2 = head->next, *p3 = p2; while (p2 && p2->next) { p1->next = p2->next; p2->next = p2->next->next; p1 = p1->next; p2 = p2->next; } p1->next = p3; return head; } };
#ifndef RAND_H #define RAND_H class Rand{ public: Rand(); //����һ��x��y֮�������� int randNum(int x,int y); }; #endif
#include "src/Math/Vector2.h" #include "src/Math/Math.h" namespace Math { Vector2::Vector2() {} Vector2::Vector2(int ax, int ay) : x(static_cast<float>(ax)), y(static_cast<float>(ay)) {} Vector2::Vector2(float ax, float ay) : x(ax), y(ay) {} Vector2::Vector2(const Vector2& a) : x(a.x), y(a.y) {} Vector2::~Vector2(){} Vector2& Vector2::operator=(const Vector2& a) { x = a.x; y = a.y; return *this; } Vector2& Vector2::operator+=(const Vector2& a) { x += a.x; y += a.y; return *this; } Vector2& Vector2::operator-=(const Vector2& a) { x -= a.x; y -= a.y; return *this; } Vector2& Vector2::operator*=(const Vector2& a) { x *= a.x; y *= a.y; return *this; } Vector2& Vector2::operator/=(const Vector2& a) { x /= a.x; y /= a.y; return *this; } Vector2& Vector2::operator*=(float a) { x *= a; y *= a; return *this; } Vector2& Vector2::operator/=(float a) { float div = 1.f / a; x *= div; y *= div; return *this; } const Vector2 Vector2::operator+(const Vector2& a) const { return Vector2(x + a.x, y + a.y); } const Vector2 Vector2::operator-(const Vector2& a) const { return Vector2(x - a.x, y - a.y); } const Vector2 Vector2::operator*(const Vector2& a) const { return Vector2(x * a.x, y * a.y); } const Vector2 Vector2::operator/(const Vector2& a) const { return Vector2(x / a.x, y / a.y); } const Vector2 Vector2::operator-() const { return Vector2(-x, -y); } float Vector2::dot(const Vector2& a) const { return x*a.x + y*a.y; } void Vector2::set_cross(const Vector2& a, const Vector2& b) { x = y; y = -x; } void Vector2::set_normalize() { float len = 1.f / length(); x *= len; y *= len; } const Vector2 Vector2::normalize() const { float len = 1.f / length(); return Vector2(x * len, y * len); } float Vector2::square_length() const { return x*x + y*y; } float Vector2::length() const { return Sqrt(square_length()); } //ここからクラス外 const Vector2 operator*(const Vector2& a, float b) { return Vector2(a.x * b, a.y * b); } const Vector2 operator*(float a, const Vector2& b) { return Vector2(a * b.x, a * b.y); } const Vector2 operator/(const Vector2& a, float b) { return Vector2(a.x / b, a.y / b); } const Vector2 operator/(float a, const Vector2& b) { return Vector2(a / b.x, a / b.y); } }//namespace Math
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include <stdio.h> #include <iostream> #include <stdlib.h> #include <windows.h> #include <string.h> #define StrSize 10 typedef struct { int value; char passedValue[StrSize]; int packetSize; } ControllerInput; typedef struct { float value; char passedValue[StrSize]; int packetSize; } LeapInput; //----------------------------------------------------------------------------- // Function-prototypes //----------------------------------------------------------------------------- HRESULT UpdateControllerState(); int AnalogToDigital(int); void FillByteSize(); void CheckDeadZone(); void CheckLeapDeadZone(); int SendData();
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QListWidget> #include <QListWidgetItem> #include "editwindow.h" #include "library.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_pushButton_2_clicked(); void on_view_btn_clicked(); void on_clear_view_btn_clicked(); void on_delete_selected_clicked(); void on_add_btn_clicked(); void on_edit_btn_clicked(); void on_sort_btn_clicked(); void on_key_word_btn_clicked(); void on_key_word_input_textChanged(); void on_choose_btn_clicked(); private: Ui::MainWindow *ui; //bool isDarkTheme = false; Library *library; QListWidget *viewList; }; #endif // MAINWINDOW_H
#ifndef H_CUSTOMERTYPE #define H_CUSTOMERTYPE //************************************************************ // Author: D.S. Malik // // class personType // This class specifies the members to implement a name. //************************************************************ #include <string> #include <list> #include "personType.h" #include "videoListType.h" using namespace std; class customerType: public personType { public: friend ostream& operator<< (ostream&, const customerType&); //Overload the relational operators. bool operator==(const customerType&) const; bool operator!=(const customerType&) const; void print() const; //Function to output the first name,last name, account number and current videos rented. //in the form firstName lastName. void setName(string first, string last, string, string video); //Function to set firstName and lastName according to the //parameters. //Postcondition: firstName = first; lastName = last; accountNum = num; video = video; void rentVideo(string); //Function to set video to video rented by user. //Postcondition: video = videoType.title; void returnVideo(string); //Function to set video to null. //Postcondition: video = ""; string showAccountNum() const; //Function to return the account number. //Postcondition: The value of accountNum is returned. bool checkCustomer(string); //Function to check whether the title is the same as the //title of the video. //Postcondition: Returns the value true if the title is the // same as the title of the video; false otherwise. bool checkNumber(string num); //Function to check whether the account number is the same as the //certain account number in list. //Postcondition: Returns the value true if the number is the // same as the number in a list; false otherwise. customerType(); //Default constructor //Sets firstName, lastName, number and videos to null strings. //Postcondition: firstName = ""; lastName = ""; accountNum = ""; video = ""; customerType(string first, string last, string num, string video); //Constructor with parameters. //Sets firstName and lastName according to the parameters. //Postcondition: firstName = first; lastName = last; accountNum = num; video = video; private: string firstName; //variable to store the first name string lastName; //variable to store the last name string accountNum; string video; }; #endif
// // main.cpp // divide-two-integers // // Created by xiedeping01 on 15/11/11. // Copyright (c) 2015年 xiedeping01. All rights reserved. // #include <iostream> #include <limits> #include <vector> using namespace std; class Solution { public: int divide(int dividend, int divisor) { // 基本思路:用减法模拟除法 // 但是要注意:符号问题、溢出问题、除零问题、性能问题 // 1. 符号问题,首先基于绝对值计算,然后补上符号 // 2. 溢出问题,计算过程中使用long long类型,并且如果结果是 1L << 31,则溢出 // 3. 除零问题,要判断除数 // 4. 性能问题,不要每次只减掉divisor // 避免除零错 if (divisor == 0) return numeric_limits<int>::max(); // 转换成绝对值,但使用long long类型避免溢出 long long a = abs((long long)dividend); long long b = abs((long long)divisor); // 用减法模拟除法 long long ret = 0; while (a >= b) { // 每次尽量减掉divisor的倍数(2, 4, 8...) for (long long c = b, i = 0; c <= a; c <<= 1, i++) { a -= c; ret += (1 << i); } } // 补上符号 if ((dividend ^ divisor) >> 31) { return (int)-ret; } // 避免结果溢出 return (ret == (1L << 31))? (int)(ret - 1): (int)ret; } }; int main(int argc, const char * argv[]) { vector<int> dividends = {2, -3, 4, -5, 5, numeric_limits<int>::max(), numeric_limits<int>::min()}; vector<int> divisors = {0, -1, 2, 3, -3, 1, -1}; for (int i = 0; i < dividends.size(); i++) { cout << dividends[i] << " / " << divisors[i] << " = " << Solution().divide(dividends[i], divisors[i]) << endl; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2009 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #ifdef GADGET_SUPPORT #include "modules/gadgets/gadgets_module.h" #include "modules/gadgets/OpGadgetManager.h" #include "modules/gadgets/OpGadgetParsers.h" GadgetsModule::GadgetsModule() : m_gadget_manager(NULL) , m_gadget_parsers(NULL) { } void GadgetsModule::InitL(const OperaInitInfo& info) { LEAVE_IF_ERROR(OpGadgetParsers::Make(m_gadget_parsers)); LEAVE_IF_ERROR(OpGadgetManager::Make(m_gadget_manager)); #ifndef HAS_COMPLEX_GLOBALS extern void init_g_gadget_start_file(); CONST_ARRAY_INIT(g_gadget_start_file); extern void init_g_gadget_start_file_type(); CONST_ARRAY_INIT(g_gadget_start_file_type); extern void init_g_gadget_default_icon(); CONST_ARRAY_INIT(g_gadget_default_icon); /*extern void init_g_gadget_default_icon_type();*/ /*CONST_ARRAY_INIT(g_gadget_default_icon_type);*/ #endif } void GadgetsModule::Destroy() { OP_DELETE(m_gadget_manager); m_gadget_manager = NULL; OP_DELETE(m_gadget_parsers); m_gadget_parsers = NULL; } #endif // GADGET_SUPPORT
#include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #include "opencv2/videoio.hpp" #include <iostream> using namespace cv; using namespace std; int s=0; int le[3][3]; int r[3][3]; Mat img1; Mat img2; void matrixl(int i,int j) { int x=0; int y=0; for(int k=i;k<i+3;k++) { for(int l=j;l<j+3;l++) { Scalar intensity = img1.at<uchar>(k,l); le[x][y]=intensity.val[0]; x++; y++; } } } void matrixr(int i,int j) { int x=0; int y=0; for(int k=i;k<i+3;k++) { for(int l=j;l<j+3;l++) { Scalar intensity = img2.at<uchar>(k,l); r[x][y]=intensity.val[0]; x++; y++; } } } int i1(int i,int j) { Scalar intensity = img1.at<uchar>(i, j); return intensity.val[0]; } int i2(int i,int j) { Scalar intensity = img2.at<uchar>(i, j); return intensity.val[0]; } void ssd() { s=0; for(int i=0;i<3;i++) for(int j=0;j<3;j++) { s=s+(i1(i,j)-i2(i,j))*(i1(i,j)-i2(i,j)); } } int main() { img1 = imread("/home/shivani/Opencv/img1.bmp",CV_LOAD_IMAGE_COLOR); img2 = imread("/home/shivani/Opencv/img2.bmp",CV_LOAD_IMAGE_COLOR); int rows = img1.rows; int cols = img1.cols; //Mat gray_image1; //Mat gray_image2; int min=3000; int u=0; //cvtColor( img1, gray_image1, GRAY2COLOR_BGR ); //cvtColor( img2, gray_image2, GRAY2COLOR_BGR); for(int i=0;i<256-3;i++) { for(int j=0;j<256-3;j++) { min=3000; u=0; cout<<"Hello"<<endl ; matrixl(i,j); for(int z=0;z<cols-3;z++) { matrixr(i,z); ssd(); if(s<min) { min=s;u=z; } } cout<<"Hello"<<endl ; } } }
// Copyright (c) 2019 The Circle Foundation // Copyright (c) 2019 fireice-uk // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include "soft_aes.hpp" #include "coin_algos.hpp" #if defined(_WIN32) || defined(_WIN64) #include <intrin.h> #include <malloc.h> #define HAS_WIN_INTRIN_API #endif #if defined(__ARM_FEATURE_SIMD32) || defined(__ARM_NEON) #include "sse2neon.h" inline uint64_t _umul128(uint64_t multiplier, uint64_t multiplicand, uint64_t* product_hi) { uint64_t a = multiplier >> 32; uint64_t b = multiplier & 0xFFFFFFFF; uint64_t c = multiplicand >> 32; uint64_t d = multiplicand & 0xFFFFFFFF; uint64_t ad = a * d; uint64_t bd = b * d; uint64_t adbc = ad + (b * c); uint64_t adbc_carry = adbc < ad ? 1 : 0; uint64_t product_lo = bd + (adbc << 32); uint64_t product_lo_carry = product_lo < bd ? 1 : 0; *product_hi = (a * c) + (adbc >> 32) + (adbc_carry << 32) + product_lo_carry; return product_lo; } #endif #if defined(__GNUC__) && !defined(ARM) && !defined(__MINGW64__) #pragma GCC target ("aes,sse2") #include <x86intrin.h> static inline uint64_t _umul128(uint64_t a, uint64_t b, uint64_t* hi) { unsigned __int128 r = (unsigned __int128)a * (unsigned __int128)b; *hi = r >> 64; return (uint64_t)r; } #endif // __GNUC__ #if !defined(ARM) struct cryptonight_ctx { cryptonight_ctx(cryptonight_algo ALGO) { long_state = (uint8_t*)_mm_malloc(cn_select_memory(ALGO), 2097152); hash_state = (uint8_t*)_mm_malloc(4096, 4096); } uint8_t* long_state; uint8_t* hash_state; }; #endif // This will shift and xor tmp1 into itself as 4 32-bit vals such as // sl_xor(a1 a2 a3 a4) = a1 (a2^a1) (a3^a2^a1) (a4^a3^a2^a1) inline __m128i sl_xor(__m128i tmp1) { __m128i tmp4; tmp4 = _mm_slli_si128(tmp1, 0x04); tmp1 = _mm_xor_si128(tmp1, tmp4); tmp4 = _mm_slli_si128(tmp4, 0x04); tmp1 = _mm_xor_si128(tmp1, tmp4); tmp4 = _mm_slli_si128(tmp4, 0x04); tmp1 = _mm_xor_si128(tmp1, tmp4); return tmp1; } template<bool SOFT_AES> inline void aes_round(__m128i key, __m128i& x0, __m128i& x1, __m128i& x2, __m128i& x3, __m128i& x4, __m128i& x5, __m128i& x6, __m128i& x7) { if(SOFT_AES) { x0 = soft_aesenc(x0, key); x1 = soft_aesenc(x1, key); x2 = soft_aesenc(x2, key); x3 = soft_aesenc(x3, key); x4 = soft_aesenc(x4, key); x5 = soft_aesenc(x5, key); x6 = soft_aesenc(x6, key); x7 = soft_aesenc(x7, key); } else { #if !defined(ARM) x0 = _mm_aesenc_si128(x0, key); x1 = _mm_aesenc_si128(x1, key); x2 = _mm_aesenc_si128(x2, key); x3 = _mm_aesenc_si128(x3, key); x4 = _mm_aesenc_si128(x4, key); x5 = _mm_aesenc_si128(x5, key); x6 = _mm_aesenc_si128(x6, key); x7 = _mm_aesenc_si128(x7, key); #endif } }