blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
bcedaafc00183fd375d5db6f58d378baf1f91d94
a97752b8d83d28d7a6eb0580a26dbb3c8afeacaf
/basic/basicActor.c++
5249fdad3d8ca355fb94a1bc27f24a23027f2741
[ "MIT" ]
permissive
camilleg/vss
1135b46d2775e448508075c1eff2372eb49e207e
b99bb5281a8cc09cf7045fb6c9315e74e281ec86
refs/heads/main
2023-06-07T00:13:59.320038
2023-06-06T21:02:04
2023-06-06T21:02:04
8,169,388
1
0
null
null
null
null
UTF-8
C++
false
false
2,231
basicActor.c++
#include "basicActor.h" ACTOR_SETUP(BasicActor, BasicActor) extern void BASICinit(void); extern int BASICstep(const char*); extern void BASICterm(void); extern void BASICflushoutput(void); extern const char* BASICoutput(void); BasicActor::BasicActor() : VActor(), fTerminated(0) { setTypeName("BasicActor"); BASICinit(); } BasicActor::~BasicActor() { BASICterm(); } void BasicActor::act() { VActor::act(); } int BasicActor::preprocess(char* cmd) { if (fTerminated) { fprintf(stderr, "vss error: BasicActor BASIC interpreter exited.\n"); return 0; } if (isDebug()) fprintf(stderr, "BASIC> %s\n", cmd); return 1; } extern int BASICfprintvss(void); extern void BASICflushprintvss(void); void BasicActor::command(const char* cmd) { if (!BASICstep(cmd)) fTerminated = 1; if (BASICfprintvss()) { // Must make a local copy of BASICoutput(), because these commands // themselves could indirectly cause a printvss and call this function! // In other words, this function must be re-entrant. char sz[5001]; strcpy(sz, BASICoutput()); // Newlines delimit (actually, terminate) VSS commands. // Don't use strtok() because it's not reentrant. char* pchPrev = sz; char* pch = strchr(pchPrev, '\n'); for (; pch; pch = strchr(pchPrev=pch+1, '\n')) { *pch = '\0'; if (isDebug()) fprintf(stderr, "BASIC_VSS> %s\n", pchPrev); actorMessageHandler(pchPrev); } BASICflushoutput(); BASICflushprintvss(); } } void BasicActor::type_in(char* cmd) { if (!preprocess(cmd)) return; command(cmd); } void BasicActor::type_and_get_floats(float hMG, char* cmd) { if (!preprocess(cmd)) return; BASICflushoutput(); command(cmd); char szCmd[200]; sprintf(szCmd, "SendData %f [%s]", hMG, BASICoutput()); BASICflushoutput(); actorMessageHandler(szCmd); } //=========================================================================== // receiveMessage // int BasicActor::receiveMessage(const char* Message) { CommandFromMessage(Message); if (CommandIs("Do")) { ifM( msg, type_in(msg) ); return Uncatch(); } if (CommandIs("SendFloats")) { ifFM( hMG, msg, type_and_get_floats(hMG, msg) ); return Uncatch(); } return VActor::receiveMessage(Message); }
c4c2101445b61524ab3a4aedc07e8cae0f742d3f
71e7675390503901564239473b56ad26bdfa13db
/src/zoidfs/hints/zoidfs-hints.h
81364cda2f51247fb71299f751e76bda4fa60fe9
[]
no_license
radix-io-archived/iofsl
1b5263f066da8ca50c7935009c142314410325d8
35f2973e8648ac66297df551516c06691383997a
refs/heads/main
2023-06-30T13:59:18.734208
2013-09-11T15:24:26
2013-09-11T15:24:26
388,571,488
0
0
null
null
null
null
UTF-8
C++
false
false
1,863
h
zoidfs-hints.h
#ifndef SRC_ZOIDFS_HINTS_ZOIDFS_HINTS_C #define SRC_ZOIDFS_HINTS_ZOIDFS_HINTS_C #include "zoidfs.h" #ifdef __cplusplus /* * We put all the zoidfs stuff in the zoidfs namespace */ namespace zoidfs { namespace hints { extern "C" { #endif /* __cplusplus */ /* predefined hints */ #define ZOIDFS_HINT_ENABLED (char*)"1" #define ZOIDFS_HINT_DISABLED (char*)"0" #define ZOIDFS_ENABLE_PIPELINE (char*)"ZOIDFS_ENABLE_PIPELINE" #define ZOIDFS_PIPELINE_SIZE (char*)"ZOIDFS_PIPELINE_SIZE" /* Maximum number of characters in a zoidfs_hint_t key * (without terminating 0) */ #define ZOIDFS_HINT_KEY_MAX 64 /* Maximum number of keys in a zoidfs_hint_t */ #define ZOIDFS_HINT_NKEY_MAX 32 /* Maximum length of a key value */ #define ZOIDFS_HINT_KEY_VALUE_MAX 256 /* new hint API */ /* zoidfs hints are modeled on the MPI info interface */ /* TODO these are currently just stubs */ int zoidfs_hint_create(zoidfs_op_hint_t * hint); int zoidfs_hint_set(zoidfs_op_hint_t hint, char * key, char * value, int bin_length); int zoidfs_hint_delete(zoidfs_op_hint_t hint, char * key); int zoidfs_hint_get(zoidfs_op_hint_t hint, char * key, int valuelen, char * value, int * flag); int zoidfs_hint_get_valuelen(zoidfs_op_hint_t hint, char * key, int * valuelen, int * flag); int zoidfs_hint_get_nkeys(zoidfs_op_hint_t hint, int * nkeys); int zoidfs_hint_get_nthkey(zoidfs_op_hint_t hint, int n, char * key); int zoidfs_hint_get_nthkeylen(zoidfs_op_hint_t hint, int n, int * keylen); int zoidfs_hint_dup(zoidfs_op_hint_t oldhint, zoidfs_op_hint_t * newhint); int zoidfs_hint_copy(zoidfs_op_hint_t * oldhint, zoidfs_op_hint_t * newhint); int zoidfs_hint_free(zoidfs_op_hint_t * hint); #ifdef __cplusplus } /* extern */ } /* namespace hints */ } /* namespace zoidfs */ #endif /* __cplusplus */ #endif /* __SRC_ZOIDFS_HINTS_ZOIDFS_HINTS_C__ */
c4bbed6a332a776d95757c3c371c4147bd56452b
3305f6c72411a014ef693a3602bfb9e40f0775b6
/ n-m-p/NPM/IVObject.cpp
56b214cc880e4de7e82ec7876834b14cc374e0fe
[]
no_license
tectronics/n-m-p
ccb30a0fab7cb90bb9c22c371f6fe53fd7ef9bcd
5e735c7c50cec066044715d3092416040d8bb4f9
refs/heads/master
2018-01-11T15:02:07.502719
2013-04-04T22:51:47
2013-04-04T22:51:47
47,603,349
0
0
null
null
null
null
UTF-8
C++
false
false
4,349
cpp
IVObject.cpp
//#include "IVObject.h" // //using namespace std; // //SoSeparator *ReadScene(const char *filename) //{ // SoSeparator *root; // SoInput in; // // if (!in.openFile(filename)) // { // cerr << "Error opening file " << filename << endl; // exit(1); // } // // root = SoDB::readAll(&in); // // if (root == NULL) // cerr << "Error reading file " << filename << endl; // else // root->ref(); // // in.closeFile(); // return root; //} // //static SoCallbackAction::Response processNodesCB(void *userData, SoCallbackAction *ca, const SoNode *node) //{ // if (node->isOfType(SoShape::getClassTypeId())) // { // SbPList *data_list = (SbPList*) userData; // IVObject *data = new IVObject; // data_list->append((void *) data); // data->objShape = node->copy(); // data->objShape->ref(); // SoVertexShape* vertShape = (SoVertexShape *)data->objShape; // // SoState* state = ca->getState(); // SoLazyElement* le = SoLazyElement::getInstance(state); // // int sIndex = 0; // if (node->isOfType(SoVertexShape::getClassTypeId())) // { // const SoCoordinateElement* ce; // ce = SoCoordinateElement::getInstance(state); // // if (vertShape->isOfType(SoNonIndexedShape::getClassTypeId())) // { // sIndex = ((SoNonIndexedShape*)vertShape)->startIndex.getValue(); // ((SoNonIndexedShape*)vertShape)->startIndex.setValue(0); // } // // if (ce->is3D()) // { // It's 3D // SoCoordinate3 *Ps = new SoCoordinate3; // Ps->point.setValues(0, ce->getNum() - sIndex,&ce->get3(sIndex)); // Ps->ref(); // data->points = (SoNode *) Ps; // } // // const SoNormalElement* ne = SoNormalElement::getInstance(state); // // SoNormalBinding::Binding nb = (SoNormalBinding::Binding)SoNormalBindingElement::get(state); // // int startNrmIndex = 0; // if (ne != NULL && ne->getNum()>0) // { // // vp->normalBinding.setValue(nb); // if (nb == SoNormalBinding::PER_VERTEX){ // startNrmIndex = sIndex; // } // data->normals = new SoNormal; // data->normals->ref(); // data->normals->vector.setValues(0, (ne->getNum())-startNrmIndex, &ne->get(startNrmIndex)); // } // } // // SbMatrix const xm = ca->getModelMatrix(); // data->transformation = new SoTransform; // data->transformation->ref(); // data->transformation->setMatrix(xm); // // data->units = new SoUnits; // data->units->ref(); // data->units->units = ca->getUnits(); // // data->shapeHints = new SoShapeHints; // data->shapeHints->ref(); // data->shapeHints->shapeType = ca->getShapeType(); // data->shapeHints->faceType = ca->getFaceType(); // data->shapeHints->vertexOrdering = ca->getVertexOrdering(); // // //data->shapeHints->vertexOrdering.getValue(); // // SoMaterial *material = new SoMaterial; // material->ref(); // material->ambientColor = SoLazyElement::getAmbient(state); // material->diffuseColor = SoLazyElement::getDiffuse(state, 0); // material->specularColor = SoLazyElement::getSpecular(state); // material->emissiveColor = SoLazyElement::getEmissive(state); // material->shininess = SoLazyElement::getShininess(state); // material->transparency = SoLazyElement::getTransparency(state, 0); // data->material = material; // } // return SoCallbackAction::CONTINUE; //} // //IVObject::IVObject() //{ // objShape = NULL; // points = NULL; // normals = NULL; // material = NULL; // transformation = NULL; // shapeHints = NULL; // units = NULL; //} // //IVObject::~IVObject() //{ // if (points) // points->unref(); // if (objShape) // objShape->unref(); // if (normals) // normals->unref(); // if (material) // material->unref(); // if (transformation) // transformation->unref(); // if (shapeHints) // shapeHints->unref(); // if (units) // units->unref(); //} // //bool IVObject::Check() const //{ // if (objShape == NULL) // return false; // if (points == NULL) // return false; // if (normals == NULL) // return false; // if (material == NULL) // return false; // if (transformation == NULL) // return false; // if (shapeHints == NULL) // return false; // if (units == NULL) // return false; // return true; //} // //IVScene::IVScene(const char *filename) //{ // SoSeparator *root = ReadScene(filename); // SoCallbackAction ca; // // ca.addPreCallback(SoNode::getClassTypeId(), processNodesCB, (void*)&objects); // ca.apply(root); //}
7a79f921a787983e3bbdaed825de3b3f9f1836e1
3655768adbd64e629096c568bafe1c5f434b4a9f
/Chapter 6/Test.cpp
8c52294b5be6fbc605cf6b58e5e928fb4e924074
[]
no_license
gatordan82/IntroductionToCppForFinancialEngineers
8a6a56c7ba33fcedd1f8fdcdd27346464a985083
2bf6ea15bff1f82128938bf095ce374e9f02be1f
refs/heads/master
2021-01-20T20:52:13.214634
2016-08-19T02:18:31
2016-08-19T02:18:31
63,662,274
0
1
null
null
null
null
UTF-8
C++
false
false
1,401
cpp
Test.cpp
#include <iostream> #include "..\Book Files\Chapter06\Complex.hpp" #include "Stack.h" using namespace std; Complex myFunc(const Complex& z) { return z * z; } Complex ComplexProduct(Complex* carr, int n) { Complex product = carr[0]; for (int j = 1; j < n; j++) product *= carr[j]; return product; } Complex ComplexSum(Complex* carr, int n) { Complex sum = carr[0]; for (int j = 1; j < n; j++) sum += carr[j]; return sum; } int main() { Complex z1(1.0, 1.0); Complex z2(2.0, 3.0); Complex z3 = z1 * z2; Complex z4 = 2.0 * z3; Complex z5 = -z3; int Size = 5; Complex* cpArray = new Complex[Size]; cpArray[0] = z1; cpArray[1] = z2; cpArray[2] = z3; cpArray[3] = z4; cpArray[4] = z5; for (int j = 0; j < Size; j++) cout << myFunc(cpArray[j]) << ", "; delete[] cpArray; cout << endl; const int N = 5; Complex fixedArray[N]; for (int i = 0; i < Size; i++) fixedArray[i] = Complex((double)i, 0.0); Complex product = ComplexProduct(fixedArray, Size); cout << "Product: " << product << endl; Complex sum = ComplexSum(fixedArray, Size); cout << "Sum: " << sum << endl; Stack st(4); st.Push(1.0); st.Push(2.0); st.Push(3.0); st.Push(4.0); st.Push(5.0); cout << "Top of stack is " << st.Pop() << endl; cin.get(); }
d9239b37b56006b5320fac23bcc7fdbd190eb241
cf418f41f6ac7e2316fd80a5695233e01d10afb9
/tests/JSONRPCTestServer/main.cpp
3a9ae752b2cf30f4dafdecece975ab5ace1f78ad
[ "Zlib" ]
permissive
wolfgang1991/CommonLibraries
7757fe0cdcfa2911260a0f3e52ac4c79730490c5
07ec5aa06566bf21b6352caa3d57952edbd94d06
refs/heads/master
2023-08-21T14:30:44.137173
2023-05-30T23:17:55
2023-05-30T23:17:55
243,551,004
0
0
NOASSERTION
2023-09-12T11:09:46
2020-02-27T15:32:35
C++
UTF-8
C++
false
false
3,920
cpp
main.cpp
#include <timing.h> #include <StringHelpers.h> #include <JSONRPC2Server.h> #include <JSONRPC2Client.h> #include <SimpleSockets.h> #include <CRC32.h> #include <iostream> #include <cassert> #include <cerrno> #include <cstring> #include <list> #include <utility> #define RPC_PORT 62746 #define SPAM_PERIOD 1.0 #define DISCOVERY_PORT 48430 //TODO: XMetaProtocolHandler refactoren? //TODO: UDPDiscovery refactoren? std::pair<char*, uint32_t> stringToDiscoveryPacket(const std::string& s){ uint32_t packetSize = s.size()+sizeof(uint32_t); char* packet = new char[packetSize]; memcpy(packet, s.c_str(), s.size()); uint32_t crc32 = htonl(crc32buf(packet, s.size())); memcpy(&packet[s.size()], &crc32, sizeof(uint32_t)); return std::make_pair(packet, packetSize); } std::pair<char*, uint32_t> dummyDiscoveryPacket = stringToDiscoveryPacket("REPLY Name C++-Server Serial 0 Proto RPC2_API1 Port 62746 AcceptConnection true\n"); class AlwaysSuccessXMetaHandler : public IMetaProtocolHandler{ public: bool tryNegotiate(ICommunicationEndpoint* socket){ return true; } bool useCompression() const{return true;} }; class TestProcedureHandler : public IRemoteProcedureCaller, IRemoteProcedureCallReceiver{ private: bool shallSpam; double lastSpamTime; public: JSONRPC2Client* client; enum ProcedureCalls{ SUM, CALL_COUNT }; TestProcedureHandler(JSONRPC2Client* client):shallSpam(false),lastSpamTime(0.0),client(client){ client->registerCallReceiver("moveXY", this); client->registerCallReceiver("registerForSpam", this); } ~TestProcedureHandler(){ delete client; } void OnProcedureResult(IRPCValue* results, uint32_t id){ if(id==SUM){ std::cout << "sum result received: " << convertRPCValueToJSONString(*results) << std::endl; } delete results; } void OnProcedureError(int32_t errorCode, const std::string& errorMessage, IRPCValue* errorData, uint32_t id){ delete errorData; } int moveXY(int a, int b){ return a+b; } IRPCValue* callProcedure(const std::string& procedure, const std::vector<IRPCValue*>& values){ if(procedure.compare("moveXY")==0){ return createRPCValue(moveXY(createNativeValue<int>(values[0]), createNativeValue<int>(values[1]))); }else if(procedure.compare("registerForSpam")==0){ shallSpam = true; } return NULL; } void update(){ client->update(); if(shallSpam){ double t = getSecs(); if(t-lastSpamTime>1.0){ lastSpamTime = t; client->callRemoteProcedure("sum", std::vector<IRPCValue*>{createRPCValue(1), createRPCValue(2)}, this, SUM); } } } }; int main(int argc, char *argv[]){ AlwaysSuccessXMetaHandler handler; JSONRPC2Server server(RPC_PORT, 2000, &handler); std::list<TestProcedureHandler> handlers; //Dummy Discover stuff IPv6UDPSocket discoverySocket; bool success = discoverySocket.bind(DISCOVERY_PORT); if(!success){ std::cout << "Error: " << strerror(errno) << std::endl; } uint32_t bufSize = 512; char buf[bufSize]; while(true){ //Connection management of JSONRPC2 stuff JSONRPC2Client* newClient = server.accept(); if(newClient){ handlers.emplace_back(newClient); } auto it = handlers.begin(); while(it!=handlers.end()){ TestProcedureHandler& handler = *it; handler.update(); if(!handler.client->isConnected()){ std::cout << "Client disconnected" << std::endl; it = handlers.erase(it); continue; } ++it; } //Dummy Discovery stuff uint32_t received = discoverySocket.recv(buf, bufSize); if(received>0){ IPv6Address fromAddress = discoverySocket.getLastDatagramAddress(); std::cout << "received: " << std::string(buf, received) << " from " << fromAddress.getAddressAsString() << ":" << fromAddress.getPort() << std::endl << std::flush; discoverySocket.setUDPTarget(fromAddress); discoverySocket.send(dummyDiscoveryPacket.first, dummyDiscoveryPacket.second); } delay(10); } return 0; }
a7fef6afe3c3fff09facb42886e20cc613921898
56a64f6acdaf9c32eb4a2256fab048e277862e1c
/03-D3D-Test/03-D3D-Test.cpp
099b3a6ef7cace1a89341d0555ca658bddccfac0
[]
no_license
lazyartist/Win-Direct3D
671dfc9c5a2b174ae6f9034839f415836e3c7ea1
7d92082d91be7a8a47a3f4a8ec3300b998908fcf
refs/heads/master
2020-07-27T13:22:50.042906
2019-11-05T08:25:43
2019-11-05T08:25:43
209,103,024
0
0
null
null
null
null
UTF-8
C++
false
false
8,444
cpp
03-D3D-Test.cpp
//#define _XM_NO_INTRINSICS_ #include "pch.h" #include <iostream> #include <d3d9.h> //#include <d3d.h> //#pragma comment (lib, "d3d9.lib") #include <DirectXMath.h> #define PI 3.14159265359 using namespace std; using namespace DirectX; void TestMatrix(); void TestMatrixLinear(); void TestMatrixQuaternion(); void TestMatrixTransformation(); void printTitle(const char *title); void printMatrix(XMMATRIX &mat); void printMatrix(const char* title, XMMATRIX &mat); void printVector(XMVECTOR &vec); void printVector(const char* title, XMVECTOR &vec); int main() { //TestMatrix(); //TestMatrixLinear(); //TestMatrixQuaternion(); TestMatrixTransformation(); return 0; } void TestMatrixTransformation() { //월드, 뷰, 투영 행렬의 설정 //LPDIRECT3DDEVICE9 pD3DDevice = nullptr;//초기화필요 //XMMATRIX matTransform; //XMFLOAT4X4 matTransform2; //XMStoreFloat4x4(&matTransform2, matTransform); //pD3DDevice->SetTransform(D3DTS_WORLD, (D3DMATRIX*)&matTransform2); //뷰 변환 행렬 함수 //XMMatrixLookAtLH(); //투영 변환 행렬 함수 //XMMatrixPerspectiveFovLH(); } void TestMatrixQuaternion() { printTitle("회전 행렬을 쿼터니온으로 만드는 함수"); { XMMATRIX matRotation = XMMatrixRotationX(PI); printMatrix("matTransform", matRotation); /* 1.0 0.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 -0.0 -1.0 0.0 0.0 0.0 0.0 1.0 */ XMVECTOR vQuaternion = XMQuaternionRotationMatrix(matRotation); printVector("vQuaternion", vQuaternion); /* 1.0 0.0 0.0 0.0 */ } printTitle("yaw, pitch, roll에 의한 쿼터니온을 만드는 함수"); { XMVECTOR vQuaternion = XMQuaternionRotationRollPitchYaw(PI, PI, PI); printVector("vQuaternion", vQuaternion); /* -0.0 0.0 0.0 1.0 */ } printTitle("임의의 축에 대해서 회전한 쿼터니온을 구하는 함수"); { XMVECTOR vQuaternion = XMQuaternionRotationAxis({ 1.0, 0, 0, 0 }, PI); printVector("vQuaternion", vQuaternion); /* 1.0 0.0 0.0 -0.0 */ } printTitle("쿼터니온으로부터 회전 행렬을 구하는 함수"); { XMVECTOR vQuaternion = XMQuaternionRotationAxis({ 1.0, 0, 0, 0 }, PI); printVector("vQuaternion", vQuaternion); /* 1.0 0.0 0.0 -0.0 */ XMMATRIX matRotation = XMMatrixRotationQuaternion(vQuaternion); printMatrix("matTransform", matRotation); /* 1.0 0.0 0.0 0.0 0.0 -1.0 -0.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 0.0 1.0 */ } printTitle("길이가 1인 쿼터이온을 구하는 함수"); { XMVECTOR vQuaternion = { 1.0, 2.0, 3.0, 4.0 }; printVector("vQuaternion", vQuaternion); /* 1.0 2.0 3.0 4.0 */ vQuaternion = XMQuaternionNormalize(vQuaternion); printVector("vQuaternion", vQuaternion); /* 0.2 0.4 0.5 0.7 */ } } void TestMatrixLinear() { printTitle("이동행렬"); { XMMATRIX matTranslation = XMMatrixTranslation(10, 20, 30); printMatrix("matTranslation", matTranslation); /* 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 10.0 20.0 30.0 1.0 */ } printTitle("크기행렬"); { XMMATRIX matScaling = XMMatrixScaling(0.5, 0.5, 0.5); printMatrix("matScaling", matScaling); /* 0.5 0.0 0.0 0.0 0.0 0.5 0.0 0.0 0.0 0.0 0.5 0.0 0.0 0.0 0.0 1.0 */ } printTitle("라디안과 호도값"); { printf_s("%f\n", XMConvertToRadians(90) ); //1.570796 printf_s("%f\n", XMConvertToDegrees(3.14) ); //179.908737 } printTitle("회전행렬"); { XMMATRIX matRotationX = XMMatrixRotationX(PI); printMatrix("matRotationX", matRotationX); /* 1.0 0.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 -0.0 -1.0 0.0 0.0 0.0 0.0 1.0 */ XMMATRIX matRotationRollPitchYaw = XMMatrixRotationRollPitchYaw(PI, PI, PI); printMatrix("matRotationRollPitchYaw", matRotationRollPitchYaw); /* 1.0 0.0 -0.0 0.0 -0.0 1.0 -0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 */ XMMATRIX matRotationAxis = XMMatrixRotationAxis({1.0, 0, 0,0}, PI); printMatrix("matRotationAxis", matRotationAxis); /* 1.0 0.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 0.0 1.0 */ } printTitle("크기, 회전, 이동 행렬의 결합"); { XMMATRIX matComposite = XMMatrixScaling(0.5, 0.5, 0.5) * XMMatrixRotationRollPitchYaw(PI, PI, PI) * XMMatrixTranslation(10, 20, 30); printMatrix("matComposite", matComposite); /* 0.5 0.0 -0.0 0.0 -0.0 0.5 -0.0 0.0 0.0 0.0 0.5 0.0 10.0 20.0 30.0 1.0 */ } } void TestMatrix() { printTitle("행렬과 단위행렬의 곱"); { XMMATRIX matMatrix = { {11, 12, 13, 14}, {21, 22, 23, 24}, {31, 32, 33, 34}, {41, 42, 43, 44}, }; //단위행렬 XMMATRIX matIdentity = XMMatrixIdentity(); //행렬과 단위행렬의 곱 방법1 XMMATRIX matResult = matMatrix * matIdentity; //행렬과 단위행렬의 곱 방법2 matResult = XMMatrixMultiply(matMatrix, matIdentity); //출력 printMatrix("matMatrix", matMatrix); printMatrix("matIdentity", matIdentity); printMatrix("matResult", matResult); /* - matMatrix - 11.0 12.0 13.0 14.0 21.0 22.0 23.0 24.0 31.0 32.0 33.0 34.0 41.0 42.0 43.0 44.0 - matIdentity - 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 - matResult - 11.0 12.0 13.0 14.0 21.0 22.0 23.0 24.0 31.0 32.0 33.0 34.0 41.0 42.0 43.0 44.0 */ } printTitle("전치행렬"); { XMMATRIX matMatrix = { {11, 12, 13, 14}, {21, 22, 23, 24}, {31, 32, 33, 34}, {41, 42, 43, 44}, }; //전치행렬 XMMATRIX matTranspose = XMMatrixTranspose(matMatrix); printMatrix("matMatrix", matMatrix); printMatrix("matTranspose", matTranspose); /* - matMatrix - 11.0 12.0 13.0 14.0 21.0 22.0 23.0 24.0 31.0 32.0 33.0 34.0 41.0 42.0 43.0 44.0 - matTranspose - 11.0 21.0 31.0 41.0 12.0 22.0 32.0 42.0 13.0 23.0 33.0 43.0 14.0 24.0 34.0 44.0 */ //전치행렬을 다시 전치행렬로 만들기 XMMATRIX matResult = XMMatrixTranspose(matTranspose); printMatrix("matResult", matResult); /* - matResult - 11.0 12.0 13.0 14.0 21.0 22.0 23.0 24.0 31.0 32.0 33.0 34.0 41.0 42.0 43.0 44.0 */ } printTitle("역행렬"); { XMMATRIX matMatrix; //회전행렬 XMMATRIX matRotation = XMMatrixRotationX(0.3f); //행렬식값(0이면 역행렬이 존재하지 않고 0이외의 값이면 역행렬이 존재한다) XMVECTOR fDeterminant; //역행렬(회전행렬은 항상 역행렬이 존재) XMMATRIX matInverse = XMMatrixInverse(&fDeterminant, matRotation); printMatrix("matTransform", matRotation); printMatrix("matInverse", matInverse); printf_s("- fDeterminant : %f\n", fDeterminant.vector4_f32[0]); /* - matTransform - 1.0 0.0 0.0 0.0 0.0 1.0 0.3 0.0 0.0 -0.3 1.0 0.0 0.0 0.0 0.0 1.0 - matInverse - 1.0 -0.0 0.0 0.0 0.0 1.0 -0.3 0.0 0.0 0.3 1.0 0.0 0.0 0.0 0.0 1.0 - fDeterminant : 1.000000 */ //회전행렬과 역행렬의 곱 = 단위행렬 XMMATRIX matResult = XMMatrixMultiply(matRotation, matInverse); printMatrix("matResult", matResult); /* - matResult - 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 */ } } //functions void printTitle(const char *title) { printf_s("=== %s ===\n", title); } void printMatrix(XMMATRIX &mat) { for (size_t i = 0; i < 4; i++) { for (size_t ii = 0; ii < 4; ii++) { printf_s("%#2.1f\t", mat.m[i][ii]); //printf_s("%f\t", mat(i, ii)); } printf_s("\n"); } } void printVector(XMVECTOR &vec) { for (size_t i = 0; i < 4; i++) { printf_s("%#2.1f\t", vec.vector4_f32[i]); } printf_s("\n"); } void printMatrix(const char *title, XMMATRIX &mat) { printf_s("- %s\n", title); printMatrix(mat); } void printVector(const char *title, XMVECTOR &vec) { printf_s("- %s\n", title); printVector(vec); }
8101b0e2e6c9f90bdeac04e16eff6de27441fdb7
cb88ccece7e0526fb7ebafd4f92ac24e688d7ed0
/main.cpp
c0b9637963f9c69087e009ea33eea9e3fda13fb2
[]
no_license
marek231/mandelbrotset
1c66ab2cc6c89b282e3664f46c6f931aaf9a7bfd
c266a19ce5dbc6261cb1072dd11fab544753197d
refs/heads/master
2020-03-17T11:36:22.814281
2018-05-15T18:40:09
2018-05-15T18:40:09
133,557,414
0
0
null
null
null
null
UTF-8
C++
false
false
5,001
cpp
main.cpp
#include <SFML/Graphics.hpp> #include <iostream> #include <array> #include <vector> #include <thread> static constexpr int IMAGE_WIDTH = 960; static constexpr int IMAGE_HEIGHT = 540; class Mandelbrot { public: Mandelbrot(); void UpdateImage(double zoom, double offset_X, double offset_Y, sf::Image& image) const; private: static const int kMaxIterations = 1000; // maximum number of iterations for ComputeMandelbrot() std::array<sf::Color, kMaxIterations + 1> colors; int ComputeMandelbrot(double c_real, double c_imag) const; sf::Color GetColor(int iterations) const; void UpdateImageSlice(double zoom, double offset_X, double offset_Y, sf::Image& image, int minY, int maxY) const; }; Mandelbrot::Mandelbrot() { for (int i = 0; i <= kMaxIterations; ++i) { colors[i] = GetColor(i); } } int Mandelbrot::ComputeMandelbrot(double c_real, double c_imag) const { double z_real = c_real; double z_imag = c_imag; for (int counter = 0; counter < kMaxIterations; ++counter) { double r2 = z_real * z_real; double i2 = z_imag * z_imag; if (r2 + i2 > 4.0) { return counter; } z_imag = 2.0 * z_real * z_imag + c_imag; z_real = r2 - i2 + c_real; } return kMaxIterations; } sf::Color Mandelbrot::GetColor(int iterations) const { /* To obtain a smooth transition from one color to another, we need to use three smooth, continuous functions that will map every number t. A slightly modified version of the Bernstein polynomials will do, as they are continuous, smooth and have values in the [0, 1) interval. Therefore, mapping the results to the range for r, g, b is as easy as multiplying each value by 255. */ int r, g, b; double t = (double)iterations / (double)kMaxIterations; r = (int)(9 * (1 - t)*t*t*t * 255); g = (int)(15 * (1 - t)*(1 - t)*t*t * 255); b = (int)(8.5*(1 - t)*(1 - t)*(1 - t)*t * 255); return sf::Color(r, g, b); } void Mandelbrot::UpdateImageSlice(double zoom, double offset_X, double offset_Y, sf::Image& image, int minY, int maxY) const { double c_real = 0 * zoom - IMAGE_WIDTH / 2.0 * zoom + offset_X; double c_imag_start = minY * zoom - IMAGE_HEIGHT / 2.0 * zoom + offset_Y; for (int x = 0; x < IMAGE_WIDTH; x++, c_real += zoom) { double c_imag = c_imag_start; for (int y = minY; y < maxY; y++, c_imag += zoom) { int value = ComputeMandelbrot(c_real, c_imag); image.setPixel(x, y, colors[value]); } } } void Mandelbrot::UpdateImage(double zoom, double offset_X, double offset_Y, sf::Image& image) const { std::vector<std::thread> threads; const int STEP = IMAGE_HEIGHT / std::thread::hardware_concurrency(); for (int i = 0; i < IMAGE_HEIGHT; i += STEP) { threads.push_back(std::thread(&Mandelbrot::UpdateImageSlice, *this, zoom, offset_X, offset_Y, std::ref(image), i, std::min(i + STEP, IMAGE_HEIGHT))); } for (auto &t : threads) { t.join(); } } int main() { double offset_X = -0.7; // and move around double offset_Y = 0.0; double zoom = 0.004; // allow the user to zoom in and out... double zoom_factor = 0.9; Mandelbrot mb; sf::ContextSettings settings; settings.antialiasingLevel = 8; sf::RenderWindow window(sf::VideoMode(IMAGE_WIDTH, IMAGE_HEIGHT), "Mandelbrot", sf::Style::Default, settings); window.setVerticalSyncEnabled(true); window.setFramerateLimit(60); sf::Image image; image.create(IMAGE_WIDTH, IMAGE_HEIGHT, sf::Color(0, 0, 0)); sf::Texture texture; sf::Sprite sprite; bool stateChanged = true; // track whether the image needs to be regenerated while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: stateChanged = true; // image needs to be recreated when the user changes zoom or offset switch (event.key.code) { case sf::Keyboard::Escape: window.close(); break; case sf::Keyboard::Equal: zoom *= zoom_factor; break; case sf::Keyboard::Dash: zoom /= zoom_factor; break; case sf::Keyboard::W: offset_Y -= 40 * zoom; break; case sf::Keyboard::S: offset_Y += 40 * zoom; break; case sf::Keyboard::A: offset_X -= 40 * zoom; break; case sf::Keyboard::D: offset_X += 40 * zoom; break; default: stateChanged = false; break; } case sf::Event::MouseWheelScrolled: if (event.mouseWheelScroll.delta == 1) { stateChanged = true; zoom *= zoom_factor; } if (event.mouseWheelScroll.delta == -1) { stateChanged = true; zoom /= zoom_factor; } break; default: break; } } if (stateChanged) { mb.UpdateImage(zoom, offset_X, offset_Y, image); texture.loadFromImage(image); sprite.setTexture(texture); stateChanged = false; } window.draw(sprite); window.display(); } }
00eeac662895630cbb4ab243906febc0fe8d885f
c3e67157a7247833e3cb311fbc5f22b66250d109
/Server/InputListener.h
383d07ede395d8f8eff27668f8509ac5abc1eab6
[]
no_license
kaagreen/ICS
c2e17f88088feab3161ed73f25ec8915c2885b83
86e766ed26cf3071ed5128e86bf9ecbcabdad9fb
refs/heads/master
2020-08-31T19:11:53.421454
2019-10-31T14:16:01
2019-10-31T14:16:01
218,763,721
0
0
null
null
null
null
UTF-8
C++
false
false
163
h
InputListener.h
#pragma once #include <Windows.h> #include <iostream> class InputListener { public: DWORD start(LPVOID mParams); protected: virtual std::string getSTDIn(); };
7303ed6268c33ab3312919f110f316b65ecb2587
0c4bd1b977cc714a8a6b2839f51c4247ecfd32b1
/C++/nnForge/nnforge/nnforge.h
b148fc3504678e734310c8915b885aaee906677a
[ "Apache-2.0" ]
permissive
ishine/neuralLOGIC
281d498b40159308815cee6327e6cf79c9426b16
3eb3b9980e7f7a7d87a77ef40b1794fb5137c459
refs/heads/master
2020-08-14T14:11:54.487922
2019-10-14T05:32:53
2019-10-14T05:32:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,879
h
nnforge.h
/* * Copyright 2011-2016 Maxim Milakov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "neural_network_exception.h" #include "convolution_layer.h" #include "sparse_convolution_layer.h" #include "hyperbolic_tangent_layer.h" #include "average_subsampling_layer.h" #include "max_subsampling_layer.h" #include "absolute_layer.h" #include "local_contrast_subtractive_layer.h" #include "rgb_to_yuv_convert_layer.h" #include "rectified_linear_layer.h" #include "softmax_layer.h" #include "maxout_layer.h" #include "sigmoid_layer.h" #include "dropout_layer.h" #include "parametric_rectified_linear_layer.h" #include "untile_layer.h" #include "data_layer.h" #include "lerror_layer.h" #include "accuracy_layer.h" #include "negative_log_likelihood_layer.h" #include "cross_entropy_layer.h" #include "gradient_modifier_layer.h" #include "concat_layer.h" #include "reshape_layer.h" #include "cdf_max_layer.h" #include "prefix_sum_layer.h" #include "upsampling_layer.h" #include "add_layer.h" #include "cdf_to_pdf_layer.h" #include "entry_convolution_layer.h" #include "batch_norm_layer.h" #include "affine_grid_generator_layer.h" #include "linear_sampler_layer.h" #include "exponential_linear_layer.h" #include "rnd.h" #include "structured_data_stream_writer.h" #include "varying_data_stream_reader.h" #include "varying_data_stream_writer.h" #include "structured_from_raw_data_reader.h" #include "structured_data_bunch_mix_reader.h" #include "neuron_value_set_data_bunch_reader.h" #include "structured_data_subset_reader.h" #include "data_transformer_util.h" #include "convert_to_polar_data_transformer.h" #include "distort_2d_data_transformer.h" #include "distort_2d_data_sampler_transformer.h" #include "elastic_deformation_2d_data_transformer.h" #include "embed_data_transformer.h" #include "extract_data_transformer.h" #include "intensity_2d_data_transformer.h" #include "noise_data_transformer.h" #include "reshape_data_transformer.h" #include "rotate_band_data_transformer.h" #include "uniform_intensity_data_transformer.h" #include "normalize_data_transformer.h" #include "natural_image_data_transformer.h" namespace nnforge { class nnforge { public: static void init(); private: nnforge() = delete; ~nnforge() = delete; }; }
6b9683a20a6f1a5cea60f3d1d84934a364b2e04c
dbf18505b5f04bd743a6b57b85708258ad5e0398
/benchmarks/sgolferval.cpp
1f47e1e7a2048d6a644a05e66f5af4418bcc1ffd
[]
no_license
thanhtrunghuynh93/kangaroo
fbdbd7f14f1aa589d27a22153eca65d105bc460a
b1d1dfcd03919ec077a92ffb7056c99ad2f6418c
refs/heads/master
2021-05-30T02:20:19.391474
2015-11-11T18:21:20
2015-11-11T18:21:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,955
cpp
sgolferval.cpp
/*! @file sgolferval.cpp @brief The solution validator program for social golfer. @details This is the source file for the solution validator for social golfer. @author M.A.Hakim Newton hakim.newton@nicta.com.au @author Duc Nghia Pham duc-nghia.pham@nicta.com.au @date 25.07.2010 QRL NICTA www.nicta.com.au */ #include "cstdlib" #include "iostream" #include "algorithm" using namespace std; /*! @fn void main(int ArgC, char * ArgV[]) */ int main (int ArgC, char * ArgV[]) { int Violatn; if (!(cin >> Violatn)) { cout << "nil" << endl; return EXIT_SUCCESS; } int Iteratn; if (!(cin >> Iteratn)) { cout << "nil" << endl; return EXIT_SUCCESS; } float Time; if (!(cin >> Time)) { cout << "nil" << endl; return EXIT_SUCCESS; } string sMemory; if (!(cin >> sMemory)) { cout << "nil" << endl; return EXIT_SUCCESS; } double Memory; if (sMemory[sMemory.size() - 1] == 'K') Memory = atof(sMemory.substr(0, sMemory.size() - 1).c_str()) * 1024; else if (sMemory[sMemory.size() - 1] == 'M') Memory = atof(sMemory.substr(0, sMemory.size() - 1).c_str()) * 1024 * 1024; else if (sMemory[sMemory.size() - 1] == 'G') Memory = atof(sMemory.substr(0, sMemory.size() - 1).c_str()) * 1024 * 1024 * 1024; else Memory = atof(sMemory.c_str()); int Tabu; if (!(cin >> Tabu)) { cout << "nil" << endl; return EXIT_SUCCESS; } int PerGroup; if (!(cin >> PerGroup)) { cout << "nil" << endl; return EXIT_SUCCESS; } int GroupCount; if (!(cin >> GroupCount)) { cout << "nil" << endl; return EXIT_SUCCESS; } int WeekCount; if (!(cin >> WeekCount)) { cout << "nil" << endl; return EXIT_SUCCESS; } int PersonCount = PerGroup * GroupCount; int AllocCount = WeekCount * PersonCount; bool Infeasible = true; if (!Violatn) { Infeasible = false; int * Alloc = new int[AllocCount]; for(int Idx = 0; Idx < AllocCount; Idx++) if (!(cin >> Alloc[Idx]) || Alloc[Idx] < 0 || Alloc[Idx] >= GroupCount) { cout << "nil" << endl; delete [] Alloc; return EXIT_SUCCESS; } for(int j = 0; !Infeasible && j < WeekCount; j++) for(int k = 0; !Infeasible && k < GroupCount; k++) { int PerCount = 0; for(int i = 0; i < PersonCount; i++) if (Alloc[j * PersonCount + i] == k) PerCount++; if (PerCount != PerGroup) Infeasible = true; } for(int i = 0; !Infeasible && i < PersonCount; i++) for(int l = i + 1; !Infeasible && l < PersonCount; l++) { int MeetCount = 0; for(int j =0; !Infeasible && j < WeekCount; j++) { if (Alloc[j * PersonCount +i] == Alloc[j * PersonCount + l]) { MeetCount++; if (MeetCount > 1) Infeasible = true; } } } delete [] Alloc; } cout << Violatn << " " << Iteratn << " " << Time << " " << Memory; cout << " " << Tabu << " " << PerGroup << " " << GroupCount << " " << WeekCount; cout << " " << Infeasible << endl; return EXIT_SUCCESS; }
66c573143dc2559fb782e1b27e2ee77a2bc200a5
bcc78d050f364849fba418360a8d207df2efe064
/src/rutils.h
2e6049e44a1d48c12cbe28d8cd8a9c45cd008b52
[]
no_license
skwashi/rigidgl
ac160e787210e7f23c981cc71cacc2f7af1a37d2
bae8421b9c69400f903a987b7a4c910110a9b9ba
refs/heads/master
2021-01-10T19:53:57.994074
2015-06-07T20:09:56
2015-06-07T20:09:56
35,351,145
0
0
null
null
null
null
UTF-8
C++
false
false
622
h
rutils.h
/** * @author Jonas Ransjö */ #ifndef RUTILS_H #define RUTILS_H #include <FreeImage.h> #include <string> #include "rtypes.h" #include "gl/mesh.h" namespace rutils { std::string readFile(const std::string& filename); std::string readFile(const char* filename); FIBITMAP* loadImage(const char* fname); bool loadImage(const std::string& fname, uint& width, uint& height, uint& bpp, byte** data); bool loadImage(const char* fname, uint& width, uint& height, uint& bpp, byte** data); bool loadObj(const std::string& fname, rgl::Mesh& mesh); bool loadObj(const char* fname, rgl::Mesh& mesh); } // namespace #endif
6127b10ad285d3248f7ec39b2278a1ffd261a6e4
9f81e16518deca908366de2998f73f70129124a4
/summary/leetcode/873.最长的斐波那契子序列的长度.cpp
2d5c7cb543ec933461a8d64675e5bf3517ba7421
[]
no_license
Breesiu/note-algorithm
47bec559c73f1807d68dc380f93577568e6e3682
fbd6f01d84502ec2e760878cbb860c5e05fb0103
refs/heads/master
2023-07-16T15:37:00.315348
2021-09-05T14:30:56
2021-09-05T14:30:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
699
cpp
873.最长的斐波那契子序列的长度.cpp
class Solution { public: int lenLongestFibSubseq(vector<int>& arr) { // dp[i][j]以i,j结尾的序列长度 int ans = 0; int n=arr.size(); map<int,int> val2rank; for(int i=0;i<n;i++)val2rank[arr[i]]=i; vector<vector<int> > dp(n,vector<int>(n,2)); for(int i=1;i<n;i++){ for(int j=i+1;j<n;j++){ if(arr[j]-arr[i]<arr[i] && val2rank.count(arr[j]-arr[i])){ int k = val2rank[arr[j]-arr[i]]; dp[i][j] = max(dp[i][j],dp[k][i]+1);//状态转移方程 } ans = max(dp[i][j],ans); } } return ans<3?0:ans; } };
6760c012eb3f83ad175784640df167f94fa2fee5
5e998be7b8a00599dbe5a513360f89a2adf3b6a4
/translator/iCPrimaryExpression.cpp
5997473f61c9814876b5d48149359821c591ded1
[]
no_license
ecolog/IndustrialC
017865c01bca616d52ddc4cdc2f971ee3f50b010
239bc97291642c3d63b175e616a3dfe64de27da2
refs/heads/master
2023-03-19T23:11:59.173670
2019-12-12T15:46:39
2019-12-12T15:46:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
814
cpp
iCPrimaryExpression.cpp
#include "iCPrimaryExpression.h" #include "CodeGenContext.h" #include "ParserContext.h" //================================================================================================= //Code generator //================================================================================================= void iCPrimaryExpression::gen_code(CodeGenContext& context) { if(NULL == expr) return; context.set_location(line_num, filename); context.to_code_fmt("("); expr->gen_code(context); context.to_code_fmt(")"); } //================================================================================================= // //================================================================================================= iCPrimaryExpression::~iCPrimaryExpression() { delete expr; }
ce0062bec6af537118d76eae38f683afb351ec8c
b50bc7c8a3ee966b05de80a318c94a8c2f616399
/MPBCompositeShapeRoom.cpp
96488ed28b7ce45ec6e71a8c4aa4231ac254630f
[]
no_license
mpb-cal/MPB-Game-Library
8420e4c5613f985b9a6d4851ecb0ab0f84b9e69a
8d1ead5288f84eb139139b8eb5ffaf52ab4442c8
refs/heads/master
2020-12-04T10:05:13.961280
2020-01-04T06:48:58
2020-01-04T06:48:58
231,721,364
0
0
null
null
null
null
UTF-8
C++
false
false
5,005
cpp
MPBCompositeShapeRoom.cpp
#include "MPBGlobal.h" #include "MPBOpenGL.h" #include "MPBShape.h" #include "MPBShapeBox.h" #include "MPBShapeFrustum.h" #include "MPBCompositeShapeRoom.h" #include "mmgr.h" MPBCompositeShapeRoom::MPBCompositeShapeRoom( MPBFLOAT xPos, MPBFLOAT yPos, MPBFLOAT zPos, MPBFLOAT width, MPBFLOAT height, MPBFLOAT depth, const MPBVector& rotation, const MPBVector& scale, MPBFLOAT wallThickness, const char* textureWall, const char* textureRoof, MPBFLOAT texSizeFrontX, MPBFLOAT texSizeFrontY, MPBFLOAT texSizeBackX, MPBFLOAT texSizeBackY, MPBFLOAT texSizeTopX, MPBFLOAT texSizeTopY, MPBFLOAT texSizeBottomX, MPBFLOAT texSizeBottomY, MPBFLOAT texSizeLeftX, MPBFLOAT texSizeLeftY, MPBFLOAT texSizeRightX, MPBFLOAT texSizeRightY, bool floor, bool roof, bool northWall, bool southWall, bool eastWall, bool westWall, bool visible ) : MPBCompositeShape() { MPBShapeBox* sb; MPBFLOAT offset = wallThickness / 10; MPB_ASSERT( offset ); if (southWall) { sb = new MPBShapeBox( width, height, wallThickness, textureWall, texSizeFrontX, texSizeFrontY, texSizeBackX, texSizeBackY, texSizeTopX, texSizeTopY, texSizeBottomX, texSizeBottomY, texSizeLeftX, texSizeLeftY, texSizeRightX, texSizeRightY, false ); sb->translate( 0, 0, -wallThickness/2 ); sb->scale( scale.x, scale.y, scale.z ); sb->translate( 0, 0, depth/2 ); sb->rotateX( rotation.x ); sb->rotateY( rotation.y ); sb->rotateZ( rotation.z ); sb->translate( xPos, yPos, zPos ); sb->setDraw( visible ); addShape( sb ); } if (northWall) { sb = new MPBShapeBox( width, height, wallThickness, textureWall, texSizeFrontX, texSizeFrontY, texSizeBackX, texSizeBackY, texSizeTopX, texSizeTopY, texSizeBottomX, texSizeBottomY, texSizeLeftX, texSizeLeftY, texSizeRightX, texSizeRightY, false ); sb->translate( 0, 0, wallThickness/2 ); sb->scale( scale.x, scale.y, scale.z ); sb->translate( 0, 0, -depth/2 ); sb->rotateX( rotation.x ); sb->rotateY( rotation.y ); sb->rotateZ( rotation.z ); sb->translate( xPos, yPos, zPos ); sb->setDraw( visible ); addShape( sb ); } if (westWall) { MPBFLOAT z; MPBFLOAT d; if (southWall) { z = zPos - wallThickness; if (northWall) { d = depth - wallThickness; } else { d = depth; } } else { z = zPos - depth/2; if (northWall) { d = depth; } else { d = depth + wallThickness; } } sb = new MPBShapeBox( wallThickness-offset, height, depth-offset, textureWall, texSizeFrontX, texSizeFrontY, texSizeBackX, texSizeBackY, texSizeTopX, texSizeTopY, texSizeBottomX, texSizeBottomY, texSizeLeftX, texSizeLeftY, texSizeRightX, texSizeRightY, false ); sb->translate( wallThickness/2, 0, 0 ); sb->scale( scale.x, scale.y, scale.z ); sb->translate( -width/2, 0, 0 ); sb->rotateX( rotation.x ); sb->rotateY( rotation.y ); sb->rotateZ( rotation.z ); sb->translate( xPos, yPos, zPos ); sb->setDraw( visible ); addShape( sb ); } if (eastWall) { MPBFLOAT z; MPBFLOAT d; if (southWall) { z = zPos - wallThickness; if (northWall) { d = depth - wallThickness; } else { d = depth; } } else { z = zPos; if (northWall) { d = depth; } else { d = depth + wallThickness; } } sb = new MPBShapeBox( wallThickness-offset, height, depth-offset, textureWall, texSizeFrontX, texSizeFrontY, texSizeBackX, texSizeBackY, texSizeTopX, texSizeTopY, texSizeBottomX, texSizeBottomY, texSizeLeftX, texSizeLeftY, texSizeRightX, texSizeRightY, false ); sb->translate( -wallThickness/2, 0, 0 ); sb->scale( scale.x, scale.y, scale.z ); sb->translate( width/2, 0, 0 ); sb->rotateX( rotation.x ); sb->rotateY( rotation.y ); sb->rotateZ( rotation.z ); sb->translate( xPos, yPos, zPos ); sb->setDraw( visible ); addShape( sb ); } if (roof) { sb = new MPBShapeBox( width, wallThickness, depth, textureRoof, texSizeFrontX, texSizeFrontY, texSizeBackX, texSizeBackY, texSizeTopX, texSizeTopY, texSizeBottomX, texSizeBottomY, texSizeLeftX, texSizeLeftY, texSizeRightX, texSizeRightY, false ); sb->scale( scale.x, scale.y, scale.z ); sb->translate( 0, height/2 + wallThickness/2, 0 ); sb->rotateX( rotation.x ); sb->rotateY( rotation.y ); sb->rotateZ( rotation.z ); sb->translate( xPos, yPos, zPos ); sb->setDraw( visible ); addShape( sb ); } if (floor) { sb = new MPBShapeBox( width-offset, wallThickness, depth-offset, textureWall, texSizeFrontX, texSizeFrontY, texSizeBackX, texSizeBackY, texSizeTopX, texSizeTopY, texSizeBottomX, texSizeBottomY, texSizeLeftX, texSizeLeftY, texSizeRightX, texSizeRightY, false ); sb->scale( scale.x, scale.y, scale.z ); sb->translate( 0, -height/2 - wallThickness/2, 0 ); sb->rotateX( rotation.x ); sb->rotateY( rotation.y ); sb->rotateZ( rotation.z ); sb->translate( xPos, yPos, zPos ); sb->setDraw( visible ); addShape( sb ); } } MPBCompositeShapeRoom::~MPBCompositeShapeRoom() { }
c99768fb0b513db31546bc9cde322712e2c2fced
56bb8d59f3c9bc145dcf556f34bccd38c8039a79
/src/wasm/chaining_util.cpp
c03c7ac5b96a08856b9ea26b1c811bcadadcb4a5
[ "Apache-2.0" ]
permissive
sleipnir/faasm
69d774f0f341142c2ed888836ca519f863afcd04
71f2e474b8ce00ae1af73f24b2104be996a15266
refs/heads/master
2023-04-28T04:15:58.988357
2021-05-14T06:39:35
2021-05-14T06:39:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,170
cpp
chaining_util.cpp
#include "WasmModule.h" #include <faabric/scheduler/Scheduler.h> #include <faabric/util/bytes.h> #include <faabric/util/func.h> #include <wasm/chaining.h> namespace wasm { int awaitChainedCall(unsigned int messageId) { int callTimeoutMs = faabric::util::getSystemConfig().chainedCallTimeout; int returnCode = 1; try { faabric::scheduler::Scheduler& sch = faabric::scheduler::getScheduler(); const faabric::Message result = sch.getFunctionResult(messageId, callTimeoutMs); returnCode = result.returnvalue(); } catch (faabric::redis::RedisNoResponseException& ex) { faabric::util::getLogger()->error( "Timed out waiting for chained call: {}", messageId); } catch (std::exception& ex) { faabric::util::getLogger()->error( "Non-timeout exception waiting for chained call: {}", ex.what()); } return returnCode; } int makeChainedCall(const std::string& functionName, int wasmFuncPtr, const char* pyFuncName, const std::vector<uint8_t>& inputData) { faabric::scheduler::Scheduler& sch = faabric::scheduler::getScheduler(); faabric::Message* originalCall = getExecutingCall(); std::string user = originalCall->user(); assert(!user.empty()); assert(!functionName.empty()); faabric::util::getLogger()->debug( "Chaining call {}/{}:{}", user, functionName, originalCall->id()); std::shared_ptr<faabric::BatchExecuteRequest> req = faabric::util::batchExecFactory(originalCall->user(), functionName, 1); faabric::Message& msg = req->mutable_messages()->at(0); msg.set_inputdata(inputData.data(), inputData.size()); msg.set_funcptr(wasmFuncPtr); msg.set_pythonuser(originalCall->pythonuser()); msg.set_pythonfunction(originalCall->pythonfunction()); if (pyFuncName != nullptr) { msg.set_pythonentry(pyFuncName); } msg.set_ispython(originalCall->ispython()); sch.callFunctions(req); sch.logChainedFunction(originalCall->id(), msg.id()); return msg.id(); } int spawnChainedThread(const std::string& snapshotKey, size_t snapshotSize, int funcPtr, int argsPtr) { faabric::scheduler::Scheduler& sch = faabric::scheduler::getScheduler(); faabric::Message* originalCall = getExecutingCall(); faabric::Message call = faabric::util::messageFactory( originalCall->user(), originalCall->function()); call.set_isasync(true); // Snapshot details call.set_snapshotkey(snapshotKey); call.set_snapshotsize(snapshotSize); // Function pointer and args // NOTE - with a pthread interface we only ever pass the function a single // pointer argument, hence we use the input data here to hold this argument // as a string call.set_funcptr(funcPtr); call.set_inputdata(std::to_string(argsPtr)); const std::string origStr = faabric::util::funcToString(*originalCall, false); const std::string chainedStr = faabric::util::funcToString(call, false); // Schedule the call sch.callFunction(call); return call.id(); } int awaitChainedCallOutput(unsigned int messageId, uint8_t* buffer, int bufferLen) { const std::shared_ptr<spdlog::logger>& logger = faabric::util::getLogger(); int callTimeoutMs = faabric::util::getSystemConfig().chainedCallTimeout; faabric::scheduler::Scheduler& sch = faabric::scheduler::getScheduler(); const faabric::Message result = sch.getFunctionResult(messageId, callTimeoutMs); if (result.type() == faabric::Message_MessageType_EMPTY) { logger->error("Cannot find output for {}", messageId); } std::vector<uint8_t> outputData = faabric::util::stringToBytes(result.outputdata()); int outputLen = faabric::util::safeCopyToBuffer(outputData, buffer, bufferLen); if (outputLen < outputData.size()) { logger->warn( "Undersized output buffer: {} for {} output", bufferLen, outputLen); } return result.returnvalue(); } }
8e9df38e0d87efb6816955d629ad6cbbb871e281
df0d09f4ac3c7abcb079d32cea4cb8c1bdecc45c
/utils/img_morphology/img_morphology.cpp
50d1cf587b176e3a853f70a84e08d541978f51a5
[ "MIT" ]
permissive
nmalex/renderfarm.js-server
3260c030c45326829abf4977baefe15fd675264d
52e1ccb44f101693c41f923491b395ceb369b258
refs/heads/master
2022-09-05T09:09:17.563918
2021-09-20T09:03:19
2021-09-20T09:03:19
155,418,831
56
9
NOASSERTION
2021-03-23T05:54:33
2018-10-30T16:23:25
TypeScript
UTF-8
C++
false
false
1,460
cpp
img_morphology.cpp
#include "stdafx.h" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv/highgui.h" #include <stdlib.h> #include <stdio.h> #include <iostream> using namespace cv; using namespace std; int main(int argc, char** argv) { if (argc != 6) { cout << " Usage: img_morphology.exe <size> <shape> <type> <input> <output>" << endl; cout << " size: 1, 2.. in pixels" << endl; cout << " shape: MORPH_RECT = 0, MORPH_CROSS = 1, MORPH_ELLIPSE = 2" << endl; cout << " type: dilate = 0, erode = 1" << endl; return -1; } try { int size = atoi(argv[1]); int shape = atoi(argv[2]); int type = atoi(argv[3]); Mat image = imread(argv[4], IMREAD_COLOR); // Read the file if (image.empty()) // Check for invalid input { cout << "Could not open or find the image" << std::endl; return 2; } if (!image.data) { cout << "Could not read the image" << std::endl; return 3; } int erosion_size = size; Mat element = getStructuringElement(shape, // MORPH_ELLIPSE, Size(2 * erosion_size + 1, 2 * erosion_size + 1), Point(erosion_size, erosion_size)); Mat erosion_dst; if (type == 0) { dilate(image, erosion_dst, element); } else { erode(image, erosion_dst, element); } imwrite(argv[5], erosion_dst); return 0; } catch (const std::exception& e) { cout << e.what() << std::endl; return 1; } }
1e0cca1fd78e9ea87e90e8fad4869a66e0686310
e9fb3905a6baa65cd3765d0d6d18ebe3d2b07934
/Src/PPLib/Cliagt.cpp
18a42bdfb189ec27e2510a85c1ff1f1e228cc4b2
[]
no_license
Shulikov-v/OpenPapyrus
bb2e26bdff669af58a1268ef84793ff9f25bb648
272cee0df983fb1d9cb0627ac627dbb15b2800cf
refs/heads/master
2021-01-21T07:10:46.251906
2017-02-26T15:27:53
2017-02-26T15:27:53
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
68,785
cpp
Cliagt.cpp
// CLIAGT.CPP // Copyright (c) A.Sobolev 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 // @codepage windows-1251 // Соглашения с клиентами об условиях торговли // #include <pp.h> #pragma hdrstop #include <ppidata.h> SLAPI PPClientAgreement::PPClientAgreement() { Init(); } SLAPI PPClientAgreement::PPClientAgreement(const PPClientAgreement & rSrc) { Init(); memcpy(this, &rSrc, offsetof(PPClientAgreement, DebtLimList)); DebtLimList = rSrc.DebtLimList; } int SLAPI PPClientAgreement::Init() { memzero(this, offsetof(PPClientAgreement, DebtLimList)); DebtLimList.freeAll(); return 1; } int FASTCALL PPClientAgreement::IsEqual(const PPClientAgreement & rS) const { #define CMP_FLD(f) if((f) != (rS.f)) return 0 CMP_FLD(Flags); CMP_FLD(BegDt); CMP_FLD(Expiry); CMP_FLD(MaxCredit); CMP_FLD(MaxDscnt); CMP_FLD(Dscnt); CMP_FLD(DefPayPeriod); CMP_FLD(PriceRoundDir); CMP_FLD(DefAgentID); CMP_FLD(DefQuotKindID); CMP_FLD(ExtObjectID); CMP_FLD(LockPrcBefore); CMP_FLD(PriceRoundPrec); CMP_FLD(RetLimPrd); CMP_FLD(RetLimPart); CMP_FLD(PaymDateBase); #undef CMP_FLD if(strcmp(Code, rS.Code) != 0) return 0; else { const uint _c1 = DebtLimList.getCount(); const uint _c2 = rS.DebtLimList.getCount(); if(_c1 != _c2) return 0; else if(_c1) { for(uint i = 0; i < _c1; i++) { const DebtLimit & r_e1 = DebtLimList.at(i); const DebtLimit & r_e2 = rS.DebtLimList.at(i); if(memcmp(&r_e1, &r_e2, sizeof(r_e1)) != 0) return 0; } } } return 1; } int SLAPI PPClientAgreement::IsEmpty() const { const long nempty_flags_mask = (AGTF_DONTCALCDEBTINBILL|AGTF_PRICEROUNDING); return ((Flags & nempty_flags_mask) || BegDt || Expiry || MaxCredit || MaxDscnt || Dscnt || DefPayPeriod || DefAgentID || DefQuotKindID || ExtObjectID || LockPrcBefore || strlen(Code) > 0 || DebtLimList.getCount() || (RetLimPrd && RetLimPart)) ? 0 : 1; } PPClientAgreement & FASTCALL PPClientAgreement::operator = (const PPClientAgreement & rSrc) { memcpy(this, &rSrc, offsetof(PPClientAgreement, DebtLimList)); DebtLimList = rSrc.DebtLimList; return *this; } struct DebtLimit_Before715 { PPID DebtDimID; double Limit; long Flags; }; int SLAPI PPClientAgreement::Serialize(int dir, SBuffer & rBuf, SSerializeContext * pCtx) { int ok = 1; uint8 ind = 0; // @v7.2.0 SArray temp_list(sizeof(DebtLimit_Before715)); // @v7.1.5 if(dir > 0) { if(IsEmpty()) ind = 1; rBuf.Write(ind); if(ind == 0) { THROW_SL(pCtx->SerializeBlock(dir, offsetof(PPClientAgreement, DebtLimList), this, rBuf, 0)); THROW_SL(pCtx->Serialize(dir, &DebtLimList, rBuf)); // @v7.2.0 #if 0 // @v7.2.0 { // @v7.1.5 { for(uint i = 0; i < DebtLimList.getCount(); i++) { DebtLimit & r_dd_item = DebtLimList.at(i); DebtLimit_Before715 item; item.DebtDimID = r_dd_item.DebtDimID; item.Limit = r_dd_item.Limit; item.Flags = r_dd_item.Flags; THROW_SL(temp_list.insert(&item)); } THROW_SL(pCtx->Serialize(dir, &temp_list, rBuf)); // } @v7.1.5 // @v7.1.5 THROW_SL(pCtx->Serialize(dir, &DebtLimList, rBuf)); #endif // } 0 @v7.2.0 } } else if(dir < 0) { rBuf.Read(ind); if(ind == 0) { THROW_SL(pCtx->SerializeBlock(dir, offsetof(PPClientAgreement, DebtLimList), this, rBuf, 0)); THROW_SL(pCtx->Serialize(dir, &DebtLimList, rBuf)); // @v7.2.0 #if 0 // @v7.2.0 { // @v7.1.5 THROW_SL(pCtx->Serialize(dir, &DebtLimList, rBuf)); // @v7.1.5 { THROW_SL(pCtx->Serialize(dir, &temp_list, rBuf)); DebtLimList.clear(); for(uint i = 0; i < temp_list.getCount(); i++) { DebtLimit_Before715 & r_item = *(DebtLimit_Before715 *)temp_list.at(i); DebtLimit dd_item; dd_item.DebtDimID = r_item.DebtDimID; dd_item.Limit = r_item.Limit; dd_item.Flags = r_item.Flags; dd_item.LockPrcBefore = ZERODATE; THROW_SL(DebtLimList.insert(&dd_item)); } // } @v7.1.5 #endif // } 0 @v7.2.0 } else { Init(); } } CATCHZOK return ok; } double SLAPI PPClientAgreement::GetCreditLimit(PPID debtDimID) const { double limit = 0.0; int has_dd_item = 0; if(debtDimID) { for(uint i = 0; !has_dd_item && i < DebtLimList.getCount(); i++) { if(DebtLimList.at(i).DebtDimID == debtDimID) { limit = DebtLimList.at(i).Limit; has_dd_item = 1; } } } return has_dd_item ? limit : MaxCredit; } int FASTCALL PPClientAgreement::IsStopped(PPID debtDimID) const { DebtLimit * p_item = GetDebtDimEntry(debtDimID); return p_item ? BIN(p_item->Flags & DebtLimit::fStop) : -1; } PPClientAgreement::DebtLimit * FASTCALL PPClientAgreement::GetDebtDimEntry(PPID debtDimID) const { DebtLimit * p_item = 0; if(debtDimID) for(uint i = 0; !p_item && i < DebtLimList.getCount(); i++) if(DebtLimList.at(i).DebtDimID == debtDimID) p_item = &DebtLimList.at(i); return p_item; } struct _PPClientAgt { // @persistent @store(PropertyTbl) @#{size=PROPRECFIXSIZE} long Tag; // Const=PPOBJ_ARTICLE long ArtID; // ->Article.ID long PropID; // Const=ARTPRP_CLIAGT long Flags; // LDATE BegDt; // LDATE Expiry; // double MaxCredit; // Максимальный кредит double MaxDscnt; // Максимальная скидка в %% (>= 100% - неограниченная) double Dscnt; // Обычная скидка в %% short DefPayPeriod; // Количество дней от отгрузки до оплаты по умолчанию PPID DefAgentID; // Агент, закрепленный за клиентом PPID DefQuotKindID; // Вид котировки, используемый для отгрузки этому клиенту char Code[12]; // @v5.7.12 Номер соглашения // PPID ExtObjectID; // @v5.9.3 Дополнительный объект (таблица дополнительных объектов для общего соглашения) LDATE LockPrcBefore; // @v6.0.7 Дата, до которой процессинг должников не меняет параметры соглашения // int16 PriceRoundDir; // @v6.4.1 Направление округления окончательной цены в документах float PriceRoundPrec; // @v6.4.1 Точность округления окончательной цены в документах int16 RetLimPrd; // @v7.1.5 Период ограничения доли возвратов от суммы товарооборота uint16 RetLimPart; // @v7.1.5 Макс доля возвратов от суммы товарооборота за период RetLimPrd (в промилле) long PaymDateBase; // @v8.4.2 }; //static int SLAPI PPObjArticle::PropToClientAgt(const PropertyTbl::Rec * pPropRec, PPClientAgreement * pAgt, int loadDebtLimList /*=0*/) { int ok = 1; const _PPClientAgt * p_agt = (const _PPClientAgt *)pPropRec; pAgt->ClientID = p_agt->ArtID; pAgt->Flags = (p_agt->Flags | AGTF_LOADED); pAgt->BegDt = p_agt->BegDt; pAgt->Expiry = p_agt->Expiry; pAgt->MaxCredit = p_agt->MaxCredit; pAgt->MaxDscnt = p_agt->MaxDscnt; pAgt->Dscnt = p_agt->Dscnt; pAgt->DefPayPeriod = p_agt->DefPayPeriod; pAgt->DefAgentID = p_agt->DefAgentID; pAgt->DefQuotKindID = p_agt->DefQuotKindID; pAgt->ExtObjectID = p_agt->ExtObjectID; STRNSCPY(pAgt->Code, p_agt->Code); pAgt->LockPrcBefore = p_agt->LockPrcBefore; pAgt->PriceRoundDir = p_agt->PriceRoundDir; pAgt->PriceRoundPrec = p_agt->PriceRoundPrec; pAgt->RetLimPrd = p_agt->RetLimPrd; // @v7.1.5 pAgt->RetLimPart = p_agt->RetLimPart; // @v7.1.5 pAgt->PaymDateBase = p_agt->PaymDateBase; // @v8.4.2 if(loadDebtLimList) { Reference * p_ref = PPRef; if(pAgt->Flags & AGTF_DDLIST715) { p_ref->GetPropArray(PPOBJ_ARTICLE, pAgt->ClientID, ARTPRP_DEBTLIMLIST2, &pAgt->DebtLimList); } else { SArray temp_list(sizeof(DebtLimit_Before715)); p_ref->GetPropArray(PPOBJ_ARTICLE, pAgt->ClientID, ARTPRP_DEBTLIMLIST, &temp_list); pAgt->DebtLimList.clear(); for(uint i = 0; i < temp_list.getCount(); i++) { DebtLimit_Before715 & r_item = *(DebtLimit_Before715 *)temp_list.at(i); PPClientAgreement::DebtLimit dd_item; dd_item.DebtDimID = r_item.DebtDimID; dd_item.Limit = r_item.Limit; dd_item.Flags = r_item.Flags; dd_item.LockPrcBefore = ZERODATE; THROW_SL(pAgt->DebtLimList.insert(&dd_item)); } } } CATCHZOK return ok; } int SLAPI PPObjArticle::HasClientAgreement(PPID id) { int yes = 0; if(id > 0) { PropertyTbl::Rec prop_rec; PPClientAgreement agt; MEMSZERO(prop_rec); if(PPRef->GetProp(PPOBJ_ARTICLE, id, ARTPRP_CLIAGT, &prop_rec, sizeof(prop_rec)) > 0) { agt.Init(); PropToClientAgt(&prop_rec, &agt, 0); agt.ClientID = id; yes = BIN(!agt.IsEmpty()); } } return yes; } int SLAPI PPObjArticle::GetClientAgreement(PPID id, PPClientAgreement * pAgt, int use_default) { int ok = 1, r, is_default = 0; int r2 = 0; Reference * p_ref = PPRef; PropertyTbl::Rec prop_rec, def_prop_rec; PPClientAgreement def_agt; PPPersonRelTypePacket rt_pack; PPIDArray rel_list; MEMSZERO(prop_rec); THROW(r = p_ref->GetProp(PPOBJ_ARTICLE, id, ARTPRP_CLIAGT, &prop_rec, sizeof(prop_rec))); if(r < 0 && id) { PPID mainorg_id = 0, mainorg_arid = 0; //PPPersonRelType relt_rec; GetMainOrgID(&mainorg_id); P_Tbl->PersonToArticle(mainorg_id, GetSellAccSheet(), &mainorg_arid); // @v8.2.2 if(id != mainorg_arid && ObjRelTyp.Search(PPPSNRELTYP_AFFIL, &relt_rec) > 0 && (relt_rec.Flags & PPPersonRelType::fInhMainOrgAgreement)) { if(id != mainorg_arid && ObjRelTyp.Fetch(PPPSNRELTYP_AFFIL, &rt_pack) > 0 && (rt_pack.Rec.Flags & PPPersonRelType::fInhMainOrgAgreement)) { // @v8.2.2 if(GetRelPersonList(id, PPPSNRELTYP_AFFIL, 0, &rel_list) > 0 && rel_list.getCount() && rel_list.lsearch(mainorg_arid) > 0) { THROW(r = p_ref->GetProp(PPOBJ_ARTICLE, mainorg_arid, ARTPRP_CLIAGT, &prop_rec, sizeof(prop_rec))); } } } // @v8.2.2 { if(r < 0 && id) { if(ObjRelTyp.Fetch(PPPSNRELTYP_AFFIL, &rt_pack) > 0 && (rt_pack.Rec.Flags & PPPersonRelType::fInhAgreements)) { if(GetRelPersonList(id, PPPSNRELTYP_AFFIL, 0, &rel_list) > 0) { for(uint i = 0; r < 0 && i < rel_list.getCount(); i++) { PPID rel_ar_id = ObjectToPerson(rel_list.get(i), 0); THROW(r = p_ref->GetProp(PPOBJ_ARTICLE, rel_ar_id, ARTPRP_CLIAGT, &prop_rec, sizeof(prop_rec))); } } } } // } @v8.2.2 if(use_default) { THROW(r2 = p_ref->GetProp(PPOBJ_ARTICLE, 0, ARTPRP_CLIAGT, &def_prop_rec, sizeof(def_prop_rec))); if(r2 > 0) PropToClientAgt(&def_prop_rec, &def_agt, 0); if(r < 0 && id) { ok = 2; if(r2 > 0) { is_default = 1; prop_rec = def_prop_rec; r = 1; } } } if(r > 0) { pAgt->Init(); PropToClientAgt(&prop_rec, pAgt, 1); pAgt->ClientID = id; if(is_default) pAgt->Flags |= AGTF_DEFAULT; // @v7.1.9 { else if(r2 > 0) { if(pAgt->RetLimPrd == 0 && pAgt->RetLimPart == 0) { pAgt->RetLimPrd = def_agt.RetLimPrd; pAgt->RetLimPart = def_agt.RetLimPart; } } // } @v7.1.9 } else { pAgt->Flags |= AGTF_LOADED; ok = -1; } CATCHZOK return ok; } int SLAPI PPObjArticle::PutClientAgreement(PPID id, PPClientAgreement * pAgt, int use_ta) { int ok = 1; _PPClientAgt _agt; THROW(CheckRights(ARTRT_CLIAGT)); if(pAgt) { MEMSZERO(_agt); _agt.Tag = PPOBJ_ARTICLE; _agt.ArtID = id; _agt.PropID = ARTPRP_CLIAGT; _agt.Flags = ((pAgt->Flags & ~AGTF_LOADED) | AGTF_DDLIST715); _agt.BegDt = pAgt->BegDt; _agt.Expiry = pAgt->Expiry; _agt.MaxCredit = pAgt->MaxCredit; _agt.MaxDscnt = pAgt->MaxDscnt; _agt.Dscnt = pAgt->Dscnt; _agt.DefPayPeriod = pAgt->DefPayPeriod; _agt.DefAgentID = pAgt->DefAgentID; _agt.DefQuotKindID = pAgt->DefQuotKindID; _agt.ExtObjectID = pAgt->ExtObjectID; _agt.LockPrcBefore = pAgt->LockPrcBefore; _agt.PriceRoundDir = pAgt->PriceRoundDir; _agt.PriceRoundPrec = pAgt->PriceRoundPrec; _agt.RetLimPrd = pAgt->RetLimPrd; // @v7.1.5 _agt.RetLimPart = pAgt->RetLimPart; // @v7.1.5 _agt.PaymDateBase = pAgt->PaymDateBase; // @v8.4.2 STRNSCPY(_agt.Code, pAgt->Code); } { Reference * p_ref = PPRef; PPTransaction tra(use_ta); THROW(tra); THROW(p_ref->PutProp(PPOBJ_ARTICLE, id, ARTPRP_CLIAGT, (pAgt ? &_agt : 0), sizeof(_agt), 0)); THROW(p_ref->PutPropArray(PPOBJ_ARTICLE, id, ARTPRP_DEBTLIMLIST, 0, 0)); // @temp(..1/06/2012) THROW(p_ref->PutPropArray(PPOBJ_ARTICLE, id, ARTPRP_DEBTLIMLIST2, (pAgt ? &pAgt->DebtLimList : 0), 0)); THROW(tra.Commit()); } CATCHZOK return ok; } // // // class AgtDialog : public TDialog { public: AgtDialog(uint dlgID) : TDialog(dlgID) { ArID = 0; } protected: DECL_HANDLE_EVENT { TDialog::handleEvent(event); if(event.isCmd(cmBills)) { if(ArID) { BillFilt flt; flt.ObjectID = ArID; flt.Flags |= BillFilt::fShowDebt; ViewGoodsBills(&flt, 1); } clearEvent(event); } } PPID ArID; }; // // // class DebtLimListDialog : public PPListDialog { public: DebtLimListDialog() : PPListDialog(DLG_DEBTLIMLIST, CTL_DEBTLIMLIST_LIST) { PPObjDebtDim dd_obj; P_DebtDimList = dd_obj.MakeStrAssocList(0); } ~DebtLimListDialog() { ZDELETE(P_DebtDimList); } int setDTS(const TSArray <PPClientAgreement::DebtLimit> * pData) { //long id = 0; if(pData) Data.copy(*pData); else Data.freeAll(); updateList(-1); if(P_DebtDimList) for(uint i = 0; i < Data.getCount(); i++) P_DebtDimList->Remove(Data.at(i).DebtDimID); return 1; } int getDTS(TSArray <PPClientAgreement::DebtLimit> * pData) { int ok = 1; CALLPTRMEMB(pData, copy(Data)); return ok; } private: DECL_HANDLE_EVENT; virtual int addItem(long * pPos, long * pID); virtual int editItem(long pos, long id); virtual int delItem(long pos, long id); virtual int setupList(); int Edit(PPClientAgreement::DebtLimit * pItem); StrAssocArray * P_DebtDimList; TSArray <PPClientAgreement::DebtLimit> Data; }; IMPL_HANDLE_EVENT(DebtLimListDialog) { PPListDialog::handleEvent(event); if(TVKEYDOWN && TVKEY == kbSpace) { uint pos = 0; long id = 0L; getSelection(&id); if(id > 0 && Data.lsearch(&id, &pos, PTR_CMPFUNC(long)) > 0) { long fstop = PPClientAgreement::DebtLimit::fStop; long flags = Data.at(pos).Flags; SETFLAG(Data.at(pos).Flags, fstop, !(flags & fstop)); updateList(pos); } clearEvent(event); } } int DebtLimListDialog::setupList() { int ok = -1; for(uint i = 0; i < Data.getCount(); i++) { StringSet ss(SLBColumnDelim); SString temp_buf; PPClientAgreement::DebtLimit debt_lim = Data.at(i); GetObjectName(PPOBJ_DEBTDIM, debt_lim.DebtDimID, temp_buf); ss.add(temp_buf, 0); (temp_buf = 0).Cat(debt_lim.Limit, SFMT_MONEY); ss.add(temp_buf, 0); (temp_buf = 0).CatChar((debt_lim.Flags & PPClientAgreement::DebtLimit::fStop) ? 'X' : ' '); ss.add(temp_buf, 0); if(!addStringToList(debt_lim.DebtDimID, ss.getBuf())) ok = PPErrorZ(); } return ok; } class DebtLimItemDialog : public TDialog { public: DebtLimItemDialog(StrAssocArray * pDebtDimList) : TDialog(DLG_DBTLIMITEM) { P_DebtDimList = pDebtDimList; SetupCalDate(CTLCAL_DBTLIMITEM_LOCKPRCB, CTL_DBTLIMITEM_LOCKPRCB); } int setDTS(const PPClientAgreement::DebtLimit * pData) { if(!RVALUEPTR(Data, pData)) MEMSZERO(Data); if(P_DebtDimList) SetupStrAssocCombo(this, CTLSEL_DBTLIMITEM_DIM, P_DebtDimList, Data.DebtDimID, 0, 0); else SetupPPObjCombo(this, CTLSEL_DBTLIMITEM_DIM, PPOBJ_DEBTDIM, Data.DebtDimID, 0, 0); setCtrlData(CTL_DBTLIMITEM_LIMIT, &Data.Limit); AddClusterAssoc(CTL_DBTLIMITEM_FLAGS, 0, PPClientAgreement::DebtLimit::fStop); SetClusterData(CTL_DBTLIMITEM_FLAGS, Data.Flags); setCtrlDate(CTL_DBTLIMITEM_LOCKPRCB, Data.LockPrcBefore); // @v7.1.5 return 1; } int getDTS(PPClientAgreement::DebtLimit * pData) { int ok = 1; uint sel = 0; getCtrlData(sel = CTLSEL_DBTLIMITEM_DIM, &Data.DebtDimID); THROW_PP(Data.DebtDimID, PPERR_USERINPUT); getCtrlData(CTL_DBTLIMITEM_LIMIT, &Data.Limit); GetClusterData(CTL_DBTLIMITEM_FLAGS, &Data.Flags); Data.LockPrcBefore = getCtrlDate(sel = CTL_DBTLIMITEM_LOCKPRCB); // @v7.1.5 THROW_SL(checkdate(Data.LockPrcBefore, 1)); // @v7.1.5 ASSIGN_PTR(pData, Data); CATCH ok = PPErrorByDialog(this, sel, -1); ENDCATCH return ok; } private: StrAssocArray * P_DebtDimList; PPClientAgreement::DebtLimit Data; }; int DebtLimListDialog::Edit(PPClientAgreement::DebtLimit * pItem) { int ok = -1; DebtLimItemDialog * dlg = new DebtLimItemDialog(P_DebtDimList); THROW(CheckDialogPtr(&dlg)); dlg->setDTS(pItem); for(int valid_data = 0; !valid_data && ExecView(dlg) == cmOK;) { if(dlg->getDTS(pItem) > 0) { if(P_DebtDimList && pItem) P_DebtDimList->Remove(pItem->DebtDimID); ok = valid_data = 1; } else PPError(); } CATCHZOKPPERR delete dlg; return ok; } int DebtLimListDialog::addItem(long * pPos, long * pID) { int ok = -1; long pos = -1, id = 0; PPClientAgreement::DebtLimit debt_lim; MEMSZERO(debt_lim); if(Edit(&debt_lim) > 0) { Data.insert(&debt_lim); pos = Data.getCount() - 1; id = debt_lim.DebtDimID; ok = 1; } ASSIGN_PTR(pID, id); ASSIGN_PTR(pPos, pos); return ok; } int DebtLimListDialog::editItem(long pos, long id) { int ok = -1; if(pos >= 0 && pos < (long)Data.getCount()) { SString dim_name; PPClientAgreement::DebtLimit debt_lim = Data.at(pos); GetObjectName(PPOBJ_DEBTDIM, id, dim_name); P_DebtDimList->Add(id, dim_name); if(Edit(&debt_lim) > 0) { Data.at(pos) = debt_lim; ok = 1; } } return ok; } int DebtLimListDialog::delItem(long pos, long id) { int ok = -1; if(pos >= 0 && pos < (long)Data.getCount()) { ok = Data.atFree(pos); if(ok > 0) { SString dim_name; GetObjectName(PPOBJ_DEBTDIM, id, dim_name); P_DebtDimList->Add(id, dim_name); } } return ok; } int SLAPI EditDebtLimList(PPClientAgreement & rCliAgt) { DIALOG_PROC_BODY(DebtLimListDialog, &rCliAgt.DebtLimList); } int SLAPI SetupPaymDateBaseCombo(TDialog * pDlg, uint ctlID, long initVal) { SString buf, id_buf, txt_buf; StrAssocArray ary; PPLoadText(PPTXT_PAYMDATEBASE, buf); StringSet ss(';', buf); for(uint i = 0; ss.get(&i, buf) > 0;) if(buf.Divide(',', id_buf, txt_buf) > 0) ary.Add(id_buf.ToLong(), txt_buf); { PPObjTag tag_obj; PPObjectTag tag_rec; for(SEnum en = PPRef->Enum(PPOBJ_TAG, 0); en.Next(&tag_rec) > 0;) { if(tag_rec.ID > PPClientAgreement::pdbTagBias && tag_rec.ObjTypeID == PPOBJ_BILL && oneof2(tag_rec.TagDataType, OTTYP_DATE, OTTYP_TIMESTAMP)) { (buf = 0).Cat("Tag").CatDiv(':', 2).Cat(tag_rec.Name); ary.Add(tag_rec.ID, 0, buf); } } } return SetupStrAssocCombo(pDlg, ctlID, &ary, initVal, 0); } int SLAPI PPObjArticle::EditClientAgreement(PPClientAgreement * agt) { class CliAgtDialog : public AgtDialog { public: CliAgtDialog() : AgtDialog(DLG_CLIAGT) { SetupCalDate(CTLCAL_CLIAGT_DATE, CTL_CLIAGT_DATE); SetupCalDate(CTLCAL_CLIAGT_EXPIRY, CTL_CLIAGT_EXPIRY); SetupCalDate(CTLCAL_CLIAGT_LOCKPRCBEFORE, CTL_CLIAGT_LOCKPRCBEFORE); enableCommand(cmOK, ArObj.CheckRights(ARTRT_CLIAGT)); } int setDTS(const PPClientAgreement * pAgt) { SString ar_name; double added_limit_val = 0.0; // @v8.2.4 int added_limit_term = 0; // @v8.2.4 data = *pAgt; ArID = data.ClientID; GetArticleName(data.ClientID, ar_name); setCtrlString(CTL_CLIAGT_CLIENT, ar_name); setCtrlReadOnly(CTL_CLIAGT_CLIENT, 1); setCtrlReadOnly(CTL_CLIAGT_CURDEBT, 1); if(data.ClientID) { DateRange cdp; PPObjBill::DebtBlock blk; BillObj->CalcClientDebt(data.ClientID, BillObj->GetDefaultClientDebtPeriod(cdp), 0, blk); setCtrlReal(CTL_CLIAGT_CURDEBT, blk.Debt); } else enableCommand(cmBills, 0); setCtrlData(CTL_CLIAGT_CODE, data.Code); setCtrlDate(CTL_CLIAGT_DATE, data.BegDt); setCtrlDate(CTL_CLIAGT_EXPIRY, data.Expiry); setCtrlDate(CTL_CLIAGT_LOCKPRCBEFORE, data.LockPrcBefore); setCtrlData(CTL_CLIAGT_MAXCREDIT, &data.MaxCredit); setCtrlData(CTL_CLIAGT_MAXDSCNT, &data.MaxDscnt); setCtrlData(CTL_CLIAGT_DSCNT, &data.Dscnt); setCtrlData(CTL_CLIAGT_PAYPERIOD, &data.DefPayPeriod); SetupPaymDateBaseCombo(this, CTLSEL_CLIAGT_PAYMDTBASE, data.PaymDateBase); // @v8.4.2 SetupArCombo(this, CTLSEL_CLIAGT_AGENT, data.DefAgentID, OLW_LOADDEFONOPEN|OLW_CANINSERT, GetAgentAccSheet(), sacfDisableIfZeroSheet); SetupPPObjCombo(this, CTLSEL_CLIAGT_QUOTKIND, PPOBJ_QUOTKIND, data.DefQuotKindID, 0, 0); if(data.ClientID) { PPClientAgreement agt; const PPID acs_id = (ArObj.GetClientAgreement(0, &agt) > 0) ? agt.ExtObjectID : 0; SString ext_obj; // @v9.1.4 PPGetWord(PPWORD_EXTOBJECT, 0, ext_obj); PPLoadString("bill_object2", ext_obj); // @v9.1.4 setLabelText(CTL_CLIAGT_EXTOBJECT, ext_obj); SetupArCombo(this, CTLSEL_CLIAGT_EXTOBJECT, data.ExtObjectID, OLW_LOADDEFONOPEN|OLW_CANINSERT, acs_id, sacfDisableIfZeroSheet); AddClusterAssoc(CTL_CLIAGT_FLAGS, 0, AGTF_DONTCALCDEBTINBILL); AddClusterAssoc(CTL_CLIAGT_FLAGS, 1, AGTF_USEMARKEDGOODSONLY); AddClusterAssoc(CTL_CLIAGT_FLAGS, 2, AGTF_DONTUSEMINSHIPMQTTY); // @v8.4.4 SetClusterData(CTL_CLIAGT_FLAGS, data.Flags); // @v8.2.4 { if(data.MaxCredit != 0.0) { PPDebtorStatConfig ds_cfg; if(PPDebtorStatConfig::Read(&ds_cfg) > 0 && ds_cfg.LimitAddedTerm > 0 && ds_cfg.LimitTerm > 0) { added_limit_term = ds_cfg.LimitAddedTerm; added_limit_val = R0((data.MaxCredit / ds_cfg.LimitTerm) * added_limit_term); } } // } @v8.2.4 } else SetupPPObjCombo(this, CTLSEL_CLIAGT_EXTOBJECT, PPOBJ_ACCSHEET, data.ExtObjectID, 0, 0); // @v8.2.4 { if(added_limit_val != 0.0) { showCtrl(CTL_CLIAGT_ADDEDLIMITVAL, 1); SString fmt_buf, label_buf; getLabelText(CTL_CLIAGT_ADDEDLIMITVAL, fmt_buf); label_buf.Printf(fmt_buf, added_limit_term); setLabelText(CTL_CLIAGT_ADDEDLIMITVAL, label_buf); setCtrlReal(CTL_CLIAGT_ADDEDLIMITVAL, added_limit_val); } else { showCtrl(CTL_CLIAGT_ADDEDLIMITVAL, 0); } // } @v8.2.4 // @v7.1.5 { SetupStringCombo(this, CTLSEL_CLIAGT_RETLIMPRD, PPTXT_CYCLELIST, data.RetLimPrd); setCtrlReal(CTL_CLIAGT_RETLIM, fdiv100i(data.RetLimPart)); // } @v7.1.5 return 1; } int getDTS(PPClientAgreement * pAgt) { int ok = 1, sel = 0; getCtrlData(CTL_CLIAGT_CODE, data.Code); getCtrlData(sel = CTL_CLIAGT_DATE, &data.BegDt); THROW_SL(checkdate(data.BegDt, 1)); getCtrlData(sel = CTL_CLIAGT_EXPIRY, &data.Expiry); THROW_SL(checkdate(data.Expiry, 1)); getCtrlData(sel = CTL_CLIAGT_LOCKPRCBEFORE, &data.LockPrcBefore); THROW_SL(checkdate(data.LockPrcBefore, 1)); getCtrlData(sel = CTL_CLIAGT_MAXCREDIT, &data.MaxCredit); THROW_PP(data.MaxCredit >= 0L, PPERR_USERINPUT); getCtrlData(sel = CTL_CLIAGT_MAXDSCNT, &data.MaxDscnt); THROW_PP(data.MaxDscnt >= 0L && data.MaxDscnt <= 100, PPERR_USERINPUT); getCtrlData(sel = CTL_CLIAGT_DSCNT, &data.Dscnt); THROW_PP(data.Dscnt >= -100 && data.Dscnt <= 100 /*&&data.Dscnt <= data.MaxDscnt*/, PPERR_INVCLIAGTDIS); getCtrlData(CTL_CLIAGT_PAYPERIOD, &data.DefPayPeriod); getCtrlData(CTL_CLIAGT_PAYMDTBASE, &data.PaymDateBase); // @v8.4.2 getCtrlData(CTLSEL_CLIAGT_AGENT, &data.DefAgentID); getCtrlData(CTLSEL_CLIAGT_QUOTKIND, &data.DefQuotKindID); getCtrlData(CTLSEL_CLIAGT_EXTOBJECT, &data.ExtObjectID); GetClusterData(CTL_CLIAGT_FLAGS, &data.Flags); // @v7.1.5 { data.RetLimPrd = (int16)getCtrlLong(CTLSEL_CLIAGT_RETLIMPRD); if(data.RetLimPrd) { double retlim = getCtrlReal(CTL_CLIAGT_RETLIM); data.RetLimPart = (retlim > 0.0) ? (uint16)(retlim * 100.0) : 0; } else data.RetLimPart = 0; // } @v7.1.5 ASSIGN_PTR(pAgt, data); CATCH ok = PPErrorByDialog(this, sel, -1); ENDCATCH return ok; } private: DECL_HANDLE_EVENT { AgtDialog::handleEvent(event); if(event.isCmd(cmRounding)) editRoundingParam(); else if(event.isCmd(cmDebtLimList)) EditDebtLimList(data); else return; clearEvent(event); } int editRoundingParam() { class CliAgtRndDialog : public TDialog { public: CliAgtRndDialog() : TDialog(DLG_CLIAGTRND) { } int setDTS(const PPClientAgreement * pData) { int ok = 1; Data = *pData; AddClusterAssoc(CTL_CLIAGTRND_FLAGS, 0, AGTF_PRICEROUNDING); SetClusterData(CTL_CLIAGTRND_FLAGS, Data.Flags); setCtrlData(CTL_CLIAGTRND_PREC, &Data.PriceRoundPrec); // ! float AddClusterAssoc(CTL_CLIAGTRND_ROUND, 0, 0); AddClusterAssoc(CTL_CLIAGTRND_ROUND, -1, 0); AddClusterAssoc(CTL_CLIAGTRND_ROUND, 1, -1); AddClusterAssoc(CTL_CLIAGTRND_ROUND, 2, +1); SetClusterData(CTL_CLIAGTRND_ROUND, Data.PriceRoundDir); AddClusterAssoc(CTL_CLIAGTRND_ROUNDVAT, 0, AGTF_PRICEROUNDVAT); SetClusterData(CTL_CLIAGTRND_ROUNDVAT, Data.Flags); SetupCtrls(); return ok; } int getDTS(PPClientAgreement * pData) { int ok = 1; GetClusterData(CTL_CLIAGTRND_FLAGS, &Data.Flags); getCtrlData(CTL_CLIAGTRND_PREC, &Data.PriceRoundPrec); // ! float GetClusterData(CTL_CLIAGTRND_ROUND, &Data.PriceRoundDir); GetClusterData(CTL_CLIAGTRND_ROUNDVAT, &Data.Flags); ASSIGN_PTR(pData, Data); return ok; } private: DECL_HANDLE_EVENT { TDialog::handleEvent(event); if(event.isClusterClk(CTL_CLIAGTRND_FLAGS)) { GetClusterData(CTL_CLIAGTRND_FLAGS, &Data.Flags); SetupCtrls(); clearEvent(event); } } void SetupCtrls() { disableCtrls(!BIN(Data.Flags & AGTF_PRICEROUNDING), CTL_CLIAGTRND_PREC, CTL_CLIAGTRND_ROUND, CTL_CLIAGTRND_ROUNDVAT, 0); } PPClientAgreement Data; }; DIALOG_PROC_BODY(CliAgtRndDialog, &data); } PPObjArticle ArObj; PPClientAgreement data; }; DIALOG_PROC_BODY(CliAgtDialog, agt); } int SLAPI PPObjArticle::EditAgreement(PPID arID) { int ok = -1, r; ArticleTbl::Rec ar_rec; if(Search(arID, &ar_rec) > 0) { int agt_kind = -1; THROW(agt_kind = GetAgreementKind(&ar_rec)); if(agt_kind == 1) { PPClientAgreement cli_agt_rec; THROW(r = GetClientAgreement(ar_rec.ID, &cli_agt_rec)); cli_agt_rec.ClientID = ar_rec.ID; if(EditClientAgreement(&cli_agt_rec) > 0) { THROW(PutClientAgreement(ar_rec.ID, &cli_agt_rec, 1)); ok = 1; } } else if(agt_kind == 2) { PPSupplAgreement suppl_agt_rec; THROW(GetSupplAgreement(ar_rec.ID, &suppl_agt_rec, 0)); suppl_agt_rec.SupplID = ar_rec.ID; if(EditSupplAgreement(&suppl_agt_rec) > 0) { THROW(PutSupplAgreement(ar_rec.ID, &suppl_agt_rec, 1)); ok = 1; } } } CATCHZOKPPERR return ok; } // static int SLAPI PPObjArticle::DefaultClientAgreement() { int ok = 1; PPObjArticle arobj; PPClientAgreement agt; THROW(CheckCfgRights(PPCFGOBJ_CLIENTDEAL, PPR_MOD, 0)); THROW(arobj.CheckRights(ARTRT_CLIAGT)); THROW(arobj.GetClientAgreement(0, &agt)); if(arobj.EditClientAgreement(&agt) > 0) THROW(arobj.PutClientAgreement(0, &agt, 1)); CATCHZOKPPERR return ok; } // // // SLAPI PPSupplAgreement::ExchangeParam::ExchangeParam() { Clear(); } int FASTCALL PPSupplAgreement::ExchangeParam::Copy(const PPSupplAgreement::ExchangeParam & rS) { #define CPY_FLD(f) f=rS.f CPY_FLD(LastDt); CPY_FLD(GoodsGrpID); CPY_FLD(ExpendOp); CPY_FLD(RcptOp); CPY_FLD(SupplRetOp); CPY_FLD(RetOp); CPY_FLD(MovInOp); CPY_FLD(MovOutOp); CPY_FLD(PriceQuotID); CPY_FLD(ProtVer); CPY_FLD(ConnAddr); CPY_FLD(ExtString); CPY_FLD(Fb); #undef CPY_FLD DebtDimList = rS.DebtDimList; // @v9.1.3 return 1; } PPSupplAgreement::ExchangeParam & FASTCALL PPSupplAgreement::ExchangeParam::operator = (const ExchangeParam & rS) { Copy(rS); return *this; } // // Descr: Структура конфигурации обмена данными с поставщиком // Хранится в таблице Property с координатами {PPOBJ_ARTICLE, SupplID, ARTPRP_SUPPLAGT_EXCH} // Начиная с @v8.5.0 структура устарела - применяется только для обратной совместимости при чтении из базы данных. // struct PPSupplExchangeCfg { // @persistent @store(PropertyTbl) SLAPI PPSupplExchangeCfg() { Clear(); } PPSupplExchangeCfg & Clear() { THISZERO(); return *this; } int SLAPI IsEmpty() const { return ((!SupplID || !GGrpID || !IP) && isempty(PrvdrSymb)); // @vmiller @added --> isempty(PrvdrSymb) // ??? } PPID Tag; // const=PPOBJ_ARTICLE PPID SupplID; // ИД поставщика PPID PropID; // const=ATRPRP_SUPPLAGT_EXCH LDATE LastDt; // Дата последнего обмена PPID GGrpID; // Группа товаров PPID TechID; // Технология обмена char ClientCode[16]; // Код данного клиента на сервере поставщика PPID ExpendOp; // Вид операции отгрузки ulong IP; // int16 Port; // PPID RcptOp; // Операция прихода PPID SupplRetOp; // Операция возврата поставщику PPID RetOp; // Операция возврата от покупател PPID MovInOp; // Перемещение со склада (расход) PPID MovOutOp; // Перемещение на склад (приход) PPID PriceQuotID; // Котировка по которой будем назначать цену в документах uint16 Ver; // Версия протокола обмена char PrvdrSymb[12]; // Символ провайдера EDI //char Reserve[12]; // @reserve }; PPSupplAgreement::ExchangeParam & FASTCALL PPSupplAgreement::ExchangeParam::operator = (const PPSupplExchangeCfg & rS) { Clear(); LastDt = rS.LastDt; GoodsGrpID = rS.GGrpID; ExpendOp = rS.ExpendOp; RcptOp = rS.RcptOp; SupplRetOp = rS.SupplRetOp; RetOp = rS.RetOp; MovInOp = rS.MovInOp; MovOutOp = rS.MovOutOp; PriceQuotID = rS.PriceQuotID; ProtVer = rS.Ver; { SString temp_buf; PutExtStrData(extssEDIPrvdrSymb, (temp_buf = rS.PrvdrSymb).Strip()); PutExtStrData(extssClientCode, (temp_buf = rS.ClientCode).Strip()); } ConnAddr.Set(rS.IP, rS.Port); return *this; } PPSupplAgreement::ExchangeParam & PPSupplAgreement::ExchangeParam::Clear() { LastDt = ZERODATE; GoodsGrpID = 0; ExpendOp = 0; RcptOp = 0; SupplRetOp = 0; RetOp = 0; MovInOp = 0; MovOutOp = 0; PriceQuotID = 0; ProtVer = 0; ConnAddr.Clear(); ExtString = 0; MEMSZERO(Fb); DebtDimList.Set(0); // @v9.1.3 return *this; } int FASTCALL PPSupplAgreement::ExchangeParam::IsEqual(const ExchangeParam & rS) const { #define CMP_FLD(f) if((f) != (rS.f)) return 0 CMP_FLD(LastDt); CMP_FLD(GoodsGrpID); CMP_FLD(ExpendOp); CMP_FLD(RcptOp); CMP_FLD(SupplRetOp); CMP_FLD(RetOp); CMP_FLD(MovInOp); CMP_FLD(MovOutOp); CMP_FLD(PriceQuotID); CMP_FLD(ProtVer); CMP_FLD(ConnAddr); CMP_FLD(ExtString); CMP_FLD(Fb.DefUnitID); // @v9.2.4 CMP_FLD(Fb.CliCodeTagID); // @v9.4.4 CMP_FLD(Fb.LocCodeTagID); // @v9.4.4 CMP_FLD(Fb.SequenceID); // @v9.4.2 CMP_FLD(Fb.StyloPalmID); // @v9.5.5 #undef CMP_FLD if(!DebtDimList.IsEqual(rS.DebtDimList)) return 0; // @v9.1.3 return 1; } int SLAPI PPSupplAgreement::ExchangeParam::Serialize_Before_v9103_(int dir, SBuffer & rBuf, SSerializeContext * pSCtx) { int ok = 1; THROW_SL(pSCtx->Serialize(dir, LastDt, rBuf)); THROW_SL(pSCtx->Serialize(dir, GoodsGrpID, rBuf)); THROW_SL(pSCtx->Serialize(dir, ExpendOp, rBuf)); THROW_SL(pSCtx->Serialize(dir, RcptOp, rBuf)); THROW_SL(pSCtx->Serialize(dir, SupplRetOp, rBuf)); THROW_SL(pSCtx->Serialize(dir, RetOp, rBuf)); THROW_SL(pSCtx->Serialize(dir, MovInOp, rBuf)); THROW_SL(pSCtx->Serialize(dir, MovOutOp, rBuf)); THROW_SL(pSCtx->Serialize(dir, PriceQuotID, rBuf)); THROW_SL(pSCtx->Serialize(dir, ProtVer, rBuf)); THROW_SL(pSCtx->SerializeBlock(dir, sizeof(Fb), &Fb, rBuf, 0)); THROW_SL(ConnAddr.Serialize(dir, rBuf, pSCtx)); THROW_SL(pSCtx->Serialize(dir, ExtString, rBuf)); CATCHZOK return ok; } int SLAPI PPSupplAgreement::ExchangeParam::Serialize_(int dir, SBuffer & rBuf, SSerializeContext * pSCtx) { int ok = 1; THROW_SL(pSCtx->Serialize(dir, LastDt, rBuf)); THROW_SL(pSCtx->Serialize(dir, GoodsGrpID, rBuf)); THROW_SL(pSCtx->Serialize(dir, ExpendOp, rBuf)); THROW_SL(pSCtx->Serialize(dir, RcptOp, rBuf)); THROW_SL(pSCtx->Serialize(dir, SupplRetOp, rBuf)); THROW_SL(pSCtx->Serialize(dir, RetOp, rBuf)); THROW_SL(pSCtx->Serialize(dir, MovInOp, rBuf)); THROW_SL(pSCtx->Serialize(dir, MovOutOp, rBuf)); THROW_SL(pSCtx->Serialize(dir, PriceQuotID, rBuf)); THROW_SL(pSCtx->Serialize(dir, ProtVer, rBuf)); THROW_SL(pSCtx->SerializeBlock(dir, sizeof(Fb), &Fb, rBuf, 0)); THROW_SL(ConnAddr.Serialize(dir, rBuf, pSCtx)); THROW_SL(pSCtx->Serialize(dir, ExtString, rBuf)); THROW_SL(DebtDimList.Serialize(dir, rBuf, pSCtx)); // @v9.1.3 CATCHZOK return ok; } int SLAPI PPSupplAgreement::ExchangeParam::IsEmpty() const { if(GoodsGrpID || !ConnAddr.IsEmpty()) return 0; else { SString temp_buf; if(GetExtStrData(extssClientCode, temp_buf) > 0 && temp_buf.NotEmptyS()) return 0; else if(GetExtStrData(extssEDIPrvdrSymb, temp_buf) > 0 && temp_buf.NotEmptyS()) return 0; else if(DebtDimList.GetCount()) // @v9.1.3 return 0; else return 1; } } int SLAPI PPSupplAgreement::ExchangeParam::GetExtStrData(int fldID, SString & rBuf) const { return PPGetExtStrData(fldID, ExtString, rBuf); } int SLAPI PPSupplAgreement::ExchangeParam::PutExtStrData(int fldID, const char * pStr) { return PPPutExtStrData(fldID, ExtString, pStr); } SLAPI PPSupplAgreement::OrderParamEntry::OrderParamEntry() { THISZERO(); } int FASTCALL PPSupplAgreement::OrderParamEntry::IsEqual(const OrderParamEntry & rS) const { #define CMP_FLD(f) if((f) != (rS.f)) return 0 CMP_FLD(GoodsGrpID); CMP_FLD(LocID); CMP_FLD(MngrID); CMP_FLD(OrdPrdDays); CMP_FLD(Fb.DuePrdDays); // @v8.5.2 CMP_FLD(Dr); #undef CMP_FLD return 1; } int SLAPI PPSupplAgreement::OrderParamEntry::Serialize(int dir, SBuffer & rBuf, SSerializeContext * pSCtx) { int ok = 1; THROW_SL(pSCtx->Serialize(dir, GoodsGrpID, rBuf)); THROW_SL(pSCtx->Serialize(dir, LocID, rBuf)); THROW_SL(pSCtx->Serialize(dir, MngrID, rBuf)); THROW_SL(pSCtx->Serialize(dir, OrdPrdDays, rBuf)); THROW_SL(Dr.Serialize(dir, rBuf, pSCtx)); THROW_SL(pSCtx->SerializeBlock(dir, sizeof(Fb), &Fb, rBuf, 0)); CATCHZOK return ok; } SLAPI PPSupplAgreement::PPSupplAgreement() { Clear(); } int FASTCALL PPSupplAgreement::IsEqual(const PPSupplAgreement & rS) const { #define CMP_FLD(f) if((f) != (rS.f)) return 0 // Ver не сравниваем - не значащее поле CMP_FLD(SupplID); CMP_FLD(Flags); CMP_FLD(BegDt); CMP_FLD(Expiry); CMP_FLD(DefPayPeriod); CMP_FLD(InvPriceAction); CMP_FLD(DefDlvrTerm); CMP_FLD(PctRet); // @v8.5.2 CMP_FLD(OrdPrdDays); CMP_FLD(DefAgentID); CMP_FLD(CostQuotKindID); CMP_FLD(PurchaseOpID); CMP_FLD(DevUpQuotKindID); CMP_FLD(DevDnQuotKindID); CMP_FLD(MngrRelID); CMP_FLD(Dr); #undef CMP_FLD if(!Ep.IsEqual(rS.Ep)) return 0; { const uint _c1 = OrderParamList.getCount(); const uint _c2 = rS.OrderParamList.getCount(); if(_c1 != _c2) return 0; else if(_c1) { for(uint i = 0; i < _c1; i++) { const OrderParamEntry & r_e1 = OrderParamList.at(i); const OrderParamEntry & r_e2 = rS.OrderParamList.at(i); if(!r_e1.IsEqual(r_e2)) return 0; } } } return 1; } PPSupplAgreement & PPSupplAgreement::Clear() { memzero(this, offsetof(PPSupplAgreement, Ep)); Ep.Clear(); OrderParamList.clear(); return *this; } int SLAPI PPSupplAgreement::IsEmpty() const { if(Flags || BegDt || Expiry || DefPayPeriod || DefAgentID || DefDlvrTerm || PctRet) return 0; else if(!Ep.IsEmpty()) return 0; else if(OrderParamList.getCount()) return 0; else return 1; } int FASTCALL PPSupplAgreement::RestoreAutoOrderParams(const PPSupplAgreement & rS) { SETFLAGBYSAMPLE(Flags, AGTF_AUTOORDER, rS.Flags); // @v8.5.2 OrdPrdDays = rS.OrdPrdDays; DefDlvrTerm = rS.DefDlvrTerm; Dr = rS.Dr; OrderParamList = rS.OrderParamList; return 1; } int SLAPI PPSupplAgreement::SearchOrderParamEntry(const OrderParamEntry & rKey, int thisPos, uint * pFoundPos) const { for(uint i = 0; i < OrderParamList.getCount(); i++) { if((int)i != thisPos) { const OrderParamEntry & r_entry = OrderParamList.at(i); if(r_entry.GoodsGrpID == rKey.GoodsGrpID && r_entry.LocID == rKey.LocID && r_entry.MngrID == rKey.MngrID) { ASSIGN_PTR(pFoundPos, i); return 1; } } } return 0; } int SLAPI PPSupplAgreement::SetOrderParamEntry(int pos, OrderParamEntry & rEntry, uint * pResultPos) { int ok = 1; const uint _c = OrderParamList.getCount(); THROW_PP(SearchOrderParamEntry(rEntry, pos, 0) == 0, PPERR_DUPSORDPE); THROW_PP(DateRepeating::IsValidPrd(rEntry.Dr.Prd), PPERR_INVDATEREP); if(pos < 0 || pos >= (int)_c) { THROW_SL(OrderParamList.insert(&rEntry)); ASSIGN_PTR(pResultPos, _c); } else { OrderParamList.at(pos) = rEntry; ASSIGN_PTR(pResultPos, (uint)pos); } CATCHZOK return ok; } int SLAPI PPSupplAgreement::Serialize(int dir, SBuffer & rBuf, SSerializeContext * pSCtx) { int ok = 1; if(dir > 0) { Ver = DS.GetVersion(); } THROW_SL(Ver.Serialize(dir, rBuf, pSCtx)); THROW_SL(pSCtx->Serialize(dir, SupplID, rBuf)); THROW_SL(pSCtx->Serialize(dir, Flags, rBuf)); THROW_SL(pSCtx->Serialize(dir, BegDt, rBuf)); THROW_SL(pSCtx->Serialize(dir, Expiry, rBuf)); THROW_SL(pSCtx->Serialize(dir, DefPayPeriod, rBuf)); THROW_SL(pSCtx->Serialize(dir, InvPriceAction, rBuf)); THROW_SL(pSCtx->Serialize(dir, DefDlvrTerm, rBuf)); THROW_SL(pSCtx->Serialize(dir, PctRet, rBuf)); // @v8.5.2 THROW_SL(pSCtx->Serialize(dir, OrdPrdDays, rBuf)); THROW_SL(pSCtx->Serialize(dir, Reserve_opd, rBuf)); // @v8.5.2 THROW_SL(pSCtx->Serialize(dir, DefAgentID, rBuf)); THROW_SL(pSCtx->Serialize(dir, CostQuotKindID, rBuf)); THROW_SL(pSCtx->Serialize(dir, PurchaseOpID, rBuf)); THROW_SL(pSCtx->Serialize(dir, DevUpQuotKindID, rBuf)); THROW_SL(pSCtx->Serialize(dir, DevDnQuotKindID, rBuf)); THROW_SL(pSCtx->Serialize(dir, MngrRelID, rBuf)); THROW_SL(Dr.Serialize(dir, rBuf, pSCtx)); THROW_SL(pSCtx->SerializeBlock(dir, sizeof(Fb), &Fb, rBuf, 0)); if(dir < 0 && Ver.IsLt(9, 1, 3)) { THROW(Ep.Serialize_Before_v9103_(dir, rBuf, pSCtx)); } else { THROW(Ep.Serialize_(dir, rBuf, pSCtx)); } THROW_SL(TSArray_Serialize(OrderParamList, dir, rBuf, pSCtx)); CATCHZOK return ok; } struct _PPSupplAgt { // @persistent @store(PropertyTbl) long Tag; // Const=PPOBJ_ARTICLE long ArtID; // ->Article.ID long PropID; // Const=ARTPRP_SUPPLAGT long Flags; // LDATE BegDt; // Дата начала действия соглашения // LDATE Expiry; // Дата окончания действия соглашения // int16 OrdPrdDays; // Период для расчета заказа поставщику при автоматическом формировании документов заказа поставщику (в днях) int16 OrdDrPrd; // Календарь для автоматического создания документов int16 OrdDrKind; // заказа поставщику int16 Reserve1; // @reserve double Reserve2; // @reserve double Reserve3; // @reserve short DefPayPeriod; // Количество дней от отгрузки до оплаты по умолчанию PPID DefAgentID; // Агент, закрепленный за поставщиком PPID CostQuotKindID; // Вид котировки, управляющей контрактными ценами поставщиков short DefDlvrTerm; // Срок доставки товара в днях, начиная с даты документа закупки short PctRet; // Максимальный объем возврата товара по накладной в процентах от суммы накладной PPID PurchaseOpID; // Вид операции закупки (драфт-приход) PPID DevUpQuotKindID; // Вид котировки, ограничивающий верхнюю границу отклонения фактических цен от контрактных PPID DevDnQuotKindID; // Вид котировки, ограничивающий нижнюю границу отклонения фактических цен от контрактных PPID MngrRelID; // Тип отношения, определяющий привязку поставщиков к менеджерам int16 InvPriceAction; // Действие при неправильной контрактной цене long OrdDrDtl; }; // static int SLAPI PPObjArticle::PropToSupplAgt(const PropertyTbl::Rec * pPropRec, PPSupplAgreement * pAgt) { const _PPSupplAgt * p_agt = (const _PPSupplAgt *)pPropRec; pAgt->SupplID = p_agt->ArtID; pAgt->Flags = (p_agt->Flags | AGTF_LOADED); pAgt->BegDt = p_agt->BegDt; pAgt->Expiry = p_agt->Expiry; pAgt->DefPayPeriod = p_agt->DefPayPeriod; pAgt->DefAgentID = p_agt->DefAgentID; pAgt->CostQuotKindID = p_agt->CostQuotKindID; pAgt->DefDlvrTerm = p_agt->DefDlvrTerm; pAgt->PctRet = p_agt->PctRet; pAgt->PurchaseOpID = p_agt->PurchaseOpID; pAgt->DevUpQuotKindID = p_agt->DevUpQuotKindID; pAgt->DevDnQuotKindID = p_agt->DevDnQuotKindID; pAgt->MngrRelID = p_agt->MngrRelID; pAgt->InvPriceAction = p_agt->InvPriceAction; // @v8.5.2 pAgt->OrdPrdDays = p_agt->OrdPrdDays; pAgt->Dr.Init(p_agt->OrdDrPrd, p_agt->OrdDrKind); pAgt->Dr.LongToDtl(p_agt->OrdDrDtl); return 1; } // static int SLAPI PPObjArticle::HasSupplAgreement(PPID id) { int yes = 0; if(id > 0) { SBuffer _buf; PropertyTbl::Rec prop_rec; Reference * p_ref = PPRef; if(p_ref->GetPropSBuffer(PPOBJ_ARTICLE, id, ARTPRP_SUPPLAGT2, _buf) > 0) yes = 1; else if(p_ref->GetProp(PPOBJ_ARTICLE, id, ARTPRP_SUPPLAGT, &prop_rec, sizeof(prop_rec)) > 0) yes = 1; } return yes; } // static int SLAPI PPObjArticle::GetSupplAgreement(PPID id, PPSupplAgreement * pAgt, int useInheritance) { int ok = -1; if(pAgt) { pAgt->Clear(); int r = 0; SBuffer _buf; Reference * p_ref = PPRef; THROW(r = p_ref->GetPropSBuffer(PPOBJ_ARTICLE, id, ARTPRP_SUPPLAGT2, _buf)); if(r > 0) { SSerializeContext ctx; THROW(pAgt->Serialize(-1, _buf, &ctx)); pAgt->Flags |= AGTF_LOADED; ok = 1; } else { PropertyTbl::Rec prop_rec; THROW(r = p_ref->GetProp(PPOBJ_ARTICLE, id, ARTPRP_SUPPLAGT, &prop_rec, sizeof(prop_rec))); if(r > 0) { PPSupplExchangeCfg _ex_cfg; THROW(p_ref->GetProp(PPOBJ_ARTICLE, id, ARTPRP_SUPPLAGT_EXCH, &_ex_cfg, sizeof(_ex_cfg))); pAgt->Ep = _ex_cfg; PropToSupplAgt(&prop_rec, pAgt); pAgt->SupplID = id; ok = 1; } else { // @v8.2.2 { if(id && useInheritance) { PPObjPersonRelType rt_obj; PPPersonRelTypePacket rt_pack; PPIDArray rel_list; if(rt_obj.Fetch(PPPSNRELTYP_AFFIL, &rt_pack) > 0 && (rt_pack.Rec.Flags & PPPersonRelType::fInhAgreements)) { PPObjArticle ar_obj; if(ar_obj.GetRelPersonList(id, PPPSNRELTYP_AFFIL, 0, &rel_list) > 0) { for(uint i = 0; r < 0 && i < rel_list.getCount(); i++) { PPID rel_ar_id = ObjectToPerson(rel_list.get(i), 0); // @v8.5.0 { if(GetSupplAgreement(rel_ar_id, pAgt, 0) > 0) { // @recursion не зависимо от версии хранения результат будет верным pAgt->SupplID = id; ok = 2; } // } @v8.5.0 /* @v8.5.0 THROW(r = p_ref->GetProp(PPOBJ_ARTICLE, rel_ar_id, ARTPRP_SUPPLAGT, &prop_rec, sizeof(prop_rec))); if(r > 0) { THROW(p_ref->GetProp(PPOBJ_ARTICLE, rel_ar_id, ARTPRP_SUPPLAGT_EXCH, &pAgt->ExchCfg, sizeof(pAgt->ExchCfg))); PropToSupplAgt(&prop_rec, pAgt); pAgt->SupplID = id; ok = 2; } */ } } } } // } @v8.2.2 if(r < 0) pAgt->Flags |= AGTF_LOADED; } } } CATCHZOK return ok; } int SLAPI PPObjArticle::PutSupplAgreement(PPID id, PPSupplAgreement * pAgt, int use_ta) { int ok = 1; Reference * p_ref = PPRef; THROW(CheckRights(ARTRT_CLIAGT)); #if 1 { SBuffer _buf; if(pAgt) { SSerializeContext ctx; THROW(pAgt->Serialize(+1, _buf, &ctx)); } { PPTransaction tra(use_ta); THROW(tra); THROW(p_ref->PutPropSBuffer(PPOBJ_ARTICLE, id, ARTPRP_SUPPLAGT2, _buf, 0)); THROW(p_ref->PutProp(PPOBJ_ARTICLE, id, ARTPRP_SUPPLAGT, 0, 0, 0)); THROW(p_ref->PutProp(PPOBJ_ARTICLE, id, ARTPRP_SUPPLAGT_EXCH, 0, 0, 0)); THROW(tra.Commit()); } } #else // }{ { _PPSupplAgt _agt; if(pAgt) { MEMSZERO(_agt); _agt.Tag = PPOBJ_ARTICLE; _agt.ArtID = id; _agt.PropID = ARTPRP_SUPPLAGT; _agt.Flags = (pAgt->Flags & ~AGTF_LOADED); _agt.BegDt = pAgt->BegDt; _agt.Expiry = pAgt->Expiry; _agt.DefPayPeriod = pAgt->DefPayPeriod; _agt.DefAgentID = pAgt->DefAgentID; _agt.CostQuotKindID = pAgt->CostQuotKindID; _agt.DefDlvrTerm = pAgt->DefDlvrTerm; _agt.PctRet = pAgt->PctRet; _agt.PurchaseOpID = pAgt->PurchaseOpID; _agt.DevUpQuotKindID = pAgt->DevUpQuotKindID; _agt.DevDnQuotKindID = pAgt->DevDnQuotKindID; _agt.MngrRelID = pAgt->MngrRelID; _agt.InvPriceAction = pAgt->InvPriceAction; _agt.OrdDrPrd = pAgt->Dr.Prd; _agt.OrdDrKind = pAgt->Dr.RepeatKind; _agt.OrdDrDtl = pAgt->Dr.DtlToLong(); _agt.OrdPrdDays = pAgt->OrdPrdDays; } THROW(p_ref->PutProp(PPOBJ_ARTICLE, id, ARTPRP_SUPPLAGT, (pAgt ? &_agt : 0), 0, use_ta)); THROW(p_ref->PutProp(PPOBJ_ARTICLE, id, ARTPRP_SUPPLAGT_EXCH, (pAgt && !pAgt->ExchCfg.IsEmpty()) ? &pAgt->ExchCfg : 0, 0, use_ta)); } #endif // } CATCHZOK return ok; } // // // static int EditOrderCalendar(DateRepeating * pData) { int ok = -1; RepeatingDialog * dlg = new RepeatingDialog; if(CheckDialogPtr(&dlg, 1)) { dlg->setDTS(pData); while(ok <= 0 && ExecView(dlg) == cmOK) { if(dlg->getDTS(pData)) { ok = 1; } else PPError(); } } else ok = 0; delete dlg; return ok; } class SupplAgtDialog : public PPListDialog { public: SupplAgtDialog(PPID supplID) : PPListDialog(supplID ? DLG_SUPPLAGT : DLG_DEFSUPPLAGT, CTL_SUPPLAGT_ORDPL) //AgtDialog(supplID ? DLG_SUPPLAGT : DLG_DEFSUPPLAGT) { ArID = supplID; SetupCalDate(CTLCAL_SUPPLAGT_DATE, CTL_SUPPLAGT_DATE); SetupCalDate(CTLCAL_SUPPLAGT_EXPIRY, CTL_SUPPLAGT_EXPIRY); enableCommand(cmOK, ArObj.CheckRights(ARTRT_CLIAGT)); enableCommand(cmExchangeCfg, ArID != 0); updateList(-1); } int setDTS(const PPSupplAgreement*); int getDTS(PPSupplAgreement*); private: DECL_HANDLE_EVENT { PPListDialog::handleEvent(event); if(event.isCmd(cmBills)) { if(ArID) { BillFilt flt; flt.ObjectID = ArID; flt.Flags |= BillFilt::fShowDebt; ViewGoodsBills(&flt, 1); } } else if(event.isCmd(cmExchangeCfg)) { EditExchangeCfg(); } else if(event.isCmd(cmOrdCalendar)) { EditOrderCalendar(&Data.Dr); } else if(event.isClusterClk(CTL_SUPPLAGT_FLAGS)) { setupCtrls(GetClusterData(CTL_SUPPLAGT_FLAGS)); } else return; clearEvent(event); } virtual int setupList() { int ok = 1; SString sub; StringSet ss(SLBColumnDelim); for(uint i = 0; i < Data.OrderParamList.getCount(); i++) { const PPSupplAgreement::OrderParamEntry & r_entry = Data.OrderParamList.at(i); ss.clear(1); sub = 0; if(r_entry.GoodsGrpID) GetGoodsName(r_entry.GoodsGrpID, sub); ss.add(sub); sub = 0; if(r_entry.LocID) GetLocationName(r_entry.LocID, sub); ss.add(sub); /* sub = 0; if(r_entry.MngrID) GetPersonName(r_entry.MngrID, sub); ss.add(sub); */ ss.add((sub = 0).Cat(r_entry.OrdPrdDays)); ss.add((sub = 0).Cat(r_entry.Fb.DuePrdDays)); ss.add(r_entry.Dr.Format(0, sub = 0)); THROW(addStringToList(i+1, ss.getBuf())); } CATCHZOK return ok; } virtual int addItem(long * pPos, long * pID) { int ok = -1; PPSupplAgreement::OrderParamEntry entry; while(ok < 0 && EditOrdParamEntry(ArID, &entry, -1) > 0) { uint pos = 0; if(!Data.SetOrderParamEntry(-1, entry, &pos)) PPError(); else { ASSIGN_PTR(pPos, pos); ASSIGN_PTR(pID, pos+1); ok = 1; } } return ok; } virtual int editItem(long pos, long id) { int ok = -1; if(pos >= 0 && pos < (long)Data.OrderParamList.getCount()) { PPSupplAgreement::OrderParamEntry & r_entry = Data.OrderParamList.at(pos); while(ok < 0 && EditOrdParamEntry(ArID, &r_entry, pos) > 0) { if(!Data.SetOrderParamEntry(pos, r_entry, 0)) PPError(); else { ok = 1; } } } return ok; } virtual int delItem(long pos, long id) { int ok = -1; if(pos >= 0 && pos < (long)Data.OrderParamList.getCount()) { Data.OrderParamList.atFree(pos); ok = 1; } return ok; } int EditExchangeCfg(); int EditOrdCalendar(); int setupCtrls(long flags); int EditOrdParamEntry(PPID arID, PPSupplAgreement::OrderParamEntry * pEntry, int pos); PPID ArID; PPSupplAgreement Data; PPObjArticle ArObj; }; int SupplAgtDialog::EditOrdParamEntry(PPID arID, PPSupplAgreement::OrderParamEntry * pEntry, int pos) { class SOrdParamEntryDialog : public TDialog { public: SOrdParamEntryDialog(PPID arID) : TDialog(DLG_SORDPE) { ArID = arID; } int setDTS(PPSupplAgreement::OrderParamEntry * pData) { RVALUEPTR(Data, pData); if(ArID) { SString temp_buf; GetArticleName(ArID, temp_buf); setCtrlString(CTL_SORDPE_SUPPL, temp_buf); } selectCtrl(CTL_SORDPE_GOODSGRP); SetupPPObjCombo(this, CTLSEL_SORDPE_GOODSGRP, PPOBJ_GOODSGROUP, Data.GoodsGrpID, 0, 0); SetupPersonCombo(this, CTLSEL_SORDPE_MNGR, Data.MngrID, 0, 0, 0); SetupLocationCombo(this, CTLSEL_SORDPE_LOC, Data.LocID, 0, LOCTYP_WAREHOUSE, 0); setCtrlData(CTL_SORDPE_ORDPRD, &Data.OrdPrdDays); setCtrlData(CTL_SORDPE_DUEPRD, &Data.Fb.DuePrdDays); return 1; } int getDTS(PPSupplAgreement::OrderParamEntry * pData) { int ok = 1; getCtrlData(CTLSEL_SORDPE_GOODSGRP, &Data.GoodsGrpID); getCtrlData(CTLSEL_SORDPE_MNGR, &Data.MngrID); getCtrlData(CTLSEL_SORDPE_LOC, &Data.LocID); getCtrlData(CTL_SORDPE_ORDPRD, &Data.OrdPrdDays); getCtrlData(CTL_SORDPE_DUEPRD, &Data.Fb.DuePrdDays); ASSIGN_PTR(pData, Data); return ok; } private: DECL_HANDLE_EVENT { TDialog::handleEvent(event); if(event.isCmd(cmOrdCalendar)) EditOrderCalendar(&Data.Dr); else return; clearEvent(event); } PPSupplAgreement::OrderParamEntry Data; PPID ArID; }; DIALOG_PROC_BODY_P1(SOrdParamEntryDialog, arID, pEntry); } int SupplAgtDialog::setupCtrls(long flags) { int to_disable = BIN(!(flags & AGTF_AUTOORDER)); disableCtrl(CTL_SUPPLAGT_ORDPRD, to_disable); enableCommand(cmOrdCalendar, !to_disable); if(to_disable) { setCtrlLong(CTL_SUPPLAGT_ORDPRD, 0L); Data.Dr.Init(0, 0); } else if(!DateRepeating::IsValidPrd(Data.Dr.Prd)) { // @v8.3.12 if(!DateRepeating::IsValidPrd(Data.OrdDrPrd)) Data.Dr.Init(PRD_DAY); } return 1; } static int EditSupplExchOpList(PPSupplAgreement::ExchangeParam * pData) { class SupplExpOpListDialog : public PPListDialog { private: ObjTagFilt PsnTagFlt; ObjTagFilt LocTagFlt; public: SupplExpOpListDialog() : PPListDialog(DLG_SUPPLEOPS, CTL_SUPPLEOPS_DBTDIM), PsnTagFlt(PPOBJ_PERSON), LocTagFlt(PPOBJ_LOCATION) { } int setDTS(const PPSupplAgreement::ExchangeParam * pData) { PPOprKind op_kind; PPIDArray op_list; if(!RVALUEPTR(Data, pData)) Data.Clear(); // Расход товара { MEMSZERO(op_kind); for(PPID op_id = 0; EnumOperations(0, &op_id, &op_kind) > 0;) if(oneof2(op_kind.OpTypeID, PPOPT_GOODSEXPEND, PPOPT_GENERIC)) op_list.add(op_id); SetupOprKindCombo(this, CTLSEL_SUPPLEOPS_EXP, Data.ExpendOp, 0, &op_list, OPKLF_OPLIST); } // Приход товара { op_list.freeAll(); MEMSZERO(op_kind); for(PPID op_id = 0; EnumOperations(0, &op_id, &op_kind) > 0;) if(oneof2(op_kind.OpTypeID, PPOPT_GOODSRECEIPT, PPOPT_GENERIC)) op_list.add(op_id); SetupOprKindCombo(this, CTLSEL_SUPPLEOPS_RCPT, Data.RcptOp, 0, &op_list, OPKLF_OPLIST); } // Возврат товара от покупател { op_list.freeAll(); MEMSZERO(op_kind); for(PPID op_id = 0; EnumOperations(0, &op_id, &op_kind) > 0;) if(oneof2(op_kind.OpTypeID, PPOPT_GOODSRETURN, PPOPT_GENERIC)) op_list.add(op_id); SetupOprKindCombo(this, CTLSEL_SUPPLEOPS_RET, Data.RetOp, 0, &op_list, OPKLF_OPLIST); SetupOprKindCombo(this, CTLSEL_SUPPLEOPS_SUPRET, Data.SupplRetOp, 0, &op_list, OPKLF_OPLIST); } // Межскладской расход товара, возврат товара поставщику { op_list.freeAll(); MEMSZERO(op_kind); for(PPID op_id = 0; EnumOperations(0, &op_id, &op_kind) > 0;) if(op_kind.OpTypeID == PPOPT_GOODSEXPEND) op_list.add(op_id); SetupOprKindCombo(this, CTLSEL_SUPPLEOPS_MOVOUT, Data.MovOutOp, 0, &op_list, OPKLF_OPLIST); } // Межсладской приход товара { op_list.freeAll(); MEMSZERO(op_kind); for(PPID op_id = 0; EnumOperations(0, &op_id, &op_kind) > 0;) if(op_kind.OpTypeID == PPOPT_GOODSRECEIPT) op_list.add(op_id); SetupOprKindCombo(this, CTLSEL_SUPPLEOPS_MOVIN, Data.MovInOp, 0, &op_list, OPKLF_OPLIST); } SetupPPObjCombo(this, CTLSEL_SUPPLEOPS_UNIT, PPOBJ_UNIT, Data.Fb.DefUnitID, OLW_CANINSERT, 0); // @v9.2.4 SetupPPObjCombo(this, CTLSEL_SUPPLEOPS_CLICTAG, PPOBJ_TAG, Data.Fb.CliCodeTagID, OLW_CANINSERT, &PsnTagFlt); // @v9.4.4 SetupPPObjCombo(this, CTLSEL_SUPPLEOPS_LOCCTAG, PPOBJ_TAG, Data.Fb.LocCodeTagID, OLW_CANINSERT, &LocTagFlt); // @v9.4.4 updateList(-1); return 1; } int getDTS(PPSupplAgreement::ExchangeParam * pData) { int ok = 1; uint sel = 0; getCtrlData(sel = CTLSEL_SUPPLEOPS_EXP, &Data.ExpendOp); // @v9.1.3 THROW_PP(Data.ExpendOp, PPERR_INVEXPENDOP); getCtrlData(CTLSEL_SUPPLEOPS_RCPT, &Data.RcptOp); getCtrlData(CTLSEL_SUPPLEOPS_SUPRET, &Data.SupplRetOp); getCtrlData(CTLSEL_SUPPLEOPS_RET, &Data.RetOp); getCtrlData(CTLSEL_SUPPLEOPS_MOVOUT, &Data.MovOutOp); getCtrlData(CTLSEL_SUPPLEOPS_MOVIN, &Data.MovInOp); getCtrlData(CTLSEL_SUPPLEOPS_UNIT, &Data.Fb.DefUnitID); // @v9.2.4 getCtrlData(CTLSEL_SUPPLEOPS_CLICTAG, &Data.Fb.CliCodeTagID); // @v9.4.4 getCtrlData(CTLSEL_SUPPLEOPS_LOCCTAG, &Data.Fb.LocCodeTagID); // @v9.4.4 ASSIGN_PTR(pData, Data); /* @v9.1.3 CATCH selectCtrl(sel); ok = 0; ENDCATCH */ return ok; } private: virtual int setupList() { int ok = 1; PPDebtDim dd_rec; for(uint i = 0; i < Data.DebtDimList.GetCount(); i++) { const PPID dd_id = Data.DebtDimList.Get(i); if(dd_id && DdObj.Search(dd_id, &dd_rec) > 0) { THROW(addStringToList(dd_id, dd_rec.Name)); } } CATCHZOK return ok; } virtual int addItem(long * pPos, long * pID) { int ok = -1; PPDebtDim dd_rec; PPID sel_id = PPObjDebtDim::Select(); if(sel_id > 0 && DdObj.Search(sel_id, &dd_rec) > 0) { if(Data.DebtDimList.Search(sel_id, 0, 0)) { PPError(PPERR_DUPDEBTDIMINLIST, dd_rec.Name); } else { if(Data.DebtDimList.Add(sel_id)) { ASSIGN_PTR(pPos, Data.DebtDimList.GetCount() - 1); ASSIGN_PTR(pID, sel_id); ok = 1; } } } return ok; } virtual int delItem(long pos, long id) { return id ? Data.DebtDimList.Remove(id, 0) : -1; } PPSupplAgreement::ExchangeParam Data; PPObjDebtDim DdObj; }; DIALOG_PROC_BODYERR(SupplExpOpListDialog, pData); } int SupplAgtDialog::EditExchangeCfg() { class SupplExchangeCfgDialog : public TDialog { public: SupplExchangeCfgDialog() : TDialog(DLG_SUPLEXCHCFG) { SetupCalDate(CTLCAL_SUPLEXCHCFG_LASTDT, CTL_SUPLEXCHCFG_LASTDT); } int setDTS(const PPSupplAgreement::ExchangeParam * pData) { SString temp_buf; PPOprKind op_kind; PPIDArray op_list; if(!RVALUEPTR(Data, pData)) Data.Clear(); SetupPPObjCombo(this, CTLSEL_SUPLEXCHCFG_GGRP, PPOBJ_GOODSGROUP, Data.GoodsGrpID, OLW_CANSELUPLEVEL, 0); SetupPPObjCombo(this, CTLSEL_SUPLEXCHCFG_STYLO, PPOBJ_STYLOPALM, Data.Fb.StyloPalmID, OLW_CANSELUPLEVEL, 0); // @v9.5.5 MEMSZERO(op_kind); for(PPID op_id = 0; EnumOperations(0, &op_id, &op_kind) > 0;) if(oneof2(op_kind.OpTypeID, PPOPT_GOODSEXPEND, PPOPT_GENERIC)) op_list.add(op_id); // SetupOprKindCombo(this, CTLSEL_SUPLEXCHCFG_OP, Data.OpID, 0, &op_list, OPKLF_OPLIST); // SetupPPObjCombo(p_dlg, CTLSEL_SUPLEXCHCFG_TECH, PPOBJ_GOODSGROUP, Data.GGrpID, 0, 0); { SString tech_symb; long _tech_id = 0; Data.GetExtStrData(PPSupplAgreement::ExchangeParam::extssTechSymbol, tech_symb); PPLoadText(PPTXT_SUPPLIXTECH, temp_buf); StringSet ss_tech_symb_list(';', temp_buf); StrAssocArray tech_list; long _ss_id = 0; for(uint ssp = 0; ss_tech_symb_list.get(&ssp, temp_buf);) { ++_ss_id; tech_list.Add(_ss_id, temp_buf); if(tech_symb.CmpNC(temp_buf) == 0) _tech_id = _ss_id; } SetupStrAssocCombo(this, CTLSEL_SUPLEXCHCFG_TECH, &tech_list, _tech_id, 0); } setCtrlData(CTL_SUPLEXCHCFG_LASTDT, &Data.LastDt); { setCtrlString(CTL_SUPLEXCHCFG_IP, Data.ConnAddr.ToStr(InetAddr::fmtAddr, temp_buf)); int16 port = Data.ConnAddr.GetPort(); setCtrlData(CTL_SUPLEXCHCFG_PORT, &port); } { Data.GetExtStrData(PPSupplAgreement::ExchangeParam::extssClientCode, temp_buf); setCtrlString(CTL_SUPLEXCHCFG_CLICODE, temp_buf); } SetupPPObjCombo(this, CTLSEL_SUPLEXCHCFG_QUOT, PPOBJ_QUOTKIND, Data.PriceQuotID, 0, 0); setCtrlData(CTL_SUPLEXCHCFG_VER, &Data.ProtVer); { Data.GetExtStrData(PPSupplAgreement::ExchangeParam::extssEDIPrvdrSymb, temp_buf); setCtrlString(CTL_SUPLEXCHCFG_PRVDR, temp_buf); } // @v9.2.0 { { Data.GetExtStrData(PPSupplAgreement::ExchangeParam::extssRemoveAddr, temp_buf); setCtrlString(CTL_SUPLEXCHCFG_TADDR, temp_buf); Data.GetExtStrData(PPSupplAgreement::ExchangeParam::extssAccsName, temp_buf); setCtrlString(CTL_SUPLEXCHCFG_TNAME, temp_buf); Data.GetExtStrData(PPSupplAgreement::ExchangeParam::extssAccsPassw, temp_buf); setCtrlString(CTL_SUPLEXCHCFG_TPW, temp_buf); } // } @v9.2.0 return 1; } int getDTS(PPSupplAgreement::ExchangeParam * pData) { int ok = 1; uint sel = 0; SString temp_buf; getCtrlData(sel = CTLSEL_SUPLEXCHCFG_GGRP, &Data.GoodsGrpID); getCtrlData(sel = CTLSEL_SUPLEXCHCFG_STYLO, &Data.Fb.StyloPalmID); // @v9.5.5 { getCtrlString(CTL_SUPLEXCHCFG_PRVDR, temp_buf = 0); Data.PutExtStrData(PPSupplAgreement::ExchangeParam::extssEDIPrvdrSymb, temp_buf); // @v9.1.3 if(temp_buf.Empty()) // @vmiller Если указан EDI провайдер, то группу товаров указывать не обязательно // @v9.1.3 THROW_PP(Data.GoodsGrpID, PPERR_INVGOODSGRP); } // getCtrlData(CTLSEL_SUPLEXCHCFG_OP, &Data.OpID); // getCtrlData(CTLSEL_SUPLEXCHCFG_TECH, &Data.TechID); { SString tech_symb; long _tech_id = getCtrlLong(CTLSEL_SUPLEXCHCFG_TECH); if(_tech_id) { PPLoadText(PPTXT_SUPPLIXTECH, temp_buf); StringSet ss_tech_symb_list(';', temp_buf); long _ss_id = 0; for(uint ssp = 0; tech_symb.Empty() && ss_tech_symb_list.get(&ssp, temp_buf);) { ++_ss_id; if(_ss_id == _tech_id) tech_symb = temp_buf; } Data.PutExtStrData(PPSupplAgreement::ExchangeParam::extssTechSymbol, tech_symb); } } { int16 port = 0; getCtrlString(sel = CTL_SUPLEXCHCFG_IP, temp_buf = 0); THROW_PP(temp_buf.NotEmptyS(), PPERR_INVIP); getCtrlData(CTL_SUPLEXCHCFG_PORT, &port); THROW_SL(Data.ConnAddr.Set(temp_buf, port)); } getCtrlData(CTL_SUPLEXCHCFG_LASTDT, &Data.LastDt); { getCtrlString(CTL_SUPLEXCHCFG_CLICODE, temp_buf = 0); Data.PutExtStrData(PPSupplAgreement::ExchangeParam::extssClientCode, temp_buf); } // @v9.2.0 { { getCtrlString(CTL_SUPLEXCHCFG_TADDR, temp_buf = 0); Data.PutExtStrData(PPSupplAgreement::ExchangeParam::extssRemoveAddr, temp_buf); getCtrlString(CTL_SUPLEXCHCFG_TNAME, temp_buf = 0); Data.PutExtStrData(PPSupplAgreement::ExchangeParam::extssAccsName, temp_buf); getCtrlString(CTL_SUPLEXCHCFG_TPW, temp_buf = 0); Data.PutExtStrData(PPSupplAgreement::ExchangeParam::extssAccsPassw, temp_buf); } // } @v9.2.0 getCtrlData(CTLSEL_SUPLEXCHCFG_QUOT, &Data.PriceQuotID); getCtrlData(CTL_SUPLEXCHCFG_VER, &Data.ProtVer); ASSIGN_PTR(pData, Data); CATCH ok = PPErrorByDialog(this, sel, -1); ENDCATCH return ok; } private: DECL_HANDLE_EVENT { TDialog::handleEvent(event); if(event.isCmd(cmaMore)) { EditSupplExchOpList(&Data); clearEvent(event); } } //int EditOps(); PPSupplAgreement::ExchangeParam Data; }; int ok = -1, valid_data = 0; //PPSupplAgreement::ExchangeParam ep; SupplExchangeCfgDialog * dlg = new SupplExchangeCfgDialog(); THROW(CheckDialogPtr(&dlg, 0)); dlg->setDTS(&Data.Ep); while(!valid_data && ExecView(dlg) == cmOK) if(dlg->getDTS(&Data.Ep) > 0) valid_data = ok = 1; CATCHZOKPPERR delete dlg; return ok; } int SupplAgtDialog::setDTS(const PPSupplAgreement * pAgt) { SString ar_name; RVALUEPTR(Data, pAgt); ArID = Data.SupplID; GetArticleName(Data.SupplID, ar_name); setCtrlString(CTL_SUPPLAGT_SUPPLIER, ar_name); disableCtrl(CTL_SUPPLAGT_SUPPLIER, 1); setCtrlData(CTL_SUPPLAGT_DATE, &Data.BegDt); setCtrlData(CTL_SUPPLAGT_EXPIRY, &Data.Expiry); setCtrlData(CTL_SUPPLAGT_PAYPERIOD, &Data.DefPayPeriod); setCtrlData(CTL_SUPPLAGT_DELIVERY, &Data.DefDlvrTerm); setCtrlData(CTL_SUPPLAGT_MAXRETURN, &Data.PctRet); SetupArCombo(this, CTLSEL_SUPPLAGT_AGENT, Data.DefAgentID, OLW_LOADDEFONOPEN|OLW_CANINSERT, GetAgentAccSheet(), sacfDisableIfZeroSheet); SetupPPObjCombo(this, CTLSEL_SUPPLAGT_OPRKIND, PPOBJ_OPRKIND, Data.PurchaseOpID, 0, (void *)PPOPT_DRAFTRECEIPT); SetupPPObjCombo(this, CTLSEL_SUPPLAGT_QUOTCOST, PPOBJ_QUOTKIND, Data.CostQuotKindID, 0, (void *)QuotKindFilt::fAll); SetupPPObjCombo(this, CTLSEL_SUPPLAGT_QUOTUP, PPOBJ_QUOTKIND, Data.DevUpQuotKindID, 0, (void *)QuotKindFilt::fAll); SetupPPObjCombo(this, CTLSEL_SUPPLAGT_QUOTDOWN, PPOBJ_QUOTKIND, Data.DevDnQuotKindID, 0, (void *)QuotKindFilt::fAll); SetupPPObjCombo(this, CTLSEL_SUPPLAGT_MNGRREL, PPOBJ_PERSONRELTYPE, Data.MngrRelID, 0); if(!ArID) { long inv_price_action = (long)Data.InvPriceAction; AddClusterAssoc(CTL_SUPPLAGT_INVPACTION, 0, PPSupplAgreement::invpaRestrict); AddClusterAssoc(CTL_SUPPLAGT_INVPACTION, 1, PPSupplAgreement::invpaWarning); AddClusterAssoc(CTL_SUPPLAGT_INVPACTION, 2, PPSupplAgreement::invpaDoNothing); SetClusterData(CTL_SUPPLAGT_INVPACTION, inv_price_action); AddClusterAssoc(CTL_SUPPLAGT_FLAGS2, 0, AGTF_USESDONPURCHOP); SetClusterData(CTL_SUPPLAGT_FLAGS2, Data.Flags); enableCommand(cmBills, 0); } else { AddClusterAssoc(CTL_SUPPLAGT_FLAGS, 0, AGTF_USEMARKEDGOODSONLY); AddClusterAssoc(CTL_SUPPLAGT_FLAGS, 1, AGTF_SUBCOSTONSUBPARTSTR); AddClusterAssoc(CTL_SUPPLAGT_FLAGS, 2, AGTF_AUTOORDER); SetClusterData(CTL_SUPPLAGT_FLAGS, Data.Flags); // @v8.5.2 long v = (long)Data.OrdPrdDays; // @v8.5.2 setCtrlLong(CTL_SUPPLAGT_ORDPRD, v); } setupCtrls(Data.Flags); updateList(-1); return 1; } int SupplAgtDialog::getDTS(PPSupplAgreement * pAgt) { int ok = 1, sel = 0; getCtrlData(sel = CTL_SUPPLAGT_DATE, &Data.BegDt); THROW_SL(checkdate(Data.BegDt, 1)); getCtrlData(sel = CTL_SUPPLAGT_EXPIRY, &Data.Expiry); THROW_SL(checkdate(Data.Expiry, 1)); getCtrlData(CTL_SUPPLAGT_PAYPERIOD, &Data.DefPayPeriod); getCtrlData(CTL_SUPPLAGT_DELIVERY, &Data.DefDlvrTerm); getCtrlData(sel = CTL_SUPPLAGT_MAXRETURN, &Data.PctRet); THROW_PP(Data.PctRet >= 0L && Data.PctRet <= 100, PPERR_USERINPUT); getCtrlData(CTLSEL_SUPPLAGT_AGENT, &Data.DefAgentID); getCtrlData(CTLSEL_SUPPLAGT_OPRKIND, &Data.PurchaseOpID); getCtrlData(CTLSEL_SUPPLAGT_QUOTCOST, &Data.CostQuotKindID); getCtrlData(CTLSEL_SUPPLAGT_QUOTUP, &Data.DevUpQuotKindID); getCtrlData(CTLSEL_SUPPLAGT_QUOTDOWN, &Data.DevDnQuotKindID); getCtrlData(CTLSEL_SUPPLAGT_MNGRREL, &Data.MngrRelID); if(!ArID) { GetClusterData(CTL_SUPPLAGT_INVPACTION, &Data.InvPriceAction); GetClusterData(CTL_SUPPLAGT_FLAGS2, &Data.Flags); } else { GetClusterData(CTL_SUPPLAGT_FLAGS, &Data.Flags); // @v8.5.2 Data.OrdPrdDays = (int16)getCtrlLong(CTL_SUPPLAGT_ORDPRD); // @v8.5.2 THROW_PP(!(Data.Flags & AGTF_AUTOORDER) || Data.OrdPrdDays > 0, PPERR_INVPERIODINPUT); } ASSIGN_PTR(pAgt, Data); CATCH ok = PPErrorByDialog(this, sel, -1); ENDCATCH return ok; } // static int SLAPI PPObjArticle::EditSupplAgreement(PPSupplAgreement * pAgt) { DIALOG_PROC_BODY_P1(SupplAgtDialog, pAgt ? pAgt->SupplID : 0, pAgt); } // static int SLAPI PPObjArticle::DefaultSupplAgreement() { int ok = 1; PPObjArticle arobj; PPSupplAgreement agt; THROW(CheckCfgRights(PPCFGOBJ_SUPPLDEAL, PPR_MOD, 0)); THROW(arobj.CheckRights(ARTRT_CLIAGT)); THROW(arobj.GetSupplAgreement(0, &agt, 0)); if(arobj.EditSupplAgreement(&agt) > 0) THROW(arobj.PutSupplAgreement(0, &agt, 1)); CATCHZOKPPERR return ok; } //static int SLAPI PPObjArticle::GetAgreementKind(const ArticleTbl::Rec * pArRec) { int ok = -1; PPObjAccSheet acs_obj; PPAccSheet acs_rec; THROW_PP(pArRec, PPERR_INVPARAM); THROW(acs_obj.Fetch(pArRec->AccSheetID, &acs_rec) > 0); if(pArRec->AccSheetID == GetSupplAccSheet() && acs_rec.Flags & ACSHF_USESUPPLAGT) ok = 2; else if(pArRec->AccSheetID == GetSellAccSheet() || acs_rec.Flags & ACSHF_USECLIAGT) ok = 1; CATCHZOK return ok; } // // Implementation of PPALDD_Agreement // PPALDD_CONSTRUCTOR(Agreement) { if(Valid) { AssignHeadData(&H, sizeof(H)); Extra[0].Ptr = new PPObjArticle; } } PPALDD_DESTRUCTOR(Agreement) { Destroy(); delete (PPObjArticle*)Extra[0].Ptr; Extra[0].Ptr = 0; } int PPALDD_Agreement::InitData(PPFilt & rFilt, long rsrv) { int ok = -1; if(rFilt.ID == H.ID) ok = DlRtm::InitData(rFilt, rsrv); else { MEMSZERO(H); H.ID = rFilt.ID; SString temp_buf; ArticleTbl::Rec ar_rec; PPObjArticle * p_ar_obj = (PPObjArticle *)(Extra[0].Ptr); if(p_ar_obj->Search(rFilt.ID, &ar_rec) > 0) { PPAccSheet acs_rec; PPObjAccSheet acc_sheet_obj; if(acc_sheet_obj.Fetch(ar_rec.AccSheetID, &acs_rec) > 0) { PPClientAgreement cli_agt; PPSupplAgreement suppl_agt; if((acs_rec.Flags & ACSHF_USECLIAGT) && p_ar_obj->GetClientAgreement(H.ID, &cli_agt, 0) > 0) { H.AgentID = cli_agt.DefAgentID; H.ExtObjectID = cli_agt.ExtObjectID; // @v7.5.9 H.QKindID = cli_agt.DefQuotKindID; H.BegDt = cli_agt.BegDt; H.Expiry = cli_agt.Expiry; H.MaxCredit = cli_agt.MaxCredit; H.MaxDscnt = cli_agt.MaxDscnt; H.Dscnt = cli_agt.Dscnt; H.DefPayPeriod = cli_agt.DefPayPeriod; STRNSCPY(H.Code, cli_agt.Code); } else if((acs_rec.Flags & ACSHF_USESUPPLAGT) && p_ar_obj->GetSupplAgreement(H.ID, &suppl_agt, 0) > 0) { H.AgentID = suppl_agt.DefAgentID; H.BegDt = suppl_agt.BegDt; H.Expiry = suppl_agt.Expiry; H.DefPayPeriod = suppl_agt.DefPayPeriod; H.DefDlvrTerm = suppl_agt.DefDlvrTerm; H.PctRet = suppl_agt.PctRet; // @v8.5.0 { suppl_agt.Ep.GetExtStrData(PPSupplAgreement::ExchangeParam::extssEDIPrvdrSymb, temp_buf = 0); temp_buf.CopyTo(H.EDIPrvdrSymb, sizeof(H.EDIPrvdrSymb)); // } @v8.5.0 // @v8.5.0 STRNSCPY(H.EDIPrvdrSymb, suppl_agt.ExchCfg.PrvdrSymb); // @v8.0.6 } } ok = DlRtm::InitData(rFilt, rsrv); } } return ok; }
163f36c7166f3301ede2cfc6e61590a64d753869
7addc813ddaa31ed381f1d2f9fa94a7915857fea
/Data Structures/Linear/Array/question4.cpp
9aa5493bebb3615a571bb04a29ff15b49f1b46df
[]
no_license
JasbirCodeSpace/Spider-Task-2
595127ee45c9282753ebf69921ee8015a465cf0c
637f6d0d2a8924950036327ebb2b959f6c227b81
refs/heads/main
2023-03-11T09:54:35.486541
2021-02-25T19:28:02
2021-02-25T19:28:02
329,349,675
0
0
null
null
null
null
UTF-8
C++
false
false
965
cpp
question4.cpp
//Question: https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0 #include <bits/stdc++.h> using namespace std; #define RANGE 3 void sort_array(int *arr, int size) { int count[RANGE] = {0}; for (size_t i = 0; i < size; i++) { count[arr[i]]++; } int j = 0; for (size_t i = 0; i < RANGE;) { if (count[i] > 0) { arr[j++] = i; count[i]--; } else { i++; } } } void print_array(int *arr, int size) { cout << endl; for (int i = 0; i < size; i++) { cout << arr[i] << " "; } cout << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int N; cin >> N; int arr[N]; for (size_t i = 0; i < N; i++) { cin >> arr[i]; } sort_array(arr, N); print_array(arr, N); return 0; }
21a0e38fabf1a925864944375387533db66964be
d69528049d01201d170538207cc8ece7457553c7
/.Archive/1071.greatest-common-divisor-of-strings/Solution.cpp
0d002a813d689629a1e91f95186fda78eda11a5c
[]
no_license
lightjiao/LeetCode
1125565fdfc581108f763150ff880e8654d98a00
513f60d14fdc942143f553a1decfca7034a9814c
refs/heads/master
2021-07-14T01:33:29.188614
2021-03-18T14:31:23
2021-03-18T14:31:23
243,549,574
1
0
null
null
null
null
UTF-8
C++
false
false
1,341
cpp
Solution.cpp
/** * 对于字符串 S 和 T,只有在 S = T + ... + T(T 与自身连接 1 次或多次)时,我们才认定 “T 能除尽 S”。 返回最长字符串 X,要求满足 X 能除尽 str1 且 X 能除尽 str2。 示例 1: 输入:str1 = "ABCABC", str2 = "ABC" 输出:"ABC" 示例 2: 输入:str1 = "ABABAB", str2 = "ABAB" 输出:"AB" 示例 3: 输入:str1 = "LEET", str2 = "CODE" 输出:"" 提示: 1 <= str1.length <= 1000 1 <= str2.length <= 1000 str1[i] 和 str2[i] 为大写英文字母 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/greatest-common-divisor-of-strings 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ #include <string> #include <iostream> #include <vector> #include <algorithm> #include "limits.h" #include <numeric> using namespace std; class Solution { public: /** * 辗转相减法 */ string gcdOfStrings(string str1, string str2) { if (str1.size() == str2.size()) { return str1 == str2 ? str1 : ""; } if (str1.size() > str2.size()) { str1 = str1.substr(str2.size()); } else { str2 = str2.substr(str1.size()); } return gcdOfStrings(str1, str2); } };
2fb8b5ce730d17046eff6699e1717a9b4e3dd4cf
7fcd19b14e8e9b8da99d60496d8bc39fa1dddf08
/greedy/spoj.cpp
26363e343bce894d2d8c6015370773baaed06a36
[]
no_license
balramsingh54/Data__stru_C-
e6103e230aef3bbc81761be56a42b4f828f5bb4d
491277c57abe5f3ce7364689f50eedf780f01fa7
refs/heads/master
2020-06-16T12:31:51.961303
2019-08-02T16:01:08
2019-08-02T16:01:08
195,575,590
0
0
null
null
null
null
UTF-8
C++
false
false
229
cpp
spoj.cpp
#include <bits/stdc++.h> #include <iostream> using namespace std; int main(int argc, char const *argv[]) { cout<<"hello"<<endl; int num, start, end; for (int i = 0; i < num; i++) { cin>>start; cin>>end; } return 0; }
4f0bb30c535c338205133af5d068ba25ca305117
447cfa0acc4a565a2ed7515bce5e12056e7583d9
/PC_Tracker/APU.SDL.OLD.DONT.TOUCH/gme_vspc/std/debugger/Voice_Control.cpp
775f802f014e5c8ff444f974c08eda8356b14af8
[]
no_license
bepisTM/SNES-Tracker
0608d4a32cd081183a01481b7768021b2576c286
b98ebf5618d2acbfc6f60519868802092ff76410
refs/heads/master
2021-05-04T23:17:42.114218
2016-04-09T03:44:13
2016-04-09T03:44:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,863
cpp
Voice_Control.cpp
#include "Voice_Control.h" #include "gme/player/Music_Player.h" Voice_Control::Voice_Control() { } void Voice_Control::checkmouse_mute(Uint16 &x,Uint16 &y) { char changed=0; SDL_Rect *r1 = &Screen::voice0vol; SDL_Rect *r2 = &Screen::voice0pitch; for (int i=0; i < 8; i++) { // if we click on the number of the voice, whether in the Pitch or Volume section if ( (x >= (r1->x) && x <= (r1->x + r1->w) && y >= (r1->y + (i*r1->h)) && y <= (r1->y+((i*r1->h))+r1->h-1) ) || ( (x >= (r2->x) && x <= (r2->x+r2->w)) && (y >= (r2->y + (i*r2->h)) && y <= (r2->y+(i*r2->h))+r2->h-1 ) ) ) { // if the voice isnt being toggle protected if (!(muted_toggle_protect & (1 << i)) ) { muted_toggle_protect |= 1<<i; changed = 1; muted ^= (1<<i); // bit toggle } } else { muted_toggle_protect &= ~(1<<i); } } if (changed) player->mute_voices(muted); } void Voice_Control::checkmouse_solo(Uint16 &x,Uint16 &y) { char changed=0; SDL_Rect *r1 = &Screen::voice0vol; SDL_Rect *r2 = &Screen::voice0pitch; for (int i=0; i < 8; i++) { if ( (x >= (r1->x) && x <= (r1->x + r1->w) && y >= (r1->y + (i*r1->h)) && y <= (r1->y+((i*r1->h))+r1->h-1) ) || ( (x >= (r2->x) && x <= (r2->x+r2->w)) && (y >= (r2->y + (i*r2->h)) && y <= (r2->y+(i*r2->h))+r2->h-1 ) ) ) { changed = 1; if (muted == Uint8(~(1 << i)) ) { muted = 0; } else muted = ~(1<<i); } } if (changed) player->mute_voices(muted); } void Voice_Control::mute(uint8_t i) { muted = i; } void Voice_Control::solo(uint8_t i) { muted = ~(1<<(i-1)); player->mute_voices(muted); } void Voice_Control::solo_bits(uint8_t i) { //fprintf(stderr, "muted = %02X, ~i = %02X", muted, ~i); if (muted == (uint8_t)(~i)) { //fprintf(stderr, "deede"); muted = 0; } else muted = ~(i); player->mute_voices(muted); } void Voice_Control::toggle_solo(uint8_t i) { if (muted == Uint8(~(1 << (i-1) ) ) ) { muted = 0; } else muted = ~(1<<(i-1)); player->mute_voices(muted); } void Voice_Control::toggle_mute(uint8_t m) { assert (m>0 && m < 9 ); muted ^= 1<<(m-1); player->mute_voices(muted); } void Voice_Control::mute_all() { player->mute_voices(muted=0); } void Voice_Control::toggle_mute_all() { if (!muted) muted = 0xff; else muted = 0; //player->mute_voices(muted^=0xff); player->mute_voices(muted); } void Voice_Control::unmute_all() { player->mute_voices(muted=0); } void Voice_Control::checkmouse(Uint16 &x, Uint16 &y, int b) { muted_toggle_protect = 0; if (b == SDL_BUTTON_LEFT) checkmouse_mute(x,y); else if (b == SDL_BUTTON_RIGHT) checkmouse_solo(x,y); } Uint8 Voice_Control::is_muted(int i) { return muted & (1<<i); }
8a5657119a69bacb2cd6d38e117df2ba9d84ddd7
6c9fe85383c316d187a3d529c93cfa4e0bfc6143
/popular/t1079.cpp
202bdf4e295bf92fa1e5cc15e0ca16e2ae018637
[]
no_license
OLDMAN007/jisuanke
59d08f0f667b3fa02d92d83f1c094f7477e79a89
c6f43a5a2da3ac3e5f240aff6d64e300307c5883
refs/heads/master
2020-12-01T06:06:31.731185
2020-02-28T06:06:23
2020-02-28T06:06:23
230,572,100
0
0
null
null
null
null
UTF-8
C++
false
false
760
cpp
t1079.cpp
// // Created by OLD MAN on 2020/1/6. // //#include<bits/stdc++.h> #include <iostream> using namespace std; int main(){ int n,m; cin>>n>>m; bool a[n]; int w=1; for(int i=0;i<n;i++){ a[i]=true; } for(int i=1;i<=m;i++){ if(i==1){ for(int j=0;j<n;j++){ a[j]=false; } } else if(i==2){ for(int j=0;j<(n+1)/2;j++) a[2*j+1]=1; } else for(int j=1;j<=n/i;j++){ a[i*j-1]=!a[i*j-1]; } } for(int i=0;i<n;i++){ if(!a[i]){ if(w){ cout<<i+1; w=0; }else{ cout<<","<<i+1; } } } }
cb82f284851111977ea0e76ddb5445cc94d1d481
aae51c7874e7f814f3591d2ccbeb66eb74e9149c
/Codeforces/Round 479 Div 3/E/E.cpp
44a312d5acbb6894088e01615af0e0b5167e08b1
[]
no_license
cortesjpb/Programacion-Competitiva
86adef35601e236dfdff3a41bb64f948aa1c097f
bf6d9984cebdbd2399879f6e828971055ad8e9cd
refs/heads/master
2021-08-16T22:17:31.702740
2020-05-05T13:09:27
2020-05-05T13:09:27
176,312,126
0
0
null
null
null
null
UTF-8
C++
false
false
820
cpp
E.cpp
#include <bits/stdc++.h> using namespace std; int n, v[100010],length[100010]; vector<int>vs[100010]; int main() { ios::sync_with_stdio(false); cin.tie(NULL); freopen("entrada.txt","r",stdin); cin>>n; vector<int>vs[n]; for(int i=0;i<n;i++) cin>>v[i]; for(int j=0;j<n;j++){ length[j]=1; for(int i=0;i<j;i++){ if(v[i]==v[j]-1){ if(length[j]<length[i]+1){ length[j]=length[i]+1; } vs[j].push_back(i+1); } } vs[j].push_back(j+1); } auto it=max_element(length,length+n); int maxi=distance(length,it); cout << vs[maxi].size() << " " << vs[maxi-1].size() << " " << vs[maxi+1].size() << endl; for (auto a: vs) cout << a.size() << endl; /*for(int i=0;i<n;i++) cout << length[i] << endl;*/ //cout << *max_element(length,length+n); return 0; }
c73b32a53edb1a8935441c315a52f57c948cff00
93a718be753edc4ec5929858923012021034390d
/passwordcheck.cpp
15c4451284ab09cfc3b8c32e1d61eea98e69de6c
[ "MIT" ]
permissive
aleezeh611/Password-Cracker-using-Distributed-Systems
8aca6ceb5aa1567436659f5d2d93ebb98ccdbbc1
6d9b41a9f20672c458a34b377e004dddefd86a5c
refs/heads/main
2023-07-18T15:52:42.672417
2021-09-11T22:05:57
2021-09-11T22:05:57
393,689,917
5
0
null
null
null
null
UTF-8
C++
false
false
10,369
cpp
passwordcheck.cpp
/* Basic Logic: -In our master machine (process id 0) we will read shadow.txt file and use tokenize function to parse the sentence to get salt and encrypted key -Then we send the length of salt, length of key, salt and encrypted key to each of the slave processes to use to search for password. -We will dynamically divide passwords among the slaves based on password lengths e.g passwords of length 1-2 will go to one process, 3-4 will go to another and so on -In case of 8(max length) not being divisible by number of processes the remainder will be taken up by the master itself to search. -To search a function runs which tests all possible combinations of alph for its allotted length and returns true or false if password found or not. -If password is found, the slave calls MPI_Abort to stop all other processes from continuing their search. NOTE: We tested out code using 4 VMs, 3 slaves and 1 Master however it works best with 1 slave since our laptops do not have enough power to bear so many VMs and become unbearably slow. Submitted By: Aleezeh Usman 18I-0529 Areesha Tahir 18I-1655 Faaira Ahmed 18I-0423 Omer Ihtizaz 18I-0404 */ #include<stdio.h> #include<unistd.h> #include<crypt.h> #include<string.h> #include<iostream> #include <queue> #include<mpi.h> #include<fstream> #include <bits/stdc++.h> using namespace std; //================================================================================================================================== // FUNCTIONS //================================================================================================================================== //Function to tokenize the data we get from shadows file to retrieve salt and encrypted password and remove useless information void tokenize(string s, string &getsalt, string &gethash, string del = " ") { int start = 0; int end = s.find(del); int count = 0; string id = "$"; string Salt = ""; while (count < 3) { //We are tokenizing based on $ sign so we get 3 tokens if (count == 1){ //First token is ID id += s.substr(start, end - start); id = id + "$"; //append $ to match format } if (count == 2){ //Second token is salt string slt = id ; slt += s.substr(start, end - start); slt = slt + "$"; //append $ to match format Salt = slt; } start = end + del.size(); end = s.find(del, start); //find position of $ in the string to get the next token which to move start and end forward to get the correct piece of string count++; } string temp = ""; temp = s.substr(start, end - start); //get the complete hash value without salt and id del = ":"; end = temp.find(del); start = del.size() - 1; gethash = temp.substr(start, end - start); getsalt = Salt; gethash = getsalt + gethash; //get complete hash value with salt and if as well } //Function used to convert character array to a string string convertToString(char* a, int size) { int i; string s = ""; for (i = 0; i <= size; i++) { s = s + a[i]; } return s; } //Main logic function which will check all possible passwords by brute force technique and return true when a password is found //Parameteres: digitstart - digitsend i.e the rangbe of length of password the function should search in bool PasswordCracker(int digitstart, int digitsend,string salt, string actualencrypt, int procid){ char testpass[8] = "*******"; //temporary char array to store possible password combinations in char alph[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; //alphabets that will be used to generate possible passwords int i = digitstart-1; //So we can dynamically change the range of length of password we are searching for for(; i < digitsend-1; i++){ //8 nested loops to create password combinations using alphabets upto 8 characters long for (int dig8 = 0; dig8 < 26 ; dig8++){ if(i>6){ testpass[i-7] = alph[dig8]; } for (int dig7 = 0; dig7 < 26 ; dig7++){ if(i>5){ testpass[i-6] = alph[dig7]; } for (int dig6 = 0; dig6 < 26 ; dig6++){ if(i>4){ testpass[i-5] = alph[dig6]; } for (int dig5 = 0; dig5 < 26 ; dig5++){ if(i>3){ testpass[i-4] = alph[dig5]; } for (int dig4 = 0; dig4 < 26 ; dig4++){ if(i>2){ testpass[i-3] = alph[dig4]; } for (int dig3 = 0; dig3 < 26 ; dig3++){ if(i>1){ testpass[i-2] = alph[dig3]; } for(int dig2 = 0; dig2<26 ; dig2++){ if(i>0){ testpass[i-1] = alph[dig2]; } for(int dig1 = 0; dig1<26 ; dig1++){ testpass[i] = alph[dig1]; string passwordoption = convertToString(testpass,i); //cout<<"P"<<procid<<":CURRENT -> "<<passwordoption<<endl; //print each password combination string currencrypt = crypt(passwordoption.c_str(),salt.c_str()); //get encrypted key if(strncmp(currencrypt.c_str(), actualencrypt.c_str(), currencrypt.length()) == 0){ //compare encrypoted key cout<<"\n\nPASSWORD FOUND: "<<passwordoption<<endl; cout<<"PROCESS -> "<< procid<<endl; return true; //if key is found return true } } if(i==0) break; } if(i<=1) break; } if(i<=2) break; } if(i<=3) break; } if(i<=4) break; } if(i<=5) break; } if(i<=6) break; } } return false; //if password is not found return false } //===================================================================================================================================== // MAIN DRIVER CODE //===================================================================================================================================== int main(int argc, char** argv){ //set up MPI----------------------------------------------------------------------------------------------------------------- int myrank,nprocs; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&nprocs); MPI_Comm_rank(MPI_COMM_WORLD,&myrank); //task division ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- int division = 8/(nprocs-1); //task division will be done by sending each machine a range of length of passwords to search from. The ranges to send depends on number of processes(excluding master so minus 1) int remainder = 8%(nprocs-1); //in case not completely divisible, alot the remainder to master node if(myrank == 0){ cout<<"ENTER USER NAME: "<<endl; char user_name[50]; //get user name at run time - dynamic generic code cin>>user_name; //get actual encrypted password and salt to compare--------------------------------------------------------------------------- string salt = ""; string actualencrypt = ""; fstream file; string line, filename; filename = "/mirror/shadow.txt"; //get actual encrypted password and its salt from shadow file file.open(filename.c_str(), ios::in); if(file.is_open()){ while (file >> line){ //get the encrypted password of given user name from shadow file if (line.find(user_name) != std::string::npos){ tokenize(line, salt, actualencrypt, "$"); //parse the information to get salt and hash break; //once found username no need to look further } } file.close(); //cout<<"SALT: "<<salt<<endl; //cout<<"HASH: "<<actualencrypt<<endl; if(salt == "" or actualencrypt == ""){ cout<<"ERROR:: No user of given name could be found -- ABORT SEARCH**"<<endl; MPI_Abort(MPI_COMM_WORLD, 1); } } else{ cout<<"SHADOWS FILE COULD NOT BE OPENED"<<endl; //in case shadow file does not open show code genericness by taking password as user input string actual = "aaaaabz"; //actual password salt = "$6$5bXhSeHX$"; //salt retreived from shadow file actualencrypt = crypt(actual.c_str(),salt.c_str()); //actual encrypted key } int n1 = salt.length(); char *sendsalt; sendsalt = &salt[0]; int n2 = actualencrypt.length(); char *sendhash; sendhash = &actualencrypt[0]; for(int i = 1 ; i < nprocs; i++){ MPI_Send(&n1, 1, MPI_INT, i, 1234, MPI_COMM_WORLD); MPI_Send(&n2, 1, MPI_INT, i, 1234, MPI_COMM_WORLD); MPI_Send(sendsalt, n1, MPI_CHAR, i, 1234, MPI_COMM_WORLD); MPI_Send(sendhash, n2, MPI_CHAR, i, 1234, MPI_COMM_WORLD); } printf("MASTER: PASSWORD CHECKING HAS BEGUN\n"); if(remainder>0){ //if max length not equalli divisible then master will search the remaining if(PasswordCracker(8-remainder+1,9,salt, actualencrypt, myrank) == false){ cout<<"\nPROCESS: "<<myrank<<" -> PASSWORD WAS NOT FOUND\n"<<endl; } else{ cout<<"***SENDING SIGNAL TO ALL PROCESSES TO ABORT SEARCH***\n"; MPI_Abort(MPI_COMM_WORLD, 1); } } } //Code for slave processes to run to search for password using all possible combinations------------------------------------------------------------------------------------------------------------- if(myrank>0){ char getsalt[100]; char gethash[500]; int saltn; int hashn; MPI_Recv(&saltn, 1, MPI_INT, 0, 1234, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&hashn, 1, MPI_INT, 0, 1234, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(getsalt, 100, MPI_CHAR, 0, 1234, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(gethash, 500, MPI_CHAR, 0, 1234, MPI_COMM_WORLD, MPI_STATUS_IGNORE); string salt = convertToString(getsalt, saltn-1); string actualencrypt = convertToString(gethash, hashn); int start_search = 1+((myrank-1)*division); //start for range of length assigned to each task int end_search = start_search+division; //end for the range of passwords length if(PasswordCracker(start_search,end_search,salt, actualencrypt, myrank) == false){ //run function for password search cout<<"\nPROCESS: "<<myrank<<" -> PASSWORD WAS NOT FOUND\n"<<endl; //if password not found display message } else{ cout<<"***SENDING SIGNAL TO ALL PROCESSES TO ABORT SEARCH***\n"; //if password found display message MPI_Abort(MPI_COMM_WORLD, 1); //then abort all processes to stop unnecessary search } } MPI_Finalize(); }
28750fbb3115da8cca56a7a5550051a09072c41c
e79cb86744b9cc5d46912f2f9acdb5ffd434f745
/src/grt/src/fastroute/src/FastRoute.cpp
798e68b92da5d16a4153faf75753ca10032fe842
[ "BSD-3-Clause", "MPL-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
The-OpenROAD-Project/OpenROAD
555cbb00ec250bb09b9e4f9a7d1454e7ac7a01ab
1f6ccc9066e7df4509ed391d87b01eadb4b3b197
refs/heads/master
2023-08-31T05:35:25.363354
2023-08-31T05:04:27
2023-08-31T05:04:27
218,110,222
979
461
BSD-3-Clause
2023-09-14T21:51:36
2019-10-28T17:48:14
Verilog
UTF-8
C++
false
false
40,730
cpp
FastRoute.cpp
//////////////////////////////////////////////////////////////////////////////// // Authors: Vitor Bandeira, Eder Matheus Monteiro e Isadora Oliveira // (Advisor: Ricardo Reis) // // BSD 3-Clause License // // Copyright (c) 2019, Federal University of Rio Grande do Sul (UFRGS) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////// #include "FastRoute.h" #include <algorithm> #include <unordered_set> #include "AbstractFastRouteRenderer.h" #include "DataType.h" #include "odb/db.h" #include "utl/Logger.h" namespace grt { using utl::GRT; FastRouteCore::FastRouteCore(odb::dbDatabase* db, utl::Logger* log, stt::SteinerTreeBuilder* stt_builder) : max_degree_(0), db_(db), overflow_iterations_(0), congestion_report_iter_step_(0), layer_orientation_(0), x_range_(0), y_range_(0), num_adjust_(0), v_capacity_(0), h_capacity_(0), x_grid_(0), y_grid_(0), x_corner_(0), y_corner_(0), tile_size_(0), enlarge_(0), costheight_(0), ahth_(0), num_layers_(0), total_overflow_(0), has_2D_overflow_(false), grid_hv_(0), verbose_(false), update_slack_(0), via_cost_(0), mazeedge_threshold_(0), v_capacity_lb_(0), h_capacity_lb_(0), logger_(log), stt_builder_(stt_builder), debug_(new DebugSetting()) { parasitics_builder_ = nullptr; } FastRouteCore::~FastRouteCore() { clearNets(); } void FastRouteCore::clear() { clearNets(); num_adjust_ = 0; v_capacity_ = 0; h_capacity_ = 0; total_overflow_ = 0; has_2D_overflow_ = false; h_edges_.resize(boost::extents[0][0]); v_edges_.resize(boost::extents[0][0]); seglist_.clear(); gxs_.clear(); gys_.clear(); gs_.clear(); tree_order_pv_.clear(); tree_order_cong_.clear(); h_edges_3D_.resize(boost::extents[0][0][0]); v_edges_3D_.resize(boost::extents[0][0][0]); parent_x1_.resize(boost::extents[0][0]); parent_y1_.resize(boost::extents[0][0]); parent_x3_.resize(boost::extents[0][0]); parent_y3_.resize(boost::extents[0][0]); net_eo_.clear(); xcor_.clear(); ycor_.clear(); dcor_.clear(); hv_.resize(boost::extents[0][0]); hyper_v_.resize(boost::extents[0][0]); hyper_h_.resize(boost::extents[0][0]); corr_edge_.resize(boost::extents[0][0]); in_region_.resize(boost::extents[0][0]); v_capacity_3D_.clear(); h_capacity_3D_.clear(); layer_grid_.resize(boost::extents[0][0]); via_link_.resize(boost::extents[0][0]); cost_hvh_.clear(); cost_vhv_.clear(); cost_h_.clear(); cost_v_.clear(); cost_lr_.clear(); cost_tb_.clear(); cost_hvh_test_.clear(); cost_v_test_.clear(); cost_tb_test_.clear(); vertical_blocked_intervals_.clear(); horizontal_blocked_intervals_.clear(); } void FastRouteCore::clearNets() { if (!sttrees_.empty()) { sttrees_.clear(); } for (FrNet* net : nets_) { delete net; } nets_.clear(); seglist_.clear(); db_net_id_map_.clear(); } void FastRouteCore::setGridsAndLayers(int x, int y, int nLayers) { x_grid_ = x; y_grid_ = y; num_layers_ = nLayers; if (std::max(x_grid_, y_grid_) >= 1000) { x_range_ = std::max(x_grid_, y_grid_); y_range_ = std::max(x_grid_, y_grid_); } else { x_range_ = 1000; y_range_ = 1000; } v_capacity_3D_.resize(num_layers_); h_capacity_3D_.resize(num_layers_); for (int i = 0; i < num_layers_; i++) { v_capacity_3D_[i] = 0; h_capacity_3D_[i] = 0; } layer_grid_.resize(boost::extents[num_layers_][MAXLEN]); via_link_.resize(boost::extents[num_layers_][MAXLEN]); hv_.resize(boost::extents[y_range_][x_range_]); hyper_v_.resize(boost::extents[y_range_][x_range_]); hyper_h_.resize(boost::extents[y_range_][x_range_]); corr_edge_.resize(boost::extents[y_range_][x_range_]); in_region_.resize(boost::extents[y_range_][x_range_]); cost_hvh_.resize(x_range_); // Horizontal first Z cost_vhv_.resize(y_range_); // Vertical first Z cost_h_.resize(y_range_); // Horizontal segment cost cost_v_.resize(x_range_); // Vertical segment cost cost_lr_.resize(y_range_); // Left and right boundary cost cost_tb_.resize(x_range_); // Top and bottom boundary cost cost_hvh_test_.resize(y_range_); // Vertical first Z cost_v_test_.resize(x_range_); // Vertical segment cost cost_tb_test_.resize(x_range_); // Top and bottom boundary cost } void FastRouteCore::addVCapacity(short verticalCapacity, int layer) { v_capacity_3D_[layer - 1] = verticalCapacity; v_capacity_ += v_capacity_3D_[layer - 1]; } void FastRouteCore::addHCapacity(short horizontalCapacity, int layer) { h_capacity_3D_[layer - 1] = horizontalCapacity; h_capacity_ += h_capacity_3D_[layer - 1]; } void FastRouteCore::setLowerLeft(int x, int y) { x_corner_ = x; y_corner_ = y; } void FastRouteCore::setTileSize(int size) { tile_size_ = size; } void FastRouteCore::setLayerOrientation(int x) { layer_orientation_ = x; } FrNet* FastRouteCore::addNet(odb::dbNet* db_net, bool is_clock, int driver_idx, int cost, int min_layer, int max_layer, float slack, std::vector<int>* edge_cost_per_layer) { int netID; bool exists; FrNet* net; getNetId(db_net, netID, exists); if (exists) { net = nets_[netID]; clearNetRoute(netID); seglist_[netID].clear(); } else { net = new FrNet; nets_.push_back(net); netID = nets_.size() - 1; db_net_id_map_[db_net] = netID; // at most (2*num_pins-2) nodes -> (2*num_pins-3) segs_ for a net } net->reset(db_net, is_clock, driver_idx, cost, min_layer, max_layer, slack, edge_cost_per_layer); return net; } void FastRouteCore::getNetId(odb::dbNet* db_net, int& net_id, bool& exists) { auto itr = db_net_id_map_.find(db_net); exists = itr != db_net_id_map_.end(); net_id = exists ? itr->second : 0; } void FastRouteCore::clearNetRoute(const int netID) { // clear used resources for the net route releaseNetResources(netID); // clear stree sttrees_[netID].nodes.reset(); sttrees_[netID].edges.reset(); } void FastRouteCore::initEdges() { const float LB = 0.9; v_capacity_lb_ = LB * v_capacity_; h_capacity_lb_ = LB * h_capacity_; // allocate memory and initialize for edges h_edges_.resize(boost::extents[y_grid_][x_grid_ - 1]); v_edges_.resize(boost::extents[y_grid_ - 1][x_grid_]); v_edges_3D_.resize(boost::extents[num_layers_][y_grid_][x_grid_]); h_edges_3D_.resize(boost::extents[num_layers_][y_grid_][x_grid_]); for (int i = 0; i < y_grid_; i++) { for (int j = 0; j < x_grid_ - 1; j++) { // 2D edge initialization h_edges_[i][j].cap = h_capacity_; h_edges_[i][j].usage = 0; h_edges_[i][j].est_usage = 0; h_edges_[i][j].red = 0; h_edges_[i][j].last_usage = 0; // 3D edge initialization for (int k = 0; k < num_layers_; k++) { h_edges_3D_[k][i][j].cap = h_capacity_3D_[k]; h_edges_3D_[k][i][j].usage = 0; h_edges_3D_[k][i][j].red = 0; } } } for (int i = 0; i < y_grid_ - 1; i++) { for (int j = 0; j < x_grid_; j++) { // 2D edge initialization v_edges_[i][j].cap = v_capacity_; v_edges_[i][j].usage = 0; v_edges_[i][j].est_usage = 0; v_edges_[i][j].red = 0; v_edges_[i][j].last_usage = 0; // 3D edge initialization for (int k = 0; k < num_layers_; k++) { v_edges_3D_[k][i][j].cap = v_capacity_3D_[k]; v_edges_3D_[k][i][j].usage = 0; v_edges_3D_[k][i][j].red = 0; } } } } void FastRouteCore::setNumAdjustments(int nAdjustments) { num_adjust_ = nAdjustments; } void FastRouteCore::setMaxNetDegree(int deg) { max_degree_ = deg; } void FastRouteCore::addAdjustment(int x1, int y1, int x2, int y2, int layer, int reducedCap, bool isReduce) { const int k = layer - 1; if (y1 == y2) { // horizontal edge const int cap = h_edges_3D_[k][y1][x1].cap; int reduce; if (cap - reducedCap < 0) { if (isReduce) { if (verbose_) logger_->warn(GRT, 113, "Underflow in reduce: cap, reducedCap: {}, {}", cap, reducedCap); } reduce = 0; } else { reduce = cap - reducedCap; } h_edges_3D_[k][y1][x1].cap = reducedCap; if (!isReduce) { const int increase = reducedCap - cap; h_edges_[y1][x1].cap += increase; } else { h_edges_3D_[k][y1][x1].red += reduce; } h_edges_[y1][x1].cap -= reduce; h_edges_[y1][x1].red += reduce; } else if (x1 == x2) { // vertical edge const int cap = v_edges_3D_[k][y1][x1].cap; int reduce; if (cap - reducedCap < 0) { if (isReduce) { if (verbose_) logger_->warn(GRT, 114, "Underflow in reduce: cap, reducedCap: {}, {}", cap, reducedCap); } reduce = 0; } else { reduce = cap - reducedCap; } v_edges_3D_[k][y1][x1].cap = reducedCap; if (!isReduce) { int increase = reducedCap - cap; v_edges_[y1][x1].cap += increase; } else { v_edges_3D_[k][y1][x1].red += reduce; } v_edges_[y1][x1].cap -= reduce; v_edges_[y1][x1].red += reduce; } } void FastRouteCore::applyVerticalAdjustments(const odb::Point& first_tile, const odb::Point& last_tile, int layer, int first_tile_reduce, int last_tile_reduce) { for (int x = first_tile.getX(); x <= last_tile.getX(); x++) { for (int y = first_tile.getY(); y < last_tile.getY(); y++) { if (x == first_tile.getX()) { int edge_cap = getEdgeCapacity(x, y, x, y + 1, layer); edge_cap -= first_tile_reduce; if (edge_cap < 0) edge_cap = 0; addAdjustment(x, y, x, y + 1, layer, edge_cap, true); } else if (x == last_tile.getX()) { int edge_cap = getEdgeCapacity(x, y, x, y + 1, layer); edge_cap -= last_tile_reduce; if (edge_cap < 0) edge_cap = 0; addAdjustment(x, y, x, y + 1, layer, edge_cap, true); } else { addAdjustment(x, y, x, y + 1, layer, 0, true); } } } } void FastRouteCore::applyHorizontalAdjustments(const odb::Point& first_tile, const odb::Point& last_tile, int layer, int first_tile_reduce, int last_tile_reduce) { for (int x = first_tile.getX(); x < last_tile.getX(); x++) { for (int y = first_tile.getY(); y <= last_tile.getY(); y++) { if (y == first_tile.getY()) { int edge_cap = getEdgeCapacity(x, y, x + 1, y, layer); edge_cap -= first_tile_reduce; if (edge_cap < 0) edge_cap = 0; addAdjustment(x, y, x + 1, y, layer, edge_cap, true); } else if (y == last_tile.getY()) { int edge_cap = getEdgeCapacity(x, y, x + 1, y, layer); edge_cap -= last_tile_reduce; if (edge_cap < 0) edge_cap = 0; addAdjustment(x, y, x + 1, y, layer, edge_cap, true); } else { addAdjustment(x, y, x + 1, y, layer, 0, true); } } } } void FastRouteCore::addVerticalAdjustments( const odb::Point& first_tile, const odb::Point& last_tile, const int layer, const interval<int>::type& first_tile_reduce_interval, const interval<int>::type& last_tile_reduce_interval) { // add intervals to set for each tile for (int x = first_tile.getX(); x <= last_tile.getX(); x++) { for (int y = first_tile.getY(); y < last_tile.getY(); y++) { if (x == first_tile.getX()) { vertical_blocked_intervals_[std::make_tuple(x, y, layer)] += first_tile_reduce_interval; } else if (x == last_tile.getX()) { vertical_blocked_intervals_[std::make_tuple(x, y, layer)] += last_tile_reduce_interval; } else { addAdjustment(x, y, x, y + 1, layer, 0, true); } } } } void FastRouteCore::addHorizontalAdjustments( const odb::Point& first_tile, const odb::Point& last_tile, const int layer, const interval<int>::type& first_tile_reduce_interval, const interval<int>::type& last_tile_reduce_interval) { // add intervals to each tiles for (int x = first_tile.getX(); x < last_tile.getX(); x++) { for (int y = first_tile.getY(); y <= last_tile.getY(); y++) { if (y == first_tile.getY()) { horizontal_blocked_intervals_[std::make_tuple(x, y, layer)] += first_tile_reduce_interval; } else if (y == last_tile.getY()) { horizontal_blocked_intervals_[std::make_tuple(x, y, layer)] += last_tile_reduce_interval; } else { addAdjustment(x, y, x + 1, y, layer, 0, true); } } } } void FastRouteCore::initBlockedIntervals(std::vector<int>& track_space) { // Calculate reduce for vertical tiles for (const auto& [tile, intervals] : vertical_blocked_intervals_) { int x = std::get<0>(tile); int y = std::get<1>(tile); int layer = std::get<2>(tile); int edge_cap = getEdgeCapacity(x, y, x, y + 1, layer); if (edge_cap > 0) { int reduce = 0; for (auto interval_it : intervals) { reduce += ceil(static_cast<float>( std::abs(interval_it.upper() - interval_it.lower())) / track_space[layer - 1]); } edge_cap -= reduce; if (edge_cap < 0) edge_cap = 0; addAdjustment(x, y, x, y + 1, layer, edge_cap, true); } } // Calculate reduce for horizontal tiles for (const auto& [tile, intervals] : horizontal_blocked_intervals_) { int x = std::get<0>(tile); int y = std::get<1>(tile); int layer = std::get<2>(tile); int edge_cap = getEdgeCapacity(x, y, x + 1, y, layer); if (edge_cap > 0) { int reduce = 0; for (const auto& interval_it : intervals) { reduce += ceil(static_cast<float>( std::abs(interval_it.upper() - interval_it.lower())) / track_space[layer - 1]); } edge_cap -= reduce; if (edge_cap < 0) edge_cap = 0; addAdjustment(x, y, x + 1, y, layer, edge_cap, true); } } } int FastRouteCore::getEdgeCapacity(int x1, int y1, int x2, int y2, int layer) { const int k = layer - 1; if (y1 == y2) { // horizontal edge return h_edges_3D_[k][y1][x1].cap; } else if (x1 == x2) { // vertical edge return v_edges_3D_[k][y1][x1].cap; } else { logger_->error( GRT, 214, "Cannot get edge capacity: edge is not vertical or horizontal."); return 0; } } int FastRouteCore::getEdgeCapacity(FrNet* net, int x1, int y1, EdgeDirection direction) { int cap = 0; // get 2D edge capacity respecting layer restrictions for (int l = net->getMinLayer(); l <= net->getMaxLayer(); l++) { if (direction == EdgeDirection::Horizontal) { cap += h_edges_3D_[l][y1][x1].cap; } else { cap += v_edges_3D_[l][y1][x1].cap; } } return cap; } void FastRouteCore::incrementEdge3DUsage(int x1, int y1, int x2, int y2, int layer) { const int k = layer - 1; if (y1 == y2) { // horizontal edge for (int x = x1; x < x2; x++) { h_edges_3D_[k][y1][x].usage++; } } else if (x1 == x2) { // vertical edge for (int y = y1; y < y2; y++) { v_edges_3D_[k][y][x1].usage++; } } } void FastRouteCore::initAuxVar() { tree_order_cong_.clear(); initNetAuxVars(); grid_hv_ = x_range_ * y_range_; parent_x1_.resize(boost::extents[y_grid_][x_grid_]); parent_y1_.resize(boost::extents[y_grid_][x_grid_]); parent_x3_.resize(boost::extents[y_grid_][x_grid_]); parent_y3_.resize(boost::extents[y_grid_][x_grid_]); } void FastRouteCore::initNetAuxVars() { int node_count = netCount(); seglist_.resize(node_count); sttrees_.resize(node_count); gxs_.resize(node_count); gys_.resize(node_count); gs_.resize(node_count); } NetRouteMap FastRouteCore::getRoutes() { NetRouteMap routes; for (int netID = 0; netID < netCount(); netID++) { if (nets_[netID]->isRouted()) continue; nets_[netID]->setIsRouted(true); odb::dbNet* db_net = nets_[netID]->getDbNet(); GRoute& route = routes[db_net]; std::unordered_set<GSegment, GSegmentHash> net_segs; const auto& treeedges = sttrees_[netID].edges; const int num_edges = sttrees_[netID].num_edges(); for (int edgeID = 0; edgeID < num_edges; edgeID++) { const TreeEdge* treeedge = &(treeedges[edgeID]); if (treeedge->len > 0) { int routeLen = treeedge->route.routelen; const std::vector<short>& gridsX = treeedge->route.gridsX; const std::vector<short>& gridsY = treeedge->route.gridsY; const std::vector<short>& gridsL = treeedge->route.gridsL; int lastX = tile_size_ * (gridsX[0] + 0.5) + x_corner_; int lastY = tile_size_ * (gridsY[0] + 0.5) + y_corner_; int lastL = gridsL[0]; for (int i = 1; i <= routeLen; i++) { const int xreal = tile_size_ * (gridsX[i] + 0.5) + x_corner_; const int yreal = tile_size_ * (gridsY[i] + 0.5) + y_corner_; GSegment segment = GSegment(lastX, lastY, lastL + 1, xreal, yreal, gridsL[i] + 1); lastX = xreal; lastY = yreal; lastL = gridsL[i]; if (net_segs.find(segment) == net_segs.end()) { net_segs.insert(segment); route.push_back(segment); } } } } } return routes; } NetRouteMap FastRouteCore::getPlanarRoutes() { NetRouteMap routes; // Get routes before layer assignment for (int netID = 0; netID < netCount(); netID++) { auto fr_net = nets_[netID]; odb::dbNet* db_net = fr_net->getDbNet(); GRoute& route = routes[db_net]; std::unordered_set<GSegment, GSegmentHash> net_segs; const auto& treeedges = sttrees_[netID].edges; const int num_edges = sttrees_[netID].num_edges(); for (int edgeID = 0; edgeID < num_edges; edgeID++) { const TreeEdge* treeedge = &(treeedges[edgeID]); if (treeedge->len > 0) { int routeLen = treeedge->route.routelen; const std::vector<short>& gridsX = treeedge->route.gridsX; const std::vector<short>& gridsY = treeedge->route.gridsY; int lastX = tile_size_ * (gridsX[0] + 0.5) + x_corner_; int lastY = tile_size_ * (gridsY[0] + 0.5) + y_corner_; // defines the layer used for vertical edges are still 2D int layer_h = 0; // defines the layer used for horizontal edges are still 2D int layer_v = 0; if (layer_orientation_ != 0) { layer_h = 1; layer_v = 2; } else { layer_h = 2; layer_v = 1; } int second_x = tile_size_ * (gridsX[1] + 0.5) + x_corner_; int lastL = (lastX == second_x) ? layer_v : layer_h; for (int i = 1; i <= routeLen; i++) { const int xreal = tile_size_ * (gridsX[i] + 0.5) + x_corner_; const int yreal = tile_size_ * (gridsY[i] + 0.5) + y_corner_; GSegment segment; if (lastX == xreal) { // if change direction add a via to change the layer if (lastL == layer_h) { segment = GSegment( lastX, lastY, lastL + 1, lastX, lastY, layer_v + 1); if (net_segs.find(segment) == net_segs.end()) { net_segs.insert(segment); route.push_back(segment); } } lastL = layer_v; segment = GSegment(lastX, lastY, lastL + 1, xreal, yreal, lastL + 1); } else { // if change direction add a via to change the layer if (lastL == layer_v) { segment = GSegment( lastX, lastY, lastL + 1, lastX, lastY, layer_h + 1); if (net_segs.find(segment) == net_segs.end()) { net_segs.insert(segment); route.push_back(segment); } } lastL = layer_h; segment = GSegment(lastX, lastY, lastL + 1, xreal, yreal, lastL + 1); } lastX = xreal; lastY = yreal; if (net_segs.find(segment) == net_segs.end()) { net_segs.insert(segment); route.push_back(segment); } } } } } return routes; } void FastRouteCore::updateDbCongestion() { auto block = db_->getChip()->getBlock(); auto db_gcell = block->getGCellGrid(); if (db_gcell) db_gcell->resetGrid(); else db_gcell = odb::dbGCellGrid::create(block); db_gcell->addGridPatternX(x_corner_, x_grid_, tile_size_); db_gcell->addGridPatternY(y_corner_, y_grid_, tile_size_); auto db_tech = db_->getTech(); for (int k = 0; k < num_layers_; k++) { auto layer = db_tech->findRoutingLayer(k + 1); if (layer == nullptr) { continue; } const unsigned short capH = h_capacity_3D_[k]; const unsigned short capV = v_capacity_3D_[k]; for (int y = 0; y < y_grid_; y++) { for (int x = 0; x < x_grid_; x++) { const unsigned short blockageH = h_edges_3D_[k][y][x].red; const unsigned short blockageV = v_edges_3D_[k][y][x].red; const unsigned short usageH = h_edges_3D_[k][y][x].usage + blockageH; const unsigned short usageV = v_edges_3D_[k][y][x].usage + blockageV; db_gcell->setCapacity(layer, x, y, capH, capV, 0); db_gcell->setUsage(layer, x, y, usageH, usageV, 0); db_gcell->setBlockage(layer, x, y, blockageH, blockageV, 0); } } } } NetRouteMap FastRouteCore::run() { if (netCount() == 0) { return getRoutes(); } v_used_ggrid_.clear(); h_used_ggrid_.clear(); int tUsage; int cost_step; int maxOverflow = 0; int minoflrnd = 0; int bwcnt = 0; // Init grid variables when debug mode is actived if (debug_->isOn()) { fastrouteRender()->setGridVariables(tile_size_, x_corner_, y_corner_); } // TODO: check this size int max_degree2 = 2 * max_degree_; xcor_.resize(max_degree2); ycor_.resize(max_degree2); dcor_.resize(max_degree2); net_eo_.reserve(max_degree2); int THRESH_M = 20; const int ENLARGE = 15; // 5 const int ESTEP1 = 10; // 10 const int ESTEP2 = 5; // 5 const int ESTEP3 = 5; // 5 int CSTEP1 = 2; // 5 const int CSTEP2 = 2; // 3 const int CSTEP3 = 5; // 15 const int COSHEIGHT = 4; int L = 0; int VIA = 2; const int Ripvalue = -1; const bool goingLV = true; const bool noADJ = false; const int thStep1 = 10; const int thStep2 = 4; const int LVIter = 3; const int mazeRound = 500; int bmfl = BIG_INT; int minofl = BIG_INT; float LOGIS_COF = 0; int slope; int max_adj; // call FLUTE to generate RSMT and break the nets into segments (2-pin nets) via_cost_ = 0; gen_brk_RSMT(false, false, false, false, noADJ); routeLAll(true); gen_brk_RSMT(true, true, true, false, noADJ); getOverflow2D(&maxOverflow); newrouteLAll(false, true); getOverflow2D(&maxOverflow); spiralRouteAll(); newrouteZAll(10); int past_cong = getOverflow2D(&maxOverflow); convertToMazeroute(); int enlarge_ = 10; int newTH = 10; bool stopDEC = false; int upType = 1; costheight_ = COSHEIGHT; if (maxOverflow > 700) { costheight_ = 8; LOGIS_COF = 1.33; VIA = 0; THRESH_M = 0; CSTEP1 = 30; } for (int i = 0; i < LVIter; i++) { LOGIS_COF = std::max<float>(2.0 / (1 + log(maxOverflow)), LOGIS_COF); LOGIS_COF = 2.0 / (1 + log(maxOverflow)); debugPrint(logger_, GRT, "patternRouting", 1, "LV routing round {}, enlarge {}.", i, enlarge_); routeLVAll(newTH, enlarge_, LOGIS_COF); past_cong = getOverflow2Dmaze(&maxOverflow, &tUsage); enlarge_ += 5; newTH -= 5; if (newTH < 1) { newTH = 1; } } // check and fix invalid embedded trees fixEmbeddedTrees(); // past_cong = getOverflow2Dmaze( &maxOverflow); InitEstUsage(); int i = 1; costheight_ = COSHEIGHT; enlarge_ = ENLARGE; int ripup_threshold = Ripvalue; minofl = total_overflow_; stopDEC = false; slope = 20; L = 1; int cost_type = 1; InitLastUsage(upType); if (total_overflow_ > 0 && overflow_iterations_ > 0 && verbose_) { logger_->info(GRT, 101, "Running extra iterations to remove overflow."); } // debug mode Rectilinear Steiner Tree before overflow iterations if (debug_->isOn() && debug_->rectilinearSTree_) { for (int netID = 0; netID < netCount(); netID++) { if (nets_[netID]->getDbNet() == debug_->net_ && !nets_[netID]->isRouted()) { StTreeVisualization(sttrees_[netID], nets_[netID], false); } } } SaveLastRouteLen(); const int max_overflow_increases = 25; float slack_th = std::numeric_limits<float>::min(); // set overflow_increases as -1 since the first iteration always sum 1 int overflow_increases = -1; int last_total_overflow = 0; float overflow_reduction_percent = -1; while (total_overflow_ > 0 && i <= overflow_iterations_ && overflow_increases <= max_overflow_increases) { if (THRESH_M > 15) { THRESH_M -= thStep1; } else if (THRESH_M >= 2) { THRESH_M -= thStep2; } else { THRESH_M = 0; } if (THRESH_M <= 0) { THRESH_M = 0; } if (total_overflow_ > 2000) { enlarge_ += ESTEP1; // ENLARGE+(i-1)*ESTEP; cost_step = CSTEP1; updateCongestionHistory(upType, stopDEC, max_adj); } else if (total_overflow_ < 500) { cost_step = CSTEP3; enlarge_ += ESTEP3; ripup_threshold = -1; updateCongestionHistory(upType, stopDEC, max_adj); } else { cost_step = CSTEP2; enlarge_ += ESTEP2; updateCongestionHistory(upType, stopDEC, max_adj); } if (total_overflow_ > 15000 && maxOverflow > 400) { enlarge_ = std::max(x_grid_, y_grid_) / 30; slope = BIG_INT; if (i == 5) { VIA = 0; LOGIS_COF = 1.33; ripup_threshold = -1; // cost_type = 3; } else if (i > 6) { if (i % 2 == 0) { LOGIS_COF += 0.5; } if (i > 40) { break; } } if (i > 10) { cost_type = 1; ripup_threshold = 0; } } enlarge_ = std::min(enlarge_, x_grid_ / 2); costheight_ += cost_step; mazeedge_threshold_ = THRESH_M; if (upType == 3) { LOGIS_COF = std::max<float>(2.0 / (1 + log(maxOverflow + max_adj)), LOGIS_COF); } else { LOGIS_COF = std::max<float>(2.0 / (1 + log(maxOverflow)), LOGIS_COF); } if (i == 8) { L = 0; upType = 2; InitLastUsage(upType); } if (maxOverflow == 1) { // L = 0; ripup_threshold = -1; slope = 5; } if (maxOverflow > 300 && past_cong > 15000) { L = 0; } mazeRouteMSMD(i, enlarge_, costheight_, ripup_threshold, mazeedge_threshold_, !(i % 3), cost_type, LOGIS_COF, VIA, slope, L, slack_th); int last_cong = past_cong; past_cong = getOverflow2Dmaze(&maxOverflow, &tUsage); if (minofl > past_cong) { minofl = past_cong; minoflrnd = i; } if (i == 8) { L = 1; } i++; if (past_cong < 200 && i > 30 && upType == 2 && max_adj <= 20) { upType = 4; stopDEC = true; } if (maxOverflow < 150) { if (i == 20 && past_cong > 200) { if (verbose_) { logger_->info(GRT, 103, "Extra Run for hard benchmark."); } L = 0; upType = 3; stopDEC = true; slope = 5; mazeRouteMSMD(i, enlarge_, costheight_, ripup_threshold, mazeedge_threshold_, !(i % 3), cost_type, LOGIS_COF, VIA, slope, L, slack_th); last_cong = past_cong; past_cong = getOverflow2Dmaze(&maxOverflow, &tUsage); str_accu(12); L = 1; stopDEC = false; slope = 3; upType = 2; } if (i == 35 && tUsage > 800000) { str_accu(25); } if (i == 50 && tUsage > 800000) { str_accu(40); } } if (i > 50) { upType = 4; if (i > 70) { stopDEC = true; } } if (past_cong > 0.7 * last_cong) { costheight_ += CSTEP3; } if (past_cong >= last_cong) { VIA = 0; } if (past_cong < bmfl) { bwcnt = 0; if (i > 140 || (i > 80 && past_cong < 20)) { copyRS(); bmfl = past_cong; L = 0; mazeRouteMSMD(i, enlarge_, costheight_, ripup_threshold, mazeedge_threshold_, !(i % 3), cost_type, LOGIS_COF, VIA, slope, L, slack_th); last_cong = past_cong; past_cong = getOverflow2Dmaze(&maxOverflow, &tUsage); if (past_cong < last_cong) { copyRS(); bmfl = past_cong; } L = 1; if (minofl > past_cong) { minofl = past_cong; minoflrnd = i; } } } else { bwcnt++; } if (bmfl > 10) { if (bmfl > 30 && bmfl < 72 && bwcnt > 50) { break; } if (bmfl < 30 && bwcnt > 50) { break; } if (i >= mazeRound) { getOverflow2Dmaze(&maxOverflow, &tUsage); break; } } if (i >= mazeRound) { getOverflow2Dmaze(&maxOverflow, &tUsage); break; } if (total_overflow_ > last_total_overflow) { overflow_increases++; } if (last_total_overflow > 0) { overflow_reduction_percent = std::max(overflow_reduction_percent, 1 - ((float) total_overflow_ / last_total_overflow)); } last_total_overflow = total_overflow_; // generate DRC report each interval if (congestion_report_iter_step_ && i % congestion_report_iter_step_ == 0) { saveCongestion(i); } } // end overflow iterations // Debug mode Tree 2D after overflow iterations if (debug_->isOn() && debug_->tree2D_) { for (int netID = 0; netID < netCount(); netID++) { if (nets_[netID]->getDbNet() == debug_->net_ && !nets_[netID]->isRouted()) { StTreeVisualization(sttrees_[netID], nets_[netID], false); } } } has_2D_overflow_ = total_overflow_ > 0; if (minofl > 0) { debugPrint(logger_, GRT, "congestionIterations", 1, "Minimal overflow {} occurring at round {}.", minofl, minoflrnd); copyBR(); } if (overflow_increases > max_overflow_increases) { if (verbose_) logger_->warn( GRT, 230, "Congestion iterations cannot increase overflow, reached the " "maximum number of times the total overflow can be increased."); } freeRR(); removeLoops(); getOverflow2Dmaze(&maxOverflow, &tUsage); layerAssignment(); costheight_ = 3; via_cost_ = 1; if (goingLV && past_cong == 0) { mazeRouteMSMDOrder3D(enlarge_, 0, 20, layer_orientation_); mazeRouteMSMDOrder3D(enlarge_, 0, 12, layer_orientation_); } fillVIA(); const int finallength = getOverflow3D(); const int numVia = threeDVIA(); checkRoute3D(); if (verbose_) { logger_->info(GRT, 111, "Final number of vias: {}", numVia); logger_->info(GRT, 112, "Final usage 3D: {}", (finallength + 3 * numVia)); } // Debug mode Tree 3D after layer assignament if (debug_->isOn() && debug_->tree3D_) { for (int netID = 0; netID < netCount(); netID++) { if (nets_[netID]->getDbNet() == debug_->net_ && !nets_[netID]->isRouted()) { StTreeVisualization(sttrees_[netID], nets_[netID], true); } } } NetRouteMap routes = getRoutes(); net_eo_.clear(); return routes; } void FastRouteCore::setVerbose(bool v) { verbose_ = v; } void FastRouteCore::setUpdateSlack(int u) { update_slack_ = u; } void FastRouteCore::setMakeWireParasiticsBuilder( AbstractMakeWireParasitics* builder) { parasitics_builder_ = builder; } void FastRouteCore::setOverflowIterations(int iterations) { overflow_iterations_ = iterations; } void FastRouteCore::setCongestionReportIterStep(int congestion_report_iter_step) { congestion_report_iter_step_ = congestion_report_iter_step; } void FastRouteCore::setCongestionReportFile(const char* congestion_file_name) { congestion_file_name_ = congestion_file_name; } void FastRouteCore::setGridMax(int x_max, int y_max) { x_grid_max_ = x_max; y_grid_max_ = y_max; } std::vector<int> FastRouteCore::getOriginalResources() { std::vector<int> original_resources(num_layers_); for (int l = 0; l < num_layers_; l++) { original_resources[l] += (v_capacity_3D_[l] + h_capacity_3D_[l]) * y_grid_ * x_grid_; } return original_resources; } void FastRouteCore::computeCongestionInformation() { cap_per_layer_.resize(num_layers_); usage_per_layer_.resize(num_layers_); overflow_per_layer_.resize(num_layers_); max_h_overflow_.resize(num_layers_); max_v_overflow_.resize(num_layers_); for (int l = 0; l < num_layers_; l++) { cap_per_layer_[l] = 0; usage_per_layer_[l] = 0; overflow_per_layer_[l] = 0; max_h_overflow_[l] = 0; max_v_overflow_[l] = 0; for (int i = 0; i < y_grid_; i++) { for (int j = 0; j < x_grid_ - 1; j++) { cap_per_layer_[l] += h_edges_3D_[l][i][j].cap; usage_per_layer_[l] += h_edges_3D_[l][i][j].usage; const int overflow = h_edges_3D_[l][i][j].usage - h_edges_3D_[l][i][j].cap; if (overflow > 0) { overflow_per_layer_[l] += overflow; max_h_overflow_[l] = std::max(max_h_overflow_[l], overflow); } } } for (int i = 0; i < y_grid_ - 1; i++) { for (int j = 0; j < x_grid_; j++) { cap_per_layer_[l] += v_edges_3D_[l][i][j].cap; usage_per_layer_[l] += v_edges_3D_[l][i][j].usage; const int overflow = v_edges_3D_[l][i][j].usage - v_edges_3D_[l][i][j].cap; if (overflow > 0) { overflow_per_layer_[l] += overflow; max_v_overflow_[l] = std::max(max_v_overflow_[l], overflow); } } } } } //////////////////////////////////////////////////////////////// const char* getNetName(odb::dbNet* db_net); const char* FrNet::getName() const { return getNetName(getDbNet()); } //////////////////////////////////////////////////////////////// void FastRouteCore::setDebugOn( std::unique_ptr<AbstractFastRouteRenderer> renderer) { debug_->renderer_ = std::move(renderer); } void FastRouteCore::setDebugSteinerTree(bool steinerTree) { debug_->steinerTree_ = steinerTree; } void FastRouteCore::setDebugTree2D(bool tree2D) { debug_->tree2D_ = tree2D; } void FastRouteCore::setDebugTree3D(bool tree3D) { debug_->tree3D_ = tree3D; } void FastRouteCore::setDebugNet(const odb::dbNet* net) { debug_->net_ = net; } void FastRouteCore::setDebugRectilinearSTree(bool rectiliniarSTree) { debug_->rectilinearSTree_ = rectiliniarSTree; } void FastRouteCore::setSttInputFilename(const char* file_name) { debug_->sttInputFileName_ = std::string(file_name); } bool FastRouteCore::hasSaveSttInput() { return (debug_->sttInputFileName_ != ""); } std::string FastRouteCore::getSttInputFileName() { return debug_->sttInputFileName_; } const odb::dbNet* FastRouteCore::getDebugNet() { return debug_->net_; } void FastRouteCore::steinerTreeVisualization(const stt::Tree& stree, FrNet* net) { if (!debug_->isOn()) { return; } fastrouteRender()->highlight(net); fastrouteRender()->setIs3DVisualization( false); //()isnt 3D because is steiner tree generated by stt fastrouteRender()->setSteinerTree(stree); fastrouteRender()->setTreeStructure(TreeStructure::steinerTreeByStt); fastrouteRender()->redrawAndPause(); } void FastRouteCore::StTreeVisualization(const StTree& stree, FrNet* net, bool is3DVisualization) { if (!debug_->isOn()) { return; } fastrouteRender()->highlight(net); fastrouteRender()->setIs3DVisualization(is3DVisualization); fastrouteRender()->setStTreeValues(stree); fastrouteRender()->setTreeStructure(TreeStructure::steinerTreeByFastroute); fastrouteRender()->redrawAndPause(); } //////////////////////////////////////////////////////////////// int FrNet::getLayerEdgeCost(int layer) const { if (edge_cost_per_layer_) return (*edge_cost_per_layer_)[layer]; else return 1; } void FrNet::addPin(int x, int y, int layer) { pin_x_.push_back(x); pin_y_.push_back(y); pin_l_.push_back(layer); } void FrNet::reset(odb::dbNet* db_net, bool is_clock, int driver_idx, int edge_cost, int min_layer, int max_layer, float slack, std::vector<int>* edge_cost_per_layer) { db_net_ = db_net; is_routed_ = false; is_critical_ = false; is_clock_ = is_clock; driver_idx_ = driver_idx; edge_cost_ = edge_cost; min_layer_ = min_layer; max_layer_ = max_layer; slack_ = slack; edge_cost_per_layer_.reset(edge_cost_per_layer); pin_x_.clear(); pin_y_.clear(); pin_l_.clear(); } } // namespace grt
526f1e5ba27d2e1bbb611038709e652964448645
fa4232a6eadc3406a21994d851ef6731780e6cac
/src/[M] 845. Longest Mountain in Array.cpp
52c81d6d6691ac87b90c5b9f66e710680663b2b2
[]
no_license
freezer-glp/leetcode-submit
8244bfcda0729bd24218e94a5fd8471763373ac0
e3e8ff335b86a039df6ca2e5a9e7ed3ca8a05eb0
refs/heads/master
2021-09-20T09:03:00.515440
2021-09-09T14:20:22
2021-09-09T14:20:22
26,519,223
0
0
null
null
null
null
UTF-8
C++
false
false
1,386
cpp
[M] 845. Longest Mountain in Array.cpp
/* Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold: B.length >= 3 There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1] (Note that B could be any subarray of A, including the entire array A.) Given an array A of integers, return the length of the longest mountain. Return 0 if there is no mountain. Example 1: Input: [2,1,4,7,3,2,5] Output: 5 Explanation: The largest mountain is [1,4,7,3,2] which has length 5. Example 2: Input: [2,2,2] Output: 0 Explanation: There is no mountain. */ class Solution { public: int longestMountain(vector<int>& A) { int n = A.size(); if (!n) return 0; int max = 0; for (int i = 0; i < n;) { int tmp = 0; if (i + 1 < n && A[i] >= A[i+1]) { i++; continue; } if (i == n - 1) break; int j = i; while (j + 1 < n && A[j] < A[j+1]) j++; if (j == n - 1) break; if (j < n) { tmp += (j - i + 1); int k = j; while(k+1 < n && A[k] > A[k+1]) k++; if (k == j) { i = k; continue; } if (k < n) tmp += (k - j); else tmp += (k - j -1); max = std::max(max, tmp); i = k; } else break; } return max; } };
fe00a4cad98c62eaff92d3ccb5c4e56d7f9b26bf
55f2a154d1ce3f0b54714176a3d5182a25ea47f7
/QFT/LorentzVector.h
353fbb760b197f89edeabf6ab6926a42fc45eb1a
[]
no_license
zaynesember/CompPhys
9c2f1478a2c8a69168448539103130f17cd3547f
7be98ae37a3c2e0705669906e26bdd5cedad7920
refs/heads/master
2021-01-14T02:24:46.485321
2020-02-19T20:57:08
2020-02-19T20:57:08
242,570,308
1
0
null
null
null
null
UTF-8
C++
false
false
1,262
h
LorentzVector.h
#ifndef LORENTZVECTOR_H #define LORENTZVECTOR_H #include <cmath> #include <math.h> #include <string> #include <iostream> #include <sstream> // Minimal four-vector class class LorentzVector{ // Partially stolen from ROOT::TLorentzVector (https://root.cern.ch/doc/master/classTLorentzVector.html) public: LorentzVector(double ix, double iy, double iz, double it) : x_(ix),y_(iy),z_(iz),t_(it){}; inline double x() const { return x_;} inline double y() const { return y_;} inline double z() const { return z_;} inline double t() const { return t_;} inline double e() const { return t_;} double perp() const ; double perp2() const ; double mass() const ; double mass2() const ; double p() const ; double phi() const ; double theta() const ; double cosTheta() const ; double eta() const ; std::string PrintPtEtaPhiM() const ; std::string PrintPEtaPhiE() const ; std::string PrintXYZT() const ; std::string Print() const ; LorentzVector operator+( const LorentzVector & right) const ; LorentzVector operator-( const LorentzVector & right) const ; double operator*(const LorentzVector & right) ; protected : double x_; double y_; double z_; double t_; }; void testLorentzVectors(); #endif
50ac54438f8ee32eb4de6464c88a195a530b95a6
2967fb4c6330941ca42fb8bdce47504050a32ae2
/c++ project/Sword finger offer/O56/O56-3.cpp
d67b5b2e44f49446b1611ed65622dfb70804f366
[]
no_license
wxx17395/Leetcode
988ec692ac4f599fbd23f65b92e835972aff1bea
eb568d571e76fd4c2fc3eabadd547680516d2f1e
refs/heads/master
2023-06-02T17:16:31.980772
2021-06-23T06:56:32
2021-06-23T06:56:32
281,373,596
0
0
null
null
null
null
UTF-8
C++
false
false
380
cpp
O56-3.cpp
#include <bits/stdc++.h> using namespace std; class Solution { public: int singleNumbers(vector<int>& nums) { int res = nums[0]; for (int i = 1; i < nums.size(); ++i){ res = res ^ nums[i]; } return res; } }; int main() { vector<int> nums{1,1,6,2,2,3,3}; cout << Solution().singleNumbers(nums) << endl; return 0; }
d5610913267a807f8e86d3bfca713f62c3045a07
741eadadf19dc7bd5acf9718ba27913d12a34ab7
/src/SimpleMessenger.cpp
fd0a4526953f7544881d053e43f4d2ecfca50a5d
[ "MIT" ]
permissive
igormich/MessengerCPP
bf449251caf7b6ef34f48a540f82d37d684e4144
fcc4d3e259ba5a395439cb341ecaaefc7e398ea3
refs/heads/main
2023-05-31T14:43:15.801986
2021-06-23T11:15:14
2021-06-23T11:15:14
379,202,074
0
0
null
null
null
null
UTF-8
C++
false
false
1,400
cpp
SimpleMessenger.cpp
// SimpleMessenger.cpp: определяет точку входа для приложения. // #include "SimpleMessenger.h" #include "ChatServer.h" #include "ChatClient.h" #include "TcpServer.h" #include "utils.h" #include <iostream> #include<sstream> #include <vector> #include <algorithm> #include <stdio.h> #include<conio.h> #include <string.h> #include <cerrno> using namespace std; string name = ""; int main(int argc, char* argv[]) { #ifdef WIN32 // Initialize Winsock int iResult; WSADATA wsaData; iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { std::cout << "WSAStartup failed: " << iResult << std::endl; return 0; } #endif if (argc == 2) { int port = atoi(argv[1]); ChatServer chat; chat.start(port); } else if (argc == 4) { name = argv[3]; int port = atoi(argv[2]); ChatClient chatClient(name); auto sendFunction = client(argv[1], port, [&chatClient](string s) {chatClient.recv(s); }); if (sendFunction == NULL) return 0; chatClient.setSendFunction(sendFunction); chatClient.startRead(); } else { cout << "Please run with following arguments:" << endl; cout << "For server: messenger PORT" << endl; cout << "For client: messenger IP PORT NAME" << endl; cout << "Usage example: messenger 196.168.0.21 666 User" << endl; return 0; } return 0; }
21d938c85be11c75576b2e43298445db607061cc
ac59696695eaf6271aa9d154fa1e34d267cb1851
/leetcode53.cpp
113e6ac7d6b5ce33426d094c34701a0e38b5aa08
[]
no_license
hanwenlei/Leetcode
35dc21805292e0b309e863c449a6117e66eac803
e65d11f71be8a6d806f4aadcff5f6a4aeb695b1f
refs/heads/master
2020-05-15T04:42:31.397408
2019-04-18T13:25:28
2019-04-18T13:25:28
182,091,998
1
0
null
null
null
null
UTF-8
C++
false
false
463
cpp
leetcode53.cpp
#include<iostream> #include<vector> #include<algorithm> #include<cstring> using namespace std; class Solution { public: int maxSubArray(vector<int>& nums) { int length = nums.size(); vector<int> dp(length); memcpy(dp.data(), nums.data(), length*sizeof(int)); for(int i = 1; i < length; ++i) { dp[i] = max(dp[i-1]+nums[i], dp[i]); } return *max_element(dp.begin(), dp.end()); } };
95a51985568d6cb7965c01082a65c7ddca3e1639
5df1a677af9379c9a82f1b29359a65ad8cbc385e
/easyctf/xor.cpp
b27a36a408cf964677a12910c0ff02affb698b10
[]
no_license
heyshb/Competitive-Programming
92741a4e7234e1ebce685c1b870f1287bee18f1a
363ef78d950afb53f0e5f1d2329f27dd7b9a44c2
refs/heads/master
2021-12-15T03:12:37.676111
2021-12-01T14:32:25
2021-12-01T14:32:25
122,315,094
1
0
null
null
null
null
UTF-8
C++
false
false
366
cpp
xor.cpp
#include <bits/stdc++.h> using namespace std; int main() { char s[100]; //scanf("%s",s); int len = 0; char c = getchar(); while(c != '\n') { s[len++] = c; c = getchar(); } //printf("%s\n",s); for (int i=0;i<=128;i++) { for (int j=0;j<len;j++)s[j] ^= i; for (int j=0;j<len;j++)printf("%c",s[j]);puts(""); for (int j=0;j<len;j++)s[j] ^= i; } }
312dc7ca4c4e5503fc40f5ec05d5a4ed4bf57a39
ed4e9404a47e20a267d71ce305634cf75ea2aaca
/Subsystems/Vision.cpp
d61bf5d24189ffc92002d9a4f3fd1e31b7088081
[]
no_license
FRCTeam1073-TheForceTeam/robot14
9cfbd66b5e9006e7116d2cad44584a7b0d5ebce0
ee1b18849613a52799e8be89a0579771b1c973e8
refs/heads/master
2020-05-19T10:41:23.081962
2014-06-29T15:01:43
2014-06-29T15:01:43
15,571,667
0
0
null
2014-05-23T18:04:06
2014-01-01T23:12:41
C++
UTF-8
C++
false
false
985
cpp
Vision.cpp
/* FIRST Team 1073's RobotBuilder (0.0.2) for WPILibExtensions --- Do not mix this code with any other version of RobotBuilder! */ #include "Vision.h" #include "../Robotmap.h" Vision::Vision() : Subsystem("Vision") { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS visionTable = 0; } void Vision::InitDefaultCommand() { // Set the default command for a subsystem here. //SetDefaultCommand(new MySpecialCommand()); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND } // Put methods for controlling this subsystem // here. Call these from Commands. bool Vision::IsHot(){ bool isHot = true; try { if (visionTable == 0) visionTable = NetworkTable::GetTable("visionTable"); isHot = visionTable->GetBoolean("Hot"); } catch(...) { printf("Network Table IsHot failed\n"); } return isHot; }
6494895091d210ac25d56bb68a832dfc92ba992f
51c795ce880d383623551271b30f0f4d266a998a
/src/zlibbuffer.h
f1a0bdc3cf946fdbc3a01e889380368d7ca6593d
[]
no_license
timofonic/proximodo
53329f0720101514621fcbe4e06d07ed1d9afca3
bb860b4d9c3460f94c7da4e0fc98fa88804265d0
refs/heads/master
2017-12-02T13:35:12.925643
2010-11-22T15:00:13
2010-11-22T15:00:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,018
h
zlibbuffer.h
//------------------------------------------------------------------ // //this file is part of Proximodo //Copyright (C) 2004 Antony BOUCHER ( kuruden@users.sourceforge.net ) // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // //------------------------------------------------------------------ // Modifications: (date, author, description) // //------------------------------------------------------------------ #ifndef __zlibbuffer__ #define __zlibbuffer__ #include <zlib.h> // (zlib 1.2.2) #include <string> #include <sstream> using namespace std; /* This class is a simple container for a zlib stream. One can feed it * with compressed (resp. uncompressed) data then immediately read * uncompressed (resp. compressed) data. * The same object can be used for compression/decompression, depending * on the value of 'shrink' when calling the reset() method. * Inflating automatically detects gzip/deflate input. * Deflating will generate gzip/deflate formatted data depending on 'modeGzip'. */ class CZlibBuffer { public: CZlibBuffer(); ~CZlibBuffer(); bool reset(bool shrink, bool modeGzip = false); void feed(string data); void dump(); void read(string& data); void free(); private: bool modeGzip; bool shrink; bool freed; int err; string buffer; z_stream stream; stringstream output; }; #endif
4d41ab9fd600698291e4cef3b35c0f56c3d421ab
2bf4c0b96359ef98939a56e8f42ae1231603e3f2
/libdiscover/backends/FlatpakBackend/FlatpakFetchDataJob.h
43266dac5837d894a5e9c10d46bd078facaa0754
[]
no_license
0fff5ec/discover
80d6d9d3a1043de78d9976b9412c97ffb92f71dd
718e6fdc1019f2a3153b1c45f79b90ec598a826d
refs/heads/master
2023-01-04T03:00:11.951925
2020-10-29T20:42:01
2020-10-29T20:42:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
706
h
FlatpakFetchDataJob.h
/* * SPDX-FileCopyrightText: 2017 Jan Grulich <jgrulich@redhat.com> * * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ #ifndef FLATPAKFETCHDATAJOB_H #define FLATPAKFETCHDATAJOB_H #include <QByteArray> extern "C" { #include <flatpak.h> #include <glib.h> } class FlatpakResource; namespace FlatpakRunnables { struct SizeInformation { bool valid = false; guint64 downloadSize; guint64 installedSize; }; SizeInformation fetchFlatpakSize(FlatpakInstallation *installation, FlatpakResource *app); QByteArray fetchMetadata(FlatpakInstallation *installation, FlatpakResource *app); } #endif // FLATPAKFETCHDATAJOB_H
7cd260e86192ee7d09ca32498b3188cbf6134575
a5568d035e6296b69cf73f168cad98c2913a6e74
/LeetCode/34.在排序数组中查找元素的第一个和最后一个位置.cpp
ccfd60b4940383ddb554cd53f10ba5a7a68f479b
[]
no_license
zgzhengSEU/Algorithm-Learning
820696b52ea9fe31a0ec53e12c6f83ba71babef9
094ec0dfd2edd4e64c2e861f8fc8c2c5b0eb16f8
refs/heads/main
2023-09-04T22:43:04.620494
2021-10-26T13:31:33
2021-10-26T13:31:33
393,593,294
1
0
null
null
null
null
UTF-8
C++
false
false
1,872
cpp
34.在排序数组中查找元素的第一个和最后一个位置.cpp
/* * @lc app=leetcode.cn id=34 lang=cpp * * [34] 在排序数组中查找元素的第一个和最后一个位置 * * https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/ * * algorithms * Medium (42.48%) * Likes: 1165 * Dislikes: 0 * Total Accepted: 317.7K * Total Submissions: 748.1K * Testcase Example: '[5,7,7,8,8,10]\n8' * * 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 * * 如果数组中不存在目标值 target,返回 [-1, -1]。 * * 进阶: * * * 你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗? * * * * * 示例 1: * * * 输入:nums = [5,7,7,8,8,10], target = 8 * 输出:[3,4] * * 示例 2: * * * 输入:nums = [5,7,7,8,8,10], target = 6 * 输出:[-1,-1] * * 示例 3: * * * 输入:nums = [], target = 0 * 输出:[-1,-1] * * * * 提示: * * * 0 * -10^9  * nums 是一个非递减数组 * -10^9  * * */ // @lc code=start class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { if(bsearch_first(nums, target)==-1)return {-1,-1}; return {bsearch_first(nums, target),bsearch_last(nums,target)}; } int bsearch_first(vector<int>&nums,int t){ int l=0,r=nums.size()-1; while(l<r){ int mid=l+r>>1; if(nums[mid]>=t)r=mid; else l=mid+1; } if(nums.empty()||nums[l]!=t)return -1; return l; } int bsearch_last(vector<int>&nums,int t){ int l=0,r=nums.size()-1; while(l<r){ int mid=l+r+1>>1; if(nums[mid]<=t)l=mid; else r=mid-1; } return l; } }; // @lc code=end
2fa7ab153b6d7fd66158156fdda33ffe7a503b26
87a2896f868dc13f89ecbb629d897f0ffe8a57e6
/Code/877b.cpp
846d8ca0a6ed03a0ea9ce0c9e68aff3622f77988
[]
no_license
sahashoo/Daily
a20a4bce60b0903fde23bea9d5244c65a9ea3928
c209cf800cbae850e2233a149d3cc8181b49fb5e
refs/heads/master
2020-04-23T04:31:13.770829
2019-02-15T20:00:34
2019-02-15T20:00:34
170,910,172
0
0
null
null
null
null
UTF-8
C++
false
false
427
cpp
877b.cpp
///age yekam bekeshi beham is no problem ._. #include<bits/stdc++.h> using namespace std; const int maxn=5e3+7; int a[maxn],b[maxn]; int main(){ ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); string s;cin>>s; int n=s.size(); for(int i=0;i<n;i++) a[i+1]=a[i]+(s[i]=='a'), b[i+1]=b[i]+(s[i]=='b'); int mx=0; for(int i=1;i<=n;i++) for(int j=i;j<=n;j++) mx=max(mx,a[n]-a[j]+b[j]-b[i-1]+a[i]); cout<<mx; }
318f863be5ac5033eebfd9bf64ce40c91cfa1e57
f6089f3201c2d051aad4418d22c8857fdb33b651
/498. Diagonal Traverse.cpp
f18eca9a9e91c96eb000db6d82aacf5bf1119cf0
[]
no_license
RitikJainRJ/Leetcode-Practice
3c1224bd568e3dfe86aad0ff71dafe1a7cf716bf
3a6a2a9b7877da1047206776096d3c00cac468e1
refs/heads/master
2023-01-01T17:30:28.680131
2020-10-17T04:47:33
2020-10-17T04:47:33
262,249,540
0
0
null
null
null
null
UTF-8
C++
false
false
651
cpp
498. Diagonal Traverse.cpp
class Solution { public: vector<int> findDiagonalOrder(vector<vector<int>>& mat) { if(mat.size() == 0 || mat[0].size() == 0) return {}; int n = mat.size(), m = mat[0].size(); vector<int> res; int i = 0, j = 0; while(i < n && j < m){ while(0 <= i && i < n && 0 <= j && j < m) res.push_back(mat[i--][j++]); i++; if(j == m) j--, i++; while(0 <= i && i < n && 0 <= j && j < m) res.push_back(mat[i++][j--]); j++; if(i == n) i--, j++; } return res; } };
31561b69cbcb0b4bd50f86ae44e782ade6666dfd
761afe0f6d97c5ed50b937ecd006901afb2c3e96
/MPI/mpi_hello_world/helloWorld.cpp
a49d038805ec1760b8ef66d10dec5affbedbed7b
[]
no_license
sebas095/HPC
819276c193344d663e1d39363c4bdcb0cdbd786d
f8b9fc860192df491b8f9fa6a41f44fe9850dc61
refs/heads/master
2020-04-19T10:51:10.094174
2016-11-23T18:42:39
2016-11-23T18:42:39
66,045,247
0
2
null
null
null
null
UTF-8
C++
false
false
417
cpp
helloWorld.cpp
#include <cstdio> #include <iostream> #include <mpi.h> using namespace std; int main(int argc, char *argv[]) { int rank, size; MPI::Init(argc, argv); // starts MPI rank = MPI::COMM_WORLD.Get_rank(); // get current process id size = MPI::COMM_WORLD.Get_size(); // get number of processes cout << "Hello world from process " << rank << " of " << size << endl; MPI::Finalize(); return 0; }
7446ac1f30457a80b996539001ada5b4cfeda580
0ea667c313cc7c3a899d292c31ceb39379c8771d
/14. DP/19b. Palindrome Partitioning II with cuts indices (LC#132) [DP].cpp
396ff2f16e7aba9429b809177dc7f8901307854f
[]
no_license
prashkrans/DSA
3503f923dfb81006ccfdcc463c64c3ffcaa8449f
c24e0aee76370f4efe5d18ec1cf8da3016a86094
refs/heads/master
2022-03-08T20:50:25.501832
2022-02-26T18:56:55
2022-02-26T18:56:55
126,618,737
0
0
null
2022-02-26T18:56:55
2018-03-24T16:33:44
C++
UTF-8
C++
false
false
2,430
cpp
19b. Palindrome Partitioning II with cuts indices (LC#132) [DP].cpp
/* DP Problem 19 - Palindrome Partitioning II (LC#132)*/ // Running time = O(n^3) i.e. cubic // Auxiliary space = O(n^2) #include<iostream> #include<vector> using namespace std; bool isPalin(string s, int i, int j) { // Can also use a bool matrix storing the values if substr(i, j) is a palindrome as in method 2 int n = j-i+1; string str = s.substr(i, n); for(int k=0; k<n/2; k++) { if(str[k]!=str[n-1-k]) return false; } return true; } void cutsIndices(int i, int j, vector<vector<int>> &K, vector<int> &cuts) { if(K[i][j] == -1) return ; else { cuts.push_back(K[i][j]); cutsIndices(i, K[i][j], K, cuts); cutsIndices(K[i][j]+1, j, K, cuts); } //cout<<"Hello World\n"; return; } int palinPartitionMin(string s) { int n = s.size(); vector<vector<int>> DP(n, vector<int>(n)); vector<vector<int>> K(n, vector<int>(n)); for(int len = 1; len<=n; len++) { for(int i=0; i<n-len+1; i++) { int j = i+len-1; if(isPalin(s, i, j)) { DP[i][j] = 0; K[i][j] = -1; } else { int minVal = INT_MAX; int kVal = -1; for(int k=i; k<j; k++) { int val = DP[i][k] + 1 + DP[k+1][j]; if(val < minVal) { minVal = val; kVal = k; } } DP[i][j] = minVal; K[i][j] = kVal; } } } cout<<"DP table = \n"; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) cout<<DP[i][j]<<" "; cout<<"\n"; } cout<<"K table = \n"; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) cout<<K[i][j]<<" "; cout<<"\n"; } vector<int> cuts; cutsIndices(0, n-1, K, cuts); if(!cuts.empty()) { cout<<"The cuts are made at the following indices = "; for(int i=0; i<cuts.size(); i++) cout<<cuts[i]+1<<" "; cout<<"\n"; cout<<"The cuts are made as follows = "; int k = 0; for(int i=0; i<n; i++){ cout<<s[i]; if(i==cuts[k]) { cout<<"|"; k++; } } cout<<"\n"; } cout<<"Thus, the minimum no. of cuts required are = "; return DP[0][n-1]; } int main() { string s; cin>>s; //vector<string> ans = palinPartitionMin(s); cout<<palinPartitionMin(s); return 0; }
0a422c77800d9d95bd459f16e16e7aa9158dffa5
e733c651cf49087e7919089175b04ebb46ee6162
/src/eva_loader.cc
89ac4742e9ec61c7c8fd52f9fb18f6e129962192
[]
no_license
gezhuang0717/mass-ana-t
a691a767eb3324b98a63d13b177966379a0f5c24
c0d838eee7ddd5b6a1ef08ec06d4a7fd49e604fd
refs/heads/master
2022-04-14T19:39:30.117876
2020-04-10T21:49:08
2020-04-10T21:49:08
254,737,716
0
0
null
null
null
null
UTF-8
C++
false
false
17,394
cc
eva_loader.cc
/* Jochen Ketter, 16. Mai 2008 * Versuch, eine dat-Datei des MM6 auszulesen. * */ #include <iostream> //#include <iomanip> #include <fstream> #include <string> #include <sstream> #include <time.h> //#include <vector> #include <cmath> //Äquivalenter Aufrufz zu math.h? //#include <math.h> #include "collection.hh" #include "eva_loader.hh" using namespace std; cEvaFileCollection::cEvaFileCollection() { } cEvaFileCollection::~cEvaFileCollection() { } cEvaFile::cEvaFile() { scan_rounds = 0; extra_info_double_1 = 0; extra_info_double_2 = 0; } cEvaFile::~cEvaFile() { } cIonDetails::cIonDetails() { } cIonDetails::~cIonDetails() { } bool cIonDetails::operator==(const cIonDetails& rhs) { if (mass_number == rhs.mass_number && element == rhs.element && charge_state == rhs.charge_state) return true; return false; } cMCSDetails::cMCSDetails() { bin_width = 0; MAX_MCS_channels = 0; MCS_recording_offset_in_bins = 0; } cMCSDetails::~cMCSDetails() { } bool cEvaFileCollection::add_evafile(const std::string& filename) { if ( !boost::filesystem::exists( filename) ) return 0; evafiles.push_back(cEvaFile()); evafiles.back().process_evafile(filename); //std::cout << "back charge:" << evafiles.back().charge_state << " element:" << evafiles.back().element << " time:" << evafiles.back().time_of_sweep << "|\n"; evafiles.sort(); return 1; } cIonDetails cEvaFile::get_ion_details() { //std::cout << "directly! charge:" << charge_state << " element:" << element << "|\n"; cIonDetails p = *this; //std::cout << "via get ! charge:" << p.charge_state << " element:" << p.element << "|\n"; return p; } list< cSimilarScans > cEvaFileCollection::get_ion_species_types(void ) { std::list< cSimilarScans > founds; for (std::list<cEvaFile>::iterator i = evafiles.begin(); i != evafiles.end(); ++i) { bool existing = false; for (std::list <cSimilarScans>::iterator j = founds.begin(); j != founds.end(); ++j) { if ( i->operator==(*j) ) { existing = true; j->number_of_similar_scans++; j->similar_evafiles.push_back( &(*i) ); } } if (existing == false) { founds.push_back( i->get_ion_details()); founds.back().similar_evafiles.push_back(&(*i) ); } } return founds; } cSimilarScans::cSimilarScans(const cIonDetails& ion_details) { cIonDetails::operator=(ion_details); number_of_similar_scans = 1; } std::string cEvaFile::smart_parse(const std::string& line, const std::string& identifier_str, const std::string& valid_ending_characters) /* Parses a line such as | Mass=Gd152 ,Charge= 1,Freq= 708035.64,Amp= 0.420000,Time=0.500000| * std::string identifier_str is like |Mass=| and valid_ending_characters like " ," which accepts * comma and white space ' ' as ending characters. Method returns the string in between. * * Correcteed 2012-10-24: Element can also be in order "152Gd" or "Gd152". Apparently * ISOLTRAP and SHIPTRAP conventions disagree. */ { // liner consists of everything after the end of identifier_str: std::string liner = line.substr(line.find(identifier_str)+identifier_str.size()); // Removing any leading whitespace liner = liner.substr(liner.find_first_not_of(" ")); liner = liner.substr(0,liner.find_first_of(valid_ending_characters)); return liner; } bool cEvaFile::process_evafile(const std::string& filename) { ifstream myinfile; //Eingabedateistream std::string dateiname_in = filename, zeile, einleser; long header_size = 0, data_start = 0, pps = 0, pps_last = 0; short nrMCA_channels = 0, nrScans = 0, recSize = 0, recSize_max = 0; double *scan_vals, time_per_channel; // int laenge = sizeof(long); //char *buffer; int i, j, k, pos; unsigned int ui; bool dataCompressed = false; myinfile.open(dateiname_in.c_str(), ios::in | ios::binary); if (!myinfile.is_open()) { cerr << "Fehler beim Oeffnen der Datei " << dateiname_in << "." << endl; cerr << endl; myinfile.clear(); cerr << "Programmende!" << endl; return 0; } //myinfile.seekg (0, ios::beg); //myinfile.read((char*) &header_size, sizeof(long)); //myinfile.read((char*) &data_start, sizeof(long)); myinfile.read((char*) &header_size, 4); myinfile.read((char*) &data_start, 4); //cout.write(buffer, laenge); /* Test, ob Zeichen ein Kontrollzeichen ist. for (i=0; i<laenge; i++){ cout << i << ": " << iscntrl(buffer[i]) << endl; } */ //cout << "HeaderSize: " << header_size << endl; //cout << "DataStart: " << data_start << endl; myinfile.close(); /* * Lesen aus dem Klartextteil: * Suchen des Labels [MCA] und Einlesen der Kanalbreite in µs sowie der * Anzahl der verwendeten Kanäle */ myinfile.open(dateiname_in.c_str(), ios::in); if (!myinfile.is_open()) { cerr << "Fehler beim Oeffnen der Datei " << dateiname_in << "." << endl; cerr << endl; myinfile.clear(); cerr << "Programmende!" << endl; return 0; } //myinfile.seekg(2*sizeof(long), ios_base::beg); myinfile.seekg(2*4, ios_base::beg); //Klartextteil der Datei durchgehen. //Binärpart beginnt nach header_size + 2 * sizeof(long), wobei //die HeaderSize und DataStart zu Beginn der Datei als long-Werte dazugezählt werden. //while (myinfile.tellg() < header_size + 2 * sizeof(long)) { while (myinfile.tellg() < header_size + 2 * 4) { getline(myinfile, zeile); //cout << zeile << endl; //Debuggingcode zum Test, ob der richtige Teil der Datei gelesen wird. //cout << zeile.find("[MCA]") << endl; //cout << "string::npos " << string::npos << endl; // Eintrag finden und die beiden interessanten Werte für // die Binbreite (Zeit pro Kanal) und die Anzahl der MCA-Kanaäle finden. if (zeile == "[MCA]"){ //if (zeile.find("[MCA]") != string::npos) { //Versuch, die Abfrage etwas robuster zu gestalten. Allerdings ist der //Klartextteil sakrosankt, da eine Änderung sofort die HeaderSize ändert. // cout << "[MCA] gefunden." << endl; getline(myinfile, zeile); pos = zeile.find("TimePerChannel"); ui = pos + 14; //Position + Länge von "TimePerChannel" // Ende bei Komma oder Ende der Zeile while (zeile[ui] != ',' && ui < zeile.length()) { //Alles, was eine Zahl oder ein Dezimaltrenner ist, wird an den //String einleser angehängt. if (isdigit(zeile[ui]) || zeile[ui] == '.') { einleser.push_back(zeile[ui]); } ui++; } //Umwandeln des Strings in eine Zahl stringstream(einleser) >> time_per_channel; bin_width = time_per_channel; //TADAA // cout << "Einleser: " << einleser << endl; // cout << "Zeit pro MCA-Kanal in µs: " << time_per_channel << "|\n"; einleser.clear(); //Die gleiche Prozedur wie oben zur Bestimmung der MCA-Kanäle. //Vereinfachung: Da die Anzahl der Kanäle eine ganze Zahl ist, // kan auf die Beandlung eines Dezimaltrenners verzichtet werden. pos = zeile.find("Channels"); ui = pos + 8; //Position while (zeile[ui] != ',' && ui < zeile.length()) { if (isdigit(zeile[ui])) { einleser.push_back(zeile[ui]); } ui++; } stringstream(einleser) >> nrMCA_channels; MAX_MCS_channels = nrMCA_channels; //TADAA // cout << "Einleser: " << einleser << endl; // cout << "Anzahl der MCA-Kanäle: " << nrMCA_channels << endl; //break; } if (zeile == "[Mass]") { // cout << "[Mass] gefunden." << endl; getline(myinfile, zeile); std::string isotope = smart_parse(zeile,"Mass="); //std::cout << "tooppi: |" << isotope << "|\n"; std::string charge = smart_parse(zeile,"Charge="); //std::cout << "charge: |" << charge << "|\n"; stringstream(charge) >> charge_state; //std::cout << "charge: " << charge_state << "\n"; /* this stage, isotope = |Gd152| and charge = 1 (integer) */ /* Could also be other way around: |152Gd| as at ISOLTRAP 2012-10-23 */ /* We will split isotope to string::element |Gd| (make it all low cases) * and int mass_numeber */ // isotope[0] = tolower(isotope[0]); //std::cout << "isotope |" << isotope << "|\n"; //////////// int first_number = isotope.find_first_of("0123456789"); int last_number = isotope.find_last_of("0123456789"); int first_letter = isotope.find_first_of("abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ"); int last_letter = isotope.find_last_of("abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ"); element = isotope.substr(first_letter,last_letter-first_letter+1); element[0] = tolower(element[0]); std::string mass_number_str = isotope.substr(first_number,last_number-first_number+1); stringstream(mass_number_str) >> mass_number; //////////// //OLD //int position = isotope.find_first_of("01234567890"); //element = isotope.substr(0,position); //std::string mass = isotope.substr(position); //std::cout << "element: |" << element << "|mass:|" << mass << "|\n"; //stringstream(mass) >> mass_number; } //Finding "Delay MCS" { std::string identifier_str = "Delay MCS : "; if (zeile.find(identifier_str) != std::string::npos ) { // value should contain "40.000" std::string value = zeile.substr(zeile.find(identifier_str) + identifier_str.size() ); MCS_recording_offset_in_bins = as_double(value)/bin_width; } } /// Custom for one particular data, should comment this out after use if (1) { std::string identifier_str = "Cyclotron MT : "; if (zeile.find(identifier_str) != std::string::npos ) { // value should contain "20000.00" std::string value = zeile.substr(zeile.find(identifier_str) + identifier_str.size() ); extra_info_string_1 = value; extra_info_double_1 = as_double(value); std::cout << "Extra info:|" << extra_info_double_1 << "|\n"; } } } myinfile.close(); /* * Öffnen der Datei um den binären Datenteil einzulesen. * Die Anzahl der Scnas wird von diesem Programmteil ermittelt. * Reihenfolge * Punkte pro Scan * Frequenzwerte der einzelnen Scanpunkte * Daten der MCA-Kanäle */ myinfile.open(dateiname_in.c_str(), ios::in | ios::binary); if (!myinfile.is_open()) { cout << "Fehler beim Oeffnen der Datei " << dateiname_in << "." << endl; cout << endl; myinfile.clear(); cout << "Programmende!" << endl; return 0; } //myinfile.seekg (0, ios::beg); //Angabe einer Anfangsposition wohl unnötig, da die untere Funktion ohnehin //vom Dateianfang sucht. //myinfile.seekg(header_size + 2 * sizeof(long), ios_base::beg); myinfile.seekg(header_size + 2 * 4, ios_base::beg); //myinfile.read((char*) &pps, sizeof(long)); myinfile.read((char*) &pps, 4); // cout << "Points per Scan: " << pps << endl; scan_vals = new double [pps]; myinfile.read( (char*) scan_vals, pps*sizeof(double)); for (i=0; i<pps; i++) { //cout << "blubber" << endl; //cout << "Hier bin ich." << endl; cout.precision(4); cout.setf(ios_base::floatfield, ios_base::fixed); //scan_vals[i] are scanned frequencies (doubles) /* cout << (i+1) << ": " << scan_vals[i] << endl; */ //cout << (i+1) << ": " << fixed << setprecision(3) << scan_vals[i] << endl; } cout.unsetf(ios_base::fixed); //cout << 1.12 << endl; myinfile.seekg(data_start, ios_base::beg); //cout << pps << endl; return 0; //cout << "Failbit " << myinfile.fail() << endl; j = 0; //* do { i = 0; while (i < pps) { myinfile.read( (char*) &recSize, sizeof(short)); if (!myinfile.eof()) { i++; j++; } else { break; } if (recSize > recSize_max) { recSize_max = recSize; } // cout << "RecSize: " << recSize << endl; myinfile.seekg(recSize, ios_base::cur); //cout << "Hier bin ich." << endl; //cout << "i: " << i << endl; } nrScans++; } while (!myinfile.eof()); myinfile.clear(); //Status des Eingabestreams der Datei zurücksetzen, da eine eof-Exception produziert wurde. //Andernfalls lassen sich keine vernünftigen Operationen mehr durchführen (zwei Stunden Fehlersuche). // */ //cout << "Gesamtzahl der Scanpunkte: " << j <<endl; nrScans--; //Vorteil dieser Konstruktion: Es paßt auch es, wenn gar kein Scan //durchgeführt wurde. War der letzte Scan vollständig, wird die Schleife ein weiteres //Mal durchlaufen, wobei sich die Anzahl der Scnas um eins erhöht und i auf null //gesetzt wird. Beides wird hier korrigiert. pps_last = (i == 0 && nrScans > 0) ? pps : i; //Punkte im letzten Scan (eventuell vorzeitiger Abbruch) //Wenn mindestens ein Scan durchgeführt wurde, ist i == 0, weil nach einem vollständigen Scan //beendet wurde. // std::cout << "Anzahl der Scans: " << nrScans << endl; // JYFLTRAP slang: "rounds" scan_rounds = nrScans; // std::cout << "Scanpunkte im letzten Scan: " << pps_last << endl; // std::cout << "pps: " << pps << endl; // std::cout << "nrMCA_channels: " << nrMCA_channels << "\n"; //short AllCounts[nrScans][pps][nrMCA_channels]; std::vector< std::vector< std::vector<short> > > AllCounts; AllCounts.resize(nrScans); // std::cout << "here?\n"; //time_t aTimes[nrScans][pps]; std::vector< std::vector<time_t> > aTimes; aTimes.resize(nrScans); // std::cout << "here2?\n"; for (i = 0; i < nrScans; i++) { AllCounts[i].resize(pps); aTimes[i].resize(pps); for (j = 0; j < pps; j++) { AllCounts[i][j].resize(nrMCA_channels); aTimes[i][j] = -1; for (k = 0; k < nrMCA_channels; k++) { AllCounts[i][j][k] = -1; } } } // std::cout << "here3?\n"; short *buffer; buffer = new short [recSize_max]; myinfile.seekg(data_start, ios_base::beg); //long testpos = data_start; for (i = 0; i < nrScans; i++) { for (j= 0; j < pps; j++) { // cout << myinfile.tellg() << endl; myinfile.read( (char*) &recSize, sizeof(short)); //cout << myinfile.tellg() << endl; // cout << myinfile.gcount() << endl; //testpos = testpos + sizeof(short) + recSize; //cout << "recSize davor: " << recSize << endl; //recSize = (short) ((recSize - sizeof(long)) / sizeof(short)); recSize = (short) ((recSize - 4) / sizeof(short)); //cout << "recSize danach: " << recSize << endl; //myinfile.read((char*) &aTimes[i][j], sizeof(long)); unsigned int buffer2; myinfile.read((char*) &buffer2, 4); aTimes[i][j] = buffer2; //cout << myinfile.gcount() << endl; // cout << "aTimes[" << i << "][" << j << "]: " << aTimes[i][j] << endl; if (recSize > 0) { myinfile.read((char*) buffer, recSize * sizeof(short)); //for (k = 0; k < recSize; k++){ cout << buffer[k] << endl; } dataCompressed = recSize < nrMCA_channels; if (dataCompressed) { for (k = 0; k < recSize/2; k++) { AllCounts[i][j][buffer[2*k]] = buffer[2*k+1]; } } else { for (k = 0; k < recSize; k++) { AllCounts[i][j][k] = buffer[k]; } } } } //myinfile.seekg(testpos, ios_base::beg); } myinfile.close(); // std::cout << "Finished reading file.\n"; for (i = 0; i < nrScans; i++) { for (j = 0; j < pps; j++) { //cout << aTimes[i][j] << endl; //cout << ctime(&aTimes[i][j]) << endl; } } for (i = 0; i < nrScans; i++) { // i: round number for (j = 0; j < pps; j++) { // j: frequency number, 0=smallest freq, pps-1 highest cUnit to_add; to_add.putFrequency(scan_vals[j]); //cout.precision(15); //cout << "freq: " << scan_vals[i] << "\n"; loc_tm time(aTimes[i][j]); to_add.putTimeString(time.get_time_as_string()); // cout << "time: " << to_add.getTimeString(); for (k = 0; k < nrMCA_channels; k++) { // k: MCS channel if (AllCounts[i][j][k] != -1) { to_add.InsertDataPoint(k,AllCounts[i][j][k],0); //cout << "Datapoint: ch:" << k << "| cts:" << AllCounts[i][j][k] << "|\n"; //cout << "Scan " << (i+1) << ", Punkt " << (j+1) // << ", Kanal " << (k+1) << ": " // << AllCounts[i][j][k] << endl; } } to_add.set_MCS_TOF_offset_in_bins(MCS_recording_offset_in_bins); bunches.push_back(to_add); } } if (nrScans > 0 && pps > 0) { // long long scantime = aTimes[0][0]/2. + aTimes[nrScans-1][pps-1]/2.; // time_of_sweep = loc_tm(scantime).get_time_as_string(); start_time_of_sweep = loc_tm(aTimes[0][0]).get_time_as_string(); end_time_of_sweep = loc_tm(aTimes[nrScans-1][pps-1]).get_time_as_string(); // std::cout << "Start:" << loc_tm(aTimes[0][0]).get_time_as_string() << "---stop:" << loc_tm(aTimes[nrScans-1][pps-1]).get_time_as_string() << "\n"; // std::cout << "middle:" << time_of_sweep << "\n"; } // cout << "Hier bin ich am Ende angelangt." << endl; delete [] scan_vals; delete [] buffer; return 0; } choise::choise() { radiobutton = new Gtk::RadioButton; } // push_back method is using this so this is why this is so well implemented choise::choise(const choise& other) { radiobutton = new Gtk::RadioButton; //std::cout << "copy constructor actually used!\n"; ss = other.ss; radiobutton->set_label(other.radiobutton->get_label()); Gtk::RadioButtonGroup grpp = other.radiobutton->get_group(); radiobutton->set_group(grpp); //std::cout << "copycons ele:" << ss->element << "|\n"; } choise::~choise() { delete radiobutton; } choise::choise(cSimilarScans* p, Gtk::RadioButtonGroup grp) { ss = p; radiobutton = new Gtk::RadioButton; std::string leibel = p->element + asString(p->mass_number) + ", " + asString(p->charge_state) + "+, " + asString(p->number_of_similar_scans) + " files"; radiobutton->set_label(leibel); radiobutton->set_group(grp); } void choise::operator=(const choise& other) { //std::cout << "assing actually used!\n"; }
0d0f086f5ef759232c7423a5f1eb309629b53217
55cfa1eed966766aeb72e54a1ed6f2591255e5c0
/SpiralMatrix.cpp
aefd31b3ac4b82a2b679046c4f161be744d42f04
[]
no_license
iCodeIN/leetcode-4
1bf2751c861ccf1652b0e5b096595e6874e568e3
9081802f99da6cfded421fe10052839bad449fd2
refs/heads/master
2023-01-13T07:22:53.362907
2020-11-13T03:56:20
2020-11-13T03:56:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,864
cpp
SpiralMatrix.cpp
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int>res; if((matrix.size()==0) || (matrix[0].size()==0)) return res; int i,j,rowbegin=0,rowend=matrix.size()-1,colbegin=0,colend=matrix[0].size()-1; while((rowbegin<=rowend) && (colbegin<=colend)) { for(j=colbegin;j<=colend;j++) res.push_back(matrix[rowbegin][j]); rowbegin++; for(i=rowbegin;i<=rowend;i++) res.push_back(matrix[i][colend]); colend--; if(rowend>=rowbegin) { for(j=colend;j>=colbegin;j--) res.push_back(matrix[rowend][j]); } rowend--; if(colend>=colbegin) { for(i=rowend;i>=rowbegin;i--) res.push_back(matrix[i][colbegin]); } colbegin++; } return res; } }; class Solution { public: vector<vector<int>> generateMatrix(int n) { if(n==0) return vector<vector<int>>(); int no=1,rowb=0,rowe=n-1,colb=0,cole=n-1,i,j; vector<vector<int>>grid(n,vector<int>(n,0)); while((rowb<=rowe) && (colb<=cole)) { for(j=colb;j<=cole;j++) { grid[rowb][j]=no; no++; } rowb++; for(i=rowb;i<=rowe;i++) { grid[i][cole]=no; no++; } cole--; for(j=cole;j>=colb;j--) { grid[rowe][j]=no; no++; } rowe--; for(i=rowe;i>=rowb;i--) { grid[i][colb]=no; no++; } colb++; } return grid; } };
47d85f65e5e2f94d93672dfb7062525c4952181d
67eb9168c8c1d30dff10a2852e4416bedd3f58e1
/.gitignore/Classes/GameScene.h
ec2cbb45c443c65f19b1dd6ad5967159664eac67
[]
no_license
LTTTTTE/Cocos2dx.game.sautda
b4dc161b0b68fb563a59a8f12025c6066e613c29
fc87faab4bca125f652bdb4d92432aed7ecba9df
refs/heads/master
2020-03-17T08:52:39.773522
2019-04-13T03:25:04
2019-04-13T03:25:04
133,452,851
0
0
null
null
null
null
UTF-8
C++
false
false
2,055
h
GameScene.h
#include "cocos2d.h" #pragma execution_character_set("utf-8") USING_NS_CC; class Player { private: double money; int cardPower; public: int arr_player_card[3]; bool isCheck; bool isHalf; bool isCall; bool isDie; bool myTurn; void setMoney() { money = 10000; } void setMoney(double a) { money = a; } void addMoney(double a) { money += a; } void subMoney(double a) { money -= a; } double showMoney() { return money; } int showCardPower() { return cardPower; } void CardCheckAlGo(); void setCardPower(int a) { if (a > cardPower)cardPower = a; } void setUp(); void setCard(); void reset_Bev(); }; class User : public Player { public: static User* user_1; static User* getInstance(); User() { setMoney(); setUp(); } }; class Computer : public Player { public: static Computer* com_1; static Computer* getInstance(); Computer() { setMoney(); setUp(); } }; class GameScene : public Layer { public: void DrawGridWindow(const int interval, const Color4F& color); static Scene* createScene(); std::vector<Sprite*>vec_spr_money; double roundMoney; double callMoney; int halfCount; void menuCallback(Ref* sender); bool onTouchBegan(Touch * aa, Event *); void gameAlgo() {}; void removeNode(Node * node); bool threeCard = false; bool roundStart = false; bool phase2 = false; bool EndPhase = true; void splitCard(); void throwMoney(); void throwLabel(); void CheckWhatYouGot(); void ui_2nd_Phase(); void ui_Update(float d); void ui_card_Update(float d); void game_director(float d); void ui_end_Phase(); virtual bool init(); CREATE_FUNC(GameScene); }; enum class Card : int { c1_0 = 100, c1_1, c2_0, c2_1, c3_0, c3_1, c4_0, c4_1, c5_0, c5_1, c6_0, c6_1, c7_0, c7_1, c8_0, c8_1, c9_0, c9_1, cA_0, cA_1 }; enum class TAG_MENU : int { tag_goback = 10 , tag_check, tag_half, tag_call, tag_die };
659223bee5867e73ba41692f997010fdbbf17cb3
1c1c1fed0952aeacb4ccd3ce9374f67f0e92cae6
/9.cpp
41bb95da218a36f20d54a52ca2da07ae01bd00b1
[]
no_license
guipolicarpo/C
1e0898de96b9fb9106dc5dc42c06f98d3d78f7a2
acb61820d01993af7a574e0797c51be40be2aa4d
refs/heads/main
2023-02-08T03:07:13.997048
2021-01-04T18:32:57
2021-01-04T18:32:57
326,767,171
0
0
null
null
null
null
ISO-8859-1
C++
false
false
372
cpp
9.cpp
#include<stdio.h> #include<math.h> #include<stdlib.h> #include<locale.h> main(){ setlocale(LC_ALL, "Portuguese");//habilita a acentuação para o português float p,a,i; printf("Digite o Peso em KG: "); scanf("%f", &p); printf("Digite a Altura em Metros: "); scanf("%f", &a); i=p/(a*a); printf("\nIMC= %2f\n", i); }
184606f0c1401e7527cf8ce130635574ac9cfc94
182bbadb0ee7f59f1abd154d06484e555a30c6d8
/core/indigo-core/reaction/src/base_reaction_substructure_matcher.cpp
687214a4e1907fc3a5305b0328b711224ab4fbb7
[ "Apache-2.0" ]
permissive
epam/Indigo
08559861adf474122366b6e2e499ed3aa56272d1
8e473e69f393c3a57ff75b7728999c5fb4cbf1a3
refs/heads/master
2023-09-02T10:14:46.843829
2023-08-25T08:39:24
2023-08-25T08:39:24
37,536,320
265
106
Apache-2.0
2023-09-14T17:34:00
2015-06-16T14:45:56
C++
UTF-8
C++
false
false
22,976
cpp
base_reaction_substructure_matcher.cpp
/**************************************************************************** * Copyright (C) from 2009 to Present EPAM Systems. * * This file is part of Indigo toolkit. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ #include "reaction/base_reaction_substructure_matcher.h" #include "molecule/molecule_3d_constraints.h" #include "molecule/molecule_arom_match.h" #include "molecule/molecule_neighbourhood_counters.h" #include "molecule/molecule_substructure_matcher.h" #include "reaction/base_reaction_substructure_matcher.h" #include "reaction/query_reaction.h" #include "reaction/reaction.h" #include "reaction/reaction_neighborhood_counters.h" using namespace indigo; IMPL_ERROR(BaseReactionSubstructureMatcher, "reaction substructure matcher"); CP_DEF(BaseReactionSubstructureMatcher); BaseReactionSubstructureMatcher::BaseReactionSubstructureMatcher(Reaction& target) : _target(target), CP_INIT, TL_CP_GET(_matchers), TL_CP_GET(_aam_to_second_side_1), TL_CP_GET(_aam_to_second_side_2), TL_CP_GET(_molecule_core_1), TL_CP_GET(_molecule_core_2), TL_CP_GET(_aam_core_first_side) { use_aromaticity_matcher = true; highlight = false; match_atoms = 0; match_bonds = 0; context = 0; remove_atom = 0; add_bond = 0; prepare = 0; _match_stereo = true; _query_nei_counters = 0; _target_nei_counters = 0; _query = 0; _matchers.clear(); _matchers.add(new _Matcher(*this)); } void BaseReactionSubstructureMatcher::setQuery(BaseReaction& query) { _query = &query; } void BaseReactionSubstructureMatcher::setNeiCounters(const ReactionAtomNeighbourhoodCounters* query_counters, const ReactionAtomNeighbourhoodCounters* target_counters) { _query_nei_counters = query_counters; _target_nei_counters = target_counters; } bool BaseReactionSubstructureMatcher::find() { if (_query == 0) throw Error("no query"); if (prepare != 0 && !prepare(*_query, _target, context)) return false; if (_query->reactantsCount() > _target.reactantsCount() || _query->productsCount() > _target.productsCount()) return false; if (_query->reactantsCount() * _target.reactantsCount() < _query->productsCount() * _target.productsCount()) _first_side = Reaction::REACTANT, _second_side = Reaction::PRODUCT; else _first_side = Reaction::PRODUCT, _second_side = Reaction::REACTANT; _initMap(*_query, _second_side, _aam_to_second_side_1); _initMap(_target, _second_side, _aam_to_second_side_2); _molecule_core_1.resize(_query->end()); _molecule_core_1.fffill(); _molecule_core_2.resize(_target.end()); _molecule_core_2.fffill(); _aam_core_first_side.clear(); _matchers.top()->match_stereo = _match_stereo; while (1) { int command = _matchers.top()->nextPair(); if (command == _CONTINUE) continue; if (command == _RETURN) { if (_checkAAM()) { _highlight(); return true; } command = _NO_WAY; } else if (command != _NO_WAY) { int mol1 = _matchers.top()->_current_molecule_1; int mol2 = _matchers.top()->_current_molecule_2; Array<int>& core1 = _matchers.top()->_current_core_1; Array<int>& core2 = _matchers.top()->_current_core_2; int mode = _matchers.top()->getMode(); //_matchers.reserve(_matchers.size() + 1); _matchers.add(new _Matcher(*_matchers.top())); _matchers.top()->setMode(command); if (!_matchers.top()->addPair(mol1, mol2, core1, core2, mode == _FIRST_SIDE)) _matchers.removeLast(); } if (command == _NO_WAY) { if (_matchers.size() > 1) { _matchers.top()->restore(); _matchers.removeLast(); } else return false; } } } // Init data for reaction substructure search void BaseReactionSubstructureMatcher::_initMap(BaseReaction& reaction, int side, std::map<int, int>& aam_map) { int i, j; int* val; aam_map.clear(); // collect aam-to-molecule index mapping for reaction second side for (i = reaction.sideBegin(side); i < reaction.sideEnd(); i = reaction.sideNext(side, i)) { BaseMolecule& i_mol = reaction.getBaseMolecule(i); for (j = i_mol.vertexBegin(); j < i_mol.vertexEnd(); j = i_mol.vertexNext(j)) { int aam_number = reaction.getAAM(i, j); if (aam_number != 0) { auto it = aam_map.find(aam_number); val = it != aam_map.end() ? &(it->second) : nullptr; if (!val) aam_map.emplace(aam_number, i); else if (*val < 0) (*val)--; else (*val) = -1; } } } } // Check correct AAM relationship between query and target reaction bool BaseReactionSubstructureMatcher::_checkAAM() { int *aam, aam1, aam2; int i, j; for (i = 1; i < _matchers.size() - 1; i++) { if (_matchers[i]->getMode() == _FIRST_SIDE) continue; BaseMolecule& mol1 = _query->getBaseMolecule(_matchers[i]->_current_molecule_1); for (j = mol1.vertexBegin(); j < mol1.vertexEnd(); j = mol1.vertexNext(j)) { int k = _matchers[i]->_current_core_1[j]; if (k < 0) continue; aam1 = _query->getAAM(_matchers[i]->_current_molecule_1, j); aam2 = _target.getAAM(_matchers[i]->_current_molecule_2, k); if (aam1 > 0 && aam2 > 0) { auto it = _aam_core_first_side.find(aam1); aam = it != _aam_core_first_side.end() ? &(it->second) : nullptr; if (aam && *aam != aam2) return false; } } } return true; } int BaseReactionSubstructureMatcher::getTargetMoleculeIndex(int query_mol_idx) { // can be optimized, but as the number of molecules // seldom exceeds 5, the linear search is acceptable for (int i = 0; i < _matchers.size() - 1; i++) if (_matchers[i]->_current_molecule_1 == query_mol_idx) return _matchers[i]->_current_molecule_2; throw Error("getTargetMoleculeIndex(): can not find mapping for query molecule %d", query_mol_idx); } const int* BaseReactionSubstructureMatcher::getQueryMoleculeMapping(int query_mol_idx) { for (int i = 0; i < _matchers.size() - 1; i++) if (_matchers[i]->_current_molecule_1 == query_mol_idx) return _matchers[i]->_current_core_1.ptr(); throw Error("getQueryMoleculeMapping(): can not find mapping for query molecule %d", query_mol_idx); } void BaseReactionSubstructureMatcher::_highlight() { if (!highlight) return; int i; for (i = 0; i < _matchers.size() - 1; i++) _target.getBaseMolecule(_matchers[i]->_current_molecule_2) .highlightSubmolecule(_query->getBaseMolecule(_matchers[i]->_current_molecule_1), _matchers[i]->_current_core_1.ptr(), true); } CP_DEF(BaseReactionSubstructureMatcher::_Matcher); BaseReactionSubstructureMatcher::_Matcher::_Matcher(BaseReactionSubstructureMatcher& context) : CP_INIT, TL_CP_GET(_current_core_1), TL_CP_GET(_current_core_2), _context(context), TL_CP_GET(_mapped_aams) { _mode = _FIRST_SIDE; _selected_molecule_1 = -1; _selected_molecule_2 = -1; _current_molecule_1 = -1; _current_molecule_2 = -1; _mapped_aams.clear(); match_stereo = true; _current_core_1.clear(); _current_core_2.clear(); } BaseReactionSubstructureMatcher::_Matcher::_Matcher(const BaseReactionSubstructureMatcher::_Matcher& other) : CP_INIT, TL_CP_GET(_current_core_1), TL_CP_GET(_current_core_2), _context(other._context), TL_CP_GET(_mapped_aams) { _current_molecule_1 = -1; _current_molecule_2 = -1; _mapped_aams.clear(); match_stereo = other.match_stereo; _current_core_1.clear(); _current_core_2.clear(); _selected_molecule_1 = -1; _selected_molecule_2 = -1; } int BaseReactionSubstructureMatcher::_Matcher::_nextPair() { int side; if (_mode == _FIRST_SIDE) side = _context._first_side; else // _SECOND_SIDE_REST side = _context._second_side; if (_enumerator.get() == 0 || !_enumerator->processNext()) { do { while (1) { if (_current_molecule_1 == -1) { for (_current_molecule_1 = _context._query->sideBegin(side); _current_molecule_1 < _context._query->sideEnd(); _current_molecule_1 = _context._query->sideNext(side, _current_molecule_1)) if (_context._molecule_core_1[_current_molecule_1] < 0) break; if (_current_molecule_1 == _context._query->sideEnd()) { if (_mode == _FIRST_SIDE) { _mode = _SECOND_SIDE_REST; _current_molecule_1 = -1; return _nextPair(); } return _RETURN; } } if (_current_molecule_2 == -1) _current_molecule_2 = _context._target.sideBegin(side); else _current_molecule_2 = _context._target.sideNext(side, _current_molecule_2); for (; _current_molecule_2 < _context._target.sideEnd(); _current_molecule_2 = _context._target.sideNext(side, _current_molecule_2)) if (_context._molecule_core_2[_current_molecule_2] < 0) break; if (_current_molecule_2 == _context._target.sideEnd()) return _NO_WAY; _enumerator.free(); BaseMolecule& mol_1 = _context._query->getBaseMolecule(_current_molecule_1); Molecule& mol_2 = _context._target.getMolecule(_current_molecule_2); if (!_initEnumerator(mol_1, mol_2)) { _enumerator.free(); continue; } break; } _enumerator->processStart(); } while (!_enumerator->processNext()); } return _mode == _FIRST_SIDE ? _SECOND_SIDE : _SECOND_SIDE_REST; } int BaseReactionSubstructureMatcher::_Matcher::nextPair() { if (_mode != _SECOND_SIDE) { int next = _nextPair(); if (next != _SECOND_SIDE) return next; // Switch to _SECOND_SIDE BaseMolecule& mol_1 = _context._query->getBaseMolecule(_current_molecule_1); int first_aam_1 = 0; int first_aam_2 = 0; int i; for (i = mol_1.vertexBegin(); i < mol_1.vertexEnd(); i = mol_1.vertexNext(i)) if (_current_core_1[i] >= 0) { first_aam_1 = _context._query->getAAM(_current_molecule_1, i); first_aam_2 = _context._target.getAAM(_current_molecule_2, _current_core_1[i]); break; } if (first_aam_1 > 0 && first_aam_2 > 0) { // Check the other side if needed auto it_1 = _context._aam_to_second_side_1.find(first_aam_1); int* mol_1_idx_ss_ptr = it_1 != _context._aam_to_second_side_1.end() ? &(it_1->second) : nullptr; auto it_2 = _context._aam_to_second_side_2.find(first_aam_2); int* mol_2_idx_ss_ptr = it_2 != _context._aam_to_second_side_2.end() ? &(it_2->second) : nullptr; if (mol_1_idx_ss_ptr == 0 && mol_2_idx_ss_ptr == 0) // There is no pair for both atom return _FIRST_SIDE; if (mol_1_idx_ss_ptr == 0 || mol_2_idx_ss_ptr == 0) // One atom has a pair atom while other hasn't one return _CONTINUE; int mol_1_idx_ss = *mol_1_idx_ss_ptr; int mol_2_idx_ss = *mol_2_idx_ss_ptr; if ((mol_1_idx_ss < 0 && mol_1_idx_ss < mol_2_idx_ss)) return _CONTINUE; // subreactions equal AAM-numbers more than superreaction if (mol_2_idx_ss < 0) return _FIRST_SIDE; // check this molecules in the completion phase if (_context._molecule_core_1[mol_1_idx_ss] >= 0) { if (_context._molecule_core_1[mol_1_idx_ss] != mol_2_idx_ss) return _CONTINUE; int first_idx_1_ss = _context._query->findAtomByAAM(mol_1_idx_ss, first_aam_1); int first_idx_2_ss = _context._target.findAtomByAAM(mol_2_idx_ss, first_aam_2); int i; for (i = 0; i < _context._matchers.size(); i++) if (_context._matchers[i]->_current_molecule_1 == mol_1_idx_ss) { if (_context._matchers[i]->_current_core_1[first_idx_1_ss] != first_idx_2_ss) return _CONTINUE; return _FIRST_SIDE; } } return _SECOND_SIDE; } return _FIRST_SIDE; } // _SECOND_SIDE if (_enumerator.get() == 0) { BaseMolecule& src_mol_1 = _context._query->getBaseMolecule(_selected_molecule_1); Molecule& src_mol_2 = _context._target.getMolecule(_selected_molecule_2); int src_aam_1 = 0; int src_aam_2 = 0; Array<int>& prev_core_1 = _context._matchers[_context._matchers.size() - 2]->_current_core_1; for (int i = src_mol_1.vertexBegin(); i < src_mol_1.vertexEnd(); i = src_mol_1.vertexNext(i)) if (prev_core_1[i] >= 0) { src_aam_1 = _context._query->getAAM(_selected_molecule_1, i); src_aam_2 = _context._target.getAAM(_selected_molecule_2, prev_core_1[i]); break; } BaseMolecule& mol_1 = _context._query->getBaseMolecule(_current_molecule_1); Molecule& mol_2 = _context._target.getMolecule(_current_molecule_2); int first_idx_1 = _context._query->findAtomByAAM(_current_molecule_1, src_aam_1); int first_idx_2 = _context._target.findAtomByAAM(_current_molecule_2, src_aam_2); // init embedding enumerator context _initEnumerator(mol_1, mol_2); if (!_enumerator->fix(first_idx_1, first_idx_2)) return _NO_WAY; _enumerator->processStart(); } if (!_enumerator->processNext()) return _NO_WAY; return _FIRST_SIDE; } bool BaseReactionSubstructureMatcher::_Matcher::_initEnumerator(BaseMolecule& mol_1, Molecule& mol_2) { // init embedding enumerator context _enumerator.create(mol_2); _enumerator->cb_match_edge = _matchBonds; _enumerator->cb_match_vertex = _matchAtoms; _enumerator->cb_edge_add = _addBond; _enumerator->cb_vertex_remove = _removeAtom; _enumerator->cb_embedding = _embedding; if (mol_1.isQueryMolecule() && _context.use_aromaticity_matcher && AromaticityMatcher::isNecessary(mol_1.asQueryMolecule())) _am = std::make_unique<AromaticityMatcher>(mol_1.asQueryMolecule(), mol_2, _context.arom_options); else _am.reset(nullptr); _enumerator->userdata = this; _enumerator->setSubgraph(mol_1); if (_context.prepare_ee != 0) { if (!_context.prepare_ee(_enumerator.ref(), mol_1, mol_2, _context.context)) return false; } return true; } bool BaseReactionSubstructureMatcher::_Matcher::addPair(int mol1_idx, int mol2_idx, const Array<int>& core1, const Array<int>& core2, bool from_first_side) { _selected_molecule_1 = mol1_idx; _selected_molecule_2 = mol2_idx; _mapped_aams.clear(); BaseMolecule& mol1 = _context._query->getBaseMolecule(mol1_idx); if (from_first_side) { int i; for (i = mol1.vertexBegin(); i < mol1.vertexEnd(); i = mol1.vertexNext(i)) if (core1[i] >= 0) { int aam1 = _context._query->getAAM(mol1_idx, i); int aam2 = _context._target.getAAM(mol2_idx, core1[i]); int* aam; if (aam1 > 0 && aam2 > 0) { auto it = _context._aam_core_first_side.find(aam1); aam = it != _context._aam_core_first_side.end() ? &(it->second) : nullptr; if (!aam) { _context._aam_core_first_side.emplace(aam1, aam2); _mapped_aams.push(aam1); } else if (*aam != aam2) { while (_mapped_aams.size() > 0) _context._aam_core_first_side.erase(_mapped_aams.pop()); return false; } } } } if (_mode == _SECOND_SIDE) { int first_aam_1 = 0; int first_aam_2 = 0; int i; for (i = mol1.vertexBegin(); i < mol1.vertexEnd(); i = mol1.vertexNext(i)) if (core1[i] >= 0) { first_aam_1 = _context._query->getAAM(mol1_idx, i); first_aam_2 = _context._target.getAAM(mol2_idx, core1[i]); break; } _current_molecule_1 = _context._aam_to_second_side_1.at(first_aam_1); _current_molecule_2 = _context._aam_to_second_side_2.at(first_aam_2); } _context._molecule_core_1[mol1_idx] = mol2_idx; _context._molecule_core_2[mol2_idx] = mol1_idx; return true; } void BaseReactionSubstructureMatcher::_Matcher::restore() { _context._molecule_core_1[_selected_molecule_1] = -1; _context._molecule_core_2[_selected_molecule_2] = -1; while (_mapped_aams.size() > 0) _context._aam_core_first_side.erase(_mapped_aams.pop()); } int BaseReactionSubstructureMatcher::_Matcher::_embedding(Graph& subgraph, Graph& supergraph, int* core_sub, int* core_super, void* userdata) { BaseReactionSubstructureMatcher::_Matcher& self = *(BaseReactionSubstructureMatcher::_Matcher*)userdata; QueryMolecule& query = (QueryMolecule&)subgraph; Molecule& target = (Molecule&)supergraph; if (self.match_stereo) { if (!MoleculeStereocenters::checkSub(query, target, core_sub, false)) return 1; if (!MoleculeCisTrans::checkSub(query, target, core_sub)) return 1; } // Check possible aromatic configuration if (self._am.get() != 0) { if (!self._am->match(core_sub, core_super)) return 1; } self._current_core_1.copy(core_sub, subgraph.vertexEnd()); self._current_core_2.copy(core_super, supergraph.vertexEnd()); return 0; } bool BaseReactionSubstructureMatcher::_Matcher::_matchAtoms(Graph& subgraph, Graph& supergraph, const int* core_sub, int sub_idx, int super_idx, void* userdata) { BaseReactionSubstructureMatcher::_Matcher* self = (BaseReactionSubstructureMatcher::_Matcher*)userdata; if (self->_context.match_atoms != 0 && !self->_context.match_atoms(*self->_context._query, self->_context._target, self->_current_molecule_1, sub_idx, self->_current_molecule_2, super_idx, self->_context.context)) return false; if (self->_mode == _SECOND_SIDE) { int *aam, aam1, aam2; aam1 = self->_context._query->getAAM(self->_current_molecule_1, sub_idx); if (aam1 != 0) { aam2 = self->_context._target.getAAM(self->_current_molecule_2, super_idx); if (aam2 != 0) { auto it = self->_context._aam_core_first_side.find(aam1); aam = it != self->_context._aam_core_first_side.end() ? &(it->second) : nullptr; if (aam && *aam != aam2) return false; } } } if (self->_context._query_nei_counters != 0 && self->_context._target_nei_counters != 0) { const MoleculeAtomNeighbourhoodCounters& mol_count1 = self->_context._query_nei_counters->getCounters(self->_current_molecule_1); const MoleculeAtomNeighbourhoodCounters& mol_count2 = self->_context._target_nei_counters->getCounters(self->_current_molecule_2); if (!mol_count1.testSubstructure(mol_count2, sub_idx, super_idx, true)) return false; } int sub_atom_inv = self->_context._query->getInversion(self->_current_molecule_1, sub_idx); int super_atom_inv = self->_context._target.getInversion(self->_current_molecule_2, super_idx); if (sub_atom_inv != STEREO_UNMARKED && sub_atom_inv != super_atom_inv) return false; return true; } bool BaseReactionSubstructureMatcher::_Matcher::_matchBonds(Graph& subgraph, Graph& supergraph, int sub_idx, int super_idx, void* userdata) { BaseReactionSubstructureMatcher::_Matcher* self = (BaseReactionSubstructureMatcher::_Matcher*)userdata; if (self->_context.match_bonds != 0 && !self->_context.match_bonds(*self->_context._query, self->_context._target, self->_current_molecule_1, sub_idx, self->_current_molecule_2, super_idx, self->_am.get(), self->_context.context)) return false; return true; } void BaseReactionSubstructureMatcher::_Matcher::_removeAtom(Graph& subgraph, int sub_idx, void* userdata) { BaseReactionSubstructureMatcher::_Matcher* self = (BaseReactionSubstructureMatcher::_Matcher*)userdata; if (self->_context.remove_atom != 0) self->_context.remove_atom((BaseMolecule&)subgraph, sub_idx, self->_am.get()); } void BaseReactionSubstructureMatcher::_Matcher::_addBond(Graph& subgraph, Graph& supergraph, int sub_idx, int super_idx, void* userdata) { BaseReactionSubstructureMatcher::_Matcher* self = (BaseReactionSubstructureMatcher::_Matcher*)userdata; if (self->_context.add_bond != 0) self->_context.add_bond((BaseMolecule&)subgraph, (Molecule&)supergraph, sub_idx, super_idx, self->_am.get()); }
ccd35b8f700f31405f9eff80a4f674f6a68b042a
45dae9ac1e487ca45b53d54dc38a132f89a804f4
/auv_ekf_localization/src/noise_oneD_kf.cpp
842fb0f160dd3c6f5eb13f73e194be6e2e896b49
[]
no_license
ignaciotb/smarc_base
227c0a3daa00325a24741ca20d766290e0723e73
95f0cee7566dd42dacb5626a8cf7ecae3dd17b55
refs/heads/master
2018-07-16T07:54:17.297116
2018-04-09T09:41:46
2018-04-09T09:41:46
108,266,557
0
0
null
2017-10-25T12:25:34
2017-10-25T12:25:33
null
UTF-8
C++
false
false
483
cpp
noise_oneD_kf.cpp
#include "noise_oneD_kf/noise_oneD_kf.hpp" OneDKF::OneDKF(double mu_init, double sigma_init, double r, double q){ // Initial params mu_ = mu_init; sigma_ = sigma_init; r_ = r; q_ = q; } double OneDKF::filter(double input){ // Predict double mu_hat = mu_; double sigma_hat = sigma_ + r_; // Update double k_t = sigma_hat / (sigma_hat + q_); mu_ = mu_hat + k_t * (input - mu_hat); sigma_ = (1 - k_t) * sigma_hat; return mu_; }
db38c626d25b3283d9c696b0cd2d6cb8d3e28391
554dae615756ca43162041afc98ad7a99e90ae8f
/ConsoleApplication31/算法提高 简单加法.cpp
1565e49c41506305c63aff72588cc653f5fe7561
[]
no_license
David-Zanen/Algorithm
a015a0f8c11aa45b19278f4d3325c45a4291d53c
fc9bf10b04e1e58c4b3e907c609a190b3a0aee46
refs/heads/master
2020-04-27T06:45:09.789726
2017-02-09T09:33:49
2017-02-09T09:33:49
174,116,799
0
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
算法提高 简单加法.cpp
/*#include<iostream> using namespace std; int main() { int he = 0; for (int a = 0; a < 1000; a++) { int j = 0; if (a % 3 == 0 || a % 5 == 0) { if (a != 0) { cout << a << endl; } j = a; } he += j; } cout << he << endl; system("pause"); return 0; }*/
cfc963c90dd5abb9940ac54e5e1283ce5a59a996
d40855c89edbb26a2bdb5ce70467365c7cafd7d5
/Ide/Interpreter.cpp
23e29691409e7b462ac7a9d6c731e0a7980a42ec
[]
no_license
markorovi/Primer-Proyecto-Datos-II
56f91b1e705290fecaeede43830ec3605550378b
fb6f81f8378bf8ad115146631cceee6a176719bd
refs/heads/master
2023-04-17T11:12:55.669279
2021-05-05T12:54:19
2021-05-05T12:54:19
353,549,961
0
0
null
2021-04-27T06:58:45
2021-04-01T02:32:21
C++
UTF-8
C++
false
false
43,902
cpp
Interpreter.cpp
// // Created by joel on 19/4/21. // #include "../Sockets/Parser.h" #include "mainwindow.h" #include <QJsonDocument> #include <QJsonObject> #include <QString> #include "Interpreter.h" Interpreter::Interpreter() { keyWords.append("int"); keyWords.append("long"); keyWords.append("char"); keyWords.append("float"); keyWords.append("double"); keyWords.append("struct"); keyWords.append("reference"); operators.append("+"); operators.append("-"); operators.append("*"); operators.append("/"); operators.append("equals"); operators.append("getAddr"); operators.append("getValue"); } Interpreter::Interpreter(QPlainTextEdit *terminalOutput, QPlainTextEdit *_appLog) { terminal = terminalOutput; appLog = _appLog; keyWords.append("int"); keyWords.append("long"); keyWords.append("char"); keyWords.append("float"); keyWords.append("double"); keyWords.append("struct"); keyWords.append("reference"); operators.append("+"); operators.append("-"); operators.append("*"); operators.append("/"); operators.append("equals"); operators.append("getAddr"); operators.append("getValue"); } Interpreter::~Interpreter() { } void Interpreter::readCode(QString code) { QStringList lines = code.split("\n"); lines.removeAll(""); for (int i = 0; i < lines.size(); i++) { words.append(lines[i].split(" ")); words[i].removeAll(""); } for (int i = 0; i < words.size() - 1; i++) { for (int j = 0; j < words[i].size(); j++) { if (words[i][j].contains("\"") && words[i][j].count("\"") == 1) { words[i][j] = words[i][j] + " " + words[i][j + 1]; //words[i].remove(j + 1); words[i].removeAt(j + 1); j--; } if (j == words[i].size() - 1 && words[i][j].contains(";")) { words[i][j].remove(";"); words[i].append("-endl"); } } } for (int i = 0; i < words.size(); i++) { for (int j = 0; j < words[i].size(); j++) { if (words[i][j].contains("reference")) { QStringList aux = words[i][j].split("<"); words[i][j] = aux[0]; words[i].insert(j + 1, "<"); aux = aux[1].split(">"); words[i].insert(j + 2, aux[0]); words[i].insert(j + 3, ">"); } else if (words[i][j].contains("print") || words[i][j].contains("printf") || words[i][j].contains("getAddr") || words[i][j].contains("getValue")) { QStringList aux = words[i][j].split("("); words[i][j] = aux[0]; words[i].insert(j + 1, "("); aux = aux[1].split(")"); words[i].insert(j + 2, aux[0]); words[i].insert(j + 3, ")"); } else if (words[i][j].contains(".")) { QStringList aux = words[i][j].split("."); words[i][j] = aux[0]; words[i].insert(j + 1, "dot"); words[i].insert(j + 2, aux[1]); } else if (words[i][j].contains("=")) { words[i][j].replace("=", "equals"); } } } for (int i = 0; i < words.size(); i++) { for (int j = 0; j < words[i].size(); j++) { if (words[i][j].contains("\t")) { words[i][j].replace("\t", ""); } } } for (int i = 0; i < words.size(); i++) { for (int j = 1; j < words[i].size() - 1; j++) { if (words[i][j] == "dot") { words[i][j - 1] = words[i][j - 1] + "." + words[i][j + 1]; words[i].removeAt(j + 1); words[i].removeAt(j); j--; j--; } } } int lastAux = words.size() - 1; words.last()[words.last().size() - 1].remove(";"); words.last().append("-endl"); qDebug() << "\n\n"; showCode(); qDebug() << "\n\n"; } QList<QStringList> Interpreter::getWords() { return words; } QString Interpreter::whatIs(QString word) { QString strAux; if (keyWords.contains(word)) { strAux = "keyWord"; } else if (operators.contains(word)) { strAux = "operator"; } else if (word == "{") { strAux = "startScope"; } else if (word == "}") { strAux = "endScope"; } else if (word == "cout" || word == "print" || word == "printf") { strAux = "stdKey"; } else if (word == "(" || word == "<<") { strAux = "bracketStart"; } else if (word == ")") { strAux = "bracketFinal"; } else if (word == "-endl") { strAux = "end"; } else if (word == "dot") { strAux = "accessTo"; } else if (word == "->") { strAux = "error"; } else { strAux = "variable"; } return strAux; } void Interpreter::interpretCode(int line) { //qDebug()<<words[line]<<"\n"; QJsonDocument doc; if(inStruct){ qDebug()<<"El valor de inStruct es: Verdadero"; } else{ qDebug()<<"El valor de inStruct es: Falso"; } //qDebug()<<words[line]; for(int i=0; i<words[line].size(); i++){ //qDebug()<<whatIs(words[line][i]); } freeingScope = false; if (line < words.size()) { scope = true; if (words[line].size() == 1) { if (whatIs(words[line][0]) == "startScope") { if (inScope) { showInAppLog("Error: No se puede concatenar scopes"); } else if (inStruct) { showInAppLog("Error: No se pueden concatenar scopes"); } else { inScope = true; scope = false; showInAppLog("Un Scope ha sido abierto"); doc.setObject(Parser::Nothing()); std::string json = Parser::ReturnChar(doc); MainWindow::setJson(json); } } else if (whatIs(words[line][0]) == "endScope") { doc.setObject(Parser::Nothing()); //Genera el documento con los rasgos de dentro std::string Json = Parser::ReturnChar(doc); //String to char (to be able to send it through sockets) //Lo pasa a string MainWindow::setJson(Json); if (inScope) { inScope = false; freeingScope = true; showInAppLog("Un Scope ha sido cerrado"); doc.setObject(Parser::Nothing()); std::string json = Parser::ReturnChar(doc); MainWindow::setJson(json); } else if (inStruct) { inStruct = false; qDebug()<<"Dentro del struct hay:"; structList.append(structs); structs.clear(); for(int i = 0; i<structList.size(); i++){ qDebug()<<""; for (int j = 0; j < structList[i].size(); ++j) { qDebug()<<structList[i][j]; } } } else { showInAppLog("Error: no se puede cerrar el Struct o el scope si no se ha iniciado uno previamente"); } } else { showInAppLog("Error: parámetros incorrectos"); } } else if (words[line].size() == 3 && words[line][0] == "struct" && whatIs(words[line][1]) == "variable" && whatIs(words[line][2]) == "startScope") { qDebug()<<"Se encuentra declarando un struct"; if (inStruct) { showInAppLog("Error: No se permite hacer concatenación de structs"); } else if (inScope) { showInAppLog("Error: No se permite hacer concatenación de structs con scopes"); } else { inStruct = true; auxStructs.append(words[line][1]); structs.append(auxStructs); auxStructs.clear(); } } else { //qDebug()<<"Starting..."; //qDebug()<<whatIs(words[line][words[line].size()-1]); if (whatIs(words[line][words[line].size() - 1]) == "end") { //qDebug()<<whatIs(words[line][0]); //qDebug()<<words[line][0]; if (whatIs(words[line][0]) == "keyWord") { //qDebug()<<whatIs(words[line][1]); if (whatIs(words[line][1]) == "variable" /*&& !isExisting(words[line][1])*/) { //qDebug()<<whatIs(words[line][2]); if (whatIs(words[line][2]) == "end") { //qDebug()<<"Declaration without definition"; QString type = words[line][0]; QString label = words[line][1]; QString Value = "null"; if(inStruct){ auxStructs.append(type); auxStructs.append(label); auxStructs.append(Value); structs.append(auxStructs); auxStructs.clear(); doc.setObject(Parser::Nothing()); //Genera el documento con los rasgos de dentro std::string Json = Parser::ReturnChar(doc); //String to char (to be able to send it through sockets) //Lo pasa a string MainWindow::setJson(Json); } else { doc.setObject(Parser::CreateJsonObj_NoAddress(type.toStdString(), label.toStdString(),"")); //Genera el documento con los rasgos de dentro std::string Json = Parser::ReturnChar(doc); //String to char (to be able to send it through sockets) //Lo pasa a string MainWindow::setJson(Json); qDebug() << type << label << Value; if (inScope) { scopeLabels.append(label); } } } else if (whatIs(words[line][2]) == "operator" && words[line][2] == "equals") { //qDebug()<<whatIs(words[line][3]); if (whatIs(words[line][3]) == "variable" /*&& isExisting(words[line][3])*/) { //qDebug()<<"3 caminos: número, char o variable"; if (!isNumber(words[line][3]) && !isChar(words[line][3])) { words[line][3] = getValue(words[line][3]); //qDebug()<<getValue(words[line][3]); } if (isNumber(words[line][3])) { //qDebug()<<"Número"; if ((words[line][0] == "int" || words[line][0] == "long" || words[line][0] == "float" || words[line][0] == "double")) { if (whatIs(words[line][4]) == "end") { QString type = words[line][0]; QString label = words[line][1]; QString Value = words[line][3]; doc.setObject(Parser::CreateJsonObj_NoAddress(type.toStdString(), label.toStdString(), Value.toStdString())); std::string Json = Parser::ReturnChar( doc); //String to char (to be able to send it through sockets) //Lo pasa a string MainWindow::setJson(Json); qDebug() << type << label << Value; if (inScope) { scopeLabels.append(label); } else if (inStruct) { qDebug()<<"Dentro del struct está: "; for(int i=0; i<structs.size();i++){ qDebug()<<structs[i]; } //structs[0].append(label); } } else if (whatIs(words[line][4]) == "operator") { if (words[line][4] == "+" || words[line][4] == "-" || words[line][4] == "*" || words[line][4] == "/") { if (whatIs(words[line][5]) == "end") { showInAppLog("Error: No se ha declarado correctamente la operación"); } else if (whatIs(words[line][5]) == "variable") { if (whatIs(words[line][6]) == "end") { if (!isNumber(words[line][5]) && !isChar(words[line][5])) { words[line][5] = getValue(words[line][5]); } QString type = words[line][0]; QString label = words[line][1]; QString Value; if (isNumber(words[line][5])) { if (words[line][4] == "+") { if (words[line][0] == "int") { //qDebug()<<"int declarado"; Value = QString::number((words[line][3].toInt() + words[line][5].toInt())); if (inScope) { scopeLabels.append(label); } } else if (words[line][0] == "float") { QString Value = QString::number((words[line][3].toFloat() + words[line][5].toFloat())); if (inScope) { scopeLabels.append(label); } } else if (words[line][0] == "double") { QString Value = QString::number((words[line][3].toDouble() + words[line][5].toDouble())); if (inScope) { scopeLabels.append(label); } } else if (words[line][0] == "long") { QString Value = QString::number((words[line][3].toLong() + words[line][5].toLong())); if (inScope) { scopeLabels.append(label); } } else { qDebug() << "Error"; } } else if (words[line][4] == "-") { if (words[line][0] == "int") { QString Value = QString::number((words[line][3].toInt() - words[line][5].toInt())); if (inScope) { scopeLabels.append(label); } } else if (words[line][0] == "float") { QString Value = QString::number((words[line][3].toFloat() - words[line][5].toFloat())); if (inScope) { scopeLabels.append(label); } } else if (words[line][0] == "double") { QString Value = QString::number((words[line][3].toDouble() - words[line][5].toDouble())); if (inScope) { scopeLabels.append(label); } } else if (words[line][0] == "long") { QString Value = QString::number((words[line][3].toLong() - words[line][5].toLong())); if (inScope) { scopeLabels.append(label); } } } else if (words[line][4] == "*") { if (words[line][0] == "int") { QString Value = QString::number((words[line][3].toInt() * words[line][5].toInt())); if (inScope) { scopeLabels.append(label); } } else if (words[line][0] == "float") { QString Value = QString::number((words[line][3].toFloat() *words[line][5].toFloat())); if (inScope) { scopeLabels.append(label); } } else if (words[line][0] == "double") { QString Value = QString::number((words[line][3].toDouble() *words[line][5].toDouble())); if (inScope) { scopeLabels.append(label); } } else if (words[line][0] == "long") { QString Value = QString::number((words[line][3].toLong() * words[line][5].toLong())); if (inScope) { scopeLabels.append(label); } } } else if (words[line][4] == "/") { if (words[line][0] == "int") { if (words[line][5].toInt() != 0) { QString Value = QString::number((words[line][3].toInt() /words[line][5].toInt())); if (inScope) { scopeLabels.append(label); } } } else if (words[line][0] == "float") { if (words[line][5].toFloat() != 0) { QString Value = QString::number((words[line][3].toFloat() /words[line][5].toFloat())); if (inScope) { scopeLabels.append(label); } } } else if (words[line][0] == "double") { if (words[line][5].toDouble() != 0) { QString Value = QString::number((words[line][3].toDouble() /words[line][5].toDouble())); if (inScope) { scopeLabels.append(label); } } } else if (words[line][0] == "long") { if (words[line][5].toLong() != 0) { QString Value = QString::number((words[line][3].toLong() / words[line][5].toLong())); if (inScope) { scopeLabels.append(label); } } else { showInAppLog("Error: no se puede dividir entre 0"); } } else { //Error showInAppLog("Error: tipo de variable incorrecto"); } } else { //Error showInAppLog("Error: Operador incorrecto"); } if(Value!=NULL){ if (!inStruct){ toDeclarate(type,label,Value); } else { doc.setObject(Parser::Nothing()); //Genera el documento con los rasgos de dentro std::string Json = Parser::ReturnChar(doc); //String to char (to be able to send it through sockets) //Lo pasa a string MainWindow::setJson(Json); auxStructs.append(type); auxStructs.append(label); auxStructs.append(Value); structs.append(auxStructs); auxStructs.clear(); } } } else { showInAppLog("Se ha ingrsado un valor incorrecto"); } } else { //Error showInAppLog("Error: Se debe terminar la línea con ;"); } } else { //Error showInAppLog("Error: Se ha digitado una variable incorrecta"); } } else { showInAppLog("Error: no se puede realizar esta operación"); } } else { showInAppLog("Error: se ha digitado algo incorrecto"); } } else if (isChar(words[line][3])) { if (words[line][0] == "char") { //qDebug()<<"Char"; if (whatIs(words[line][4]) == "end") { QString type = words[line][0]; QString label = words[line][1]; QString Value = words[line][3]; Value.remove("\""); if (Value.size() == 1) { doc.setObject(Parser::CreateJsonObj_NoAddress(type.toStdString(),label.toStdString(), Value.toStdString())); std::string Json = Parser::ReturnChar(doc); //String to char (to be able to send it through sockets) //Lo pasa a string MainWindow::setJson(Json); qDebug() << type << label << Value; if (inScope) { scopeLabels.append(label); } } else { showInAppLog("Error: no ha ingresado un char"); } } else { //Error showInAppLog("Error: Se debe terminar la línea con ;"); } } else { showInAppLog("Error: no existe ese tipo de variable"); } } else if (words[line][3].contains("\"")) { showInAppLog("Error: se ha digitado algo incorrecto"); } else { //Variable guardada en memoria //Buscar variable en memoria // QString aux = getValue(words[line][3]); showInAppLog("Error: se ha producido un error"); // showInAppLog(aux); } } else if(isChar(words[line][3])){ if(whatIs(words[line][4])=="end"){ //qDebug()<<"hola"; words[line][3].remove("\""); QString type = words[line][0]; QString label = words[line][1]; QString Value = words[line][3]; if(Value.size()<2){ toDeclarate(type, label, Value); } else { showInAppLog("Error: No se ha ingresado un char"); } } else { showInAppLog("Error: Se debe terminar la línea con ;"); } } else { //Error showInAppLog("Error: No se reconoce la variable"); // QString aux = getValue(words[line][3]); // showInAppLog(aux); } } else { //Error showInAppLog("Error: No se reconoce la variable"); } } else { //Error showInAppLog("Error: se ha digitado un operador incorrecto"); } } else if (whatIs(words[line][0]) == "variable") { //Buscar si existe y si no, tirar error } else if (whatIs(words[line][0]) == "stdKey") { doc.setObject(Parser::Nothing()); std::string Json = Parser::ReturnChar(doc); //String to char (to be able to send it through sockets) //Lo pasa a string MainWindow::setJson(Json); //Printear en la terminal } else { //Error showInAppLog("Error: se ha digitado algo incorrecto"); } } else if ((whatIs(words[line][0]) == "stdKey")) { doc.setObject(Parser::Nothing()); std::string Json = Parser::ReturnChar(doc); //String to char (to be able to send it through sockets) //Lo pasa a string MainWindow::setJson(Json); if ((whatIs(words[line][1]) == "bracketStart")) { if (words[line][1] == "<<") { if (whatIs(words[line][2]) == "variable") { if (whatIs(words[line][3]) == "end") { if(!isNumber(words[line][2])&&!isChar(words[line][2])){ words[line][2]=getValue(words[line][2]); } showInTerminal(words[line][2]); } else { showInAppLog("Error: Se debe terminar la línea con ;"); } } else { showInAppLog("Error: No se reconoce la variable"); } } else if (words[line][1] == "(") { } } else { showInAppLog("Error: no se puede utilizar el cout"); } } else if(isStruct(words[line][0])){ if(whatIs(words[line][1])=="variable"){ if(whatIs(words[line][2])=="end"){ int integers = 0, doubles = 0, longs = 0, floats = 0, chars = 0; for(int i = 0; i<structList.size(); i++) { if(words[line][0]==structList[i][0][0]){ for (int j = 0; j < structList[i].size(); j++) { integers += structList[i][j].count("int"); doubles += structList[i][j].count("double"); longs += structList[i][j].count("long"); floats += structList[i][j].count("float"); chars += structList[i][j].count("char"); } doc.setObject(Parser::CreateJsonObj_NewStructObject(words[line][1].toStdString(), std::to_string(integers),std::to_string(doubles),std::to_string(longs),std::to_string(floats),std::to_string(chars))); std::string json = Parser::ReturnChar(doc); MainWindow::setJson(json); client->Start(); usleep(10000); for (int j = 1; j<structList[i].size(); j++){ qDebug()<<"Tipo de dato: "<<structList[i][j][0]; qDebug()<<"Struct al que pertenece "<<structList[i][0][0]; qDebug()<<"Nombre del atributo: "<<structList[i][j][1]; doc.setObject(Parser::CreateJsonObj_FillStruct(structList[i][j][0].toStdString(), structList[i][0][0].toStdString(), structList[i][j][1].toStdString())); std::string json = Parser::ReturnChar(doc); MainWindow::setJson(json); client->Start(); usleep(10000); } } } qDebug()<<"Cantidad de ints:"<<integers; qDebug()<<"Cantidad de doubles:"<<doubles; qDebug()<<"Cantidad de longs:"<<longs; qDebug()<<"Cantidad de floats:"<<floats; qDebug()<<"Cantidad de char:"<<chars; } else { showInAppLog("Error: Se debe terminar la línea con ;"); } } else { showInAppLog("Error: No se reconoce la variable"); } } else if(askFor(words[line][0])=="struct"){ qDebug()<<"Sí es un struct"; qDebug()<<words[line][1]; if(whatIs(words[line][1])=="accessTo"){ qDebug()<<"IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII"; qDebug()<<isAttribute(words[line][0], words[line][2]); qDebug()<<"EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"; if(isAttribute(words[line][0], words[line][2])=="true"){ qDebug()<<"Sí es un atributo"; if(whatIs(words[line][3])=="equals"){ qDebug()<<"Sí es un igual"; if(whatIs(words[line][4])=="variable"){ qDebug()<<"Sí es una variable"; if(whatIs(words[line][5])=="end"){ if(!isNumber(words[line][4])&&!isChar(words[line][4])) { getValue(words[line][4]); } qDebug()<<"Entrada final"; } else { showInAppLog("Error: No fue posible realizar la instruccion"); } } else { showInAppLog("Error: No fue posible realizar la instruccion"); } } else { showInAppLog("Error: No fue posible realizar la instruccion"); } } else { showInAppLog("Error: No fue posible realizar la instruccion"); } } else { showInAppLog("Error: No fue posible realizar la instruccion"); } } else { //Error showInAppLog("Error: No fue posible realizar la instruccion"); } } else{ showInAppLog("Error: Se debe terminar la línea con ;"); } } } qDebug() << scopeLabels; //qDebug()<< MainWindow::getJson().c_str()<<endl; // QJsonDocument doc2 = Parser::ReturnJson(MainWindow::getJson); //Devolver lo que llego por el socket a json // std::cout<<Parser::ReturnStringValueFromJson(doc, "name"); //Obtener un valor de json } void Interpreter::showCode() { for (int i = 0; i < words.size(); i++) { qDebug() << words[i]; } } bool Interpreter::isNumber(QString value) { bool aux = true; bool dotOne = true; for (int i = 0; i < value.size(); i++) { QString a = "."; aux = value[i].isDigit(); if (value[value.size() - 1] == a[0]) { dotOne = false; aux = false; } if (!aux) { if (value[i] == a[0] && dotOne) { aux = true; dotOne = false; } else { break; } } } return aux; } bool Interpreter::isChar(QString value) { bool aux = false; if(value[0]=="\"" && value[2]=="\"" && value.size()==3){ qDebug()<<value; aux = true; } else if(value.startsWith("\"") && value.endsWith("\"") && value.count("\"")==2 && value.size()>3){ aux=true; } aux = value.startsWith("\"")&&value.endsWith("\"")&&value.count("\"")<3; return aux; } void Interpreter::setTerminal(QPlainTextEdit *terminalOutput) { terminal = terminalOutput; } void Interpreter::setAppLog(QPlainTextEdit *newAppLog) { appLog = newAppLog; } void Interpreter::showInTerminal(QString msg) { terminal->appendPlainText(">> " + msg); } void Interpreter::showInAppLog(QString msg) { appLog->appendPlainText(">> " + msg); if(msg.contains("Error")) { setStopProgram(true); } } void Interpreter::freeScope() { freeingScope = true; } bool Interpreter::isScope() const { return scope; } bool Interpreter::isFreeingScope() const { return freeingScope; } const QStringList &Interpreter::getScopeLabels() const { return scopeLabels; } void Interpreter::setFreeingScope(bool freeingScope) { Interpreter::freeingScope = freeingScope; } void Interpreter::setClient(Client *client) { Interpreter::client = client; } QString Interpreter::getValue(QString aux) { QJsonDocument doc; doc.setObject(Parser::CreateJsonObj_Asking(aux.toStdString())); std::string json = Parser::ReturnChar(doc); MainWindow::setJson(json); client->Start(); qDebug() << "LO QUE IMPORTA, aux = " + aux + " y el qDebug " + QString::fromStdString(Parser::ReturnStringValueFromJson(Client::getReceived(), "value")); return QString::fromStdString(Parser::ReturnStringValueFromJson(Client::getReceived(), "value")); } void Interpreter::toDeclarate(QString type, QString label, QString Value){ QJsonDocument doc; doc.setObject(Parser::CreateJsonObj_NoAddress(type.toStdString(), label.toStdString(), Value.toStdString())); std::string Json = Parser::ReturnChar(doc); //String to char (to be able to send it through sockets) //Lo pasa a string MainWindow::setJson(Json); qDebug() << type << label << Value; } bool Interpreter::isStruct(QString aux) { for (int i = 0; i < structList.size(); ++i) { if(structList[i][0][0]==aux){ return true; } } return false; } QString Interpreter::askFor(QString aux) { QJsonDocument doc; doc.setObject(Parser::CreateJsonObj_whatType(aux.toStdString())); std::string Json = Parser::ReturnChar(doc); //String to char (to be able to send it through sockets) //Lo pasa a string MainWindow::setJson(Json); client->Start(); usleep(10000); return QString::fromStdString(Parser::ReturnStringValueFromJson(Client::getReceived(), "value")); } QString Interpreter::isAttribute(QString name, QString attribute) { QJsonDocument doc; doc.setObject(Parser::CreateJsonObj_isAttribute(name.toStdString(),attribute.toStdString())); std::string Json = Parser::ReturnChar(doc); //String to char (to be able to send it through sockets) //Lo pasa a string MainWindow::setJson(Json); qDebug()<<QString::fromStdString(Parser::ReturnStringValueFromJson(doc,"toDo"));; client->Start(); //usleep(10000); // qDebug()<<"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // if(QString::fromStdString(Parser::ReturnStringValueFromJson(Client::getReceived(), "value"))=="true"){ // aux= true; // } else { // aux= false; // } return QString::fromStdString(Parser::ReturnStringValueFromJson(Client::getReceived(), "value")); } void Interpreter::setStopProgram(bool stopProgram) { Interpreter::stopProgram = stopProgram; } bool Interpreter::isStopProgram() const { return stopProgram; }
de1c531ee00fd296952619a49d79feaf2fa877d8
e5efbbf17f8e20a54d0846b8cecb12120fa24270
/User.h
903c6f6d5617f7d3705eb323a955d6ee88a1b3e6
[]
no_license
Rehaoulia/RDBMS
e2cfd0c51ad8bda249a056795a716024cd9c3606
0430cff6b81dc00c2cebee0ae3aca1e0c5fc7f8f
refs/heads/master
2022-06-13T02:55:03.398610
2020-05-11T13:32:47
2020-05-11T13:32:47
263,051,310
0
0
null
null
null
null
UTF-8
C++
false
false
498
h
User.h
#ifndef USER_H #define USER_H #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; class User { string username; string password; public: void setUsername(string username) { this->username = username; } string getUsername() { return this->username; } void setPassword(string password) { this->password = password; } string getPassword() { return this->password; } }; #endif /* USER_H */
5d143242a9c6d72892e92f7c6b9e2dbfd24dd952
4de4ab6973267f0a57dcc594f7170cc1051d67b1
/math/prime-factors.h
7c8f374d6ce2415416a6398ccd0567bd8719f281
[]
no_license
ilpropheta/daje
c358f33106de8326ae6e3eed4850a3be3e190b38
e76b9dc2d53492d50676ad43109294b33665ae9d
refs/heads/master
2020-12-25T16:47:57.094988
2019-01-23T11:39:31
2019-01-23T11:39:31
38,163,724
7
1
null
null
null
null
UTF-8
C++
false
false
852
h
prime-factors.h
#include <cmath> #include <vector> std::vector<int> prime_factors_of(int n) { std::vector<int> factors; while (n%2 == 0) // while n is even { factors.push_back(2); n = n/2; } for (auto i=3; i <= std::sqrt(n); i+=2) // i is odd here (skip 2 numbers) { while (n%i == 0) { factors.push_back(i); n = n/i; } } if (n > 2) factors.push_back(n); return factors; } int sum_of_prime_factors(int n) { auto sum = 0; while (n%2 == 0) // while n is even { sum += 2; n = n/2; } for (auto i=3; i <= std::sqrt(n); i+=2) // i is odd here (skip 2 numbers) { while (n%i == 0) { sum += i; n = n/i; } } if (n > 2) sum += n; return sum; }
4b1703c95e6fbbd1170ecc47979d4092038f8537
0263f671a43ccfc240b5800be9ad81ab9139af7f
/src/loss.h
76a8e65a295cdfdd4de61ec85aec9ee84ab9ed7e
[]
no_license
MhYao2014/PMIVec
02433644de22e55d613a24c9f7370efddecf1cb6
339b355d4fdd4d05db06ffc9cc1a0d347e8b213f
refs/heads/master
2023-01-18T19:00:06.051058
2020-11-29T01:43:36
2020-11-29T01:43:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,551
h
loss.h
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <memory> #include <random> #include <vector> #include "matrix.h" #include "model.h" #include "real.h" #include "utils.h" #include "vector.h" namespace fasttext { class Loss { private: protected: std::vector<real> t_sigmoid_; std::vector<real> t_log_; std::shared_ptr<Matrix>& wo_; real log(real x) const; real sigmoid(real x) const; public: explicit Loss(std::shared_ptr<Matrix>& wo); virtual ~Loss() = default; virtual void forward( const std::vector<int32_t>& targets, int32_t targetIndex, int32_t secTargetIdex, Model::State& state, real lr, bool backprop) = 0; }; class BinaryLogisticLoss : public Loss { protected: void biLogiFirst( int32_t target, Model::State& state, bool labelIsPositive, real lr, bool backprop, real &tmpLossFirst) const; void biLogiSecond( int32_t outId, int32_t secOutId, Model::State& state, bool labelIsPositive, real lr, bool backprop, real &tmpLossSecond) const; public: explicit BinaryLogisticLoss(std::shared_ptr<Matrix>& wo); virtual ~BinaryLogisticLoss() noexcept override = default; }; class NegativeSamplingLoss : public BinaryLogisticLoss { protected: static const int32_t NEGATIVE_TABLE_SIZE = 10000000; int neg_; std::vector<int32_t> negatives_; std::uniform_int_distribution<size_t> uniform_; int32_t getNegative(int32_t target, std::minstd_rand& rng); public: explicit NegativeSamplingLoss( std::shared_ptr<Matrix>& wo, int neg, const std::vector<int64_t>& targetCounts); ~NegativeSamplingLoss() noexcept override = default; void forward( const std::vector<int32_t>& targets, int32_t targetIndex, int32_t secTargetIdex, Model::State& state, real lr, bool backprop) override; }; } // namespace fasttext
627135c07456eb109a7ebdb518e919d7ae0476d2
fa306bcc990815d4504c58a9dede66afe59c318f
/src/marrhildreth.cpp
acece9a68d4b18d38030dad738f269b9e210c851
[]
no_license
buzzcz/ZVI
1bc15e4d5f19699d6f4f809f9e6c3e2a92b074c6
ab28c3bfb16794300b9f3fdaf477610b8ea287fd
refs/heads/master
2021-01-21T04:41:04.984709
2016-06-23T06:47:22
2016-06-23T06:47:22
54,061,277
0
0
null
null
null
null
UTF-8
C++
false
false
4,234
cpp
marrhildreth.cpp
#include "marrhildreth.h" #include "ui_marrhildreth.h" #include "QDebug" MarrHildreth::MarrHildreth(cv::Mat *src, QWidget *parent) : QMainWindow(parent), ui(new Ui::MarrHildreth) { ui->setupUi(this); MarrHildreth::resize(parent->size()); prepareGUI(); cv::cvtColor(*src, img, CV_BGR2GRAY); } MarrHildreth::~MarrHildreth() { delete ui; } void MarrHildreth::showEvent(QShowEvent *event) { QMainWindow::showEvent(event); detectEdges(); } void MarrHildreth::resizeEvent(QResizeEvent *event) { QMainWindow::resizeEvent(event); showImage(); } void MarrHildreth::showImage() { if (!edges.empty()) { cv::Mat tmp; double width = ui->label->width(), height = ui->label->height(); if (width >= height) { double ratio = height / edges.rows; width = edges.cols * ratio; } else { double ratio = width / edges.cols; height = edges.rows * ratio; } cv::resize(edges, tmp, cv::Size(width, height)); ui->label->setPixmap(QPixmap::fromImage(QImage((unsigned char*) tmp.data, tmp.cols, tmp.rows, tmp.step, QImage::Format_Indexed8))); } } void MarrHildreth::prepareGUI() { connect(ui->saveButton, SIGNAL(clicked(bool)), this, SLOT(saveImage())); connect(ui->tresholdSpin, SIGNAL(valueChanged(int)), this, SLOT(detectEdges())); } void MarrHildreth::detectEdges() { cv::Mat blured; cv::blur(img, blured, cv::Size(3,3)); edges = blured.clone(); int logOperator[5][5] = { {0, 0, -1, 0, 0}, {0, -1, -2, -1, 0}, {-1, -2, 16, -2, -1}, {0, -1, -2, -1, 0}, {0, 0, -1, 0, 0} }; int l1 = 5; int border1 = 2; int border2 = 1; int h = edges.rows; int w = edges.cols; int tempImage[h][w]; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { tempImage[i][j] = 0; edges.at<uchar>(i, j) = 0; } } //log convolution int value; for (int i = border1; i < h - border1; i++) { for (int j = border1; j < w - border1; j++) { value = 0; for (int k = 0; k < l1; k++) { for (int l = 0; l < l1; l++) { value = value + (logOperator[k][l] * blured.at<uchar>(i - border1 + k, j - border1 + l)); } } tempImage[i][j] = value; } } //zero crossing + tresholding int max = 0; for (int k = 0;k < h; k++) { for (int i = 0; i < w; i++) { if (tempImage[k][i] > max) max = tempImage[k][i]; } } int treshold = this->ui->tresholdSpin->value(); for (int i = border2; i < h - border2; i++) { for (int j = border2; j < w - border2; j++) { if (tempImage[i][j] != 0) { if ((tempImage[i][j + 1] >= 0 && tempImage[i][j - 1] < 0) || (tempImage[i][j + 1] < 0 && tempImage[i][j - 1] >= 0)) { if (tempImage[i][j] > treshold) { edges.at<uchar>(i, j) = 255; } } else if ((tempImage[i + 1][j] >= 0 && tempImage[i - 1][j] < 0) || (tempImage[i + 1][j] < 0 && tempImage[i - 1][j] >= 0)) { if (tempImage[i][j] > treshold) { edges.at<uchar>(i, j) = 255; } } else if ((tempImage[i + 1][j + 1] >= 0 && tempImage[i - 1][j - 1] < 0) || (tempImage[i + 1][j + 1] < 0 && tempImage[i - 1][j - 1] >= 0)) { if (tempImage[i][j] > treshold) { edges.at<uchar>(i, j) = 255; } } else if ((tempImage[i - 1][j + 1] >= 0 && tempImage[i + 1][j - 1] < 0) || (tempImage[i - 1][j + 1] < 0 && tempImage[i + 1][j - 1] >= 0)) { if (tempImage[i][j] > treshold) { edges.at<uchar>(i, j) = 255; } } } } } showImage(); } void MarrHildreth::saveImage() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save Image"), QDir::currentPath(), tr("Image Files (*.png *.jpg *.bmp)")); if (!fileName.isNull() && !fileName.isEmpty()) { QFileInfo info(fileName); if (info.suffix().isNull() || info.suffix().isEmpty()) fileName.append(".png"); else if (QString::compare(info.suffix(), "png", Qt::CaseInsensitive) != 0 && QString::compare(info.suffix(), "jpg", Qt::CaseInsensitive) != 0 && QString::compare(info.suffix(), "bmp", Qt::CaseInsensitive) != 0) fileName.append(".png"); imwrite(fileName.toStdString(), edges); QMessageBox ok; ok.setWindowTitle(tr("Image saved")); ok.setText(tr("Image has been saved succesfully")); ok.exec(); } }
db9b1d3795cbaa7fd2d48ac4aef9ceb1a8aa2c1a
2f1603e96c470b091193c93fbac78734ceb91767
/src/F_euclidean.cpp
47de9e7c20146b3941dbc9d89505d8004fc41867
[]
no_license
YolandaKok/Recommender-System
8e84aa78a05e2bb0247f50a5fb846ca2a55dca2f
de9215f345db9697e2f37013ddf9510547a0e99d
refs/heads/master
2020-03-31T10:00:13.189914
2019-03-26T21:25:29
2019-03-26T21:25:29
152,118,743
2
0
null
null
null
null
UTF-8
C++
false
false
1,623
cpp
F_euclidean.cpp
#include "F.h" #include <iostream> #include <random> #include "F_euclidean.h" #include "H_euclidean.h" #include <ctime> #include <functional> #include "H.h" using namespace std; F_euclidean::F_euclidean(int k, int tablesize, double dimension, double w):F(k, dimension) { /* Generate Rk */ generateRk(k); this->tablesize = tablesize; this->dimension = dimension; /* Create k H_euclidean functions */ for( int i = 0; i < getK(); i++ ) { setH((H_euclidean*)new H_euclidean(w, dimension, 0.0, w), i); } } /* Generate Rk values for the euclidean F */ void F_euclidean::generateRk(int k) { int i; this->Rk = (int*) malloc(sizeof(int) * getK()); for(i = 0; i < getK(); i++) this->Rk[i] = rand() % (RAND_MAX / 2); } int F_euclidean::structureSize() { return sizeof(class F_euclidean) + sizeof(int) * getK() + getK() * sizeof(class H_euclidean); } int F_euclidean::uniform_distribution(int rangeLow, int rangeHigh) { double myRand = rand()/(1.0 + RAND_MAX); int range = rangeHigh - rangeLow + 1; int myRand_scaled = (myRand * range) + rangeLow; return myRand_scaled; } int F_euclidean::hashForPoint(Point *p) { long long int M = (long long int)pow(2.0, 32.0) - 5, mod, sum = 0; for(int i = 0; i < getK(); i++) { sum += modulo((getH(i)->hashForPoint(p) * this->Rk[i]), M); } sum = modulo(sum, M); sum = modulo(sum, this->tablesize); return sum; } /* Used the definition of modulo for positive and negative number */ long long int F_euclidean::modulo(long long int x, long long y) { return (x % y + y) % y; } F_euclidean::~F_euclidean() { free(this->Rk); }
414c4bd93791ba3cd81538815c643755b0a1b729
ecddb70401ca5f5527e46cab79523bfe4f03567e
/Codeforces/908D.cpp
3d26acc27966bf0232f0637c3a8249608fadf4c4
[]
no_license
Hoikoro/procon
176d80e4fbb42ceb4b6e713ecc9b6e8dd1b2f784
40bb6e3c36cedd22a37b3f5f296c423de5f7aac0
refs/heads/master
2021-01-21T20:43:04.551437
2018-08-13T15:52:18
2018-08-13T15:52:18
94,674,970
0
0
null
null
null
null
UTF-8
C++
false
false
1,416
cpp
908D.cpp
#include <bits/stdc++.h> using namespace std; //make_tuple emplace_back next_permutation push_back make_pair second first setprecision #if MYDEBUG #include "lib/cp_debug.h" #else #define DBG(...) ; #endif using LL = long long; constexpr LL LINF=334ll<<53; constexpr int INF=15<<26; constexpr LL MOD=1E9+7; struct Problem{ LL k,pa,pb,pp; void solve(){ cin >> k >> pa >> pb; pp=pa+pb; vector<vector<LL>> dp (k+1,vector<LL>(k)); dp[1][0]=1; LL ans=0; for(LL i=1; i<=k; ++i){ for(LL j=0; j<k-i; ++j){ dp[i][j+i]+=(dp[i][j]*pb%MOD)*modpow(pp,min(i-1,k-1-i-j)); dp[i][j+i]%=MOD; dp[i+1][j]+=dp[i][j]*pa; dp[i+1][j]%=MOD; } for(LL j=k-i; j<k; ++j){ ans+=dp[i][j]*(((j+i)*pb+pa)%MOD)%MOD; ans%=MOD; } } LL den=modpow(modpow(pp,k-1)*pb%MOD,MOD-2); cout << ans*den%MOD << "\n"; } long long modpow(long long a, long long n,long long mod=MOD){ long long i=1,ret=1,p=a; while(i<=n){ if(i&n) ret=(ret*p)%mod; i=(i<<1); p=(p*p)%mod; } return ret; } }; int main(){ cin.tie(0); ios_base::sync_with_stdio(false); Problem p; p.solve(); return 0; }
f7e562c1ada92f8bf28506b85a2dc0602e09cd73
e5091c3a8477fa12e1adfdb1f3d826eb6e9bb2be
/Other/shell_game.cpp
093a9a3585f4aa4a07ff5817e50ab25567479e51
[]
no_license
leonardoAnjos16/Competitive-Programming
1db3793bfaa7b16fc9a2854c502b788a47f1bbe1
4c9390da44b2fa3c9ec4298783bfb3258b34574d
refs/heads/master
2023-08-14T02:25:31.178582
2023-08-06T06:54:52
2023-08-06T06:54:52
230,381,501
7
0
null
null
null
null
UTF-8
C++
false
false
367
cpp
shell_game.cpp
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout << setprecision(8) << fixed; long double r, R, h; cin >> r >> R >> h; long double H = h / (R - r) * R; long double theta = atan(H / R) / 2.0; long double ans = min(R * tan(theta), h / 2.0); cout << ans << "\n"; }
d74262cad28be3add57e6a4b9641a126f9ec1a8a
13a68c469c0a317cb86b98781ba63852a0d67b37
/include/Matching.h
5524e369a0e9297a8651996b975df5df3f473fa5
[]
no_license
kdeleo/HOTVR
25b110d549cca2363395d6f855154b6d0052963b
3aa3cccd1eaf3929bf93aa66ad3c749d19f544c5
refs/heads/master
2020-12-06T01:35:02.874985
2016-07-26T13:25:00
2016-07-26T13:25:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,286
h
Matching.h
#ifndef Matching_H #define Matching_H #include "SFrameTools/include/Objects.h" #include <fastjet/PseudoJet.hh> #include "SFrameTools/include/fwd.h" #include "SFrameTools/include/boost_includes.h" // for shared_array #include <TMVA/Reader.h> #include "TVector3.h" #include <limits> #include <algorithm> #include <memory> #include <TF1.h> #include "Utils.h" #include "EventCalc.h" #include "include/Cleaner.h" #include "FactorizedJetCorrector.h" #include "JetCorrectorParameters.h" #include <TStopwatch.h> #include <fastjet/PseudoJet.hh> //typedef ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > LorentzVectorXYZE; class Matching{ private: static Matching* m_instance; mutable SLogger m_logger; private: std::vector<fastjet::PseudoJet> _hadrons; //std::vector<fastjet::PseudoJet> _partons; std::vector<fastjet::PseudoJet> _parton_jets; fastjet::ClusterSequence* _clust_seq; TStopwatch timer; bool IsParton(GenParticle* p); GenParticle get_genparticle(GenParticle genparticle,std::vector<GenParticle>* genparticles, std::vector<int> &help); bool IsStableHadron(GenParticle* p); bool IsTop(GenParticle* p); bool FinalStateParton(GenParticle* p, std::vector<GenParticle>* genparticles); bool BeforeTopDecay(GenParticle* p, std::vector<GenParticle>* genparticles); GenParticle* GetDaughter(GenParticle* p, std::vector<GenParticle>* genparticles, int n); void UpdateSkipList(GenParticle* top, std::vector<GenParticle>* genparticles, std::vector<bool>& skip); fastjet::PseudoJet convert_particle(GenParticle* genparticle); std::vector<fastjet::PseudoJet> get_parton_jets(std::vector<fastjet::PseudoJet> parts); bool IsHadronic(GenParticle* p, std::vector<GenParticle>* genparticles); public: void Run_matching(std::vector<GenParticle>* genparticles); Matching(); ~Matching(); static Matching* Instance(); std::vector<fastjet::PseudoJet> get_hadrons(){return _hadrons;}; bool IsMatched(fastjet::PseudoJet jet, double matching_distance, fastjet::PseudoJet denominator_jet); fastjet::PseudoJet get_closest_jet(std::vector<fastjet::PseudoJet> jets,fastjet::PseudoJet denominator_jet); std::vector<fastjet::PseudoJet> get_denominator_jets(TString idVersion); // std::vector<fastjet::PseudoJet> get_genjets(); }; #endif
bf5dc81b6d2b3a51e589185781f2caf09018d846
a53b3537dd04e9c16ab9c1d656366d509c69231a
/gametreenode.h
60080ed45d366238fb3949fd24a603dec7752b1c
[]
no_license
igloooo/cpp-project-five-in-a-row
2e1fdad896e64918787ac5a6e4652bc73a7092b5
759e0e8b08bf3d3ac088ded58004e34f84bcc2f6
refs/heads/master
2021-06-02T21:03:43.140760
2018-08-08T08:54:06
2018-08-08T08:54:06
127,509,574
1
0
null
null
null
null
UTF-8
C++
false
false
1,937
h
gametreenode.h
/* * File: gametreenode.h * ----------------------------- * The file defines the interface for GameTreeNode class. */ #ifndef GAMETREENODE_H #define GAMETREENODE_H #include "gamemodel.h" #include "coordinate.h" #include <iostream> #include <string> #include <ostream> using namespace std; /* * Class: GameTreeNode * -------------------------- * This class represents a game tree. Note that the game tree currently uses * double linked lists to store children. */ class GameTreeNode { public: GameTreeNode(int x, int y, string color); GameTreeNode(Coordinate xy, string color); //~GameTreeNode(); bool hasParent(); bool hasSiblingH(); bool hasSiblingT(); bool hasChild(); GameTreeNode & get_parent(); GameTreeNode & get_sibling_h(); GameTreeNode & get_sibling_t(); GameTreeNode & get_child(); void set_parent(GameTreeNode & parent); void set_sibling_h(GameTreeNode & sibling); void set_sibling_t(GameTreeNode & sibling); void set_child(GameTreeNode & child); int get_x(); int get_y(); string get_color(); int get_state_value(); void set_state_value(int value); GameTreeNode & ExpandSiblingH(int x, int y); GameTreeNode & ExpandSiblingH(Coordinate xy); GameTreeNode & ExpandSiblingT(int x, int y); GameTreeNode & ExpandSiblingT(Coordinate xy); GameTreeNode & ExpandChild(int x, int y); GameTreeNode & ExpandChild(Coordinate xy); //Use this method when trying to take a move GameTreeNode & GetNewState(int x, int y); GameTreeNode & GetNewState(Coordinate xy); string toString(); private: int x; int y; string color; int state_value; GameTreeNode *parent; GameTreeNode *sibling_h; GameTreeNode *sibling_t; GameTreeNode *child; void set_xy(int x, int y); void set_color(string color); }; ostream & operator<<(ostream &os, GameTreeNode & node); #endif // GAMETREENODE_H
1654c31c4680a00a896c30d1668a692de1cbcff8
ab786d963e4e959cbf185b3673133c468f40e5f8
/CPP1/sumcubes.cpp
e211f49f44925197255b86edbe6fbcfecb4358c0
[ "MIT" ]
permissive
mrnettek/CPP
beb2a37c0238fb398b74ed771bb24d05bec9d0b7
25127ae2dea8c4841787ae94669c56a716ee2bea
refs/heads/master
2021-06-28T19:17:38.106119
2020-12-31T18:52:29
2020-12-31T18:52:29
210,626,641
0
0
null
null
null
null
UTF-8
C++
false
false
472
cpp
sumcubes.cpp
// print sums of cubes #include <iostream> using namespace std; int main() { int limit; cout << "Enter the number of rows to be seen: "; cin >> limit; for (int r = 1; r <= limit; r++) { int total = 0; for (int term = 1; term <= r; term++) { cout << "cube " << term; if (term < r) cout << " + "; else cout << " = "; total = total + term * term * term; } cout << total << endl; } return 0; }
e46c7156ee1103469cfb799e0f01d2e04cb852e6
5ab7032615235c10c68d738fa57aabd5bc46ea59
/compote.cpp
62b8434df22de4e88149a06cf614166aaa3305b3
[]
no_license
g-akash/spoj_codes
12866cd8da795febb672b74a565e41932abf6871
a2bf08ecd8a20f896537b6fbf96a2542b8ecf5c0
refs/heads/master
2021-09-07T21:07:17.267517
2018-03-01T05:41:12
2018-03-01T05:41:12
66,132,917
2
0
null
null
null
null
UTF-8
C++
false
false
636
cpp
compote.cpp
#include <iostream> #include <vector> #include <unordered_map> #include <string> #include <math.h> #include <map> #include <queue> #include <algorithm> using namespace std; #define ll long long int #define umm(x,y) unordered_map<x,y > #define pb push_back #define foi(n) for(int i=0;i<n;i++) #define foj(n) for(int j=0;j<n;j++) #define foi1(n) for(int i=1;i<=n;i++) #define vi vector<int> #define vvi vector<vi > #define si size() int main() { int a,b,c; cin>>a>>b>>c; int x=0,y=a; while(y-x>1) { int mid = (x+y)/2; if(2*mid<=b&&4*mid<=c)x=mid; else y=mid; } if(2*y<=b&&4*y<=c)cout<<7*y<<endl; else cout<<7*x<<endl; }
2438d5578b5e38b4cde9d40b10d9a42597d12e7f
5d52bc93a95bd590b3b492549a6738531168b0f9
/constraint.cpp
90ca8f8a0e5a0d5743b5867c0bf7fdf767b58f26
[]
no_license
TimKrause2/caams-euler-parameters
b93773937b76b2f28b9fecf8ee4954070b446192
3567b22127b872d62480c4786842950da214c416
refs/heads/master
2022-05-20T11:56:23.465849
2022-05-01T17:37:40
2022-05-01T17:37:40
241,159,857
2
0
null
null
null
null
UTF-8
C++
false
false
19,364
cpp
constraint.cpp
#include "constraint.h" #include <stdio.h> #include <GL/gl.h> #include <GL/freeglut.h> #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/type_ptr.hpp> Constraint::Constraint( Body *body1, Body *body2): body1(body1), body2(body2) { } caams::matrix Constraint::dPHI(void) { caams::matrix q1_dot(7,1); caams::matrix q2_dot(7,1); q1_dot.sub(body1->rk_r_dot,1,1); q1_dot.sub(body1->rk_p_dot,4,1); q2_dot.sub(body2->rk_r_dot,1,1); q2_dot.sub(body2->rk_p_dot,4,1); return Body1Jacobian()*q1_dot + Body2Jacobian()*q2_dot; } caams::matrix Constraint::h(const caams::matrix &p_dot, const caams::matrix &s_p) { return -2.0*caams::G(p_dot)*~caams::L(p_dot)*s_p; } SphericalJoint::SphericalJoint( Body *body1, Body *body2, caams::matrix s1_p, caams::matrix s2_p): Constraint(body1,body2), s1_p(s1_p), s2_p(s2_p) { N_eqn = 3; } caams::matrix SphericalJoint::Body1Jacobian(void) { caams::matrix r(3,7); r.sub(caams::matrix(3,3,caams::init_identity),1,1); r.sub(2.0*(caams::G(body1->rk_p)*caams::a_minus(s1_p)+s1_p*~body1->rk_p),1,4); return r; } caams::matrix SphericalJoint::Body2Jacobian(void) { caams::matrix r(3,7); r.sub(-caams::matrix(3,3,caams::init_identity),1,1); r.sub(-2.0*(caams::G(body2->rk_p)*caams::a_minus(s2_p)+s2_p*~body2->rk_p),1,4); return r; } caams::matrix SphericalJoint::Body1ModifiedJacobian(void) { caams::matrix r(3,7); r.sub(caams::matrix(3,3,caams::init_identity),1,1); r.sub(2.0*(caams::G(body1->rk_p)*caams::a_minus(s1_p)),1,4); return r; } caams::matrix SphericalJoint::Body2ModifiedJacobian(void) { caams::matrix r(3,7); r.sub(-caams::matrix(3,3,caams::init_identity),1,1); r.sub(-2.0*(caams::G(body2->rk_p)*caams::a_minus(s2_p)),1,4); return r; } caams::matrix SphericalJoint::PHI(void) { return body1->rk_r + caams::Ap(body1->rk_p)*s1_p - body2->rk_r - caams::Ap(body2->rk_p)*s2_p; } caams::matrix SphericalJoint::ModifiedGamma(void) { return h(body1->rk_p_dot,s1_p) - h(body2->rk_p_dot,s2_p); } void SphericalJoint::Draw(void) { caams::matrix s1(body1->r + caams::Ap(body1->p)*s1_p); caams::matrix s2(body2->r + caams::Ap(body2->p)*s2_p); glBegin(GL_LINES); glColor3f(1.0f,1.0f,0.0f); glVertex3dv(body1->r.data); glVertex3dv(s1.data); glColor3f(0.0f,1.0f,1.0f); glVertex3dv(body2->r.data); glVertex3dv(s2.data); glEnd(); } SphericalSphericalJoint::SphericalSphericalJoint( Body *body1, Body *body2, caams::matrix s1_p, caams::matrix s2_p, double length): Constraint(body1,body2), s1_p(s1_p), s2_p(s2_p), length(length) { N_eqn = 1; } caams::matrix SphericalSphericalJoint::Body1Jacobian(void) { caams::matrix d( body2->rk_r+caams::Ap(body2->rk_p)*s2_p -body1->rk_r-caams::Ap(body1->rk_p)*s1_p); caams::matrix r(1,7); r.sub(-2.0*~d,1,1); caams::matrix B1(2.0*(caams::G(body1->rk_p)*caams::a_minus(s1_p) + s1_p*~body1->rk_p)); r.sub(-2.0*~d*B1,1,4); return r; } caams::matrix SphericalSphericalJoint::Body2Jacobian(void) { caams::matrix d( body2->rk_r+caams::Ap(body2->rk_p)*s2_p -body1->rk_r-caams::Ap(body1->rk_p)*s1_p); caams::matrix r(1,7); r.sub(2.0*~d,1,1); caams::matrix B2(2.0*(caams::G(body2->rk_p)*caams::a_minus(s2_p) + s2_p*~body2->rk_p)); r.sub(2.0*~d*B2,1,4); return r; } caams::matrix SphericalSphericalJoint::Body1ModifiedJacobian(void) { caams::matrix d( body2->rk_r+caams::Ap(body2->rk_p)*s2_p -body1->rk_r-caams::Ap(body1->rk_p)*s1_p); caams::matrix r(1,7); r.sub(-2.0*~d,1,1); r.sub(-4.0*~d*caams::G(body1->rk_p)*caams::a_minus(s1_p),1,4); return r; } caams::matrix SphericalSphericalJoint::Body2ModifiedJacobian(void) { caams::matrix d( body2->rk_r+caams::Ap(body2->rk_p)*s2_p -body1->rk_r-caams::Ap(body1->rk_p)*s1_p); caams::matrix r(1,7); r.sub(2.0*~d,1,1); r.sub(4.0*~d*caams::G(body2->rk_p)*caams::a_minus(s2_p),1,4); return r; } caams::matrix SphericalSphericalJoint::PHI(void) { caams::matrix d( body2->rk_r+caams::Ap(body2->rk_p)*s2_p -body1->rk_r-caams::Ap(body1->rk_p)*s1_p); return ~d*d - caams::matrix(1,1,length*length); } caams::matrix SphericalSphericalJoint::ModifiedGamma(void) { caams::matrix d( body2->rk_r+caams::Ap(body2->rk_p)*s2_p -body1->rk_r-caams::Ap(body1->rk_p)*s1_p); caams::matrix omega1(2.0*caams::G(body1->rk_p)*body1->rk_p_dot); caams::matrix omega2(2.0*caams::G(body2->rk_p)*body2->rk_p_dot); caams::matrix d_dot( body2->rk_r_dot + caams::SS(omega2)*caams::Ap(body2->rk_p)*s2_p -body1->rk_r_dot - caams::SS(omega1)*caams::Ap(body1->rk_p)*s1_p); return 2.0*(~d*(h(body2->rk_p_dot,s2_p)-h(body1->rk_p_dot,s1_p))-~d_dot*d_dot); } void SphericalSphericalJoint::Draw(void) { caams::matrix s1(body1->r + caams::Ap(body1->p)*s1_p); caams::matrix s2(body2->r + caams::Ap(body2->p)*s2_p); caams::matrix d(s2-s1); double l = caams::norm(d); printf("SpericalSphericalJoint length:%lf\n",l); glBegin(GL_LINES); glColor3f(1.0f,0.5f,0.5f); glVertex3dv(body1->r.data); glVertex3dv(s1.data); glColor3f(0.5f,0.5f,0.5f); glVertex3dv(s1.data); glVertex3dv(s2.data); glColor3f(0.5f,1.0f,0.5f); glVertex3dv(s2.data); glVertex3dv(body2->r.data); glEnd(); } Normal1_1::Normal1_1( Body *body1, Body *body2, caams::matrix s1_p, caams::matrix s2_p): Constraint(body1,body2), s1_p(s1_p), s2_p(s2_p) { N_eqn = 1; } caams::matrix Normal1_1::Body1Jacobian(void) { caams::matrix s2(caams::Ap(body2->rk_p)*s2_p); caams::matrix C1(2.0*(caams::G(body1->rk_p)*caams::a_minus(s1_p)+s1_p*~body1->rk_p)); caams::matrix r(1,7,caams::zeros); r.sub(~s2*C1,1,4); return r; } caams::matrix Normal1_1::Body2Jacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix C2(2.0*(caams::G(body2->rk_p)*caams::a_minus(s2_p)+s2_p*~body2->rk_p)); caams::matrix r(1,7,caams::zeros); r.sub(~s1*C2,1,4); return r; } caams::matrix Normal1_1::Body1ModifiedJacobian(void) { caams::matrix s2(caams::Ap(body2->rk_p)*s2_p); caams::matrix r(1,7,caams::zeros); r.sub(~s2*caams::G(body1->rk_p)*caams::a_minus(s1_p),1,4); return r; } caams::matrix Normal1_1::Body2ModifiedJacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix r(1,7,caams::zeros); r.sub(~s1*caams::G(body2->rk_p)*caams::a_minus(s2_p),1,4); return r; } caams::matrix Normal1_1::PHI(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix s2(caams::Ap(body2->rk_p)*s2_p); return ~s1*s2; } caams::matrix Normal1_1::ModifiedGamma(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix s2(caams::Ap(body2->rk_p)*s2_p); caams::matrix omega1(2.0*caams::G(body1->rk_p)*body1->rk_p_dot); caams::matrix omega2(2.0*caams::G(body2->rk_p)*body2->rk_p_dot); caams::matrix s1_dot(caams::SS(omega1)*s1); caams::matrix s2_dot(caams::SS(omega2)*s2); return ~s1*h(body2->rk_p_dot,s2_p) + ~s2*h(body1->rk_p_dot,s1_p) - 2.0*~s1_dot*s2_dot; } void Normal1_1::Draw(void) { } Normal2_1::Normal2_1( Body *body1, Body *body2, caams::matrix s1_p, caams::matrix s1B_p, caams::matrix s2B_p): Constraint(body1,body2), s1_p(s1_p), s1B_p(s1B_p), s2B_p(s2B_p) { N_eqn = 1; } caams::matrix Normal2_1::Body1Jacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix d(body2->rk_r + caams::Ap(body2->rk_p)*s2B_p -body1->rk_r - caams::Ap(body1->rk_p)*s1B_p); caams::matrix B1(2.0*(caams::G(body1->rk_p)*caams::a_minus(s1B_p)+s1B_p*~body1->rk_p)); caams::matrix C1(2.0*(caams::G(body1->rk_p)*caams::a_minus(s1_p)+s1_p*~body1->rk_p)); caams::matrix r(1,7); r.sub(-~s1,1,1); r.sub(-~s1*B1 + ~d*C1,1,4); return r; } caams::matrix Normal2_1::Body2Jacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix B2(2.0*(caams::G(body2->rk_p)*caams::a_minus(s2B_p)+s2B_p*~body1->rk_p)); caams::matrix r(1,7); r.sub(~s1,1,1); r.sub(~s1*B2,1,4); return r; } caams::matrix Normal2_1::Body1ModifiedJacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix d(body2->rk_r + caams::Ap(body2->rk_p)*s2B_p -body1->rk_r - caams::Ap(body1->rk_p)*s1B_p); caams::matrix r(1,7); r.sub(-~s1,1,1); r.sub(-2.0*~s1*caams::G(body1->rk_p)*caams::a_minus(s1B_p) + 2.0*~d*caams::G(body1->rk_p)*caams::a_minus(s1_p),1,4); return r; } caams::matrix Normal2_1::Body2ModifiedJacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix r(1,7); r.sub(~s1,1,1); r.sub(2.0*~s1*caams::G(body2->rk_p)*caams::a_minus(s2B_p),1,4); return r; } caams::matrix Normal2_1::PHI(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix d(body2->rk_r + caams::Ap(body2->rk_p)*s2B_p -body1->rk_r - caams::Ap(body1->rk_p)*s1B_p); return ~s1*d; } caams::matrix Normal2_1::ModifiedGamma(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix d(body2->rk_r + caams::Ap(body2->rk_p)*s2B_p -body1->rk_r - caams::Ap(body1->rk_p)*s1B_p); caams::matrix omega1(2.0*caams::G(body1->rk_p)*body1->rk_p_dot); caams::matrix omega2(2.0*caams::G(body2->rk_p)*body2->rk_p_dot); caams::matrix s1_dot(caams::SS(omega1)*s1); caams::matrix d_dot( body2->rk_r_dot + caams::SS(omega2)*caams::Ap(body2->rk_p)*s2B_p - body1->rk_r_dot - caams::SS(omega1)*caams::Ap(body1->rk_p)*s1B_p); return ~s1*(h(body2->rk_p_dot,s2B_p)-h(body1->rk_p_dot,s1B_p)) + ~d*h(body1->rk_p_dot,s1_p) - 2.0*~s1_dot*d_dot; } void Normal2_1::Draw(void) { } Parallel1_2::Parallel1_2( Body *body1, Body *body2, caams::matrix s1_p, caams::matrix s2_p): Constraint(body1,body2), s1_p(s1_p), s2_p(s2_p) { N_eqn = 2; } caams::matrix Parallel1_2::Body1Jacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix s2(caams::Ap(body2->rk_p)*s2_p); caams::matrix C1(caams::G(body1->rk_p)*caams::a_minus(s1_p) + s1_p*~body1->rk_p); caams::matrix r(2,7,caams::zeros); caams::matrix PHI_p(-caams::SS(s2)*C1); switch(caams::maxComponent(s1)){ case 1: r.sub(PHI_p.sub(2,4,2,1),1,4); break; case 2: r.sub(PHI_p.sub(1,4,1,1),1,4); r.sub(PHI_p.sub(1,4,3,1),2,4); break; case 3: r.sub(PHI_p.sub(2,4,1,1),1,4); break; } return r; } caams::matrix Parallel1_2::Body2Jacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix C2(caams::G(body2->rk_p)*caams::a_minus(s2_p) + s2_p*~body2->rk_p); caams::matrix r(2,7,caams::zeros); caams::matrix PHI_p(caams::SS(s1)*C2); switch(caams::maxComponent(s1)){ case 1: r.sub(PHI_p.sub(2,4,2,1),1,4); break; case 2: r.sub(PHI_p.sub(1,4,1,1),1,4); r.sub(PHI_p.sub(1,4,3,1),2,4); break; case 3: r.sub(PHI_p.sub(2,4,1,1),1,4); break; } return r; } caams::matrix Parallel1_2::Body1ModifiedJacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix s2(caams::Ap(body2->rk_p)*s2_p); caams::matrix r(2,7,caams::zeros); caams::matrix PHI_p(-2.0*caams::SS(s2)*caams::G(body1->rk_p)*caams::a_minus(s1_p)); switch(caams::maxComponent(s1)){ case 1: r.sub(PHI_p.sub(2,4,2,1),1,4); break; case 2: r.sub(PHI_p.sub(1,4,1,1),1,4); r.sub(PHI_p.sub(1,4,3,1),2,4); break; case 3: r.sub(PHI_p.sub(2,4,1,1),1,4); break; } return r; } caams::matrix Parallel1_2::Body2ModifiedJacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix r(2,7,caams::zeros); caams::matrix PHI_p(2.0*caams::SS(s1)*caams::G(body2->rk_p)*caams::a_minus(s2_p)); switch(caams::maxComponent(s1)){ case 1: r.sub(PHI_p.sub(2,4,2,1),1,4); break; case 2: r.sub(PHI_p.sub(1,4,1,1),1,4); r.sub(PHI_p.sub(1,4,3,1),2,4); break; case 3: r.sub(PHI_p.sub(2,4,1,1),1,4); break; } return r; } caams::matrix Parallel1_2::PHI(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix s2(caams::Ap(body2->rk_p)*s2_p); caams::matrix r_all(caams::SS(s1)*s2); caams::matrix r(2,1); switch(caams::maxComponent(s1)){ case 1: r.sub(r_all.sub(2,1,2,1),1,1); break; case 2: r.sub(r_all.sub(1,1,1,1),1,1); r.sub(r_all.sub(1,1,3,1),2,1); break; case 3: r.sub(r_all.sub(2,1,1,1),1,1); break; } return r; } caams::matrix Parallel1_2::ModifiedGamma(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix s2(caams::Ap(body2->rk_p)*s2_p); caams::matrix omega1(2.0*caams::G(body1->rk_p)*body1->rk_p_dot); caams::matrix omega2(2.0*caams::G(body2->rk_p)*body2->rk_p_dot); caams::matrix s1_dot(caams::SS(omega1)*s1); caams::matrix s2_dot(caams::SS(omega2)*s2); caams::matrix r_all(caams::SS(s1)*h(body2->rk_p_dot,s2_p) -caams::SS(s2)*h(body1->rk_p_dot,s1_p) -2.0*caams::SS(s1_dot)*s2_dot); caams::matrix r(2,1); switch(caams::maxComponent(s1)){ case 1: r.sub(r_all.sub(2,1,2,1),1,1); break; case 2: r.sub(r_all.sub(1,1,1,1),1,1); r.sub(r_all.sub(1,1,3,1),2,1); break; case 3: r.sub(r_all.sub(2,1,1,1),1,1); break; } return r; } void Parallel1_2::Draw(void) { } Parallel2_2::Parallel2_2( Body *body1, Body *body2, caams::matrix s1_p, caams::matrix s1B_p, caams::matrix s2B_p): Constraint(body1,body2), s1_p(s1_p), s1B_p(s1B_p), s2B_p(s2B_p) { N_eqn = 2; } caams::matrix Parallel2_2::Body1Jacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix d( body2->rk_r+caams::Ap(body2->rk_p)*s2B_p -body1->rk_r-caams::Ap(body1->rk_p)*s1B_p); caams::matrix r(2,7); caams::matrix PHI_q(3,7); PHI_q.sub(-caams::SS(s1),1,1); caams::matrix B1(2.0*(caams::G(body1->rk_p)*caams::a_minus(s1B_p) + s1B_p*~body1->rk_p)); caams::matrix C1(2.0*(caams::G(body1->rk_p)*caams::a_minus(s1_p) + s1_p*~body1->rk_p)); PHI_q.sub(-caams::SS(s1)*B1 - caams::SS(d)*C1,1,4); switch(caams::maxComponent(s1)){ case 1: r.sub(PHI_q.sub(2,7,2,1),1,1); break; case 2: r.sub(PHI_q.sub(1,7,1,1),1,1); r.sub(PHI_q.sub(1,7,3,1),2,1); break; case 3: r.sub(PHI_q.sub(2,7,1,1),1,1); break; } return r; } caams::matrix Parallel2_2::Body2Jacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix r(2,7); caams::matrix PHI_q(3,7); PHI_q.sub(caams::SS(s1),1,1); caams::matrix B2(2.0*(caams::G(body2->rk_p)*caams::a_minus(s2B_p) + s2B_p*~body2->rk_p)); PHI_q.sub(caams::SS(s1)*B2,1,4); switch(caams::maxComponent(s1)){ case 1: r.sub(PHI_q.sub(2,7,2,1),1,1); break; case 2: r.sub(PHI_q.sub(1,7,1,1),1,1); r.sub(PHI_q.sub(1,7,3,1),2,1); break; case 3: r.sub(PHI_q.sub(2,7,1,1),1,1); break; } return r; } caams::matrix Parallel2_2::Body1ModifiedJacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix d( body2->rk_r+caams::Ap(body2->rk_p)*s2B_p -body1->rk_r-caams::Ap(body1->rk_p)*s1B_p); caams::matrix r(2,7); caams::matrix PHI_q(3,7); PHI_q.sub(-caams::SS(s1),1,1); PHI_q.sub(-2.0*caams::SS(s1)*caams::G(body1->rk_p)*caams::a_minus(s1B_p) -2.0*caams::SS(d)*caams::G(body1->rk_p)*caams::a_minus(s1_p),1,4); switch(caams::maxComponent(s1)){ case 1: r.sub(PHI_q.sub(2,7,2,1),1,1); break; case 2: r.sub(PHI_q.sub(1,7,1,1),1,1); r.sub(PHI_q.sub(1,7,3,1),2,1); break; case 3: r.sub(PHI_q.sub(2,7,1,1),1,1); break; } return r; } caams::matrix Parallel2_2::Body2ModifiedJacobian(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix r(2,7); caams::matrix PHI_q(3,7); PHI_q.sub(caams::SS(s1),1,1); PHI_q.sub(2.0*caams::SS(s1)*caams::G(body2->rk_p)*caams::a_minus(s2B_p),1,4); switch(caams::maxComponent(s1)){ case 1: r.sub(PHI_q.sub(2,7,2,1),1,1); break; case 2: r.sub(PHI_q.sub(1,7,1,1),1,1); r.sub(PHI_q.sub(1,7,3,1),2,1); break; case 3: r.sub(PHI_q.sub(2,7,1,1),1,1); break; } return r; } caams::matrix Parallel2_2::PHI(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix d( body2->rk_r+caams::Ap(body2->rk_p)*s2B_p -body1->rk_r-caams::Ap(body1->rk_p)*s1B_p); caams::matrix r_all(caams::SS(s1)*d); caams::matrix r(2,1); switch(caams::maxComponent(s1)){ case 1: r.data[0] = r_all.data[1]; r.data[1] = r_all.data[2]; break; case 2: r.data[0] = r_all.data[0]; r.data[1] = r_all.data[2]; break; case 3: r.data[0] = r_all.data[0]; r.data[1] = r_all.data[1]; break; } return r; } caams::matrix Parallel2_2::ModifiedGamma(void) { caams::matrix s1(caams::Ap(body1->rk_p)*s1_p); caams::matrix omega1(2.0*caams::G(body1->rk_p)*body1->rk_p_dot); caams::matrix s1_dot(caams::SS(omega1)*s1); caams::matrix d( body2->rk_r+caams::Ap(body2->rk_p)*s2B_p -body1->rk_r-caams::Ap(body1->rk_p)*s1B_p); caams::matrix omega2(2.0*caams::G(body2->rk_p)*body2->rk_p_dot); caams::matrix d_dot( body2->rk_r_dot + caams::SS(omega2)*caams::Ap(body2->rk_p)*s2B_p -body1->rk_r_dot - caams::SS(omega1)*caams::Ap(body1->rk_p)*s1B_p); caams::matrix r_all(caams::SS(s1)*(h(body2->rk_p_dot,s2B_p)-h(body1->rk_p_dot,s1B_p)) -caams::SS(d)*h(body1->rk_p_dot,s1_p) -2.0*caams::SS(s1_dot)*d_dot); caams::matrix r(2,1); switch(caams::maxComponent(s1)){ case 1: r.data[0] = r_all.data[1]; r.data[1] = r_all.data[2]; break; case 2: r.data[0] = r_all.data[0]; r.data[1] = r_all.data[2]; break; case 3: r.data[0] = r_all.data[0]; r.data[1] = r_all.data[1]; break; } return r; } void Parallel2_2::Draw(void) { }
49c182eb7aa304b4758214bdebf1f4fbfce99fe7
d352af82d968c645f5566ba31d809b811a229e1c
/src/utilities/GenException.hh
a3396f18b50ab7f672deb1fc9fd5ea32c8c1e465
[ "MIT" ]
permissive
robertsj/libdetran
9b20ce691cc8eaa84e3845483ac6ae9f80da40ce
be5e1cd00fecf3a16669d8e81f29557939088628
refs/heads/dev
2023-01-21T16:53:09.485828
2023-01-16T16:38:38
2023-01-16T16:38:38
3,748,964
8
10
MIT
2023-01-26T14:22:09
2012-03-17T16:28:54
C++
UTF-8
C++
false
false
1,680
hh
GenException.hh
//----------------------------------*-C++-*----------------------------------// /** * @file GenException.hh * @author Jeremy Roberts * @date 04/09/2011 * @brief GenException class definition. * @note Modified version of K. Huff's class from cyclus */ //---------------------------------------------------------------------------// #ifndef detran_utilities_GENEXCEPTION_HH #define detran_utilities_GENEXCEPTION_HH #include "utilities/utilities_export.hh" #include "utilities/Definitions.hh" #include <iostream> #include <exception> #include <string> namespace detran_utilities { /** * A generic mechanism to manually manage exceptions */ class UTILITIES_EXPORT GenException: public std::exception { public: /// Constructs a new GenException with the default message. GenException(); /** * @brief Constructs a new GenException with a provided message * * @param line line of code erring * @param file file in which error occurs * @param msg the message */ GenException(int line, std::string file, std::string msg); /** * Returns the error message associated with this GenException. * * @return the message */ virtual const char* what() const throw (); /** * Destroys this GenException. */ virtual ~GenException() throw (); protected: /// The message associated with this exception. std::string myMessage; /// A string to prepend to all message of this class. static std::string prepend; }; /// Easy macro for throwing exceptions. #define THROW(m) throw detran_utilities::GenException(__LINE__,__FILE__,m); } // end namespace detran_utilities #endif // detran_utilities_GENEXCEPTION_HH
957f4510215a521a8a867763e26283610c8f3152
3df6011276af21ce94495a298b11f6ce038c222b
/src/thgemDetectorMessenger.cc
b73c52bd733332f921e541b944b834d73f831327
[]
no_license
Virgo825/THGEM_Stop
ee30e280b0751301d83ed1f21b3fce55b3746db0
fc9ec614e6f42ea7c7d30fae481bda4cb43b32e3
refs/heads/master
2022-04-18T12:39:54.473205
2020-04-12T03:19:54
2020-04-12T03:19:54
176,075,240
0
0
null
null
null
null
UTF-8
C++
false
false
9,863
cc
thgemDetectorMessenger.cc
#include "thgemDetectorMessenger.hh" #include "thgemDetectorConstruction.hh" #include "thgemPhysics.hh" #include "G4RunManager.hh" #include "G4SystemOfUnits.hh" #include "G4UnitsTable.hh" #include "G4UIdirectory.hh" #include "G4UIcmdWithAString.hh" #include "G4UIcmdWithAnInteger.hh" #include "G4UIcmdWithADoubleAndUnit.hh" thgemDetectorMessenger::thgemDetectorMessenger(thgemDetectorConstruction* det) : G4UImessenger(), fDetectorConstruction(det) { fTHGEMDirectory = new G4UIdirectory("/thgem/"); fTHGEMDirectory->SetGuidance("UI commands specific to this example."); fDetDirectory = new G4UIdirectory("/thgem/detector/"); fDetDirectory->SetGuidance("Detector construction control."); fCathodeMatCmd = new G4UIcmdWithAString("/thgem/detector/setCathodeMaterial", this); fCathodeMatCmd->SetGuidance("Select Material of the Cathode."); fCathodeMatCmd->SetParameterName("choice", false); fCathodeMatCmd->AvailableForStates(G4State_PreInit, G4State_Idle); fTransformMatCmd = new G4UIcmdWithAString("/thgem/detector/setTransformMaterial", this); fTransformMatCmd->SetGuidance("Select Material of the Transform."); fTransformMatCmd->SetParameterName("choice", false); fTransformMatCmd->AvailableForStates(G4State_PreInit, G4State_Idle); fGasMatCmd = new G4UIcmdWithAString("/thgem/detector/setGasMaterial", this); fGasMatCmd->SetGuidance("Select Material of the Gas."); fGasMatCmd->SetParameterName("choice", false); fGasMatCmd->AvailableForStates(G4State_PreInit, G4State_Idle); fStepMaxCmd = new G4UIcmdWithADoubleAndUnit("/thgem/detector/stepMax", this); fStepMaxCmd->SetGuidance("Define a step max."); fStepMaxCmd->SetParameterName("stepMax", false); fStepMaxCmd->SetUnitCategory("Length"); fStepMaxCmd->AvailableForStates(G4State_Idle); fCathodeThickCmd = new G4UIcmdWithADoubleAndUnit("/thgem/detector/setCathodeThick", this); fCathodeThickCmd->SetGuidance("Select thick of the Cathode."); fCathodeThickCmd->SetParameterName("Thick", false); fCathodeThickCmd->SetUnitCategory("Length"); fCathodeThickCmd->AvailableForStates(G4State_PreInit, G4State_Idle); fTransformThickCmd = new G4UIcmdWithADoubleAndUnit("/thgem/detector/setTransformThick", this); fTransformThickCmd->SetGuidance("Select thick of the Transform."); fTransformThickCmd->SetParameterName("Thick", false); fTransformThickCmd->SetUnitCategory("Length"); fTransformThickCmd->AvailableForStates(G4State_PreInit, G4State_Idle); fGasThickCmd = new G4UIcmdWithADoubleAndUnit("/thgem/detector/setGasThick", this); fGasThickCmd->SetGuidance("Select thick of the Gas."); fGasThickCmd->SetParameterName("Thick", false); fGasThickCmd->SetUnitCategory("Length"); fGasThickCmd->AvailableForStates(G4State_PreInit, G4State_Idle); fPhysicsDir = new G4UIdirectory("/thgem/physics/"); fPhysicsDir->SetGuidance("Particle and energy ranges for Garfield++ physics model."); fIonizationModelCmd = new G4UIcommand("/thgem/physics/setIonizationModel", this); fIonizationModelCmd->SetGuidance("Select ionization model for Garfield++"); fIonizationModelCmd->SetGuidance(" and choose whether to use default particles"); fIonizationModelCmd->SetGuidance(" and energy ranges for the chosen model"); G4UIparameter *ionizationModelPrm = new G4UIparameter("ionizationModel", 's', false); ionizationModelPrm->SetGuidance("ionization model (1. PAIPhot, 2. PAI, 3. Heed)"); ionizationModelPrm->SetGuidance(" 1. PAIPhot model in Geant4, delta electrons transported by Heed"); ionizationModelPrm->SetGuidance(" 2, PAI model in Geant4, delta electrons transported by Heed"); ionizationModelPrm->SetGuidance(" 3. Use directly Heed"); fIonizationModelCmd->SetParameter(ionizationModelPrm); G4UIparameter *useDefaultPrm = new G4UIparameter("useDefaults", 'b', false); useDefaultPrm->SetGuidance("true to use default, false to manully choose particles and energies"); fIonizationModelCmd->SetParameter(useDefaultPrm); fIonizationModelCmd->AvailableForStates(G4State_PreInit); fGeant4ParticleCmd = new G4UIcommand("/thgem/physics/setGeant4ParticleTypeAndEnergy", this); fGeant4ParticleCmd->SetGuidance("Select particle types and energies for PAI and PAIPhot model"); fGeant4ParticleCmd->SetGuidance(" in Geant4"); G4UIparameter *particleGeant4Prm = new G4UIparameter("particleName", 's', false); particleGeant4Prm->SetGuidance("Particle name (e-, e+, mu-, mu+, proton, pi-, pi+, alpha, Li7, He3, GenericIon)"); fGeant4ParticleCmd->SetParameter(particleGeant4Prm); G4UIparameter *minEnergyGeant4Prm = new G4UIparameter("minimumEnergyGeant4", 'd', false); minEnergyGeant4Prm->SetGuidance("minimum energy"); minEnergyGeant4Prm->SetParameterRange("minimumEnergyGeant4>=0"); fGeant4ParticleCmd->SetParameter(minEnergyGeant4Prm); G4UIparameter *maxEnergyGeant4Prm = new G4UIparameter("maximumEnergyGeant4", 'd', false); maxEnergyGeant4Prm->SetGuidance("maximum energy"); maxEnergyGeant4Prm->SetParameterRange("maximumEnergyGeant4>=0"); fGeant4ParticleCmd->SetParameter(maxEnergyGeant4Prm); G4UIparameter *unitGeant4Prm = new G4UIparameter("unit", 's', false); unitGeant4Prm->SetGuidance("unit of energy"); G4String unitListGeant4 = G4UIcommand::UnitsList(G4UIcommand::CategoryOf("MeV")); unitGeant4Prm->SetParameterCandidates(unitListGeant4); fGeant4ParticleCmd->SetParameter(unitGeant4Prm); fGeant4ParticleCmd->AvailableForStates(G4State_PreInit); fGarfieldParticleCmd = new G4UIcommand("/thgem/physics/setGarfieldParticleTypeAndEnergy", this); fGarfieldParticleCmd->SetGuidance("Select particle types and energies for Heed model"); fGarfieldParticleCmd->SetGuidance(" For PAI and PAIPhot model choose at which energy electrons are"); fGarfieldParticleCmd->SetGuidance(" transport as delta electrons by Heed, and treatment of gammas"); G4UIparameter *particleGarfieldPrm = new G4UIparameter("particleName", 's', false); particleGarfieldPrm->SetGuidance("Particle name (gamma, e-, e+, mu-, mu+, proton, anti_proton, pi-, pi+, kaon, kaon+, alpha, Li7, deuteron)"); fGarfieldParticleCmd->SetParameter(particleGarfieldPrm); G4UIparameter *minEnergyGarfieldPrm = new G4UIparameter("minimumEnergyGarfield", 'd', false); minEnergyGarfieldPrm->SetGuidance("minimum energy"); minEnergyGarfieldPrm->SetParameterRange("minimumEnergyGarfield>=0"); fGarfieldParticleCmd->SetParameter(minEnergyGarfieldPrm); G4UIparameter *maxEnergyGarfieldPrm = new G4UIparameter("maximumEnergyGarfield", 'd', false); maxEnergyGarfieldPrm->SetGuidance("maximum energy"); maxEnergyGarfieldPrm->SetParameterRange("maximumEnergyGarfield>=0"); fGarfieldParticleCmd->SetParameter(maxEnergyGarfieldPrm); G4UIparameter *unitGarfieldPrm = new G4UIparameter("unit", 's', false); unitGarfieldPrm->SetGuidance("unit of energy"); G4String unitListGarfield = G4UIcommand::UnitsList(G4UIcommand::CategoryOf("MeV")); unitGarfieldPrm->SetParameterCandidates(unitListGarfield); fGarfieldParticleCmd->SetParameter(unitGarfieldPrm); fGarfieldParticleCmd->AvailableForStates(G4State_PreInit); } thgemDetectorMessenger::~thgemDetectorMessenger() { delete fTHGEMDirectory; delete fDetDirectory; delete fCathodeMatCmd; delete fTransformMatCmd; delete fGasMatCmd; delete fStepMaxCmd; delete fCathodeThickCmd; delete fTransformThickCmd; delete fGasThickCmd; delete fPhysicsDir; delete fIonizationModelCmd; delete fGeant4ParticleCmd; delete fGarfieldParticleCmd; } void thgemDetectorMessenger::SetNewValue(G4UIcommand* command, G4String newValue) { if(command == fCathodeMatCmd) fDetectorConstruction->SetCathodeMaterial(newValue); if(command == fTransformMatCmd) fDetectorConstruction->SetTransformMaterial(newValue); if(command == fGasMatCmd) fDetectorConstruction->SetGasMaterial(newValue); if(command == fStepMaxCmd) fDetectorConstruction->SetMaxStep(fStepMaxCmd->GetNewDoubleValue(newValue)); if(command == fCathodeThickCmd) fDetectorConstruction->SetCathodeThick(fCathodeThickCmd->GetNewDoubleValue(newValue)); if(command == fTransformThickCmd) fDetectorConstruction->SetTransformThick(fTransformThickCmd->GetNewDoubleValue(newValue)); if(command == fGasThickCmd) fDetectorConstruction->SetGasThick(fGasThickCmd->GetNewDoubleValue(newValue)); if(command == fIonizationModelCmd) { thgemPhysics *physics = thgemPhysics::GetInstance(); G4String modelName; G4bool useDefaults; std::istringstream is(newValue); std::cout << newValue << std::endl; is >> modelName >> std::boolalpha >> useDefaults; physics->SetIonizationModel(modelName, useDefaults); } if(command == fGeant4ParticleCmd) { thgemPhysics *physics = thgemPhysics::GetInstance(); G4String particleName, unit, programName; G4double minEnergy; G4double maxEnergy; std::istringstream is(newValue); is >> particleName >> minEnergy >> maxEnergy >> unit; minEnergy *= G4UIcommand::ValueOf(unit); maxEnergy *= G4UIcommand::ValueOf(unit); physics->AddParticleName(particleName, minEnergy, maxEnergy, "geant4"); } if (command == fGarfieldParticleCmd) { thgemPhysics *physics = thgemPhysics::GetInstance(); G4String particleName, unit, programName; G4double minEnergy; G4double maxEnergy; std::istringstream is(newValue); is >> particleName >> minEnergy >> maxEnergy >> unit; minEnergy *= G4UIcommand::ValueOf(unit); maxEnergy *= G4UIcommand::ValueOf(unit); physics->AddParticleName(particleName, minEnergy, maxEnergy, "garfield"); } }
bbf1351fb35940c4ac4c6348785022fdff4608e5
0f01dab3b868e94298fc54d5b449c71f435a56e3
/游戏组件/子游戏/二人双扣/游戏客户端/DlgPlayVoice.cpp
6f5c4eb09fa20c1b88150cfebd1e35341764b325
[]
no_license
ydcrow/refFoxuc
c6284476ed530263a5ffb8f8e7d37251e393c0d2
f85601c050bb5f24883c88bbef0982b16ff952e3
refs/heads/master
2023-02-07T06:03:06.317797
2020-12-26T02:49:37
2020-12-26T02:49:37
null
0
0
null
null
null
null
GB18030
C++
false
false
7,526
cpp
DlgPlayVoice.cpp
// DlgPlayVoice.cpp : 实现文件 // #include "stdafx.h" #include "DlgPlayVoice.h" #include "Windows.h" #include ".\dlgplayvoice.h" // CDlgPlayVoice 对话框 ////////////////////////////////////////////////////////////////////////// BEGIN_MESSAGE_MAP(CDlgPlayVoice, CSkinDialogEx) ON_CBN_SELCHANGE(IDC_COMBO1,OnSelectChange) ON_NOTIFY(NM_DBLCLK, IDC_LIST_VOICE, OnNMDblclkListVoice) ON_WM_TIMER() END_MESSAGE_MAP() ////////////////////////////////////////////////////////////////////////// //构造函数 CDlgPlayVoice::CDlgPlayVoice() : CSkinDialogEx(IDD_DLG_PLAYVOICE) { m_nCurSelect=0; m_bTimerRun=false; return; } //析构函数 CDlgPlayVoice::~CDlgPlayVoice() { CDirectSound*pDirectSound=NULL; while(m_DSObjectList.GetSize()>0) { pDirectSound=m_DSObjectList.RemoveHead(); pDirectSound->Stop(); delete pDirectSound; } } bool CDlgPlayVoice::GetWndState() { return m_bIsShow; } bool CDlgPlayVoice::InitVoiceList() { m_PlayList[0][0]="打快打快"; m_PlayList[0][1]="动作快点"; m_PlayList[0][2]="没炸弹啊?"; m_PlayList[0][3]="破牌"; m_PlayList[0][4]="全部当算"; m_PlayList[0][5]="全大"; m_PlayList[0][6]="全散"; m_PlayList[0][7]="没吃不倒霉"; m_PlayList[0][8]="脑都炸散了"; m_PlayList[0][9]="你想要什么牌啊,讲来那"; m_PlayList[0][10]="没意思没意思"; m_PlayList[0][11]="睡着了,你动都不动"; m_PlayList[0][12]="卡你怎么打的这么苦啊"; m_PlayList[0][13]="炸弹不炸你带家啊"; m_PlayList[0][14]="把你炸晕过去!"; m_PlayList[0][15]="卡你屋里造炸弹啊"; m_PlayList[0][16]="风头霉头两隔壁"; m_PlayList[0][17]="跟你打,靠造化,打赢的"; m_PlayList[0][18]="当炸不炸,炸起秘密炸"; m_PlayList[0][19]="拔了打死得"; m_PlayList[0][20]="动作抓紧点"; m_PlayList[0][21]="对子"; m_PlayList[0][22]="放心,我帮你看着"; m_PlayList[0][23]="黄天,里牌摸来,当数北"; m_PlayList[0][24]="卡你打,真打霉"; m_PlayList[0][25]="卡你卡么牌"; m_PlayList[0][26]="卡你怎么打的这么苦啊"; m_PlayList[0][27]="里牌都打的出,人都被你气死"; m_PlayList[0][28]="你怎么了,动都不动"; m_PlayList[0][29]="三带一"; m_PlayList[0][30]="真没意思啊"; m_PlayList[1][0]="拔老打死到"; m_PlayList[1][1]="把你炸晕过去"; m_PlayList[1][2]="打快点2"; m_PlayList[1][3]="当炸不炸,炸气秘密炸"; m_PlayList[1][4]="动作快点1"; m_PlayList[1][5]="风头霉头两隔壁2"; m_PlayList[1][6]="跟你打,靠造化,打赢啊"; m_PlayList[1][7]="关公门前舞大刀啊1"; m_PlayList[1][8]="没吃不倒霉1"; m_PlayList[1][9]="没吃不倒霉2"; m_PlayList[1][10]="没味道,没味道1"; m_PlayList[1][11]="没炸弹1"; m_PlayList[1][12]="脑都被炸散了1"; m_PlayList[1][13]="你家里造炸弹的1"; m_PlayList[1][14]="破牌"; m_PlayList[1][15]="全部当算2"; m_PlayList[1][16]="全大1"; m_PlayList[1][17]="全散1"; m_PlayList[1][18]="听唱词啊你,都不动2"; m_PlayList[1][19]="想要和什么牌,讲来1"; m_PlayList[1][20]="哑巴吃黄连有苦讲不出1"; m_PlayList[1][21]="炸弹不炸你带回家啊"; m_PlayList[1][22]="站在哪里看大字报啊,都不动"; m_PlayList[2][0]="被颠人砖头扔了"; m_PlayList[2][1]="打快打快"; m_PlayList[2][2]="打快点那"; m_PlayList[2][3]="动作快点呢"; m_PlayList[2][4]="对家没料"; m_PlayList[2][5]="放心我帮你瞄着"; m_PlayList[2][6]="和你搭伙痛苦"; m_PlayList[2][7]="没吃不倒霉"; m_PlayList[2][8]="没炸弹啊"; m_PlayList[2][9]="你是什么牌型"; m_PlayList[2][10]="破牌"; m_PlayList[2][11]="全大"; m_PlayList[2][12]="全散"; m_PlayList[2][13]="让他打,白卵车"; m_PlayList[2][14]="三拖一"; m_PlayList[2][15]="双拖双"; m_PlayList[2][16]="偷鸡"; m_PlayList[2][17]="形势看透"; m_PlayList[2][18]="牙列开糖金杏列了"; m_PlayList[2][19]="炸弹不炸带回家啊"; m_PlayList[2][20]="炸的跟南斯拉夫一样"; m_PlayList[2][21]="这盘没有救了"; m_PlayList[2][22]="自己打错了,不怨"; m_nVoiceNo[0]=31; m_nVoiceNo[1]=23; m_nVoiceNo[2]=23; SetTimer(1,3000,0); int index=0; CString str; for(;index<m_nVoiceNo[m_nCurSelect];index++) { str.Format("%d.%s",index+1,m_PlayList[m_nCurSelect][index]); m_ListCtrl.InsertItem(index,"1"); m_ListCtrl.SetItemText(index,0,str); } ((CComboBox*)GetDlgItem(IDC_COMBO1))->SetCurSel(m_nCurSelect); return true; } bool CDlgPlayVoice::ShowWindow(bool bFlags) { bool bReturn=m_bIsShow; m_bIsShow=bFlags; int nCmdShow=SW_SHOW; __super::ShowWindow(bFlags?SW_SHOW:SW_HIDE); return bReturn; } //控件绑定 void CDlgPlayVoice::DoDataExchange(CDataExchange * pDX) { __super::DoDataExchange(pDX); DDX_Control(pDX, IDOK, m_btOK); DDX_Control(pDX,IDC_LIST_VOICE,m_ListCtrl); } //初始化函数 BOOL CDlgPlayVoice::OnInitDialog() { __super::OnInitDialog(); //设置标题 SetWindowText(TEXT("游戏语音")); DWORD dwStyle = m_ListCtrl.GetExtendedStyle(); dwStyle=dwStyle|LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES; m_ListCtrl.ModifyStyle(WS_HSCROLL | WS_VSCROLL,0,0); m_ListCtrl.SetExtendedStyle(dwStyle); //设置扩展风格 CRect ListRect; m_ListCtrl.SetTextBkColor(RGB(248,249,251)); m_ListCtrl.SetTextColor(RGB(87,100,110)); m_ListCtrl.GetClientRect(&ListRect); m_ListCtrl.InsertColumn(0,"声音列表",LVCFMT_CENTER,ListRect.Width()-17); return TRUE; } //确定消息 void CDlgPlayVoice::OnOK() { static bool flags=true; if(flags) { // SetTimer(1,1000,0); flags=false; m_bTimerRun=true; } POSITION pos = m_ListCtrl.GetFirstSelectedItemPosition(); if (pos != NULL) { int nItem = m_ListCtrl.GetNextSelectedItem(pos); int nSel = ((CComboBox*)GetDlgItem(IDC_COMBO1))->GetCurSel(); AfxGetMainWnd()->PostMessage(WM_PLAYVOICE,nItem,nSel); } } void CDlgPlayVoice::OnCancel() { __super::ShowWindow(SW_HIDE); m_bIsShow=false; } void CDlgPlayVoice::OnSelectChange() { int k=((CComboBox*)GetDlgItem(IDC_COMBO1))->GetCurSel(); if(k!=m_nCurSelect) { int index=0; CString str; m_ListCtrl.DeleteAllItems(); for(;index<m_nVoiceNo[k];index++) { str.Format("%d.%s",index+1,m_PlayList[k][index]); m_ListCtrl.InsertItem(index,"1"); m_ListCtrl.SetItemText(index,0,str); } m_nCurSelect=k; ((CComboBox*)GetDlgItem(IDC_COMBO1))->SetCurSel(k); } } void CDlgPlayVoice::OnNMDblclkListVoice(NMHDR *pNMHDR, LRESULT *pResult) { // TODO: 在此添加控件通知处理程序代码 OnOK(); *pResult = 0; } void CDlgPlayVoice::OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized) { if(pWndOther!=this) { ShowWindow(SW_HIDE); m_bIsShow=false; } CSkinDialogEx::OnActivate(nState, pWndOther, bMinimized); // TODO: 在此处添加消息处理程序代码 } void CDlgPlayVoice::PlayVoice(CString&str) { CDirectSound*pDirectSound=new CDirectSound(); if(pDirectSound->Create(str,this)) { m_DSObjectList.AddTail(pDirectSound); pDirectSound->Play(); } else { delete pDirectSound; AfxMessageBox("音频文件加载失败!"); } } void CDlgPlayVoice::OnTimer(UINT nIDEvent) { // TODO: 在此添加消息处理程序代码和/或调用默认值 CDirectSound*pDirectSound=NULL; while(m_DSObjectList.GetSize()>0) { pDirectSound=m_DSObjectList.GetHead(); if(pDirectSound->IsEnd()) { pDirectSound=m_DSObjectList.RemoveHead(); pDirectSound->Stop(); delete pDirectSound; } else break; } CSkinDialogEx::OnTimer(nIDEvent); }
4c458a286793e20728d298993bd88974483bf5f1
9aec6b424f3b4e0b85fd54c3a0b96f691c39f13f
/Luogu/Basics/P1000.cpp
7e07854a0dd9bf6fd7363c32a64cc043afa3e0c2
[ "MIT" ]
permissive
yechs/C-Algorithms
2af994b4feda8e93b8d8ca9107fb47aff4680e4e
a2aaf927d8c8e0d89140a34d115ac49c0f489066
refs/heads/master
2021-09-10T09:30:29.003789
2018-03-23T15:32:26
2018-03-23T15:38:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,531
cpp
P1000.cpp
// P1000 超级玛丽 // https://www.luogu.org/problemnew/show/P1000 #include <stdio.h> int main(){ printf( " ********\n" " ************\n" " ####....#.\n" " #..###.....##....\n" " ###.......###### ### ###\n" " ........... #...# #...#\n" " ##*####### #.#.# #.#.#\n" " ####*******###### #.#.# #.#.#\n" " ...#***.****.*###.... #...# #...#\n" " ....**********##..... ### ###\n" " ....**** *****....\n" " #### ####\n" " ###### ######\n" "##############################################################\n" "#...#......#.##...#......#.##...#......#.##------------------#\n" "###########################################------------------#\n" "#..#....#....##..#....#....##..#....#....#####################\n" "########################################## #----------#\n" "#.....#......##.....#......##.....#......# #----------#\n" "########################################## #----------#\n" "#.#..#....#..##.#..#....#..##.#..#....#..# #----------#\n" "########################################## ############\n" ); return 0; }
770c9e3b053423aa38d0525332fdee2d9f4ac027
95dcf1b68eb966fd540767f9315c0bf55261ef75
/build/pc/ACDK_4_14_0/acdk/acdk_xml/src/acdk/xml/parsers/DocumentBuilderFactory.h
f647054a9be902a97ae158106c174ff42ef0d0a6
[]
no_license
quinsmpang/foundations.github.com
9860f88d1227ae4efd0772b3adcf9d724075e4d1
7dcef9ae54b7e0026fd0b27b09626571c65e3435
refs/heads/master
2021-01-18T01:57:54.298696
2012-10-14T14:44:38
2012-10-14T14:44:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,332
h
DocumentBuilderFactory.h
// -*- mode:C++; tab-width:2; c-basic-offset:2; indent-tabs-mode:nil -*- // // Copyright(C) 2000-2003 by Roger Rene Kommer / artefaktur, Kassel, Germany. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public License (LGPL). // // // This library 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 // License ACDK-FreeLicense document enclosed in the distribution // for more for more details. // This file is part of the Artefaktur Component Development Kit: // ACDK // // Please refer to // - http://www.acdk.de // - http://www.artefaktur.com // - http://acdk.sourceforge.net // for more information. // // $Header: /cvsroot/acdk/acdk/acdk_xml/src/acdk/xml/parsers/DocumentBuilderFactory.h,v 1.2 2005/02/05 10:45:37 kommer Exp $ #ifndef acdk_xml_parsers_DocumentBuilderFactory_h #define acdk_xml_parsers_DocumentBuilderFactory_h #include "DocumentBuilder.h" #include "ParserConfigurationException.h" #include <acdk/lang/IllegalArgumentException.h> namespace acdk { namespace xml { namespace parsers { ACDK_DECL_CLASS(DocumentBuilderFactory); class ACDK_XML_PUBLIC DocumentBuilderFactory : extends acdk::lang::Object { ACDK_WITH_METAINFO(DocumentBuilderFactory) private: bool _validating; bool _namespaceAware; bool _whitespace; bool _expandEntityRef; bool _ignoreComments; bool _coalescing; protected: DocumentBuilderFactory() : _validating(false) , _namespaceAware(false) , _whitespace(false) , _expandEntityRef(false) , _ignoreComments(false) , _coalescing(false) { } public: virtual RObject getAttribute(IN(RString) name) THROWS1(RIllegalArgumentException) = 0; virtual void setAttribute(IN(RString) name, IN(RObject) value) THROWS1(RIllegalArgumentException) = 0; virtual bool isCoalescing() { return _coalescing; } virtual bool isExpandEntityReferences() { return _expandEntityRef; } virtual bool isIgnoringComments() { return _ignoreComments; } virtual bool isIgnoringElementContentWhitespace() { return _whitespace; } virtual bool isNamespaceAware() { return _namespaceAware; } virtual bool isValidating() { return _validating; } virtual RDocumentBuilder newDocumentBuilder() THROWS1(RParserConfigurationException) = 0; /* static DocumentBuilderFactory newInstance() { try { return (DocumentBuilderFactory) ClassStuff.createFactory ( defaultPropName, "gnu.xml.dom.JAXPFactory"); } catch (ClassCastException e) { throw new FactoryConfigurationError (e, "Factory class is the wrong type"); } } */ virtual void setCoalescing(bool value) { _coalescing = value; } virtual void setExpandEntityReferences(bool value) { _expandEntityRef = value; } virtual void setIgnoringComments(bool value) { _ignoreComments = value; } virtual void setIgnoringElementContentWhitespace(bool value) { _whitespace = value; } virtual void setNamespaceAware(bool value) { _namespaceAware = value; } virtual void setValidating(bool value) { _validating = value; } }; } // namespace parsers } // namespace xml } // namespace acdk #endif //acdk_xml_parsers_DocumentBuilderFactory_h
b6d037dce0b4039065f85b911ecab6b4318ac7b2
4c822a527e9c36a5d881cf6976ab6dc684859b62
/include/greylock/key.hpp
cb943aca7951c3555027c1e92263876caf38ee64
[]
no_license
cdsalmons/greylock
f3dbbbb3d3f583776f8d51ea176823dbc5b2859a
3b85a9932fb6b3d0eb196e6cccd9659c80a0636f
refs/heads/master
2020-12-11T02:03:29.138519
2015-09-19T18:04:24
2015-09-19T18:04:24
45,578,889
1
0
null
2015-11-05T01:24:52
2015-11-05T01:24:51
null
UTF-8
C++
false
false
1,487
hpp
key.hpp
#ifndef __INDEXES_KEY_HPP #define __INDEXES_KEY_HPP #include "greylock/core.hpp" #include <string> namespace ioremap { namespace greylock { struct key { std::string id; eurl url; uint64_t timestamp = 0; std::vector<size_t> positions; MSGPACK_DEFINE(id, url, positions, timestamp); void set_timestamp(long tsec, long nsec) { timestamp = tsec; timestamp <<= 30; timestamp |= nsec & ((1<<30) - 1); } void get_timestamp(long &tsec, long &nsec) const { tsec = timestamp >> 30; nsec = timestamp & ((1<<30) - 1); } size_t size() const { return id.size() + url.size(); } bool operator<(const key &other) const { if (timestamp < other.timestamp) return true; if (timestamp > other.timestamp) return false; return id < other.id; } bool operator<=(const key &other) const { if (timestamp < other.timestamp) return true; if (timestamp > other.timestamp) return false; return id <= other.id; } bool operator==(const key &other) const { return (timestamp == other.timestamp) && (id == other.id); } bool operator!=(const key &other) const { return id != other.id; } operator bool() const { return id.size() != 0; } bool operator !() const { return !operator bool(); } std::string str() const { long tsec, tnsec; get_timestamp(tsec, tnsec); return id + ":" + url.str() + ":" + elliptics::lexical_cast(tsec) + "." + elliptics::lexical_cast(tnsec); } }; }} // namespace ioremap::greylock #endif // __INDEXES_KEY_HPP
0a182b80ebfd958c057e132ced98032025e703b4
c0f0941e3d6f62dbe6932da3d428ae2afed53b43
/simulation/g4simulation/g4detectors/BeamLineMagnetSubsystem.h
ef484682f58be2508661c506de6716374970a956
[]
no_license
sPHENIX-Collaboration/coresoftware
ffbb1bd5c107f45c1b3574996aba6693169281ea
19748d09d1997dfc21522e8e3816246691f46512
refs/heads/master
2023-08-03T15:55:20.018519
2023-08-01T23:33:03
2023-08-01T23:33:03
34,742,432
39
208
null
2023-09-14T20:25:46
2015-04-28T16:29:55
C++
UTF-8
C++
false
false
2,234
h
BeamLineMagnetSubsystem.h
// Tell emacs that this is a C++ source // -*- C++ -*-. #ifndef G4DETECTORS_BEAMLINEMAGNETSUBSYSTEM_H #define G4DETECTORS_BEAMLINEMAGNETSUBSYSTEM_H #include "PHG4DetectorSubsystem.h" #include <string> // for string class BeamLineMagnetDetector; class PHCompositeNode; class PHG4Detector; class PHG4DisplayAction; class PHG4SteppingAction; class BeamLineMagnetSubsystem : public PHG4DetectorSubsystem { public: //! constructor BeamLineMagnetSubsystem(const std::string& name = "CYLINDER", const int layer = 0); //! destructor ~BeamLineMagnetSubsystem() override; //! init runwise stuff /*! creates the m_Detector object and place it on the node tree, under "DETECTORS" node (or whatever) reates the stepping action and place it on the node tree, under "ACTIONS" node creates relevant hit nodes that will be populated by the stepping action and stored in the output DST */ int InitRunSubsystem(PHCompositeNode*) override; //! event processing /*! get all relevant nodes from top nodes (namely hit list) and pass that to the stepping action */ int process_event(PHCompositeNode*) override; //! Print info (from SubsysReco) void Print(const std::string& what = "ALL") const override; //! accessors (reimplemented) PHG4Detector* GetDetector(void) const override; PHG4SteppingAction* GetSteppingAction(void) const override { return m_SteppingAction; } PHG4DisplayAction* GetDisplayAction() const override { return m_DisplayAction; } // this method is used to check if it can be used as mothervolume // Subsystems which can be mothervolume need to implement this // and return true bool CanBeMotherSubsystem() const override { return true; } private: void SetDefaultParameters() override; //! detector geometry /*! defives from PHG4Detector */ BeamLineMagnetDetector* m_Detector = nullptr; //! particle tracking "stepping" action /*! derives from PHG4SteppingActions */ PHG4SteppingAction* m_SteppingAction = nullptr; //! display attribute setting /*! derives from PHG4DisplayAction */ PHG4DisplayAction* m_DisplayAction = nullptr; std::string m_HitNodeName; std::string m_AbsorberNodeName; }; #endif // G4DETECTORS_BEAMLINEMAGNETSUBSYSTEM_H
524bad1432db6e23b33696ac5da46314c06b88bb
a96b2cdbb446b845fcb0c14a6c2a775468a3e078
/newWorld/distribution/distributeur/mainwindow.h
489bce867443e1592016680ef8e61808e6c7f005
[]
no_license
prostain/newWorld_catalogue
c18c9b15d2d4d633e2cfc5317adffdbbf1c60481
3e0fe04c36a0d97bc936566183de2d44ac8b6ee6
refs/heads/master
2021-04-18T21:29:40.386735
2018-06-01T13:00:52
2018-06-01T13:00:52
126,461,391
0
0
null
null
null
null
UTF-8
C++
false
false
551
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include<QNetworkAccessManager> #include<QJsonArray> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QNetworkAccessManager *pmyNWM,QString theName, QString theSurname, QString theIdentifiant, QWidget *parent = 0 ); ~MainWindow(); private: Ui::MainWindow *ui; QString name,surname,id; QNetworkReply *reply; QJsonArray jsArray; QNetworkAccessManager * myNWM; }; #endif // MAINWINDOW_H
4cf67009cb164105adeffe490cb8c93f9915370e
ac30c7b64f773de916dfad7b65f851290f3182ce
/MainWindow/newplayerscreendialog.cpp
99b1265e6cf197e48ac96d362b5ffb75e22ad542
[]
no_license
SethMarkarian/CS205-Labs
9bace5d921e78a1df2d4647517dda299fb96c2ef
5b620a82de6fa964f7f95d5c60a70fa9a61633f7
refs/heads/master
2020-05-02T21:56:08.893258
2019-03-28T15:52:49
2019-03-28T15:52:49
178,235,581
1
0
null
null
null
null
UTF-8
C++
false
false
981
cpp
newplayerscreendialog.cpp
#include "newplayerscreendialog.h" #include "ui_newplayerscreendialog.h" NewPlayerScreenDialog::NewPlayerScreenDialog(QWidget *parent) : QDialog(parent), ui(new Ui::NewPlayerScreenDialog) { ui->setupUi(this); } NewPlayerScreenDialog::~NewPlayerScreenDialog() { delete ui; } void NewPlayerScreenDialog::on_Enter_clicked() { QString a = ui->FirstName->text(); std::string b = a.toLocal8Bit().constData(); char * fn = strcpy(new char[a.length() - 1], b.c_str()); ret.push_back(fn); QString c = ui->LastName->text(); std::string d = c.toLocal8Bit().constData(); char * ln = strcpy(new char[d.length() - 1], d.c_str()); ret.push_back(ln); QString e = ui->Address->text(); std::string f = e.toLocal8Bit().constData(); char * ad = strcpy(new char[f.length() - 1], f.c_str()); ret.push_back(ad); close(); } Player * NewPlayerScreenDialog::getNewPlayer() { return new Player(nullptr, ret[0], ret[1], ret[2]); }
270ee837869392a09f011460c784782535bab932
057a475216e9beed41983481aafcaf109bbf58da
/src/Common/CurrentMetrics.cpp
b3dee29e02fcfbf4a7fe83cdc5cf3565ca44afdc
[ "Apache-2.0" ]
permissive
ClickHouse/ClickHouse
fece5204263a5b4d693854b6039699265f1bb27f
6649328db809d51a694c358571539bc5820464be
refs/heads/master
2023-08-31T18:48:36.615225
2023-08-31T17:51:24
2023-08-31T17:51:24
60,246,359
23,878
5,449
Apache-2.0
2023-09-14T20:10:52
2016-06-02T08:28:18
C++
UTF-8
C++
false
false
22,142
cpp
CurrentMetrics.cpp
#include <Common/CurrentMetrics.h> /// Available metrics. Add something here as you wish. #define APPLY_FOR_BUILTIN_METRICS(M) \ M(Query, "Number of executing queries") \ M(Merge, "Number of executing background merges") \ M(Move, "Number of currently executing moves") \ M(PartMutation, "Number of mutations (ALTER DELETE/UPDATE)") \ M(ReplicatedFetch, "Number of data parts being fetched from replica") \ M(ReplicatedSend, "Number of data parts being sent to replicas") \ M(ReplicatedChecks, "Number of data parts checking for consistency") \ M(BackgroundMergesAndMutationsPoolTask, "Number of active merges and mutations in an associated background pool") \ M(BackgroundMergesAndMutationsPoolSize, "Limit on number of active merges and mutations in an associated background pool") \ M(BackgroundFetchesPoolTask, "Number of active fetches in an associated background pool") \ M(BackgroundFetchesPoolSize, "Limit on number of simultaneous fetches in an associated background pool") \ M(BackgroundCommonPoolTask, "Number of active tasks in an associated background pool") \ M(BackgroundCommonPoolSize, "Limit on number of tasks in an associated background pool") \ M(BackgroundMovePoolTask, "Number of active tasks in BackgroundProcessingPool for moves") \ M(BackgroundMovePoolSize, "Limit on number of tasks in BackgroundProcessingPool for moves") \ M(BackgroundSchedulePoolTask, "Number of active tasks in BackgroundSchedulePool. This pool is used for periodic ReplicatedMergeTree tasks, like cleaning old data parts, altering data parts, replica re-initialization, etc.") \ M(BackgroundSchedulePoolSize, "Limit on number of tasks in BackgroundSchedulePool. This pool is used for periodic ReplicatedMergeTree tasks, like cleaning old data parts, altering data parts, replica re-initialization, etc.") \ M(BackgroundBufferFlushSchedulePoolTask, "Number of active tasks in BackgroundBufferFlushSchedulePool. This pool is used for periodic Buffer flushes") \ M(BackgroundBufferFlushSchedulePoolSize, "Limit on number of tasks in BackgroundBufferFlushSchedulePool") \ M(BackgroundDistributedSchedulePoolTask, "Number of active tasks in BackgroundDistributedSchedulePool. This pool is used for distributed sends that is done in background.") \ M(BackgroundDistributedSchedulePoolSize, "Limit on number of tasks in BackgroundDistributedSchedulePool") \ M(BackgroundMessageBrokerSchedulePoolTask, "Number of active tasks in BackgroundProcessingPool for message streaming") \ M(BackgroundMessageBrokerSchedulePoolSize, "Limit on number of tasks in BackgroundProcessingPool for message streaming") \ M(CacheDictionaryUpdateQueueBatches, "Number of 'batches' (a set of keys) in update queue in CacheDictionaries.") \ M(CacheDictionaryUpdateQueueKeys, "Exact number of keys in update queue in CacheDictionaries.") \ M(DiskSpaceReservedForMerge, "Disk space reserved for currently running background merges. It is slightly more than the total size of currently merging parts.") \ M(DistributedSend, "Number of connections to remote servers sending data that was INSERTed into Distributed tables. Both synchronous and asynchronous mode.") \ M(QueryPreempted, "Number of queries that are stopped and waiting due to 'priority' setting.") \ M(TCPConnection, "Number of connections to TCP server (clients with native interface), also included server-server distributed query connections") \ M(MySQLConnection, "Number of client connections using MySQL protocol") \ M(HTTPConnection, "Number of connections to HTTP server") \ M(InterserverConnection, "Number of connections from other replicas to fetch parts") \ M(PostgreSQLConnection, "Number of client connections using PostgreSQL protocol") \ M(OpenFileForRead, "Number of files open for reading") \ M(OpenFileForWrite, "Number of files open for writing") \ M(TotalTemporaryFiles, "Number of temporary files created") \ M(TemporaryFilesForSort, "Number of temporary files created for external sorting") \ M(TemporaryFilesForAggregation, "Number of temporary files created for external aggregation") \ M(TemporaryFilesForJoin, "Number of temporary files created for JOIN") \ M(TemporaryFilesUnknown, "Number of temporary files created without known purpose") \ M(Read, "Number of read (read, pread, io_getevents, etc.) syscalls in fly") \ M(RemoteRead, "Number of read with remote reader in fly") \ M(Write, "Number of write (write, pwrite, io_getevents, etc.) syscalls in fly") \ M(NetworkReceive, "Number of threads receiving data from network. Only ClickHouse-related network interaction is included, not by 3rd party libraries.") \ M(NetworkSend, "Number of threads sending data to network. Only ClickHouse-related network interaction is included, not by 3rd party libraries.") \ M(SendScalars, "Number of connections that are sending data for scalars to remote servers.") \ M(SendExternalTables, "Number of connections that are sending data for external tables to remote servers. External tables are used to implement GLOBAL IN and GLOBAL JOIN operators with distributed subqueries.") \ M(QueryThread, "Number of query processing threads") \ M(ReadonlyReplica, "Number of Replicated tables that are currently in readonly state due to re-initialization after ZooKeeper session loss or due to startup without ZooKeeper configured.") \ M(MemoryTracking, "Total amount of memory (bytes) allocated by the server.") \ M(MergesMutationsMemoryTracking, "Total amount of memory (bytes) allocated by background tasks (merges and mutations).") \ M(EphemeralNode, "Number of ephemeral nodes hold in ZooKeeper.") \ M(ZooKeeperSession, "Number of sessions (connections) to ZooKeeper. Should be no more than one, because using more than one connection to ZooKeeper may lead to bugs due to lack of linearizability (stale reads) that ZooKeeper consistency model allows.") \ M(ZooKeeperWatch, "Number of watches (event subscriptions) in ZooKeeper.") \ M(ZooKeeperRequest, "Number of requests to ZooKeeper in fly.") \ M(DelayedInserts, "Number of INSERT queries that are throttled due to high number of active data parts for partition in a MergeTree table.") \ M(ContextLockWait, "Number of threads waiting for lock in Context. This is global lock.") \ M(StorageBufferRows, "Number of rows in buffers of Buffer tables") \ M(StorageBufferBytes, "Number of bytes in buffers of Buffer tables") \ M(DictCacheRequests, "Number of requests in fly to data sources of dictionaries of cache type.") \ M(Revision, "Revision of the server. It is a number incremented for every release or release candidate except patch releases.") \ M(VersionInteger, "Version of the server in a single integer number in base-1000. For example, version 11.22.33 is translated to 11022033.") \ M(RWLockWaitingReaders, "Number of threads waiting for read on a table RWLock.") \ M(RWLockWaitingWriters, "Number of threads waiting for write on a table RWLock.") \ M(RWLockActiveReaders, "Number of threads holding read lock in a table RWLock.") \ M(RWLockActiveWriters, "Number of threads holding write lock in a table RWLock.") \ M(GlobalThread, "Number of threads in global thread pool.") \ M(GlobalThreadActive, "Number of threads in global thread pool running a task.") \ M(LocalThread, "Number of threads in local thread pools. The threads in local thread pools are taken from the global thread pool.") \ M(LocalThreadActive, "Number of threads in local thread pools running a task.") \ M(MergeTreeDataSelectExecutorThreads, "Number of threads in the MergeTreeDataSelectExecutor thread pool.") \ M(MergeTreeDataSelectExecutorThreadsActive, "Number of threads in the MergeTreeDataSelectExecutor thread pool running a task.") \ M(BackupsThreads, "Number of threads in the thread pool for BACKUP.") \ M(BackupsThreadsActive, "Number of threads in thread pool for BACKUP running a task.") \ M(RestoreThreads, "Number of threads in the thread pool for RESTORE.") \ M(RestoreThreadsActive, "Number of threads in the thread pool for RESTORE running a task.") \ M(MarksLoaderThreads, "Number of threads in thread pool for loading marks.") \ M(MarksLoaderThreadsActive, "Number of threads in the thread pool for loading marks running a task.") \ M(IOPrefetchThreads, "Number of threads in the IO prefertch thread pool.") \ M(IOPrefetchThreadsActive, "Number of threads in the IO prefetch thread pool running a task.") \ M(IOWriterThreads, "Number of threads in the IO writer thread pool.") \ M(IOWriterThreadsActive, "Number of threads in the IO writer thread pool running a task.") \ M(IOThreads, "Number of threads in the IO thread pool.") \ M(IOThreadsActive, "Number of threads in the IO thread pool running a task.") \ M(ThreadPoolRemoteFSReaderThreads, "Number of threads in the thread pool for remote_filesystem_read_method=threadpool.") \ M(ThreadPoolRemoteFSReaderThreadsActive, "Number of threads in the thread pool for remote_filesystem_read_method=threadpool running a task.") \ M(ThreadPoolFSReaderThreads, "Number of threads in the thread pool for local_filesystem_read_method=threadpool.") \ M(ThreadPoolFSReaderThreadsActive, "Number of threads in the thread pool for local_filesystem_read_method=threadpool running a task.") \ M(BackupsIOThreads, "Number of threads in the BackupsIO thread pool.") \ M(BackupsIOThreadsActive, "Number of threads in the BackupsIO thread pool running a task.") \ M(DiskObjectStorageAsyncThreads, "Obsolete metric, shows nothing.") \ M(DiskObjectStorageAsyncThreadsActive, "Obsolete metric, shows nothing.") \ M(StorageHiveThreads, "Number of threads in the StorageHive thread pool.") \ M(StorageHiveThreadsActive, "Number of threads in the StorageHive thread pool running a task.") \ M(TablesLoaderThreads, "Number of threads in the tables loader thread pool.") \ M(TablesLoaderThreadsActive, "Number of threads in the tables loader thread pool running a task.") \ M(DatabaseOrdinaryThreads, "Number of threads in the Ordinary database thread pool.") \ M(DatabaseOrdinaryThreadsActive, "Number of threads in the Ordinary database thread pool running a task.") \ M(DatabaseOnDiskThreads, "Number of threads in the DatabaseOnDisk thread pool.") \ M(DatabaseOnDiskThreadsActive, "Number of threads in the DatabaseOnDisk thread pool running a task.") \ M(DatabaseCatalogThreads, "Number of threads in the DatabaseCatalog thread pool.") \ M(DatabaseCatalogThreadsActive, "Number of threads in the DatabaseCatalog thread pool running a task.") \ M(DestroyAggregatesThreads, "Number of threads in the thread pool for destroy aggregate states.") \ M(DestroyAggregatesThreadsActive, "Number of threads in the thread pool for destroy aggregate states running a task.") \ M(HashedDictionaryThreads, "Number of threads in the HashedDictionary thread pool.") \ M(HashedDictionaryThreadsActive, "Number of threads in the HashedDictionary thread pool running a task.") \ M(CacheDictionaryThreads, "Number of threads in the CacheDictionary thread pool.") \ M(CacheDictionaryThreadsActive, "Number of threads in the CacheDictionary thread pool running a task.") \ M(ParallelFormattingOutputFormatThreads, "Number of threads in the ParallelFormattingOutputFormatThreads thread pool.") \ M(ParallelFormattingOutputFormatThreadsActive, "Number of threads in the ParallelFormattingOutputFormatThreads thread pool running a task.") \ M(ParallelParsingInputFormatThreads, "Number of threads in the ParallelParsingInputFormat thread pool.") \ M(ParallelParsingInputFormatThreadsActive, "Number of threads in the ParallelParsingInputFormat thread pool running a task.") \ M(MergeTreeBackgroundExecutorThreads, "Number of threads in the MergeTreeBackgroundExecutor thread pool.") \ M(MergeTreeBackgroundExecutorThreadsActive, "Number of threads in the MergeTreeBackgroundExecutor thread pool running a task.") \ M(AsynchronousInsertThreads, "Number of threads in the AsynchronousInsert thread pool.") \ M(AsynchronousInsertThreadsActive, "Number of threads in the AsynchronousInsert thread pool running a task.") \ M(StartupSystemTablesThreads, "Number of threads in the StartupSystemTables thread pool.") \ M(StartupSystemTablesThreadsActive, "Number of threads in the StartupSystemTables thread pool running a task.") \ M(AggregatorThreads, "Number of threads in the Aggregator thread pool.") \ M(AggregatorThreadsActive, "Number of threads in the Aggregator thread pool running a task.") \ M(DDLWorkerThreads, "Number of threads in the DDLWorker thread pool for ON CLUSTER queries.") \ M(DDLWorkerThreadsActive, "Number of threads in the DDLWORKER thread pool for ON CLUSTER queries running a task.") \ M(StorageDistributedThreads, "Number of threads in the StorageDistributed thread pool.") \ M(StorageDistributedThreadsActive, "Number of threads in the StorageDistributed thread pool running a task.") \ M(DistributedInsertThreads, "Number of threads used for INSERT into Distributed.") \ M(DistributedInsertThreadsActive, "Number of threads used for INSERT into Distributed running a task.") \ M(StorageS3Threads, "Number of threads in the StorageS3 thread pool.") \ M(StorageS3ThreadsActive, "Number of threads in the StorageS3 thread pool running a task.") \ M(ObjectStorageS3Threads, "Number of threads in the S3ObjectStorage thread pool.") \ M(ObjectStorageS3ThreadsActive, "Number of threads in the S3ObjectStorage thread pool running a task.") \ M(ObjectStorageAzureThreads, "Number of threads in the AzureObjectStorage thread pool.") \ M(ObjectStorageAzureThreadsActive, "Number of threads in the AzureObjectStorage thread pool running a task.") \ M(MergeTreePartsLoaderThreads, "Number of threads in the MergeTree parts loader thread pool.") \ M(MergeTreePartsLoaderThreadsActive, "Number of threads in the MergeTree parts loader thread pool running a task.") \ M(MergeTreeOutdatedPartsLoaderThreads, "Number of threads in the threadpool for loading Outdated data parts.") \ M(MergeTreeOutdatedPartsLoaderThreadsActive, "Number of active threads in the threadpool for loading Outdated data parts.") \ M(MergeTreePartsCleanerThreads, "Number of threads in the MergeTree parts cleaner thread pool.") \ M(MergeTreePartsCleanerThreadsActive, "Number of threads in the MergeTree parts cleaner thread pool running a task.") \ M(IDiskCopierThreads, "Number of threads for copying data between disks of different types.") \ M(IDiskCopierThreadsActive, "Number of threads for copying data between disks of different types running a task.") \ M(SystemReplicasThreads, "Number of threads in the system.replicas thread pool.") \ M(SystemReplicasThreadsActive, "Number of threads in the system.replicas thread pool running a task.") \ M(RestartReplicaThreads, "Number of threads in the RESTART REPLICA thread pool.") \ M(RestartReplicaThreadsActive, "Number of threads in the RESTART REPLICA thread pool running a task.") \ M(QueryPipelineExecutorThreads, "Number of threads in the PipelineExecutor thread pool.") \ M(QueryPipelineExecutorThreadsActive, "Number of threads in the PipelineExecutor thread pool running a task.") \ M(ParquetDecoderThreads, "Number of threads in the ParquetBlockInputFormat thread pool.") \ M(ParquetDecoderThreadsActive, "Number of threads in the ParquetBlockInputFormat thread pool running a task.") \ M(ParquetEncoderThreads, "Number of threads in ParquetBlockOutputFormat thread pool.") \ M(ParquetEncoderThreadsActive, "Number of threads in ParquetBlockOutputFormat thread pool running a task.") \ M(OutdatedPartsLoadingThreads, "Number of threads in the threadpool for loading Outdated data parts.") \ M(OutdatedPartsLoadingThreadsActive, "Number of active threads in the threadpool for loading Outdated data parts.") \ M(DistributedBytesToInsert, "Number of pending bytes to process for asynchronous insertion into Distributed tables. Number of bytes for every shard is summed.") \ M(BrokenDistributedBytesToInsert, "Number of bytes for asynchronous insertion into Distributed tables that has been marked as broken. Number of bytes for every shard is summed.") \ M(DistributedFilesToInsert, "Number of pending files to process for asynchronous insertion into Distributed tables. Number of files for every shard is summed.") \ M(BrokenDistributedFilesToInsert, "Number of files for asynchronous insertion into Distributed tables that has been marked as broken. Number of files for every shard is summed.") \ M(TablesToDropQueueSize, "Number of dropped tables, that are waiting for background data removal.") \ M(MaxDDLEntryID, "Max processed DDL entry of DDLWorker.") \ M(MaxPushedDDLEntryID, "Max DDL entry of DDLWorker that pushed to zookeeper.") \ M(PartsTemporary, "The part is generating now, it is not in data_parts list.") \ M(PartsPreCommitted, "Deprecated. See PartsPreActive.") \ M(PartsCommitted, "Deprecated. See PartsActive.") \ M(PartsPreActive, "The part is in data_parts, but not used for SELECTs.") \ M(PartsActive, "Active data part, used by current and upcoming SELECTs.") \ M(PartsOutdated, "Not active data part, but could be used by only current SELECTs, could be deleted after SELECTs finishes.") \ M(PartsDeleting, "Not active data part with identity refcounter, it is deleting right now by a cleaner.") \ M(PartsDeleteOnDestroy, "Part was moved to another disk and should be deleted in own destructor.") \ M(PartsWide, "Wide parts.") \ M(PartsCompact, "Compact parts.") \ M(PartsInMemory, "In-memory parts.") \ M(MMappedFiles, "Total number of mmapped files.") \ M(MMappedFileBytes, "Sum size of mmapped file regions.") \ M(MMappedAllocs, "Total number of mmapped allocations") \ M(MMappedAllocBytes, "Sum bytes of mmapped allocations") \ M(AsynchronousReadWait, "Number of threads waiting for asynchronous read.") \ M(PendingAsyncInsert, "Number of asynchronous inserts that are waiting for flush.") \ M(KafkaConsumers, "Number of active Kafka consumers") \ M(KafkaConsumersWithAssignment, "Number of active Kafka consumers which have some partitions assigned.") \ M(KafkaProducers, "Number of active Kafka producer created") \ M(KafkaLibrdkafkaThreads, "Number of active librdkafka threads") \ M(KafkaBackgroundReads, "Number of background reads currently working (populating materialized views from Kafka)") \ M(KafkaConsumersInUse, "Number of consumers which are currently used by direct or background reads") \ M(KafkaWrites, "Number of currently running inserts to Kafka") \ M(KafkaAssignedPartitions, "Number of partitions Kafka tables currently assigned to") \ M(FilesystemCacheReadBuffers, "Number of active cache buffers") \ M(CacheFileSegments, "Number of existing cache file segments") \ M(CacheDetachedFileSegments, "Number of existing detached cache file segments") \ M(FilesystemCacheSize, "Filesystem cache size in bytes") \ M(FilesystemCacheSizeLimit, "Filesystem cache size limit in bytes") \ M(FilesystemCacheElements, "Filesystem cache elements (file segments)") \ M(FilesystemCacheDownloadQueueElements, "Filesystem cache elements in download queue") \ M(FilesystemCacheDelayedCleanupElements, "Filesystem cache elements in background cleanup queue") \ M(AsyncInsertCacheSize, "Number of async insert hash id in cache") \ M(S3Requests, "S3 requests") \ M(KeeperAliveConnections, "Number of alive connections") \ M(KeeperOutstandingRequets, "Number of outstanding requests") \ M(ThreadsInOvercommitTracker, "Number of waiting threads inside of OvercommitTracker") \ M(IOUringPendingEvents, "Number of io_uring SQEs waiting to be submitted") \ M(IOUringInFlightEvents, "Number of io_uring SQEs in flight") \ M(ReadTaskRequestsSent, "The current number of callback requests in flight from the remote server back to the initiator server to choose the read task (for s3Cluster table function and similar). Measured on the remote server side.") \ M(MergeTreeReadTaskRequestsSent, "The current number of callback requests in flight from the remote server back to the initiator server to choose the read task (for MergeTree tables). Measured on the remote server side.") \ M(MergeTreeAllRangesAnnouncementsSent, "The current number of announcement being sent in flight from the remote server to the initiator server about the set of data parts (for MergeTree tables). Measured on the remote server side.") \ M(CreatedTimersInQueryProfiler, "Number of Created thread local timers in QueryProfiler") \ M(ActiveTimersInQueryProfiler, "Number of Active thread local timers in QueryProfiler") \ #ifdef APPLY_FOR_EXTERNAL_METRICS #define APPLY_FOR_METRICS(M) APPLY_FOR_BUILTIN_METRICS(M) APPLY_FOR_EXTERNAL_METRICS(M) #else #define APPLY_FOR_METRICS(M) APPLY_FOR_BUILTIN_METRICS(M) #endif namespace CurrentMetrics { #define M(NAME, DOCUMENTATION) extern const Metric NAME = Metric(__COUNTER__); APPLY_FOR_METRICS(M) #undef M constexpr Metric END = Metric(__COUNTER__); std::atomic<Value> values[END] {}; /// Global variable, initialized by zeros. const char * getName(Metric event) { static const char * strings[] = { #define M(NAME, DOCUMENTATION) #NAME, APPLY_FOR_METRICS(M) #undef M }; return strings[event]; } const char * getDocumentation(Metric event) { static const char * strings[] = { #define M(NAME, DOCUMENTATION) DOCUMENTATION, APPLY_FOR_METRICS(M) #undef M }; return strings[event]; } Metric end() { return END; } } #undef APPLY_FOR_METRICS
c84ec485b21fb6e0038bcb0fdc91c15fa8df643b
432aeac234e03a0775cc23243e4d8d71e36a6dc5
/Pointer/Pointer/main.cpp
771c61136b12284278fbe1e4548c72dbd8abf02a
[]
no_license
KnifestRapGameMurder/Pointers
7c28522ba3b014bff510010708d68d5cc32684b9
c1fb9ed57b5c2d82bce8fb00d7f62a3e6726903b
refs/heads/master
2020-08-20T20:42:58.197839
2019-10-18T17:54:20
2019-10-18T17:54:20
216,064,507
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,021
cpp
main.cpp
#include<iostream> using namespace std; //#define POINTERS_BASICS #define DECLARATION_OF_POINTERS void main() { setlocale(LC_ALL, ""); #ifdef POINTERS_BASICS int a = 2; int *pa = &a; cout << a << endl; cout << &a << endl; cout << pa << endl; cout << *pa << endl; int *pb; int b = 3; pb = &b; cout << pb << endl; cout << *pb << endl; // int - int // int* - указатель на int // double - doouble // double* - указатель на double #endif #ifdef DECLARATION_OF_POINTERS int a, b, c; //Обьявление трех переменных одним выражением. int *pa, *pb, *pc; //Обьявление трех указателей одним выражением. int* pd, pe, pf; //обьявиться один указатель на int (pd) //и две переменные типа int (pe и pf). #endif const int n = 5; short Arr[n] = { 3,5,8,13,21 }; cout << Arr << endl; for (int i = 0; i < n; i++) { cout << *(Arr + i) << "\t"; } cout << endl; }
ddc647164a4a5c9d2b522ffed8204d899d8e78f9
5070c5a5279f3a7a3c9ed09133037b0f774c4661
/fuzzer-windows-master/ie_sandbox/HelloWorld/hook.cpp
2b51804a57448ac6219a3a0541eaba88853e1f6e
[]
no_license
Trietptm-on-Security/font_suites
6047a95534c3c03f412621fadd49c2662b948d0e
d23d222ae093806a57c60decf559575975cfa75c
refs/heads/master
2018-04-13T15:50:09.562027
2016-07-29T08:28:24
2016-07-29T08:28:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,081
cpp
hook.cpp
#include "stdafx.h" #include "resource.h" #include "HelloWorld_i.h" #include "dllmain.h" #include <Windows.h> #include "hook.h" #include "log.h" BOOL install_hook(void) { HINSTANCE dllHandle = NULL; writeLog("[*] Installing hook....\r\n"); writeLog("[*] Looking for ole32.dll\r\n"); dllHandle = LoadLibrary((LPCWSTR)L"ole32.dll"); // Get an handle to the iertutil.dll library if(dllHandle != NULL) writeLog("[+] ole32.dll correctly imported!\r\n"); else { writeLog("[-] Unable to find iertutil.dll... aborting!\r\n"); return NULL; } writeLog("[*] Looking for method\r\n"); // Get the entry point for the CoCreateUserBroker method (exported as #58 entry) int (*NdrStubCall2_ptr)(void *, void *, void *, void *) = (int (*)(void *, void *, void *, void *)) GetProcAddress(dllHandle, (LPCSTR)"NdrStubCall2"); if(NdrStubCall2_ptr != NULL) writeLog("[+] Method CoCreateUserBroker correctly found!\r\n"); else { writeLog("[-] Unable to find CoCreateUserBroker method.... aborting!\r\n"); return NULL; } // Return the IEUserBroker object return true; }
b283e01e6de0f774278e40497dd905ff54256cb7
a10417092f4e47e98468d8d4f956f73d370e205d
/cs200_intro_to_programming/labs/lab3/task1_2.cpp
81555846e5404ea7f30fc86efd786164151b2938
[]
no_license
ghanisol/lums
da36e8b052f00104bba35b1eaf51ed0eb2beaf73
0407dbbcf326ee58629de5059eff181ea1ee0f07
refs/heads/master
2020-04-03T09:42:45.386971
2018-10-31T21:59:07
2018-10-31T21:59:07
155,173,951
0
2
null
null
null
null
UTF-8
C++
false
false
322
cpp
task1_2.cpp
#include <iostream> #include <string> using namespace std; int main() { string name = "Faizan"; int length = name.length(); int i = 0; char l = 0; while (i <= length) { cout << "Enter the letter\n"; cin >> l; if (l == name[i]) { cout << "The " << i << "number is :" << l << endl; i++; } } }
c993aa7dd1ee6dfdfb19f113f8ec9176577b8295
dcee7da72687faac26f64139486e93d416af369d
/Effects/Tunel/moEffectTunel.cpp
ba6849370e9a1a5700c59e190051a962566557d2
[]
no_license
moldeo/moldeoplugins
871d0c70047b4074c0aa08c0f5dbe156a38b2dba
609af7c5e4271723dfc3394343fabd0b431fb934
refs/heads/master
2022-02-14T17:39:50.461902
2022-02-07T11:30:28
2022-02-07T11:30:28
25,303,561
1
1
null
null
null
null
ISO-8859-2
C++
false
false
10,533
cpp
moEffectTunel.cpp
/******************************************************************************* moEffectTunel.cpp **************************************************************************** * * * This source is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This code 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. * * * * A copy of the GNU General Public License is available on the World * * Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also * * obtain it by writing to the Free Software Foundation, * * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * **************************************************************************** Copyright(C) 2006 Fabricio Costa Authors: Fabricio Costa Andrés Colubri *******************************************************************************/ #include "moEffectTunel.h" //======================== // Factory //======================== moEffectTunelFactory *m_EffectTunelFactory = NULL; MO_PLG_API moEffectFactory* CreateEffectFactory(){ if(m_EffectTunelFactory==NULL) m_EffectTunelFactory = new moEffectTunelFactory(); return(moEffectFactory*) m_EffectTunelFactory; } MO_PLG_API void DestroyEffectFactory(){ delete m_EffectTunelFactory; m_EffectTunelFactory = NULL; } moEffect* moEffectTunelFactory::Create() { return new moEffectTunel(); } void moEffectTunelFactory::Destroy(moEffect* fx) { delete fx; } //======================== // Efecto //======================== moEffectTunel::moEffectTunel() { SetName("tunel"); } moEffectTunel::~moEffectTunel() { Finish(); } moConfigDefinition * moEffectTunel::GetDefinition( moConfigDefinition *p_configdefinition ) { //default: alpha, color, syncro p_configdefinition = moEffect::GetDefinition( p_configdefinition ); p_configdefinition->Add( moText("texture"), MO_PARAM_TEXTURE, TUNEL_TEXTURE, moValue( "default", "TXT") ); p_configdefinition->Add( moText("blending"), MO_PARAM_BLENDING, TUNEL_BLENDING, moValue( "0", MO_VALUE_NUM ).Ref() ); p_configdefinition->Add( moText("translatex"), MO_PARAM_TRANSLATEX, TUNEL_TRANSLATEX ); p_configdefinition->Add( moText("translatey"), MO_PARAM_TRANSLATEY, TUNEL_TRANSLATEY ); p_configdefinition->Add( moText("translatez"), MO_PARAM_TRANSLATEZ, TUNEL_TRANSLATEZ ); p_configdefinition->Add( moText("rotate"), MO_PARAM_ROTATEZ, TUNEL_ROTATE ); p_configdefinition->Add( moText("target_translatex"), MO_PARAM_TRANSLATEX, TUNEL_TARGET_TRANSLATEX ); p_configdefinition->Add( moText("target_translatey"), MO_PARAM_TRANSLATEY, TUNEL_TARGET_TRANSLATEY ); p_configdefinition->Add( moText("target_translatez"), MO_PARAM_TRANSLATEZ, TUNEL_TARGET_TRANSLATEZ ); p_configdefinition->Add( moText("target_rotate"), MO_PARAM_ROTATEZ, TUNEL_TARGET_ROTATE ); p_configdefinition->Add( moText("sides"), MO_PARAM_NUMERIC, TUNEL_SIDES, moValue("12", "INT" ) ); p_configdefinition->Add( moText("segments"), MO_PARAM_NUMERIC, TUNEL_SEGMENTS, moValue("32", "INT" ) ); p_configdefinition->Add( moText("wireframe"), MO_PARAM_NUMERIC, TUNEL_SEGMENTS, moValue("0", "INT" ) ); return p_configdefinition; } MOboolean moEffectTunel::Init() { if (!PreInit()) return false; moDefineParamIndex( TUNEL_INLET, moText("inlet") ); moDefineParamIndex( TUNEL_OUTLET, moText("outlet") ); moDefineParamIndex( TUNEL_SCRIPT, moText("script") ); moDefineParamIndex( TUNEL_ALPHA, moText("alpha") ); moDefineParamIndex( TUNEL_COLOR, moText("color") ); moDefineParamIndex( TUNEL_SYNC, moText("syncro") ); moDefineParamIndex( TUNEL_PHASE, moText("phase") ); moDefineParamIndex( TUNEL_TEXTURE, moText("texture") ); moDefineParamIndex( TUNEL_BLENDING, moText("blending") ); moDefineParamIndex( TUNEL_TRANSLATEX, moText("translatex") ); moDefineParamIndex( TUNEL_TRANSLATEY, moText("translatey") ); moDefineParamIndex( TUNEL_TRANSLATEZ, moText("translatez") ); moDefineParamIndex( TUNEL_ROTATE, moText("rotate") ); moDefineParamIndex( TUNEL_TARGET_TRANSLATEX, moText("target_translatex") ); moDefineParamIndex( TUNEL_TARGET_TRANSLATEY, moText("target_translatey") ); moDefineParamIndex( TUNEL_TARGET_TRANSLATEZ, moText("target_translatez") ); moDefineParamIndex( TUNEL_TARGET_ROTATE, moText("target_rotate") ); moDefineParamIndex( TUNEL_SIDES, moText("sides") ); moDefineParamIndex( TUNEL_SEGMENTS, moText("segments") ); moDefineParamIndex( TUNEL_WIREFRAME, moText("wireframe") ); return true; } void moEffectTunel::UpdateParameters() { sides = m_Config.Int( moR(TUNEL_SIDES) ); if (sides>MAXTUNELSIDES) sides = MAXTUNELSIDES; segments = m_Config.Int( moR(TUNEL_SEGMENTS) ); if (segments>MAXTUNELSEGMENTS) segments = MAXTUNELSEGMENTS; wireframe_mode = m_Config.Int( moR(TUNEL_WIREFRAME) ) == 1; } void moEffectTunel::Draw( moTempo* tempogral,moEffectState* parentstate) { int I, J, texture_a; GLdouble C, J1, J2; GLdouble Angle, Speed; BeginDraw( tempogral, parentstate); UpdateParameters(); Angle =(m_EffectState.tempo.getTempo()/2.0); Speed =(m_EffectState.tempo.getTempo()/2.0)*TEXTURE_SPEED; // Guardar y resetar la matriz de vista del modelo // glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glPushMatrix(); // Store The Modelview Matrix glLoadIdentity(); // Reset The View // Funcion de blending y de alpha channel // glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_ALPHA); // Cambiar la proyeccion para usar el z-buffer // glEnable(GL_DEPTH_TEST); // Enables Depth Testing glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_DEPTH_BUFFER_BIT); if (wireframe_mode) { glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); } else { glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); } // Draw glTranslatef( m_Config.Eval( moR(TUNEL_TRANSLATEX) ), m_Config.Eval( moR(TUNEL_TRANSLATEY) ), m_Config.Eval( moR(TUNEL_TRANSLATEZ) ) ); glRotatef( m_Config.Eval( moR(TUNEL_ROTATE)), 0.0, 0.0, 1.0 ); /* moTexture* pImage = (moTexture*) m_Config.Texture( [moR(TUNEL_TEXTURE) ); if (pImage!=NULL) { if (pImage->GetType()==MO_TYPE_MOVIE) { glBlendFunc(GL_SRC_COLOR,GL_ONE_MINUS_SRC_COLOR); } else { glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); } } */ glBindTexture( GL_TEXTURE_2D, m_Config.GetGLId( moR(TUNEL_TEXTURE)) ); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT); // setup TUNEL coordinates float fsides = (float)sides; float fsegments = (float)segments; int segments_end = ( segments * 2 ) / 3 ; for( I=0; I<=sides; I++) for( J=0; J<segments; J++) { float radius = (3.0 - J/fsides);//se achica con la distancia... /* float target_x = m_Config.Eval( moR(TUNEL_TARGET_TRANSLATEX)); float target_y = m_Config.Eval( moR(TUNEL_TARGET_TRANSLATEY)); float target_z = m_Config.Eval( moR(TUNEL_TARGET_TRANSLATEZ)); float target_rotate = m_Config.Eval( moR(TUNEL_TARGET_ROTATE)) * 2.0f * MO_PI / 180.0f; */ float target_x = m_Config.Eval( moR(TUNEL_TARGET_TRANSLATEX)) * ( 2*sin((Angle+2.0*J)/29) + cos((Angle+2*J)/13) - 2*sin(Angle/29) - cos(Angle/13) ); float target_y = m_Config.Eval( moR(TUNEL_TARGET_TRANSLATEY)) * ( 2*cos((Angle+2.0*J)/33) + sin((Angle+2*J)/17) - 2*cos(Angle/33) - sin(Angle/17) ); float target_z = 0.0; float target_rotate = (J/fsides) * m_Config.Eval( moR(TUNEL_TARGET_ROTATE)) * 2.0f * MO_PI / 180.0f; ///fade rotation with distance... Tunnels[I][J].X = radius*cos( target_rotate + (I* 2*MO_PI )/fsides ) + target_x;// + 2*sin((Angle+2.0*J)/29) + cos((Angle+2*J)/13) - 2*sin(Angle/29) - cos(Angle/13); Tunnels[I][J].Y = radius*sin( target_rotate + (I* 2*MO_PI )/fsides ) + target_y;// + 2*cos((Angle+2.0*J)/33) + sin((Angle+2*J)/17) - 2*cos(Angle/33) - sin(Angle/17); Tunnels[I][J].Z = -J + (target_z*J) / (float)segments ; } // draw TUNEL for( J=segments-2; J>=0; J--) { // precalculate texture v coords for speed J1 = J/fsegments + Speed; J2 =(J+1.0)/fsegments + Speed; // near the end of the TUNEL, fade the effect away if(J > segments_end ) C = 1.0-(J-segments_end)/(segments-segments_end); else C = 1.0; SetColor( m_Config[moR(TUNEL_COLOR)], m_Config[moR(TUNEL_ALPHA)], m_EffectState ); SetBlending( (moBlendingModes) m_Config.Int( moR(TUNEL_BLENDING) ) ); glBegin(GL_QUADS); for( I=0; I<sides; I++) { glTexCoord2f((I-3.0)/fsides, J1); glVertex3f(Tunnels[ I][ J].X, Tunnels[ I][ J].Y, Tunnels[ I][ J].Z); glTexCoord2f((I-2.0)/fsides, J1); glVertex3f(Tunnels[I+1][ J].X, Tunnels[I+1][ J].Y, Tunnels[I+1][ J].Z); glTexCoord2f((I-2.0)/fsides, J2); glVertex3f(Tunnels[I+1][ J+1].X, Tunnels[I+1][ J+1].Y, Tunnels[I+1][ J+1].Z); glTexCoord2f((I-3.0)/fsides, J2); glVertex3f(Tunnels[ I][ J+1].X, Tunnels[ I][ J+1].Y, Tunnels[ I][ J+1].Z); } glEnd(); } // Dejamos todo como lo encontramos // glDisable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glPopMatrix(); // Restore The Old Projection Matrix glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glPopMatrix(); // Restore The Old Projection Matrix EndDraw(); } MOboolean moEffectTunel::Finish() { return PreFinish(); }
6585d668cc46548b22193cb07e53a27f234c1ec0
8956c3eca551051a080502acfb42432678d1cf97
/udemy/deepdive/secondSection/palindrome/palindrome/palindrome.cpp
2d3b6c568aa13faf1c843617ae43c53d0bb3b0bb
[]
no_license
aHojo/CPPLearning
5ef4380f6ed6c1970f27844249ed1edb1e17328c
497fa09cd91da20d74022394116aa68fbcb10241
refs/heads/master
2020-05-07T21:44:20.016741
2019-07-17T13:33:25
2019-07-17T13:33:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
palindrome.cpp
// palindrome.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> int main() { int num, temp, rev, reversed = 0; std::cout << "Enter a number to find out if palindrome: "; std::cin >> num; temp = num; while (temp != 0) { rev = temp % 10; reversed = reversed * 10 + rev; temp /= 10; } if (reversed == num) { std::cout << "Palindrome: " << num << " - " << reversed << "\n"; } else { std::cout << "Not palindrome " << num << " - " << reversed << "\n"; } return 0; }
e016e8b2e0a562f08155d4c17b99bbf76ce51a09
c291f81e729d070421443a1553892db4a4edd58b
/src/interactionMesh/TimedPoseContainer.h
fdbc2a036b3b0c6c935cf1e7a3c951c63489113f
[]
no_license
lyh458/InteractionModels_DemoCode
2ed94d96b4453953a2dbcdf8f53b2983f25d6510
ef46a10245a1e2c002c489b48baca4487ce447a0
refs/heads/master
2020-07-15T19:57:58.678927
2017-10-20T16:38:56
2017-10-20T16:38:56
205,638,579
1
0
null
2019-09-01T06:30:33
2019-09-01T06:30:32
null
UTF-8
C++
false
false
1,663
h
TimedPoseContainer.h
/* * TimedPoseContainer.h * * Created on: Feb 28, 2013 * Author: ddvogt */ #ifndef TIMEDPOSECONTAINER_H_ #define TIMEDPOSECONTAINER_H_ #include "Timer.h" #include "PoseContainer.h" namespace iMod { ///< Define a standard time type typedef boost::posix_time::ptime Time_t; ///< Define a standard list of time stamps typedef std::list<Time_t> Times_t; /*! * A simple timed posture structure * */ struct TimedPosture{ Pose_t pose; Time_t timeAdded; ///< Time when the pose has been added to the container friend std::ostream& operator<< (std::ostream &out, TimedPosture &p){ out<<boost::posix_time::to_simple_string(p.timeAdded)<<" "; for(unsigned int i=0;i<p.pose.size();i++) out<<p.pose[i]<<" "; return out; } }; class TimedPoseContainer: public iMod::PoseContainer { Times_t timesAdded; public: TimedPoseContainer(); virtual ~TimedPoseContainer(); /*! * Adds a new pose to the container * @param newPose The pose that will be added to the container */ void addPose(Pose_t newPose); /*! * returns the last added pose in the container * @return the actual posture that is returned */ TimedPosture getLastPose(); /*! * Get a specific posture * @param index The index of the posture which is to be returned * @param pose The timed pose that will be filled with the posture at index @param index * @return True if the posture has been found, e.g. the index exists */ bool getPose(int index, TimedPosture &pose); /*! * Get the first pose in the container * @return The first pose in the container */ TimedPosture getFirstPose(); }; } /* namespace iMod */ #endif /* TIMEDPOSECONTAINER_H_ */
dd04b849a6091c984a749317b9b71bacd47d433b
c31fe707725cae00cbd7fe691fb9e42a7b24a52c
/C++ & SFML/2.Pato_Fodder/Codigo/Viento.cpp
dde17cd700e81f8c3618f03ac4cc731cbd6e4bec
[]
no_license
nlattessi/unl-vg
be90dbef3ea2e8583a7dbb4fe14bde427c5c6f3b
96cbbd3604655fb36bcd44fac4213355c2acc249
refs/heads/master
2016-09-06T16:21:24.285941
2015-04-28T19:57:35
2015-04-28T19:57:35
34,751,988
0
0
null
null
null
null
ISO-8859-3
C++
false
false
786
cpp
Viento.cpp
#include "Viento.h" Viento::Viento() { dirViento = 0; fuerzaViento = 0; timerViento = 0.0f; cambiaViento = 10.0f; //Cambio el viento cada 10 segundos } Viento::~Viento() { } void Viento::Update(float _ft) { //Actualizo el viento y cambio //su dirección y velocidad si //se cumple el tiempo seteado timerViento += _ft; if (timerViento > cambiaViento) //Veo si es momento de cambiar el viento { switch (sf::Randomizer::Random(0,2)) { case 0: //0: sin viento dirViento = 1; break; case 1: //1: viento izq dirViento = -1; break; case 2: //2: viento der. dirViento = 1; break; } if (dirViento != 0) fuerzaViento = (sf::Randomizer::Random(0, 10)) * 10; //Tomo una fuerza aleatoria timerViento = 0.0f; //Reinicio el contador } }
11e88f72df34c9b07ea7bd602e5fc27bab4ebbbf
cef5f57c6243ab5f93e8b54cdfabb454c1502333
/cpp/main.cpp
618058de3ca0b2e270b6a9e0ce6a19897303972d
[]
no_license
uriellopes/PetFera
239d48b70f617ba097e8f291cbfb1888d5ec110c
f05ffbd5dbc8d8810f366229b446ed22029dbe6a
refs/heads/master
2022-03-30T23:55:41.154659
2019-11-25T13:34:03
2019-11-25T13:34:03
220,641,660
0
0
null
null
null
null
UTF-8
C++
false
false
56,560
cpp
main.cpp
#include <iostream> using std::cin; using std::cout; using std::endl; #include <algorithm> using std::find_if; #include <memory> using std::shared_ptr; #include <sstream> using std::stringstream; #include <fstream> using std::ofstream; using std::ifstream; #include <vector> using std::vector; #include "../includes/anfibioexotico.h" #include "../includes/mamiferoexotico.h" #include "../includes/aveexotica.h" #include "../includes/reptilexotico.h" #include "../includes/anfibionativo.h" #include "../includes/mamiferonativo.h" #include "../includes/avenativa.h" #include "../includes/reptilnativo.h" #include "../includes/tratador.h" #include "../includes/veterinario.h" //Verifica o tipo de SO para definir o tipo da variavel para limpar o terminal #ifdef _WIN32 #define LIMPAR "CLS" #else #define LIMPAR "clear" #endif //Função para pressionar enter para continuar void clear() { system(LIMPAR); } //Função para checar se o input é um int bool checarDigito(string &input) { for (unsigned int i = 0; i < input.size(); i++) { if (!isdigit(input[i])) { return false; break; } } return true; } //Função pressionar para continuar void pressToCont() { cout << "Pressione Enter para continuar..."; cin.ignore(); } //Função para ler os dados dos arquivos void lerDados(vector<shared_ptr<Funcionario>> &f, vector<shared_ptr<Animal>> &a) { ifstream file_funcionarios("funcionarios.csv"); vector<string> values; string line, value; while(!file_funcionarios.eof()) { getline(file_funcionarios, line); if ( !line.empty() ) { stringstream temp(line); values.clear(); while(getline(temp, value, ';')) { values.push_back(value); } switch (stoi(values[0])) { case 0: f.push_back(shared_ptr<Tratador>(new Tratador(stoi(values[1]), values[2], values[3], stoi(values[4]), values[5], *values[6].c_str(), values[7], stoi(values[8])))); break; case 1: f.push_back(shared_ptr<Veterinario>(new Veterinario(stoi(values[1]), values[2], values[3], stoi(values[4]), values[5], *values[6].c_str(), values[7], values[8]))); break; } } } file_funcionarios.close(); ifstream file_animais("animais.csv"); while(!file_animais.eof()) { getline(file_animais, line); if ( !line.empty() ) { stringstream temp(line); values.clear(); while(getline(temp, value, ';')) { values.push_back(value); } switch (stoi(values[0])) { case 0: a.push_back(shared_ptr<Mamifero>(new Mamifero(stoi(values[1]), values[2], values[3], values[4], *values[5].c_str(), stod(values[6]), values[7], stoi(values[8]), stoi(values[9]), values[10], values[11]))); break; case 1: a.push_back(shared_ptr<Anfibio>(new Anfibio(stoi(values[1]), values[2], values[3], values[4], *values[5].c_str(), stod(values[6]), values[7], stoi(values[8]), stoi(values[9]), values[10], stoi(values[11]), values[12]))); break; case 2: a.push_back(shared_ptr<Ave>(new Ave(stoi(values[1]), values[2], values[3], values[4], *values[5].c_str(), stod(values[6]), values[7], stoi(values[8]), stoi(values[9]), values[10], stoi(values[11]), stoi(values[12])))); break; case 3: a.push_back(shared_ptr<Reptil>(new Reptil(stoi(values[1]), values[2], values[3], values[4], *values[5].c_str(), stod(values[6]), values[7], stoi(values[8]), stoi(values[9]), values[10], stoi(values[11]), values[12]))); break; case 4: a.push_back(shared_ptr<MamiferoNativo>(new MamiferoNativo(stoi(values[1]), values[2], values[3], values[4], *values[5].c_str(), stod(values[6]), values[7], stoi(values[8]), stoi(values[9]), values[10], values[11], values[12], values[13], values[14]))); break; case 5: a.push_back(shared_ptr<MamiferoExotico>(new MamiferoExotico(stoi(values[1]), values[2], values[3], values[4], *values[5].c_str(), stod(values[6]), values[7], stoi(values[8]), stoi(values[9]), values[10], values[11], values[12], values[13]))); break; case 6: a.push_back(shared_ptr<AnfibioNativo>(new AnfibioNativo(stoi(values[1]), values[2], values[3], values[4], *values[5].c_str(), stod(values[6]), values[7], stoi(values[8]), stoi(values[9]), values[10], stoi(values[11]), values[12], values[13], values[14], values[15]))); break; case 7: a.push_back(shared_ptr<AnfibioExotico>(new AnfibioExotico(stoi(values[1]), values[2], values[3], values[4], *values[5].c_str(), stod(values[6]), values[7], stoi(values[8]), stoi(values[9]), values[10], stoi(values[11]), values[12], values[13], values[14]))); break; case 8: a.push_back(shared_ptr<AveNativa>(new AveNativa(stoi(values[1]), values[2], values[3], values[4], *values[5].c_str(), stod(values[6]), values[7], stoi(values[8]), stoi(values[9]), values[10], stoi(values[11]), stoi(values[12]), values[13], values[14], values[15]))); break; case 9: a.push_back(shared_ptr<AveExotica>(new AveExotica(stoi(values[1]), values[2], values[3], values[4], *values[5].c_str(), stod(values[6]), values[7], stoi(values[8]), stoi(values[9]), values[10], stoi(values[11]), stoi(values[12]), values[13], values[14]))); break; case 10: a.push_back(shared_ptr<ReptilNativo>(new ReptilNativo(stoi(values[1]), values[2], values[3], values[4], *values[5].c_str(), stod(values[6]), values[7], stoi(values[8]), stoi(values[9]), values[10], stoi(values[11]), values[12], values[13], values[14], values[15]))); break; case 11: a.push_back(shared_ptr<ReptilExotico>(new ReptilExotico(stoi(values[1]), values[2], values[3], values[4], *values[5].c_str(), stod(values[6]), values[7], stoi(values[8]), stoi(values[9]), values[10], stoi(values[11]), values[12], values[13], values[14]))); break; } } } file_animais.close(); } //Função para salvar os dados nos arquivos void salvarDados(vector<shared_ptr<Funcionario>> &f, vector<shared_ptr<Animal>> &a) { ofstream file_funcionarios("funcionarios.csv"); for (unsigned i = 0; i < f.size(); i++) { file_funcionarios << *f[i] << endl; } file_funcionarios.close(); ofstream file_animais("animais.csv"); for (unsigned i = 0; i < a.size(); i++) { file_animais << *a[i] << endl; } file_animais.close(); } //Função para cadastrar um mamifero domestico void cadastrarMamiferoDomestico(vector<shared_ptr<Animal>> &a) { int id, tratador, veterinario; string nome, nome_cientifico, dieta, batismo, cor_do_pelo; char sexo; double tamanho; cout << "Digite as informaçoes do novo animal: " << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { cout << endl << "Já existe um animal cadastrado com esse ID" << endl << endl; cin.ignore(); } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "Nome Cientifico: "; getline(cin, nome_cientifico); cout << "Sexo: "; cin >> sexo; cout << "Tamanho: "; cin >> tamanho; cout << "Dieta: "; cin.ignore(); getline(cin, dieta); cout << "ID do tratador ( Digite 0 caso nao tenha tratador): "; cin >> tratador; cout << "ID do veterinario ( Digite 0 caso nao tenha veterinario ): "; cin >> veterinario; cout << "Nome de batismo: "; cin.ignore(); getline(cin, batismo); cout << "Cor do pelo: "; getline(cin, cor_do_pelo); a.push_back(shared_ptr<Mamifero>(new Mamifero(id, "Mammalia", nome, nome_cientifico, sexo, tamanho, dieta, tratador, veterinario, batismo, cor_do_pelo))); cout << endl << "Novo animal cadastrado com sucesso!" << endl << endl; } } //Função para cadastrar um mamifero silvestre nativo void cadastrarMamiferoNativo(vector<shared_ptr<Animal>> &a) { int id, tratador, veterinario; string nome, nome_cientifico, dieta, batismo, cor_do_pelo, uf_origem, autorizacao, autorizacao_ibama; char sexo; double tamanho; cout << "Digite as informaçoes do novo animal: " << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { cout << endl << "Já existe um animal cadastrado com esse ID" << endl << endl; cin.ignore(); } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "Nome Cientifico: "; getline(cin, nome_cientifico); cout << "Sexo: "; cin >> sexo; cout << "Tamanho: "; cin >> tamanho; cout << "Dieta: "; cin.ignore(); getline(cin, dieta); cout << "ID do tratador ( Digite 0 caso nao tenha tratador): "; cin >> tratador; cout << "ID do veterinario ( Digite 0 caso nao tenha veterinario ): "; cin >> veterinario; cout << "Nome de batismo: "; cin.ignore(); getline(cin, batismo); cout << "Cor do pelo: "; getline(cin, cor_do_pelo); cout << "UF de origem: "; getline(cin, uf_origem); cout << "Autorizacao: "; getline(cin, autorizacao); cout << "Autorizacao do Ibama: "; getline(cin, autorizacao_ibama); a.push_back(shared_ptr<MamiferoNativo>(new MamiferoNativo(id, "Mammalia", nome, nome_cientifico, sexo, tamanho, dieta, tratador, veterinario, batismo, cor_do_pelo, uf_origem, autorizacao, autorizacao_ibama))); cout << endl << "Novo animal cadastrado com sucesso!" << endl << endl; } } //Função para cadastrar um mamifero silvestre exotico void cadastrarMamiferoExotico(vector<shared_ptr<Animal>> &a) { int id, tratador, veterinario; string nome, nome_cientifico, dieta, batismo, cor_do_pelo, pais_origem, autorizacao_ibama; char sexo; double tamanho; cout << "Digite as informaçoes do novo animal: " << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { cout << endl << "Já existe um animal cadastrado com esse ID" << endl << endl; cin.ignore(); } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "Nome Cientifico: "; getline(cin, nome_cientifico); cout << "Sexo: "; cin >> sexo; cout << "Tamanho: "; cin >> tamanho; cout << "Dieta: "; cin.ignore(); getline(cin, dieta); cout << "ID do tratador ( Digite 0 caso nao tenha tratador): "; cin >> tratador; cout << "ID do veterinario ( Digite 0 caso nao tenha veterinario ): "; cin >> veterinario; cout << "Nome de batismo: "; cin.ignore(); getline(cin, batismo); cout << "Cor do pelo: "; getline(cin, cor_do_pelo); cout << "Pais de origem: "; getline(cin, pais_origem); cout << "Autorizacao do Ibama: "; getline(cin, autorizacao_ibama); a.push_back(shared_ptr<MamiferoExotico>(new MamiferoExotico(id, "Mammalia", nome, nome_cientifico, sexo, tamanho, dieta, tratador, veterinario, batismo, cor_do_pelo, pais_origem, autorizacao_ibama))); cout << endl << "Novo animal cadastrado com sucesso!" << endl << endl; } } //Função com menu para escolher se o mamifero é domestico, nativo ou exotico void cadastrarMamifero(vector<shared_ptr<Animal>> &a) { string input; int escolha; bool sair = false, error = false; //Loop para verificar se o input é uma opção válida e caso seja, realizer a operação referente a escolha do { clear(); cout << endl << "########################################################" << endl; cout << "### NOVO MAMIFERO ###" << endl; cout << "########################################################" << endl; cout << endl << "Escolha o tipo do novo mamifero: " << endl << endl; cout << "[1] - Domestico" << endl; cout << "[2] - Nativo" << endl; cout << "[3] - Exotico" << endl; cout << endl; cout << "[0] - Sair" << endl << endl; if (error) { error = false; cout << "**Digite uma opcao valida!**" << endl; } cout << "Opcao: "; cin >> input; if (checarDigito(input)) { escolha = stoi(input, nullptr); if (escolha >= 0 && escolha <= 3) { switch (escolha) { case 0: sair = true; break; case 1: clear(); cadastrarMamiferoDomestico(a); pressToCont(); break; case 2: clear(); cadastrarMamiferoNativo(a); pressToCont(); break; case 3: clear(); cadastrarMamiferoExotico(a); pressToCont(); break; } } else { error = true; } } else { error = true; } } while (!sair); } //Função para cadastrar um anfibio domestico void cadastrarAnfibioDomestico(vector<shared_ptr<Animal>> &a) { int id, tratador, veterinario, total_de_mudas; string nome, nome_cientifico, dieta, batismo, ultima_muda; char sexo; double tamanho; cout << "Digite as informaçoes do novo animal: " << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { cout << endl << "Já existe um animal cadastrado com esse ID" << endl << endl; cin.ignore(); } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "Nome Cientifico: "; getline(cin, nome_cientifico); cout << "Sexo: "; cin >> sexo; cout << "Tamanho: "; cin >> tamanho; cout << "Dieta: "; cin.ignore(); getline(cin, dieta); cout << "ID do tratador ( Digite 0 caso nao tenha tratador): "; cin >> tratador; cout << "ID do veterinario ( Digite 0 caso nao tenha veterinario ): "; cin >> veterinario; cout << "Nome de batismo: "; cin.ignore(); getline(cin, batismo); cout << "Total de mudas: "; cin >> total_de_mudas; cout << "Ultima muda: "; cin.ignore(); getline(cin, ultima_muda); a.push_back(shared_ptr<Anfibio>(new Anfibio(id, "Amphibia", nome, nome_cientifico, sexo, tamanho, dieta, tratador, veterinario, batismo, total_de_mudas, ultima_muda))); cout << endl << "Novo animal cadastrado com sucesso!" << endl << endl; } } //Função para cadastrar um anfibio nativo void cadastrarAnfibioNativo(vector<shared_ptr<Animal>> &a) { int id, tratador, veterinario, total_de_mudas; string nome, nome_cientifico, dieta, batismo, ultima_muda, uf_origem, autorizacao, autorizacao_ibama; char sexo; double tamanho; cout << "Digite as informaçoes do novo animal: " << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { cout << endl << "Já existe um animal cadastrado com esse ID" << endl << endl; cin.ignore(); } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "Nome Cientifico: "; getline(cin, nome_cientifico); cout << "Sexo: "; cin >> sexo; cout << "Tamanho: "; cin >> tamanho; cout << "Dieta: "; cin.ignore(); getline(cin, dieta); cout << "ID do tratador ( Digite 0 caso nao tenha tratador): "; cin >> tratador; cout << "ID do veterinario ( Digite 0 caso nao tenha veterinario ): "; cin >> veterinario; cout << "Nome de batismo: "; cin.ignore(); getline(cin, batismo); cout << "Total de mudas: "; cin >> total_de_mudas; cout << "Ultima muda: "; cin.ignore(); getline(cin, ultima_muda); cout << "UF da origem: "; getline(cin, uf_origem); cout << "Autorizacao: "; getline(cin, autorizacao); cout << "Autorizacao do Ibama: "; getline(cin, autorizacao_ibama); a.push_back(shared_ptr<AnfibioNativo>(new AnfibioNativo(id, "Amphibia", nome, nome_cientifico, sexo, tamanho, dieta, tratador, veterinario, batismo, total_de_mudas, ultima_muda, uf_origem, autorizacao, autorizacao_ibama))); cout << endl << "Novo animal cadastrado com sucesso!" << endl << endl; } } //Função para cadastrar um anfibio exotico void cadastrarAnfibioExotico(vector<shared_ptr<Animal>> &a) { int id, tratador, veterinario, total_de_mudas; string nome, nome_cientifico, dieta, batismo, ultima_muda, pais_origem, autorizacao_ibama; char sexo; double tamanho; cout << "Digite as informaçoes do novo animal: " << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { cout << endl << "Já existe um animal cadastrado com esse ID" << endl << endl; cin.ignore(); } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "Nome Cientifico: "; getline(cin, nome_cientifico); cout << "Sexo: "; cin >> sexo; cout << "Tamanho: "; cin >> tamanho; cout << "Dieta: "; cin.ignore(); getline(cin, dieta); cout << "ID do tratador ( Digite 0 caso nao tenha tratador): "; cin >> tratador; cout << "ID do veterinario ( Digite 0 caso nao tenha veterinario ): "; cin >> veterinario; cout << "Nome de batismo: "; cin.ignore(); getline(cin, batismo); cout << "Total de mudas: "; cin >> total_de_mudas; cout << "Ultima muda: "; cin.ignore(); getline(cin, ultima_muda); cout << "Pais de origem: "; getline(cin, pais_origem); cout << "Autorizacao do Ibama: "; getline(cin, autorizacao_ibama); a.push_back(shared_ptr<AnfibioExotico>(new AnfibioExotico(id, "Amphibia", nome, nome_cientifico, sexo, tamanho, dieta, tratador, veterinario, batismo, total_de_mudas, ultima_muda, pais_origem, autorizacao_ibama))); cout << endl << "Novo animal cadastrado com sucesso!" << endl << endl; } } //Função com menu para escolher se o anfibio é domestico, nativo ou exotico void cadastrarAnfibio(vector<shared_ptr<Animal>> &a) { string input; int escolha; bool sair = false, error = false; //Loop para verificar se o input é uma opção válida e caso seja, realizer a operação referente a escolha do { clear(); cout << endl << "########################################################" << endl; cout << "### NOVO ANFIBIO ###" << endl; cout << "########################################################" << endl; cout << endl << "Escolha o tipo do novo mamifero: " << endl << endl; cout << "[1] - Domestico" << endl; cout << "[2] - Nativo" << endl; cout << "[3] - Exotico" << endl; cout << endl; cout << "[0] - Sair" << endl << endl; if (error) { error = false; cout << "**Digite uma opcao valida!**" << endl; } cout << "Opcao: "; cin >> input; if (checarDigito(input)) { escolha = stoi(input, nullptr); if (escolha >= 0 && escolha <= 3) { switch (escolha) { case 0: sair = true; break; case 1: clear(); cadastrarAnfibioDomestico(a); pressToCont(); break; case 2: clear(); cadastrarAnfibioNativo(a); pressToCont(); break; case 3: clear(); cadastrarAnfibioExotico(a); pressToCont(); break; } } else { error = true; } } else { error = true; } } while (!sair); } //Função para cadastrar ave domestica void cadastrarAveDomestica(vector<shared_ptr<Animal>> &a) { int id, tratador, veterinario; string nome, nome_cientifico, dieta, batismo; char sexo; double tamanho, tamanho_do_bico_cm, envergadura_das_asas; cout << "Digite as informaçoes do novo animal: " << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { cout << endl << "Já existe um animal cadastrado com esse ID" << endl << endl; cin.ignore(); } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "Nome Cientifico: "; getline(cin, nome_cientifico); cout << "Sexo: "; cin >> sexo; cout << "Tamanho: "; cin >> tamanho; cout << "Dieta: "; cin.ignore(); getline(cin, dieta); cout << "ID do tratador ( Digite 0 caso nao tenha tratador): "; cin >> tratador; cout << "ID do veterinario ( Digite 0 caso nao tenha veterinario ): "; cin >> veterinario; cout << "Nome de batismo: "; cin.ignore(); getline(cin, batismo); cout << "Tamanho do bico: "; cin >> tamanho_do_bico_cm; cout << "Envergadura das asas: "; cin >> envergadura_das_asas; cin.ignore(); a.push_back(shared_ptr<Ave>(new Ave(id, "Aves", nome, nome_cientifico, sexo, tamanho, dieta, tratador, veterinario, batismo, tamanho_do_bico_cm, envergadura_das_asas))); cout << endl << "Novo animal cadastrado com sucesso!" << endl << endl; } } //Função para cadastrar ave nativa void cadastrarAveNativa(vector<shared_ptr<Animal>> &a) { int id, tratador, veterinario; string nome, nome_cientifico, dieta, batismo, uf_origem, autorizacao, autorizacao_ibama; char sexo; double tamanho, tamanho_do_bico_cm, envergadura_das_asas; cout << "Digite as informaçoes do novo animal: " << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { cout << endl << "Já existe um animal cadastrado com esse ID" << endl << endl; cin.ignore(); } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "Nome Cientifico: "; getline(cin, nome_cientifico); cout << "Sexo: "; cin >> sexo; cout << "Tamanho: "; cin >> tamanho; cout << "Dieta: "; cin.ignore(); getline(cin, dieta); cout << "ID do tratador ( Digite 0 caso nao tenha tratador): "; cin >> tratador; cout << "ID do veterinario ( Digite 0 caso nao tenha veterinario ): "; cin >> veterinario; cout << "Nome de batismo: "; cin.ignore(); getline(cin, batismo); cout << "Tamanho do bico: "; cin >> tamanho_do_bico_cm; cout << "Envergadura das asas: "; cin >> envergadura_das_asas; cout << "UF da origem: "; cin.ignore(); getline(cin, uf_origem); cout << "Autorizacao: "; getline(cin, autorizacao); cout << "Autorizacao do Ibama: "; getline(cin, autorizacao_ibama); a.push_back(shared_ptr<AveNativa>(new AveNativa(id, "Aves", nome, nome_cientifico, sexo, tamanho, dieta, tratador, veterinario, batismo, tamanho_do_bico_cm, envergadura_das_asas, uf_origem, autorizacao, autorizacao_ibama))); cout << endl << "Novo animal cadastrado com sucesso!" << endl << endl; } } //Função para cadastrar ave exotica void cadastrarAveExotica(vector<shared_ptr<Animal>> &a) { int id, tratador, veterinario; string nome, nome_cientifico, dieta, batismo, pais_origem, autorizacao_ibama; char sexo; double tamanho, tamanho_do_bico_cm, envergadura_das_asas; cout << "Digite as informaçoes do novo animal: " << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { cout << endl << "Já existe um animal cadastrado com esse ID" << endl << endl; cin.ignore(); } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "Nome Cientifico: "; getline(cin, nome_cientifico); cout << "Sexo: "; cin >> sexo; cout << "Tamanho: "; cin >> tamanho; cout << "Dieta: "; cin.ignore(); getline(cin, dieta); cout << "ID do tratador ( Digite 0 caso nao tenha tratador): "; cin >> tratador; cout << "ID do veterinario ( Digite 0 caso nao tenha veterinario ): "; cin >> veterinario; cout << "Nome de batismo: "; cin.ignore(); getline(cin, batismo); cout << "Tamanho do bico: "; cin >> tamanho_do_bico_cm; cout << "Envergadura das asas: "; cin >> envergadura_das_asas; cout << "Pais de origem: "; cin.ignore(); getline(cin, pais_origem); cout << "Autorizacao do Ibama: "; getline(cin, autorizacao_ibama); a.push_back(shared_ptr<AveExotica>(new AveExotica(id, "Aves", nome, nome_cientifico, sexo, tamanho, dieta, tratador, veterinario, batismo, tamanho_do_bico_cm, envergadura_das_asas, pais_origem, autorizacao_ibama))); cout << endl << "Novo animal cadastrado com sucesso!" << endl << endl; } } //Função com menu para escolher se a ave é domestica, nativa ou exotica void cadastrarAve(vector<shared_ptr<Animal>> &a) { string input; int escolha; bool sair = false, error = false; //Loop para verificar se o input é uma opção válida e caso seja, realizer a operação referente a escolha do { clear(); cout << endl << "###################################################" << endl; cout << "### NOVA AVE ###" << endl; cout << "###################################################" << endl; cout << endl << "Escolha o tipo do novo mamifero: " << endl << endl; cout << "[1] - Domestica" << endl; cout << "[2] - Nativa" << endl; cout << "[3] - Exotica" << endl; cout << endl; cout << "[0] - Sair" << endl << endl; if (error) { error = false; cout << "**Digite uma opcao valida!**" << endl; } cout << "Opcao: "; cin >> input; if (checarDigito(input)) { escolha = stoi(input, nullptr); if (escolha >= 0 && escolha <= 3) { switch (escolha) { case 0: sair = true; break; case 1: clear(); cadastrarAveDomestica(a); pressToCont(); break; case 2: clear(); cadastrarAveNativa(a); pressToCont(); break; case 3: clear(); cadastrarAveExotica(a); pressToCont(); break; } } else { error = true; } } else { error = true; } } while (!sair); } //Função para cadastrar reptil domestico void cadastrarReptilDomestico(vector<shared_ptr<Animal>> &a) { int id, tratador, veterinario; string nome, nome_cientifico, dieta, batismo, tipo_veneno; char sexo; double tamanho; bool venenoso; cout << "Digite as informaçoes do novo animal: " << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { cout << endl << "Já existe um animal cadastrado com esse ID" << endl << endl; cin.ignore(); } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "Nome Cientifico: "; getline(cin, nome_cientifico); cout << "Sexo: "; cin >> sexo; cout << "Tamanho: "; cin >> tamanho; cout << "Dieta: "; cin.ignore(); getline(cin, dieta); cout << "ID do tratador ( Digite 0 caso nao tenha tratador): "; cin >> tratador; cout << "ID do veterinario ( Digite 0 caso nao tenha veterinario ): "; cin >> veterinario; cout << "Nome de batismo: "; cin.ignore(); getline(cin, batismo); cout << "Venenoso ([1] - Sim / [0] - Nao): "; cin >> venenoso; cout << "Tipo do veneno: "; cin.ignore(); getline(cin, tipo_veneno); a.push_back(shared_ptr<Reptil>(new Reptil(id, "Reptilia", nome, nome_cientifico, sexo, tamanho, dieta, tratador, veterinario, batismo, venenoso, tipo_veneno))); cout << endl << "Novo animal cadastrado com sucesso!" << endl << endl; } } //Função para cadastrar reptil nativo void cadastrarReptilNativo(vector<shared_ptr<Animal>> &a) { int id, tratador, veterinario; string nome, nome_cientifico, dieta, batismo, tipo_veneno, uf_origem, autorizacao, autorizacao_ibama; char sexo; double tamanho; bool venenoso; cout << "Digite as informaçoes do novo animal: " << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { cout << endl << "Já existe um animal cadastrado com esse ID" << endl << endl; cin.ignore(); } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "Nome Cientifico: "; getline(cin, nome_cientifico); cout << "Sexo: "; cin >> sexo; cout << "Tamanho: "; cin >> tamanho; cout << "Dieta: "; cin.ignore(); getline(cin, dieta); cout << "ID do tratador ( Digite 0 caso nao tenha tratador): "; cin >> tratador; cout << "ID do veterinario ( Digite 0 caso nao tenha veterinario ): "; cin >> veterinario; cout << "Nome de batismo: "; cin.ignore(); getline(cin, batismo); cout << "Venenoso ([1] - Sim / [0] - Nao): "; cin >> venenoso; cout << "Tipo do veneno: "; cin.ignore(); getline(cin, tipo_veneno); cout << "UF da origem: "; getline(cin, uf_origem); cout << "Autorizacao: "; getline(cin, autorizacao); cout << "Autorizacao do Ibama: "; getline(cin, autorizacao_ibama); a.push_back(shared_ptr<ReptilNativo>(new ReptilNativo(id, "Reptilia", nome, nome_cientifico, sexo, tamanho, dieta, tratador, veterinario, batismo, venenoso, tipo_veneno, uf_origem, autorizacao, autorizacao_ibama))); cout << endl << "Novo animal cadastrado com sucesso!" << endl << endl; } } //Função para cadastrar reptil exotico void cadastrarReptilExotico(vector<shared_ptr<Animal>> &a) { int id, tratador, veterinario; string nome, nome_cientifico, dieta, batismo, tipo_veneno, pais_origem, autorizacao_ibama; char sexo; double tamanho; bool venenoso; cout << "Digite as informaçoes do novo animal: " << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { cout << endl << "Já existe um animal cadastrado com esse ID" << endl << endl; cin.ignore(); } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "Nome Cientifico: "; getline(cin, nome_cientifico); cout << "Sexo: "; cin >> sexo; cout << "Tamanho: "; cin >> tamanho; cout << "Dieta: "; cin.ignore(); getline(cin, dieta); cout << "ID do tratador ( Digite 0 caso nao tenha tratador): "; cin >> tratador; cout << "ID do veterinario ( Digite 0 caso nao tenha veterinario ): "; cin >> veterinario; cout << "Nome de batismo: "; cin.ignore(); getline(cin, batismo); cout << "Venenoso ([1] - Sim / [0] - Nao): "; cin >> venenoso; cout << "Tipo do veneno: "; cin.ignore(); getline(cin, tipo_veneno); cout << "Pais de origem: "; getline(cin, pais_origem); cout << "Autorizacao do Ibama: "; getline(cin, autorizacao_ibama); a.push_back(shared_ptr<ReptilExotico>(new ReptilExotico(id, "Reptilia", nome, nome_cientifico, sexo, tamanho, dieta, tratador, veterinario, batismo, venenoso, tipo_veneno, pais_origem, autorizacao_ibama))); cout << endl << "Novo animal cadastrado com sucesso!" << endl << endl; } } //Função com menu para escolher se o reptil é domestico, nativo ou exotico void cadastrarReptil(vector<shared_ptr<Animal>> &a) { string input; int escolha; bool sair = false, error = false; //Loop para verificar se o input é uma opção válida e caso seja, realizer a operação referente a escolha do { clear(); cout << endl << "###################################################" << endl; cout << "### NOVO REPTIL ###" << endl; cout << "###################################################" << endl; cout << endl << "Escolha o tipo do novo mamifero: " << endl << endl; cout << "[1] - Domestico" << endl; cout << "[2] - Nativo" << endl; cout << "[3] - Exotico" << endl; cout << endl; cout << "[0] - Sair" << endl << endl; if (error) { error = false; cout << "**Digite uma opcao valida!**" << endl; } cout << "Opcao: "; cin >> input; if (checarDigito(input)) { escolha = stoi(input, nullptr); if (escolha >= 0 && escolha <= 3) { switch (escolha) { case 0: sair = true; break; case 1: clear(); cadastrarReptilDomestico(a); pressToCont(); break; case 2: clear(); cadastrarReptilNativo(a); pressToCont(); break; case 3: clear(); cadastrarReptilExotico(a); pressToCont(); break; } } else { error = true; } } else { error = true; } } while (!sair); } //Função para cadastrar um novo animal void cadastrarAnimal(vector<shared_ptr<Animal>> &a) { string input; int escolha; bool sair = false, error = false; //Loop para verificar se o input é uma opção válida e caso seja, realizer a operação referente a escolha do { clear(); cout << endl << "########################################################" << endl; cout << "### NOVO ANIMAL ###" << endl; cout << "########################################################" << endl; cout << endl << "Escolha a classe do novo animal: " << endl << endl; cout << "[1] - Adicionar novo animal mamifero" << endl; cout << "[2] - Adicionar novo animal anfibio" << endl; cout << "[3] - Adicionar novo animal ave" << endl; cout << "[4] - Adicionar novo animal reptil" << endl; cout << endl; cout << "[0] - Sair" << endl << endl; if (error) { error = false; cout << "**Digite uma opcao valida!**" << endl; } cout << "Opcao: "; cin >> input; if (checarDigito(input)) { escolha = stoi(input); if (escolha >= 0 && escolha <= 4) { switch (escolha) { case 0: sair = true; break; case 1: clear(); cadastrarMamifero(a); pressToCont(); break; case 2: clear(); cadastrarAnfibio(a); pressToCont(); break; case 3: clear(); cadastrarAve(a); pressToCont(); break; case 4: clear(); cadastrarReptil(a); pressToCont(); break; } } else { error = true; } } else { error = true; } } while (!sair); } //Função para remover um animal void removerAnimal(vector<shared_ptr<Animal>> &a) { int id; cout << "Digite o ID do animal: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { a.erase(it); cout << "Animal removido com sucesso!" << endl; } else { cout << "Não existe animal com esse id cadastrado!" << endl; } cin.ignore(); } //Função para alterar dados de um animal void alterarAnimal(vector<shared_ptr<Animal>> &a) { int id; cout << "Digite o ID do animal: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { a[std::distance(a.begin(), it)]->atualizarDados(); cout << endl << "Informacoes do animal atualizadas com sucesso!" << endl << endl; } else { cout << endl << "Não existe animal com esse id cadastrado!" << endl << endl; cin.ignore(); } } //Função para consultar as informacoes de um animal void consultarAnimal(vector<shared_ptr<Animal>> &a) { int id; cout << "Digite o ID do animal: "; cin >> id; vector<shared_ptr<Animal>>::iterator it = find_if(a.begin(), a.end(), [&id](const shared_ptr<Animal> & obj) {return obj->getId() == id;}); if( it != a.end() ) { a[std::distance(a.begin(), it)]->mostrarDados(); } else { cout << endl << "Não existe animal com esse id cadastrado!" << endl << endl; } cin.ignore(); } //Função para consultar um animal sob a responsabilidade de um tratador ou veterinario void consultarAnimalPorFuncionario(vector<shared_ptr<Animal>> &a, vector<shared_ptr<Funcionario>> &f) { int id; bool existe = false; cout << "Digite o ID do tratador ou do veterinario: "; cin >> id; vector<shared_ptr<Funcionario>>::iterator it = find_if(f.begin(), f.end(), [&id](const shared_ptr<Funcionario> & obj) {return obj->getId() == id;}); if( it != f.end() ) { for (unsigned i = 0; i < a.size(); i++) { if( a[i]->getIdTratador() == id || a[i]->getIdVeterinario() == id) { a[i]->mostrarDados(); existe = true; } } if( !existe ) { cout << endl << "Não existe nenhum animal aos cuidados desse funcionario" << endl << endl; } } else { cout << endl << "Não existe tratador ou veterinario com esse id cadastrado!" << endl << endl; } cin.ignore(); } //Funcao para mostrar os animais de acordo com a classe void mostrarAnimais(vector<shared_ptr<Animal>> &a) { string input; int escolha; bool sair = false, error = false; //Loop para verificar se o input é uma opção válida e caso seja, realizer a operação referente a escolha do { clear(); cout << endl << "#########################################################" << endl; cout << "### ANIMAIS ###" << endl; cout << "#########################################################" << endl; cout << endl << "Escolha o tipo de animal: " << endl << endl; cout << "[1] - Mamifero" << endl; cout << "[2] - Anfibio" << endl; cout << "[3] - Ave" << endl; cout << "[4] - Reptil" << endl; cout << endl; cout << "[0] - Sair" << endl << endl; if (error) { error = false; cout << "**Digite uma opcao valida!**" << endl; } cout << "Opcao: "; cin >> input; if (checarDigito(input)) { escolha = stoi(input, nullptr); if (escolha >= 0 && escolha <= 4) { switch (escolha) { case 0: sair = true; break; default: clear(); for (unsigned i = 0; i < a.size(); i++) { a[i]->mostrarAnimais(escolha - 1); } cin.ignore(); pressToCont(); break; } } else { error = true; } } else { error = true; } } while (!sair); } //Menu de animais void menuAnimal(vector<shared_ptr<Animal>> &a, vector<shared_ptr<Funcionario>> &f) { string input; int escolha; bool sair = false, error = false; //Loop para verificar se o input é uma opção válida e caso seja, realizer a operação referente a escolha do { clear(); cout << endl << "########################################################" << endl; cout << "### ANIMAIS ###" << endl; cout << "########################################################" << endl; cout << endl << "Escolha uma das seguintes opcoes: " << endl << endl; cout << "[1] - Adicionar novo animal" << endl; cout << "[2] - Remover animal" << endl; cout << "[3] - Alterar dados de um animal" << endl; cout << "[4] - Consultar animal" << endl; cout << "[5] - Consultar animais sob responsabilidade de um tratador ou veterinario" << endl; cout << "[6] - Mostrar animais" << endl; cout << endl; cout << "[0] - Sair" << endl << endl; if (error) { error = false; cout << "**Digite uma opcao valida!**" << endl; } cout << "Opcao: "; cin >> input; if (checarDigito(input)) { escolha = stoi(input, nullptr); if (escolha >= 0 && escolha <= 6) { switch (escolha) { case 0: sair = true; break; case 1: clear(); cadastrarAnimal(a); pressToCont(); break; case 2: clear(); removerAnimal(a); pressToCont(); break; case 3: clear(); alterarAnimal(a); pressToCont(); break; case 4: clear(); consultarAnimal(a); pressToCont(); break; case 5: clear(); consultarAnimalPorFuncionario(a, f); pressToCont(); break; case 6: clear(); mostrarAnimais(a); pressToCont(); break; } } else { error = true; } } else { error = true; } } while (!sair); } //Função para cadastrar um tratador void novoTratador(vector<shared_ptr<Funcionario>> &f) { int id, idade, nivel_seguranca; char fator_rh; string nome, cpf, tipo_sanguineo, especialidade; cout << "Digite as informaçoes do novo tratador" << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Funcionario>>::iterator it = find_if(f.begin(), f.end(), [&id](const shared_ptr<Funcionario> & obj) {return obj->getId() == id;}); if( it != f.end() ) { cout << endl << "Já existe um funcionario cadastrado com esse ID" << endl << endl; } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "CPF: "; getline(cin, cpf); cout << "Idade: "; cin >> idade; cout << "Tipo Sanguineo (A, B, AB ou O): "; cin.ignore(); getline(cin, tipo_sanguineo); cout << "Fator RH ( + ou -): "; cin >> fator_rh; cout << "Especialidade: "; cin.ignore(); getline(cin, especialidade); cout << "Nivel de segurança: "; cin >> nivel_seguranca; f.push_back(shared_ptr<Tratador>(new Tratador(id, nome, cpf, idade, tipo_sanguineo, fator_rh, especialidade, nivel_seguranca))); cout << endl << "Novo tratador cadastrado com sucesso!" << endl << endl; } cin.ignore(); } //Função para cadastrar um veterinario void novoVeterinario(vector<shared_ptr<Funcionario>> &f) { int id, idade; char fator_rh; string nome, cpf, tipo_sanguineo, especialidade, crmv; cout << "Digite as informaçoes do novo tratador" << endl; cout << "ID: "; cin >> id; vector<shared_ptr<Funcionario>>::iterator it = find_if(f.begin(), f.end(), [&id](const shared_ptr<Funcionario> & obj) {return obj->getId() == id;}); if( it != f.end() ) { cout << endl << "Já existe um funcionario cadastrado com esse ID" << endl << endl; } else { cout << "Nome: "; cin.ignore(); getline(cin, nome); cout << "CPF: "; getline(cin, cpf); cout << "Idade: "; cin >> idade; cout << "Tipo Sanguineo (A, B, AB ou O): "; cin.ignore(); getline(cin, tipo_sanguineo); cout << "Fator RH ( + ou -): "; cin >> fator_rh; cout << "Especialidade: "; cin.ignore(); getline(cin, especialidade); cout << "CRMV: "; getline(cin, crmv); f.push_back(shared_ptr<Veterinario>(new Veterinario(id, nome, cpf, idade, tipo_sanguineo, fator_rh, especialidade, crmv))); cout << endl << "Novo veterinario cadastrado com sucesso!" << endl << endl; } //cin.ignore(); } //Função para remover um funcionario void removerFuncionario(vector<shared_ptr<Funcionario>> &f) { int id; cout << "Digite o ID do funcionario: "; cin >> id; vector<shared_ptr<Funcionario>>::iterator it = find_if(f.begin(), f.end(), [&id](const shared_ptr<Funcionario> & obj) {return obj->getId() == id;}); if( it != f.end() ) { f.erase(it); cout << "Funcionario removido com sucesso!" << endl; } else { cout << "Não existe funcionario com esse id cadastrado!" << endl; } cin.ignore(); } //Função para alterar dados de um funcionario void alterarFuncionario(vector<shared_ptr<Funcionario>> &f) { int id; cout << "Digite o ID do funcionario: "; cin >> id; vector<shared_ptr<Funcionario>>::iterator it = find_if(f.begin(), f.end(), [&id](const shared_ptr<Funcionario> & obj) {return obj->getId() == id;}); if( it != f.end() ) { f[std::distance(f.begin(), it)]->atualizarDados(); cout << "Informacoes do funcionario atualizadas com sucesso!" << endl; } else { cout << "Não existe funcionario com esse id cadastrado!" << endl; } cin.ignore(); } void consultarFuncionario(vector<shared_ptr<Funcionario>> &f) { int id; cout << "Digite o ID do funcionario: "; cin >> id; vector<shared_ptr<Funcionario>>::iterator it = find_if(f.begin(), f.end(), [&id](const shared_ptr<Funcionario> & obj) {return obj->getId() == id;}); if( it != f.end() ) { f[std::distance(f.begin(), it)]->mostrarDados(); } else { cout << "Não existe funcionario com esse id cadastrado!" << endl; } cin.ignore(); } //Funcao para mostrar os funcionarios de acordo com o tipo void mostrarFuncionarios(vector<shared_ptr<Funcionario>> &f) { string input; int escolha; bool sair = false, error = false; //Loop para verificar se o input é uma opção válida e caso seja, realizer a operação referente a escolha do { clear(); cout << endl << "#############################################################" << endl; cout << "### FUNCIONARIOS ###" << endl; cout << "#############################################################" << endl; cout << endl << "Escolha o tipo de funcionario: " << endl << endl; cout << "[1] - Tratador" << endl; cout << "[2] - Veterinario" << endl; cout << endl; cout << "[0] - Sair" << endl << endl; if (error) { error = false; cout << "**Digite uma opcao valida!**" << endl; } cout << "Opcao: "; cin >> input; if (checarDigito(input)) { escolha = stoi(input, nullptr); if (escolha >= 0 && escolha <= 2) { switch (escolha) { case 0: sair = true; break; default: clear(); for (unsigned i = 0; i < f.size(); i++) { f[i]->mostrarFuncionarios(escolha - 1); } cin.ignore(); pressToCont(); break; } } else { error = true; } } else { error = true; } } while (!sair); } //Menu de funcionarios void menuFuncionarios(vector<shared_ptr<Funcionario>> &f) { string input; int escolha; bool sair = false, error = false; //Loop para verificar se o input é uma opção válida e caso seja, realizer a operação referente a escolha do { clear(); cout << endl << "#############################################################" << endl; cout << "### FUNCIONARIOS ###" << endl; cout << "#############################################################" << endl; cout << endl << "Escolha uma das seguintes opcoes: " << endl << endl; cout << "[1] - Adicionar novo tratador" << endl; cout << "[2] - Adicionar novo veterinario" << endl; cout << "[3] - Remover funcionario" << endl; cout << "[4] - Alterar dados de um funcionario" << endl; cout << "[5] - Consultar funcionario" << endl; cout << "[6] - Mostrar funcionarios" << endl; cout << endl; cout << "[0] - Sair" << endl << endl; if (error) { error = false; cout << "**Digite uma opcao valida!**" << endl; } cout << "Opcao: "; cin >> input; if (checarDigito(input)) { escolha = stoi(input, nullptr); if (escolha >= 0 && escolha <= 6) { switch (escolha) { case 0: sair = true; break; case 1: clear(); novoTratador(f); pressToCont(); break; case 2: clear(); novoVeterinario(f); pressToCont(); break; case 3: clear(); removerFuncionario(f); pressToCont(); break; case 4: clear(); alterarFuncionario(f); pressToCont(); break; case 5: clear(); consultarFuncionario(f); pressToCont(); break; case 6: clear(); mostrarFuncionarios(f); pressToCont(); break; } } else { error = true; } } else { error = true; } } while (!sair); } //Função que mostra o menu principal void menuPrincipal(vector<shared_ptr<Funcionario>> &f, vector<shared_ptr<Animal>> &a) { string input; int escolha; bool sair = false, error = false; //Loop para verificar se o input é uma opção válida e caso seja, realizer a operação referente a escolha do { clear(); cout << endl << "############################################################" << endl; cout << "### BEM VINDO!! ###" << endl; cout << "############################################################" << endl; cout << endl << "Escolha uma das seguintes opcoes: " << endl << endl; cout << "[1] - Animais" << endl; cout << "[2] - Funcionarios" << endl; cout << endl; cout << "[0] - Sair" << endl << endl; if (error) { error = false; cout << "**Digite uma opcao valida!**" << endl; } cout << "Opcao: "; cin >> input; if (checarDigito(input)) { escolha = stoi(input, nullptr); if (escolha >= 0 && escolha <= 2) { switch (escolha) { case 0: sair = true; break; case 1: menuAnimal(a, f); break; case 2: menuFuncionarios(f); break; } } else { error = true; } } else { error = true; } } while (!sair); } int main() { vector<shared_ptr<Animal>> animais; vector<shared_ptr<Funcionario>> funcionarios; lerDados(funcionarios, animais); menuPrincipal(funcionarios, animais); salvarDados(funcionarios, animais); return 0; }
c64bc279ff82645cbecd52e7d6b80636b370fe74
f0be8b268cb4405a9d40a1ea943a5352018173bb
/222 Count Complete Tree Nodes.cpp
ee3b5f4196fb72300a6e9a91efcb8502d612dfd2
[]
no_license
iroot900/Algorithm-Practice-300-Plus
1b2cdce48104dec540e045dfcab6290fefe60e4b
5b97c69c991d2b2f330d7b667e79dd32b53e44f5
refs/heads/master
2020-07-10T21:34:39.125332
2015-09-01T21:40:20
2015-09-01T21:40:20
36,990,843
0
0
null
null
null
null
UTF-8
C++
false
false
680
cpp
222 Count Complete Tree Nodes.cpp
/** * 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: // This one is very unique, as not in a usualy traverse way. int countNodes(TreeNode* root) { int left=0, right=0;//it's binary , left right, half will not be used. auto ltree=root, rtree=root; while(ltree) {++left;ltree=ltree->left;} while(rtree) {++right;rtree=rtree->right;} if(left==right) return pow(2,left)-1; // using recursion. return countNodes(root->left)+countNodes(root->right)+1; } };
91fe9cb73a1d1375ce0346a8f78a34919b70e2f1
ec2de16739cd71afef4a632a606e83444daf21b1
/DevC++/Code power/doicoso.cpp
3774b6ada680d1d5ad03a839e9fd521d6d4c4b42
[]
no_license
minhcongnguyen1508/Code-Java-C--UET
f96bc409c720cb80aaa2f96da81b3870e0937292
24c8018fac67479e0fc01c2068c9ee1a7a700311
refs/heads/master
2020-04-22T00:21:17.478448
2019-02-10T12:58:07
2019-02-10T12:58:07
169,976,733
0
0
null
null
null
null
UTF-8
C++
false
false
295
cpp
doicoso.cpp
# include <iostream> # include <algorithm> # include <string> # include <vector> using namespace std; int main(){ long long n; cin>> n; vector <int> a; if(n < 0) n = -n; while(n!=0){ a.push_back(n%2); n=n/2; } for(int i = a.size() - 1; i >= 0; i--){ cout<< a[i]; } return 0; }
cdd55ce8e5b6f47f245b252e288c4011844b182e
26142d3dd05db1bfba6063fb316ec7f59d6ce268
/Compopt/Nouna_PCVRP/qt-project/ver01/nouna_project/src/initialsolution.cpp
4604aaea3e8b189d7832d397825d598ec5c9fa86
[]
no_license
tikhoncheva/work
f9130e638d44d4418ea0ecec6d29b762b5a7ab86
9b1cc41a0e851df1506ffe0c4061087f33c7ba77
refs/heads/master
2021-01-21T12:36:04.777282
2016-01-13T10:09:35
2016-01-13T10:09:35
19,025,157
1
0
null
null
null
null
UTF-8
C++
false
false
18,830
cpp
initialsolution.cpp
#include "hrd/initialsolution.h" bool compareTime ( const std::pair<double, int>& a, const std::pair<double, int>& b) { return a.first > b.first; } bool isZero (const unsigned int a) { return a==0; } bool visited (std::pair<unsigned int, bool> a) { return !a.second; } /* * returns position on the minimum positive value in the container */ template <class ForwardIterator> ForwardIterator find_posmin( ForwardIterator first, ForwardIterator last ) { if (first==last) return last; ForwardIterator smallest = first; while (++first!=last) { if (*first>=0 && (*first<*smallest || *smallest<0)) { smallest=first; } } if (*smallest<0) return last; else return smallest; } /* * ------------------------------------------------------------------------------------ */ std::vector<std::pair<unsigned int, bool> > specialPresorting(std::vector<stHousehold> _households) { unsigned int N = _households.size(); std::vector<std::pair<double,int> > iT(N, std::make_pair(0.,0)); // interview time for (unsigned int i=0; i<N; ++i) { double it = (1-_households[i].type)*10*_households[i].nPersons // 10 min for standart interview + _households[i].type *30*_households[i].nPersons; // 30 min for special cases iT[i] = std::make_pair(it,i); } std::sort(iT.begin(), iT.end(), compareTime); // mark all households as unvisited std::vector<std::pair<unsigned int, bool> > toDo; for (unsigned int i=0; i<N; ++i) toDo.push_back(std::make_pair( iT[i].second, true)); return toDo; } std::vector<std::pair<unsigned int, bool> > specialPresorting2( std::vector<std::vector<std::pair<double, unsigned int> > > _village_household) { unsigned int V = _village_household.size(); // sort Villages in decreasing order of the interview times all it households std::vector<std::pair<double,int> > itime(V, std::make_pair(0.,0)); for (unsigned int i=0; i<V; ++i) { double itime_i = 0.; std::sort(_village_household[i].begin(), _village_household[i].end(), compareTime); itime_i = std::accumulate(_village_household[i].begin(), _village_household[i].end(), 0.0, [](double sum, const std::pair<double, int>& b){ return sum + b.first;} ); itime[i] = std::make_pair(itime_i,i); } std::sort(itime.begin(), itime.end(), compareTime); // sort housesholds in the order of villages std::vector<std::pair<unsigned int, bool> > toDo; for (unsigned int i=0; i<V; ++i) // for each village for (unsigned int h=0; h < _village_household[i].size(); ++h) toDo.push_back(std::make_pair(_village_household[i][h].second, true)); return toDo; } /* * ------------------------------------------------------------------------------------ */ void planForAWeek0 (std::vector<std::pair<unsigned int, bool> >& ToVis, std::vector<stInterviewer>& _interviewer, // _interviewer const std::vector<stHousehold> _household, // _households const std::vector<std::vector<double> > _distmatrix // distmatrix ) { unsigned int N = ToVis.size(); const unsigned int K = _interviewer.size(); // maximal number of available _interviewers const unsigned int home = 142-101; // Capital (Nouna) unsigned int first; //start household unsigned int predV; // predecessor of the hh j in the tour unsigned int nextV; // next village to go unsigned int k; // route/_interviewer number unsigned int hhID; // hhID std::vector<unsigned int> visitedV; // visited villages std::vector<unsigned int> visitedHh;// visited _households stRoute tmpRoute; const double tmax = 5*8*60.0; // maximal worktime pro day (in min) double t_work = 0.; // worktime of one _interviewer double ti; // interview time double t_changev; // time to move in other village double t_home; // time to come back at the start // pick randomly first unvisited household first = 0; first = rand()%(N-1); while (!ToVis[first].second) first= (first+1)%N; k = 1; // start planning for the first _interviewer predV = home; visitedV.push_back(home); // start from the capital // for j, j+1, ..., N-1, 0, 1, ..., j-1 for (unsigned int i=first; i<N+first; ++i) { if (!ToVis[i%N].second) //skip already visited citys continue; hhID = ToVis[i%N].first; nextV = _household[hhID].villageID - 101; // if hh is not in the previous village if (predV !=nextV) { t_changev = _distmatrix[predV][nextV]; visitedV.push_back(nextV); } else t_changev = 0; // Interview time ti = _household[hhID].itime; t_home = _distmatrix[nextV][home]; if (t_work + t_changev + ti + t_home < tmax) { t_work += t_changev + ti; // we don't need to come back now visitedHh.push_back(hhID); } else { // interviewer k does not have any free time t_work += _distmatrix[predV][home];// return back from previous location visitedV.push_back(home); // save route in _interviewer k tmpRoute.villages = visitedV; tmpRoute.households = visitedHh; tmpRoute.time = t_work; _interviewer[k-1].routes.push_back(tmpRoute); // start new route //k = std::min(k+1,K); k = k+1; if (k > K) { break; } visitedV.erase(visitedV.begin()+1, visitedV.end()); visitedHh.erase(visitedHh.begin(), visitedHh.end()); // new route starts with the current hh, // which previous interviewer could not visit any more visitedV.push_back(nextV); visitedHh.push_back(hhID); t_work= _distmatrix[home][nextV] + ti; } ToVis[i%N].second = false; predV = nextV; } } void fillTheGaps0 (unsigned int w, std::vector<std::pair<unsigned int, bool> >& ToVis, std::vector<stInterviewer>& _interviewer, // _interviewer const std::vector<stHousehold> _household, // _households const std::vector<std::vector<double> > _distmatrix // distmatrix ) { unsigned int N = ToVis.size(); const unsigned int K = _interviewer.size(); // maximal number of available interviewers const unsigned int home = 142-101; // Capital (Nouna) unsigned int first; // start household unsigned int predV; // predecessor of the hh j in the tour unsigned int nextV; // next village to go unsigned int hhID; // hhID const double tmax = 5*8*60.; // maximal worktime pro week (in min) double ti; // interview time double t_changev; // time to move in other village double t_home; // time to come back at the start std::vector<double> remaining_time; std::vector<double> remaining_time_new; remaining_time.resize(K); remaining_time_new.resize(K); std::cout << "Remaining time at the beginning:" << std::endl; for (unsigned int k=0; k<K; ++k) { remaining_time[k] = tmax - _interviewer[k].routes[w].time; std::cout << tmax << "-" << _interviewer[k].routes[w].time << " = " << remaining_time[k] << " "; _interviewer[k].routes[w].villages.pop_back(); // delete home at the end of all routes } std::cout << std::endl; // go through all citys and try to add them in already existing routes first = 0; unsigned int i=first; bool allFull = false; while( ++i<N && !allFull) // ~ for j, j+1, ..., N-1, 0, 1, ..., j-1 { if (!ToVis[i%N].second) //skip already visited citys continue; hhID = ToVis[i%N].first; // next household to visite nextV = _household[hhID].villageID - 101; // village of the next household // Interview time ti = _household[hhID].itime; // if interviewer would come back home after this hh t_home = _distmatrix[nextV][home]; // for each Interviewer calculate the remaining time, if he takes the hh for (unsigned int k=0; k<K; ++k) { predV = _interviewer[k].routes[w].villages.back(); // previous village in tour k // travel time between previous village and new village t_changev = _distmatrix[predV][nextV]; remaining_time_new[k] = remaining_time[k] - (t_changev + ti + t_home); } // find min remaining time over all positive values unsigned int k_min = find_posmin(remaining_time_new.begin(), remaining_time_new.end()) - remaining_time_new.begin(); if (k_min==K) // all values in remaining_time_ are negative continue; predV= _interviewer[k_min].routes[w].villages.back(); // last village in the route t_changev = _distmatrix[predV][nextV]; _interviewer[k_min].routes[w].households.push_back(hhID); if (predV != nextV) _interviewer[k_min].routes[w].villages.push_back(nextV); _interviewer[k_min].routes[w].time += ti + t_changev; remaining_time[k_min] = remaining_time_new[k_min] + t_home; // we dont want to come back immediately ToVis[i%N].second = false; // set hh as visited allFull = std::all_of(remaining_time.begin(), remaining_time.end(), isZero); } // close all routes: add time to go home // assign routes to Interviewer for (unsigned int k=0; k<K; ++k) { predV = _interviewer[k].routes[w].villages.back(); // last village in the route _interviewer[k].routes[w].villages.push_back(home); _interviewer[k].routes[w].time += _distmatrix[predV][home]; } } /* * Do not close routes after a hh didn't pass in */ void planForAWeek (std::vector<std::pair<unsigned int, bool> >& ToVis, std::vector<stInterviewer>& _interviewer, // _interviewer const std::vector<stHousehold> _household, // _households const std::vector<std::vector<double> > _distmatrix // distmatrix ) { unsigned int N = ToVis.size(); const unsigned int K = _interviewer.size(); // maximal number of available interviewers const unsigned int home = 142-101; // Capital (Nouna) unsigned int first; //start household unsigned int predV; // predecessor of the hh j in the tour unsigned int nextV; // next village to go unsigned int hhID; // hhID std::vector<std::vector<unsigned int> > visitedV; // visited villages std::vector<std::vector<unsigned int> > visitedHh;// visited _households stRoute tmpRoute; const double tmax = 5*8*60.; // maximal worktime pro week (in min) double ti; // interview time double t_changev; // time to move in other village double t_home; // time to come back at the start std::vector<double> remaining_time; std::vector<double> remaining_time_new; // each route starts at capital (home) visitedV.resize(K); visitedHh.resize(K); remaining_time.resize(K); remaining_time_new.resize(K); for (unsigned int k=0; k<K; ++k) { visitedV[k].push_back(home); remaining_time[k] = tmax; } // pick randomly first unvisited household (an the beginning of period all hh need to be visited) first = rand()%(N-1); while (!ToVis[first].second) first= (first+1)%N; unsigned int i=first; bool allFull = false; while( ++i<(N+first) && !allFull) // ~ for j, j+1, ..., N-1, 0, 1, ..., j-1 { // select a household if (!ToVis[i%N].second) //skip already visited citys continue; hhID = ToVis[i%N].first; // next household to visite nextV = _household[hhID].villageID - 101; // village of the next household // Interview time ti = (1-_household[hhID].type)*10*_household[hhID].nPersons // 10 min for standart interview + _household[hhID].type *30*_household[hhID].nPersons; // 30 min for special cases // if interviewer would come back home after this hh t_home = _distmatrix[nextV][home]; // for each Interviewer calculate the remaining time, if he takes the hh for (unsigned int k=0; k<K; ++k) { predV = visitedV[k].back(); // previous village in tour k // travel time between previous village and new village t_changev = _distmatrix[predV][nextV]; remaining_time_new[k] = remaining_time[k] - (t_changev + ti + t_home); } // find min remaining time over all positive values unsigned int k_min = find_posmin(remaining_time_new.begin(), remaining_time_new.end()) - remaining_time_new.begin(); if (k_min==K) // all values in remaining_time_ are negative continue; predV= visitedV[k_min].back(); t_changev = _distmatrix[predV][nextV]; remaining_time[k_min] = remaining_time_new[k_min] + t_home; // we dont want to come back immediately visitedHh[k_min].push_back(hhID); if (predV !=nextV) visitedV[k_min].push_back(nextV); ToVis[i%N].second = false; // set hh as visited allFull = std::all_of(remaining_time.begin(), remaining_time.end(), isZero); } // close all routes: add time to go home // assign routes to Interviewer for (unsigned int k=0; k<K; ++k) { predV = visitedV[k][visitedV[k].size()-1]; // last village in the route remaining_time[k] -= _distmatrix[predV][home]; visitedV[k].push_back(home); tmpRoute.villages = visitedV[k]; tmpRoute.households = visitedHh[k]; tmpRoute.time = tmax - remaining_time[k]; _interviewer[k].routes.push_back(tmpRoute); } } /* * Initial Solution */ void initialsolution(std::vector<stVillage> _villages, // villages std::vector<stHousehold> _households, // _households std::vector<stInterviewer>& _interviewer, // _interviewer std::vector<stInterviewer>& _cleaner, // _interviewer std::vector<std::vector<double> > _distmatrix,// distmatrix std::vector<std::vector<std::pair<double, unsigned int> > > _village_household ) { unsigned int N = _households.size(); unsigned int weeks = 16; std::vector<std::pair<unsigned int, bool> > ToVis(N, std::make_pair(0, true)); // sort households in decreasing order their interview times // ToVis = specialPresorting(_households); ToVis = specialPresorting2(_village_household); // erase previous tours for (unsigned int k=0; k < _interviewer.size(); ++k) { _interviewer[k].nRoutes = 0; _interviewer[k].routes.erase(_interviewer[k].routes.begin(), _interviewer[k].routes.end()); } // plan nex week unsigned int totalVisHh = 0; for (unsigned int w=0; w<weeks; ++w) // planning horizon is 16 weeks { // unvisited hh, _interviewer, _households, distmatrix // planForADay(d, ToVis, _interviewer, _households, _distmatrix); //planForAWeek( ToVis, _interviewer, _households, _distmatrix); planForAWeek0( ToVis, _interviewer, _households, _distmatrix); //fillTheGaps0(ToVis, _interviewer, _households, _distmatrix); // unsigned int sumVisHh = 0; // for (unsigned int i=0; i<_interviewer.size(); ++i) // sumVisHh += _interviewer[i].routes[week].households.size(); // std::cout << "# of Households, visited at the week " << week << " of the first period: " // << sumVisHh << std::endl; // totalVisHh += sumVisHh; } double totalRemainingTime = 0.; for (unsigned int i=0; i<_interviewer.size(); ++i) for (unsigned int w=0; w< 16; ++w) { totalVisHh += _interviewer[i].routes[w].households.size(); totalRemainingTime += 5*8*60. -_interviewer[i].routes[w].time; } std::cout << "Total number of the visited households in first period: " << totalVisHh << std::endl; std::cout << " Still to visite " << N - totalVisHh << std::endl; std::cout << "Total remaining free time: " << totalRemainingTime << "min"<< std::endl; double totalReamingITime = 0.; double totalITime = 0; for (unsigned int h=0; h<N; ++h) { totalITime += _households[h].itime; if (ToVis[h].second) totalReamingITime += _households[h].itime; } std::cout << "Total interview time:" << totalITime << "min" << std::endl; std::cout << "Total remaining interview time:" << totalReamingITime << "min" << std::endl; // --------------------------------------------------------------------------------- std::cout << "Fill the gaps:" << std::endl; for (unsigned int w=0; w<1; ++w) // planning horizon is 16 weeks { fillTheGaps0(w, ToVis, _interviewer, _households, _distmatrix); } totalVisHh = 0; totalRemainingTime = 0.; for (unsigned int i=0; i<_interviewer.size(); ++i) for (unsigned int w=0; w< 16; ++w) { totalVisHh += _interviewer[i].routes[w].households.size(); totalRemainingTime +=_interviewer[i].routes[w].time; } totalReamingITime = 0.; for (unsigned int h=0; h<N; ++h) if (ToVis[h].second) totalReamingITime += _households[h].itime; std::cout << "Total number of the visited households in first period: " << totalVisHh << std::endl; std::cout << " Still to visite " << N - totalVisHh << std::endl; std::cout << "Total remaining free time: " << totalRemainingTime << "min"<< std::endl; std::cout << "Total remaining interview time:" << totalReamingITime << "min" << std::endl; }
be936c92772aa23b305853d27e90dc377e9eeabb
2be6bac64906c13e9429491eeaec9290727a85ae
/20210311_AE0022.cpp
6a56344a3f047c2015f696e01c1504e66fe34083
[]
no_license
Renesys/algolab
141b291a4c087366cd3ec8670ff352dd7f1e7ad3
ec34b539410dc4944e97bbd5767e770c15a6f34f
refs/heads/master
2021-06-22T22:08:28.614479
2021-04-05T11:35:31
2021-04-05T11:35:31
207,927,038
0
0
null
null
null
null
UTF-8
C++
false
false
1,733
cpp
20210311_AE0022.cpp
#include<iostream> #include<fstream> #include<cstdio> #include<deque> #include<vector> #include<string> #include<algorithm> #define MAX 10000007 using namespace std; vector<int> prime; int is_prime[10001]; int chk[10001]; int res; void make_prime() { int idx = 2; for (int i = 1; i <= 10000; i++) { is_prime[i] = true; } is_prime[0] = is_prime[1] = false; for (int i = 2; i <= 10000; i++) { if (!is_prime[i]) continue; for (int j = i * 2; j <= 10000; j += i) { is_prime[j] = false; } } for (int i = 1000; i <= 10000; i++) { if (is_prime[i]) { prime.push_back(i); } } } deque<pair<int, int>> dq; void search_path(pair<int, int> src, int dest) { if (res != MAX) { return; } else if (src.second == dest) { if (res > src.first) { res = src.first; } return; } //choose candidate int arr[4] = { 1000, 100, 10, 1 }; string s = to_string(src.second); for (int i = 0; i < 4; i++) { int t = 0; //add except pivot line for (int j = 0; j < 4; j++) { if (i != j) { t += ((s[j]-'0') * arr[j]); } } //add pivot line for (int j = 0; j < 10; j++) { if (i == 0 && j == 0) continue; t += j * arr[i]; if (is_prime[t] && !chk[t]) { dq.push_back({ src.first + 1, t }); chk[t] = true; } t -= j*arr[i]; } } //BFS while (!dq.empty()) { pair<int, int> next = dq.front(); dq.pop_front(); search_path(next, dest); } return; } int main() { ifstream f("input.txt"); int CA; f >> CA; make_prime(); for (int ca = 1; ca <= CA; ca++) { for (int i = 0; i <= 10000; i++) { chk[i] = false; } int a, b; dq.clear(); res = MAX; f >> a >> b; chk[a] = true; search_path({ 0,a }, b); printf("#%d %d\n", ca, res); } return 0; }
0f9bfdd3d62745d6e88c7457374c9ce55ba5ca9b
354f83b7e8edfd95b18c87e192a97afff0b062af
/Example/EZ_Start_Kit_Example/PHR/PHR.ino
828a4e443cf01b7b00b49a84db050d807a417ca5
[]
no_license
iCShopMgr/EZ_Start_Kit_for_BlocklyDuino_feat.liou
743f404e6419e712d96d897fbcda3eca7f1efdc5
0d6a2ce7b0d4b5ed174f2ccac2782994246379cc
refs/heads/main
2023-01-24T23:58:43.211032
2020-12-12T11:33:41
2020-12-12T11:33:41
320,814,636
5
1
null
null
null
null
UTF-8
C++
false
false
724
ino
PHR.ino
/* * Generated using BlocklyDuino: * * https://github.com/MediaTek-Labs/BlocklyDuino-for-LinkIt * * Date: Mon, 13 Jul 2020 09:57:38 GMT */ #include "Wire.h" #include "U8g2lib.h" U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); int phr_value() { return analogRead(A1); } void setup() { u8g2.begin(); u8g2.setFont(u8g2_font_6x10_tf); u8g2.setFontRefHeightExtendedText(); u8g2.setDrawColor(1); u8g2.setFontPosTop(); u8g2.setFontDirection(0); u8g2.clearDisplay(); pinMode(A1, INPUT); } void loop() { u8g2.firstPage(); do { u8g2.drawStr(0, 0, String(String() + "PHR: " + phr_value()).c_str()); u8g2.sendBuffer(); } while (u8g2.nextPage()); delay(100); }
06508ce958e691938220b2da614052d2b3e1b3f7
ab60b4c558ec2ee675824ecaf2dd685c409a19bd
/CoinFlipping/coin.h
73e1975b2d36c0f33e3ce0ac160975aaed196e75
[]
no_license
migodz/Qt-CoinFlippingGame
494f00f4988d88987db2ca01756f025363345f3c
6fcf93d1a0b0f4f4144e9fe7a599bd3172e35dd6
refs/heads/master
2022-11-13T04:48:16.647439
2020-07-10T11:48:51
2020-07-10T11:48:51
277,995,864
1
0
null
null
null
null
UTF-8
C++
false
false
499
h
coin.h
#ifndef COIN_H #define COIN_H #include <QPushButton> #include <QTimer> class Coin : public QPushButton { Q_OBJECT public: QTimer * timer1; QTimer * timer2; bool isFrontSide; bool isAnimating = false; bool isWon = false; int posX, posY; int min = 1; int max = 8; //explicit Coin(QWidget *parent = nullptr); Coin(QString imgPath); void filpSide(); void mousePressEvent(QMouseEvent *); signals: }; #endif // COIN_H
d347edcdac452af8f55a8198c9e5930cd77187a9
ed2e3a3a01b96b9cc9e4d2615843142d69f4a3cd
/GraphicsLib/Sprite.cpp
bf1395a9afaf2975c9f3dd29447ec7b1795140cc
[]
no_license
Kellers176/Snake
800b7a30903db4f9f0038fb626aa0a64b0cd529a
7ab9d3bec48e2306f9e9b04986d92a72e4739609
refs/heads/master
2020-03-28T08:32:09.022885
2018-09-08T22:04:40
2018-09-08T22:04:40
147,971,877
0
0
null
null
null
null
UTF-8
C++
false
false
1,631
cpp
Sprite.cpp
/*Author: Kelly Herstine Class: EGP-310 <Section 01> Assignment: Assignment 2 Certification of Authenticity: I certify that this assignment is entirely my own work.*/ #include "Sprite.h" Sprite::Sprite() { mLocationOfSpriteX = 0; mLocationOfSpriteY = 0; mHeightOfSprite = 10; mWidthOfSprite = 10; mFilename = ""; } Sprite::Sprite(int height, int width, int locX, int locY, GraphicsBuffer* bitmap) { mHeightOfSprite = height; mWidthOfSprite = width; mLocationOfSpriteX = locX; mLocationOfSpriteY = locY; mBuffer = bitmap; } Sprite::Sprite(int height, int width, int locX, int locY, GraphicsBuffer bitmap) { mSecondBuffer = bitmap; mHeightOfSprite = height; mWidthOfSprite = width; mLocationOfSpriteX = locX; mLocationOfSpriteY = locY; } Sprite::~Sprite() { } void Sprite::setLocationOfSpriteX(int x) { mLocationOfSpriteX = x; } void Sprite::setLocationOfSpriteY(int y) { mLocationOfSpriteY = y; } void Sprite::setWidthOfSprite(int x) { mWidthOfSprite = x; } void Sprite::setHeightOfSprite(int y) { mHeightOfSprite = y; } void Sprite::setGraphicsBuffer(GraphicsBuffer* buffer) { mBuffer = buffer; } int Sprite::getLocationOfSpriteX() { return mLocationOfSpriteX; } int Sprite::getLocationOfSpriteY() { return mLocationOfSpriteY; } int Sprite::getWidthOfSprite() { return mWidthOfSprite; } int Sprite::getHeightOfSprite() { return mHeightOfSprite; } GraphicsBuffer* Sprite::getGraphicsBuffer() { return mBuffer; } GraphicsBuffer Sprite::getBitmap() { return mSecondBuffer; }
5ee52bcaab94edf490bd2ebe5656346f91582fac
35e036a7b1fdf3b5112b602193b8219d7abe5654
/Source/CLLeaderboardTutorialPlugin/Private/LeaderboardPlugin.cpp
ceb971e60c03419733da818f8ce60511978ba4ef
[]
no_license
ialex32x/LeaderboardSlateTutorial
ded2f20eb4b87429ee1e5dea46ae14600bc2a857
4752a212f5ce8fa0958ada5dd51c815cea490b46
refs/heads/master
2022-10-24T20:27:42.823517
2020-06-11T05:54:42
2020-06-11T05:54:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
920
cpp
LeaderboardPlugin.cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "Modules/ModuleManager.h" #include "ILeaderboardPlugin.h" #include "LeaderboardStyle.h" class FCLLeaderboardTutorialPlugin : public ICLLeaderboardTutorialPlugin { /** IModuleInterface implementation */ virtual void StartupModule() override; virtual void ShutdownModule() override; }; IMPLEMENT_MODULE( FCLLeaderboardTutorialPlugin, CLLeaderboardTutorialPlugin ) void FCLLeaderboardTutorialPlugin::StartupModule() { // This code will execute after your module is loaded into memory (but after global variables are initialized, of course.) FLeaderboardStyle::Initialize(); } void FCLLeaderboardTutorialPlugin::ShutdownModule() { // This function may be called during shutdown to clean up your module. For modules that support dynamic reloading, // we call this function before unloading the module. FLeaderboardStyle::Shutdown(); }
b3ff95bb362bd2088459934716404111a0e92833
f1cfd30641a3e1f11ec73a8ab07ef28e40919989
/VendingMachineAPI/src/CreamDecorator.h
44cba742dff8c1da11f5325cee726c044d85b444
[]
no_license
zalak13/C_Plus_Plus-Projects
2d22f4925e58577076385552d3d7b06e5c81254b
c96f97577c74e5ee51ddf7aa8c7bdd879bf2c420
refs/heads/master
2021-01-13T11:51:44.530026
2017-06-08T03:43:12
2017-06-08T03:43:12
81,693,895
0
0
null
null
null
null
UTF-8
C++
false
false
722
h
CreamDecorator.h
/* * CreamDecorator.h * * Created on: Dec 5, 2016 * Author: zshah */ #ifndef CREAMDECORATOR_H_ #define CREAMDECORATOR_H_ #include "IngredientWrapper.h" class CreamDecorator : public IngredientWrapper { public: CreamDecorator( Coffee *coffee) : IngredientWrapper(coffee) {} // Pass the Coffee Object we are wrapping Ingredients to Cream decorator std::string getDescription() { return IngredientWrapper::getDescription() + ", Cream Added "; } double cost() { return ( 0.25 + IngredientWrapper::cost() ); // First make a call to the object we're decorating } // (Coffee) then add the cost of decorator (Cream) }; #endif /* CREAMDECORATOR_H_ */
31306bdc9c86a78e8ed9b4fdfcda48f7a22c866b
157c466d9577b48400bd00bf4f3c4d7a48f71e20
/Source/ProjectR/UI/ItemManagement/UC_PopupContent_EquipmentItemFilter.cpp
6161fdcc9c62a896f25d06e1381e79cbac8bad81
[]
no_license
SeungyulOh/OverlordSource
55015d357297393c7315c798f6813a9daba28b15
2e2339183bf847663d8f1722ed0f932fed6c7516
refs/heads/master
2020-04-19T16:00:25.346619
2019-01-30T06:41:12
2019-01-30T06:41:12
168,291,223
8
1
null
null
null
null
UTF-8
C++
false
false
1,371
cpp
UC_PopupContent_EquipmentItemFilter.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "ProjectR.h" #include "UC_PopupContent_EquipmentItemFilter.h" #include "UI/Control/RScrollView.h" #include "GlobalIntegrated.h" #include "GameInfo/RInventory.h" #include "Table/ItemTableInfo.h" #include "UI/Common/ItemInventory_ScrollData.h" #include "UI/Component/CheckBox_Radio.h" #include "UI/Component/CanvasPanel_RadioGroup.h" #include "Table/CharacterTableInfo.h" #include "UI/Control/RScrollItem.h" #include "UC_GenericPopup.h" #include "UI/RWidgetManager.h" #include "UI/Component/CheckBox_Radio.h" #include "Network/PacketDataStructures.h" void UUC_PopupContent_EquipmentItemFilter::NativeConstruct() { Super::NativeConstruct(); } void UUC_PopupContent_EquipmentItemFilter::NativeDestruct() { Super::NativeDestruct(); } void UUC_PopupContent_EquipmentItemFilter::InvalidateData() { Super::InvalidateData(); } void UUC_FilterItem::NativePreConstruct() { Super::NativePreConstruct(); // set the localized text and default check state CheckBox_Filter->SetCheckedState(CheckedByDefault ? ECheckBoxState::Checked : ECheckBoxState::Unchecked); if (OverrideText.IsEmpty()) { Text_Filter->LocalizingKey = LocalizingKey; Text_Filter->StringTableType = StringTableType; Text_Filter->ApplyLocalizedText(); } else { Text_Filter->SetText(OverrideText); } }
1c67c6b43e40e4139752a835ce3feffb84432da5
5934de78d0f1e6611352024df26548e7807d1930
/exp1/Stack.h
854adf392de2a16e33815990058dad774d9e11bb
[]
no_license
hutianyi003/wordparse
8e1dae2e7d322062d9ff83f2466142e3d97a0865
24297703187e1d8dc8d71c846c892e45b7bab450
refs/heads/master
2021-05-07T01:44:46.762401
2017-12-25T04:44:47
2017-12-25T04:44:47
110,326,698
0
0
null
null
null
null
UTF-8
C++
false
false
1,954
h
Stack.h
#pragma once namespace ds { template<class datatype> class Stack { public: Stack<datatype>(); Stack<datatype>(const Stack<datatype> &rhs); ~Stack<datatype>(); void operator=(const Stack& rhs) = delete; void pop(); bool push(const datatype& rhs); datatype top(); bool empty(); int size(); private: const static int EVERY_ADD_SIZE = 256;//every time add memory size int stacksize, maxstacksize; datatype *base; }; //templates must write in .h files /*------------------------stack--------------------------------*/ template<class datatype> inline Stack<datatype>::Stack() :stacksize(0), maxstacksize(EVERY_ADD_SIZE) { base = new datatype[maxstacksize]; return; } template<class datatype> inline Stack<datatype>::Stack(const Stack<datatype>& rhs): stacksize(rhs.stacksize), maxstacksize(rhs.maxstacksize) { base = new datatype[maxstacksize]; for (int i = 0; i < stacksize; i++) *(base + i) = *(rhs.base + i); return; } template<class datatype> inline Stack<datatype>::~Stack() { delete[] base; return; } template<class datatype> inline void Stack<datatype>::pop() { if (stacksize == 0) return; stacksize--; } template<class datatype> inline bool Stack<datatype>::push(const datatype & rhs) { if (stacksize == maxstacksize) { maxstacksize += EVERY_ADD_SIZE; datatype *newbase = new datatype[maxstacksize]; for (int i = 0; i < stacksize; i++) *(newbase + i) = *(base + i); delete[] base; base = newbase; } base[stacksize++] = rhs; return true; } template<class datatype> inline datatype Stack<datatype>::top() { if (!stacksize) { throw 0; } return base[stacksize-1]; } template<class datatype> inline bool Stack<datatype>::empty() { return (stacksize == 0); } template<class datatype> inline int Stack<datatype>::size() { return stacksize; } }
24fe82a0abb026eae9291caeee8dfd4a6347a233
c2c60ab2b7b0d71ae5f8bc4ca51b4b5f0dc3fb22
/lhx/res/10.6/files/sydneyhen/UFO-Alert/a51d18c/DisplayCharter.h
6db072ae104df5a8f3012ea1fd2b891d16e017dc
[]
no_license
xinhecuican/githubDB_work
13e54ae21f79b40e834c40f9da8e6ac667119f64
e6fc0dcf3795834b3b065ea75f443aee81e28718
refs/heads/master
2023-08-25T15:50:11.494228
2021-10-12T00:14:58
2021-10-12T00:19:21
396,585,591
0
0
null
2021-08-16T13:34:21
2021-08-16T02:43:22
Python
UTF-8
C++
false
false
1,422
h
DisplayCharter.h
#include <ArduinoJson.h> #include <Adafruit_DotStar.h> #define RING_LEDCOUNT 15 class DisplayCharter { public: DisplayCharter(); void Init(); void Clear(); void SetLeds(byte pos, byte count, unsigned int color); void SetBackground(String color); void SetWirl(byte wspeed, bool clockwise); void SetMorph(int period, byte mspeed); unsigned int ParseLedArg(String argument, unsigned int iPos); void ParseWhirlArg(String argument); void ParseMorphArg(String argument); void Display(Adafruit_DotStar &dotstar); private: int GetPixelColor(int i); private: unsigned int ledColor[RING_LEDCOUNT]; unsigned int backgroundColor; byte whirlSpeed; bool whirlClockwise; byte offset; byte whirlTick; byte morphingState; int morphPeriod; int morphPeriodTick; byte morphSpeed; byte morphSpeedTick; byte morphingPercentage; }; //------------------------------------------------------------------------------------------------------ class IPDisplay { public: IPDisplay(); void ShowIp(String ip, DisplayCharter* displayCh); void ProcessTick(); void StopShowingIp(); private: bool showIp; String ipAddress; unsigned int pos; unsigned int tick; bool shortBreak; unsigned int color; unsigned int colorValue; unsigned int ipspeed; DisplayCharter* displayCharter; };
601dabde8e193031c102ae25163f9b4b63fbeeb0
ea38b0830b44ec3f919ea23440890175e2e7b564
/Codeforces/Educational Codeforces Round 47 (Rated for Div. 2)/A - Game Shopping.cpp
851c13223268442498ecdd3d22a45dc65382bdb2
[ "CC0-1.0" ]
permissive
AbhijeetKrishnan/codebook
456fe2386cf582e1a125958bf3a56f3cfa2ed484
c5bf6068586f460f7d2905b77c3295ae0da37613
refs/heads/master
2022-12-19T14:45:55.874001
2022-12-06T22:26:52
2022-12-06T22:26:52
62,959,828
0
0
null
null
null
null
UTF-8
C++
false
false
485
cpp
A - Game Shopping.cpp
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<int> c(n), a(m); for (auto &e : c) { cin >> e; } for (auto &e : a) { cin >> e; } int ans = 0; int i = 0, j = 0; while (i < n && j < m) { if (a[j] >= c[i]) { ++ans; ++i; ++j; } else { ++i; } } cout << ans; return 0; }
7c0a2fbc7842c0f8436844535c89f41de7085381
668df9c06a5dd14667d4e929714bb1e9004b66f2
/CSE335/Final_project/TreeLib/Fruit.cpp
ce8b288d804f9efcc557e20e959845e9d17d7252
[]
no_license
SpudMSU/Classwork
36583aa628e168adf8408963edd9779d9a117462
9007d332dfb6c4172a09f0eabd6311bcf1ffd5e7
refs/heads/main
2023-01-13T09:47:32.124458
2020-11-09T18:19:07
2020-11-09T18:19:07
311,411,829
0
0
null
null
null
null
UTF-8
C++
false
false
38
cpp
Fruit.cpp
#include "pch.h" #include "Fruit.h"
a41970a2eabc9bfbdcdd1cfae13ac5c19af0acae
2e9aec1aaa079726596da6e51a11d54dd9ed4192
/ABC166/C.cpp
2c09003735bd8bd6e8521edb1de4ee2e2538a544
[]
no_license
Alignof/ABC_practice
c38e9cc4685dcb3cea9a5e1db77f8eaa32b33800
965eac44bd8446fca7175af9b2d7dd02e1482dba
refs/heads/master
2022-12-26T03:11:47.266907
2020-09-27T13:21:47
2020-09-27T13:21:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
890
cpp
C.cpp
#include <bits/stdc++.h> #define SIZE 10 #define PI 3.141592653589793 using namespace std; typedef long long ll; int main(void){ cin.tie(0); ios::sync_with_stdio(false); int N,M; int x,y; int i,j; int tower; bool flag; int answer=0; int counter=0; ll tmp; vector<ll> H; vector<ll> maxH; cin >> N >> M; maxH.resize(N); for(i=0;i<N;i++){ cin >> tmp; H.emplace_back(tmp); } for(i=0;i<M;i++){ cin >> x; cin >> y; maxH[x-1]=max(maxH[x-1],H[y-1]); maxH[y-1]=max(maxH[y-1],H[x-1]); } /* my answer for(i=0;i<N;i++){ tower=i+1; flag=true; for(j=0;j<M;j++){ if(road[j].first==tower && H[tower-1] <=H[road[j].second-1]) flag=false; if(road[j].second==tower && H[tower-1]<=H[road[j].first -1]) flag=false; } if(flag) counter++; } */ for(i=0;i<N;i++) if(H[i]>maxH[i]) counter++; answer=counter; cout << answer << endl; return 0; }
143b04d8d148caf02726f16f65c92f0057414530
90af0fa8944c9bcb677178774d4c2c7bfe2b6e79
/U22/Project/main.cpp
c76e95ca50bc2737acc65fffc27ba8e3d97240d1
[ "MIT" ]
permissive
OiC-SysDev-Game/WonderWolfGirl
33a5db5e7bde89bb49a90fc32950d66662a6fd52
6118d47fea259ec7437d5b9a7c3f967fe2eb4fa0
refs/heads/main
2023-07-05T11:23:24.258746
2021-07-30T05:41:13
2021-07-30T05:41:13
381,572,812
0
0
null
null
null
null
UTF-8
C++
false
false
514
cpp
main.cpp
#include "U22.h" #include "GameApplicaion.h" int main(int argc, char* argv[]) { auto framework = new u22::Framework(); auto app = std::make_shared<u22::GameApplication>(); auto info = u22::ApplicationInfo(); info.window_width = 1920; info.window_height = 1080; info.window_position_x = 40; info.window_position_y = 40; framework->Setup(app, &info); int result = framework->Run(); framework->Cleanup(); delete framework; framework = nullptr; return result; }
2dc4566c6ed9ef5d4cb78a13951b9743c483d924
323acf3482dd68de8542a8d6c67d585fb5f20f13
/localization_siar/functions/include/functions/RandomNumberGenerator.h
c2147060c3d32998437a6d7693c28aca04df4b19
[]
no_license
robotics-upo/siar_packages
1870d623a9c19c55804f781fa6d90a71e15069bb
741c98fd0fbec4e862c7f4794d7513d6100421b3
refs/heads/master
2021-08-01T09:07:55.707761
2018-02-16T10:45:26
2018-02-16T10:45:26
71,160,119
3
2
null
null
null
null
UTF-8
C++
false
false
1,514
h
RandomNumberGenerator.h
#ifndef __RANDOM_NUMBER_GENERATOR_H__ #define __RANDOM_NUMBER_GENERATOR_H__ #include <boost/random.hpp> #include <boost/date_time/posix_time/posix_time.hpp> /** @brief Random number generator To get a random number between 0 and 1: <pre> double random = RandomNumberGenerator::rnd01();</pre> */ namespace functions { class RandomNumberGenerator { private: //!Generator pointer (mersenne twister) boost::mt19937 *gen; //!Uniform Distribution [0..1] pointer boost::uniform_01<boost::mt19937> *distribution; RandomNumberGenerator(RandomNumberGenerator const&); // Don't want copy void operator=(RandomNumberGenerator const&); // Don't want assign public: /** * @brief Default constructor, recomended. */ RandomNumberGenerator(); //!Destructor. ~RandomNumberGenerator(); //!gets a pointor to the generator boost::mt19937 *getGen(){ return gen; } //!Gets a random number between 0 and 1. Samples a uniform distribution. double rnd01(); inline double rnd(double low = 0.0, double high = 1.0) { return rnd01()*(high - low) + low;} static double getRandomNumber(double low = 0.0, double high = 1.0); double randomGaussian(double sigma, double mean); void dispose(); //! @brief Makes all internal pointers point to NULL void pointersToNULL(); static RandomNumberGenerator *instance; }; } #endif //__RANDOM_NUMBER_GENERATOR_H__
ead17eeb00074855e418f629865c15dd04c7db4e
fab9e40b2fd160fce383b6b7941ff662864050c3
/AlgKolorowania.hpp
5b51b5534a1ad922efe0da00c90ee05d1c912f41
[]
no_license
wachuuu/tabu-search-graph-coloring
5a53c87b3817444e768ba0adb7863170dd1afbc0
327263312167ff22e827c874838b1c5ca39fe00f
refs/heads/master
2023-04-06T02:52:08.914109
2021-04-05T19:42:32
2021-04-05T19:42:32
317,313,282
4
0
null
null
null
null
UTF-8
C++
false
false
884
hpp
AlgKolorowania.hpp
#ifndef AlgKolorowania_hpp #define AlgKolorowania_hpp #include <iostream> #include "Graf.hpp" class AlgKolorowania { private: //struktura danych do przechowywania grafu std::vector<std::vector<int>> listy_sasiedztwa; int n; //liczba wierzcholkow //metody pomocnicze bool istnieje(int val1, int val2); /*algorytm zachlanny*/ //kolory wierzcholkow grafu std::vector<std::vector<int>> tab_colors; /*metaheurystyka tabusearch*/ //lista tabu std::vector<int> tabu_list; public: //Pobranie instancji grafu AlgKolorowania(int n, std::vector<std::vector<int>> listy, bool debug=false); //Algorytm zachłanny int zachlanny(int start_v=0, std::vector<int> tabu={}, bool debug=false); //Algorytm tabu search oparty na algorytmie zachlannym int tabu_search_greedy(bool debug=false); //Algorytm tabu search oparty dopuszczajacy konflikty int tabu_search_random(bool debug=false); }; #endif
157bd74f6a231913b0bf49e14f652629ee380e28
49043e84564baa99cf10e5a9cdec85021b1760e8
/include/wifi-telemetry/wifi/wifi_dpp_exchange.hpp
2bee85597cd82c6e0432b9f57f2acb55f1079d80
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
microsoft/wifi-telemetry
235b77344528e5f4f7c61dd02e9c54a471918bb8
52cf172797d480b0a92696448756e8a3125e8a2f
refs/heads/main
2023-05-15T11:25:57.744257
2021-06-11T18:33:00
2021-06-11T18:33:00
368,251,675
6
2
null
null
null
null
UTF-8
C++
false
false
2,472
hpp
wifi_dpp_exchange.hpp
#ifndef __WIFI_DPP_EXCHANGE_HPP__ #define __WIFI_DPP_EXCHANGE_HPP__ #include <chrono> #include <optional> #include <string> #include <unordered_set> #include "wifi-telemetry/wifi/wifi_80211.hpp" #include "wifi-telemetry/wifi/wifi_common.hpp" #include "wifi-telemetry/wifi/wifi_dpp.hpp" struct WifiDppExchange { WifiDppExchange(WifiDppDeviceRole device_role_, WifiDppRole role_) : WifiDppExchange(device_role_, role_, std::chrono::system_clock::now()) {} WifiDppExchange(WifiDppDeviceRole device_role_, WifiDppRole role_, std::chrono::time_point<std::chrono::system_clock> timestamp_start_) : device_role(device_role_), role(role_), timestamp_start(timestamp_start_) {} virtual ~WifiDppExchange(void) = default; void start(void) { if (!timestamp_start) timestamp_start = std::chrono::system_clock::now(); } void stop(void) { if (timestamp_start && !timestamp_end) { timestamp_end = std::chrono::system_clock::now(); duration = std::chrono::duration_cast<std::chrono::milliseconds>(timestamp_end.value() - timestamp_start.value()); } } WifiDppDeviceRole device_role; WifiDppRole role; WifiDppFailureType failure_type = WifiDppFailureType::None; std::optional<std::string> failure_details; std::optional<std::chrono::time_point<std::chrono::system_clock>> timestamp_start; std::optional<std::chrono::time_point<std::chrono::system_clock>> timestamp_end; std::optional<std::chrono::milliseconds> duration; }; struct WifiDppExchangeEnrollee : public WifiDppExchange { WifiDppExchangeEnrollee(WifiDppRole role_) : WifiDppExchange(WifiDppDeviceRole::Enrollee, role_) {} WifiDppExchangeEnrolleeState state = WifiDppExchangeEnrolleeState::Bootstrapping; std::unordered_set<uint32_t> chirp_frequencies; }; struct WifiDppExchangeConfigurator : public WifiDppExchange { WifiDppExchangeConfigurator(int32_t peer_id_, const wifi_80211_mac peer_bssid_, uint32_t frequency_, WifiDppRole role_) : WifiDppExchange(WifiDppDeviceRole::Configurator, role_), peer_id(peer_id_), peer_bssid(peer_bssid_), frequency(frequency_) {} WifiDppExchangeConfiguratorState state = WifiDppExchangeConfiguratorState::Bootstrapping; int32_t peer_id; wifi_80211_mac peer_bssid; uint32_t frequency; }; #endif //__WIFI_DPP_EXCHANGE_HPP__
86f9edf1167805b7d3d01af2112e623d3910e567
0f6d4b49c785c88eb665fe6b39bbe7a8e9801862
/3ds_Max/RealtimeReferencingUtility/RefMenu.cpp
e48e8442ecbc87e12501df936efb557695c2b2b9
[]
no_license
Adolar13/RealtimeReferencing
8cfa8be786ab3e73730a06c3247ef705bb08575c
5c047fd673206a19d474a1d87f623a481ae797b6
refs/heads/master
2021-07-17T19:35:42.585596
2017-10-22T13:45:12
2017-10-22T13:45:12
105,901,272
0
0
null
null
null
null
UTF-8
C++
false
false
3,367
cpp
RefMenu.cpp
#include "RefMenu.h" #include "ui_ref_menu.h" #define Controller SceneController::Instance() RefMenu::RefMenu(QWidget* parent):QWidget(/*parent*/), ui(new Ui::RefMenuRollup()) { ui->setupUi(this); ui->pathEdit->setText("C:/Temp"); //Connect Buttons to functions connect(ui->pathButton, &QPushButton::clicked, [this] {OpenPathExplorer(); }); connect(ui->createNodeButton, &QPushButton::clicked, [this] {CreateButtonClicked(); }); connect(ui->removeNodeButton, &QPushButton::clicked, [this] {RemoveButtonClicked(); }); connect(ui->autoUpdateCheck, &QCheckBox::clicked, [this] {AutoCheckBoxChanged(ui->autoUpdateCheck->isChecked()); }); connect(ui->updateButton, &QPushButton::clicked, [this] {Controller->Update("_refRoot.json"); }); //connect(ui->createNodeButton, &QPushButton::clicked, [this] {Controller->CreateObject(ui->pathEdit->text().toLatin1().data(), "test"); }); //TESTS!!!! //connect(ui->testButton, &QPushButton::clicked, [this] {Controller->TestFunction(); }); } RefMenu::~RefMenu(void) { delete ui; } void RefMenu::OpenPathExplorer() { QFileDialog *fd = new QFileDialog; fd->setFileMode(QFileDialog::Directory); fd->setOption(QFileDialog::ShowDirsOnly); fd->setViewMode(QFileDialog::Detail); fd->setDirectory(ui->pathEdit->text()); int result = fd->exec(); QString directory; if (result) { directory = fd->selectedFiles()[0]; ui->pathEdit->setText(directory); } } void RefMenu::CreateButtonClicked() { if (fileExists(ui->pathEdit->text() + "/_refRoot.json")) { //Update UI ui->createNodeButton->setDisabled(true); ui->removeNodeButton->setDisabled(false); ui->updateButton->setDisabled(false); ui->autoUpdateCheck->setDisabled(false); Controller->CreateRefScene(ui->pathEdit->text().toLatin1().data()); } else { QMessageBox::information( this, tr("Realtime Referencing"), tr("No References found in selected path!")); } } void RefMenu::RemoveButtonClicked() { ui->createNodeButton->setDisabled(false); ui->removeNodeButton->setDisabled(true); ui->updateButton->setDisabled(true); ui->autoUpdateCheck->setDisabled(true); Controller->DeleteRefScene(); } void RefMenu::AddFileWatcher() { watcher = new QFileSystemWatcher(); watcher->addPath(ui->pathEdit->text()); watcher->addPath(ui->pathEdit->text()+"/_refRoot.json"); QStringList directoryList = watcher->directories(); Q_FOREACH(QString directory, directoryList) qDebug() << "Directory name" << directory << "\n"; QObject::connect(watcher, SIGNAL(fileChanged(QString)), this, SLOT(showModified(QString))); } void RefMenu::showModified(const QString& str) { Sleep(10); wchar_t *wchar = new wchar_t[str.length() + 1]; str.toWCharArray(wchar); wchar[str.length()] = 0; QString refR = ui->pathEdit->text() + "/_refRoot.json"; if (str == refR) { Controller->Print(L"Yeah"); Controller->Update("_refRoot.json"); } else { Controller->Print(wchar); std::string s = str.toStdString(); const char* p = s.c_str(); Controller->Update(p); } } void RefMenu::AutoCheckBoxChanged(bool state) { if (state) { AddFileWatcher(); } else { delete watcher; } } bool RefMenu::fileExists(QString path) { QFileInfo check_file(path); // check if file exists and if yes: Is it really a file and no directory? if (check_file.exists() && check_file.isFile()) { return true; } else { return false; } }
1d5eef07517cc773ac28a5498353fab598f71687
08ccece97e72de1954f391fce8c6feab69d09b06
/MusicVisualization/MusicVisualization.h
2051adbeb6a052a3bbd30c0afd0c64de90d9eae7
[]
no_license
MohanChi/MusicVisualization
6f2a63e494d2ad8040f838e48ea6f5dae7d6ed3c
e1516236ad6c08256da65f1876fd1f2db86fa1e0
refs/heads/main
2023-07-01T18:10:13.430060
2021-08-13T03:10:40
2021-08-13T03:10:40
366,259,302
1
0
null
2021-08-13T03:10:40
2021-05-11T04:54:14
C++
UTF-8
C++
false
false
255
h
MusicVisualization.h
#pragma once #include <QtWidgets/QMainWindow> #include "ui_MusicVisualization.h" class MusicVisualization : public QMainWindow { Q_OBJECT public: MusicVisualization(QWidget *parent = Q_NULLPTR); private: Ui::MusicVisualizationClass ui; };
1b9e8869615f4a8aab46efdb6241a8adb5a64ca3
5bfbe0bdec8cf84ab8f80a958ab4e42c3a006e7f
/src/NettleDriver.cpp
ca8cb016baec2412be86351ebc2830fec574a89f
[]
no_license
cpbrew/project
7cb1fd8182a85f22ccb12cfe312fed8e9efa2316
753777870f72be03a25986a8ab4f47ce2dfcbae9
refs/heads/master
2021-01-12T09:31:33.650657
2016-12-14T12:33:58
2016-12-14T12:33:58
76,182,621
0
0
null
null
null
null
UTF-8
C++
false
false
4,711
cpp
NettleDriver.cpp
#include "NettleDriver.h" #include "utils.h" #include <nettle/aes.h> #include <nettle/blowfish.h> #include <nettle/salsa20.h> #include <nettle/arcfour.h> #include <nettle/yarrow.h> #include <nettle/sha2.h> #include <nettle/ripemd160.h> NettleDriver::NettleDriver() { } NettleDriver::~NettleDriver() { } string NettleDriver::encryptAES256(string key, string message) { addPadding(message, AES_BLOCK_SIZE); struct aes256_ctx ctx; const uint8_t *k = (const uint8_t *)key.data(); const uint8_t *m = (const uint8_t *)message.data(); uint8_t *c = new uint8_t[message.length()]; aes256_set_encrypt_key(&ctx, k); aes256_encrypt(&ctx, message.length(), c, m); return string((char *)c, message.length()); } string NettleDriver::decryptAES256(string key, string cipher) { struct aes256_ctx ctx; const uint8_t *k = (const uint8_t *)key.data(); const uint8_t *c = (const uint8_t *)cipher.data(); uint8_t *m = new uint8_t[cipher.length()]; aes256_set_decrypt_key(&ctx, k); aes256_decrypt(&ctx, cipher.length(), m, c); return removePadding(string((char *)m, cipher.length())); } string NettleDriver::encryptBlowfish(string key, string message) { addPadding(message, BLOWFISH_BLOCK_SIZE); struct blowfish_ctx ctx; const uint8_t *k = (const uint8_t *)key.data(); const uint8_t *m = (const uint8_t *)message.data(); uint8_t *c = new uint8_t[message.length()]; blowfish_set_key(&ctx, key.length(), k); blowfish_encrypt(&ctx, message.length(), c, m); return string((char *)c, message.length()); } string NettleDriver::decryptBlowfish(string key, string cipher) { struct blowfish_ctx ctx; const uint8_t *k = (const uint8_t *)key.data(); const uint8_t *c = (const uint8_t *)cipher.data(); uint8_t *m = new uint8_t[cipher.length()]; blowfish_set_key(&ctx, key.length(), k); blowfish_decrypt(&ctx, cipher.length(), m, c); return removePadding(string((char *)m, cipher.length())); } string NettleDriver::processSalsa20(string key, string iv, string message) { struct salsa20_ctx ctx; const uint8_t *k = (const uint8_t *)key.data(); const uint8_t *i = (const uint8_t *)iv.data(); const uint8_t *m = (const uint8_t *)message.data(); uint8_t *c = new uint8_t[message.length()]; salsa20_256_set_key(&ctx, k); salsa20_set_nonce(&ctx, i); salsa20_crypt(&ctx, message.length(), c, m); return string((char *)c, message.length()); } string NettleDriver::processArc4(string key, string message) { struct arcfour_ctx ctx; const uint8_t *k = (const uint8_t *)key.data(); const uint8_t *m = (const uint8_t *)message.data(); uint8_t *c = new uint8_t[message.length()]; arcfour_set_key(&ctx, key.length(), k); arcfour_crypt(&ctx, message.length(), c, m); return string((char *)c, message.length()); } void NettleDriver::generateRSAKeypair(struct rsa_public_key *pub, struct rsa_private_key *priv) { struct yarrow256_ctx ctx; string seed("seed me!"); yarrow256_init(&ctx, 0, NULL); yarrow256_seed(&ctx, seed.length(), (const uint8_t *)seed.data()); rsa_public_key_init(pub); rsa_private_key_init(priv); rsa_generate_keypair(pub, priv, &ctx, (nettle_random_func *)yarrow256_random, NULL, NULL, 2048, 17); } mpz_t *NettleDriver::encryptRSA(struct rsa_public_key key, string message) { mpz_t *c = new mpz_t[1]; mpz_init(*c); struct yarrow256_ctx ctx; string seed("seed me!"); yarrow256_init(&ctx, 0, NULL); yarrow256_seed(&ctx, seed.length(), (const uint8_t *)seed.data()); if (!rsa_encrypt(&key, &ctx, (nettle_random_func *)yarrow256_random, message.length(), (const uint8_t *)message.data(), *c)) abort(); return c; } string NettleDriver::decryptRSA(struct rsa_private_key key, mpz_t *cipher) { size_t len = 10485760; // 10MB uint8_t *m = new uint8_t[len]; if (!rsa_decrypt(&key, &len, m, *cipher)) abort(); return string((char *)m, len); } string NettleDriver::hashSHA512(string message) { struct sha512_ctx ctx; uint8_t *d = new uint8_t[SHA512_DIGEST_SIZE]; sha512_init(&ctx); sha512_update(&ctx, message.length(), (const uint8_t *)message.data()); sha512_digest(&ctx, SHA512_DIGEST_SIZE, d); return btoh((char *)d, SHA512_DIGEST_SIZE); } string NettleDriver::hashRIPEMD160(string message) { struct ripemd160_ctx ctx; uint8_t *d = new uint8_t[RIPEMD160_DIGEST_SIZE]; ripemd160_init(&ctx); ripemd160_update(&ctx, message.length(), (const uint8_t *)message.data()); ripemd160_digest(&ctx, RIPEMD160_DIGEST_SIZE, d); return btoh((char *)d, RIPEMD160_DIGEST_SIZE); }
0a24c0089d5499da20ba78d3334283bcaaffef1b
995dd38f2fc36daadbf91b0d6f09b79b0fd8241e
/ProyectosSDL/HolaSDL/Paddle.cpp
75748036461158f52a301ee71575f4dd2de80437
[]
no_license
CarlosDuranDominguez/TPV
c7dbddb5b59dae7282c06283360b72d9541510a8
31b3571ca104184f7dabeef37706d07c734ef641
refs/heads/master
2020-04-02T07:28:04.713423
2019-04-11T13:53:06
2019-04-11T13:53:06
154,197,731
0
1
null
2018-12-05T20:45:29
2018-10-22T18:47:50
C
UTF-8
C++
false
false
8,790
cpp
Paddle.cpp
#include "Paddle.h" #include <algorithm> #include "ArkanoidSettings.h" #include "Bullet.h" #include "Game.h" Paddle::Paddle() : rightMovement_(false), leftMovement_(false), speed_(0), leftAnchor_(0), rightAnchor_(0), sticky_(false), actionType_() {} Paddle::Paddle(const float32 x, const float32 y, const float32 width, const float32 height, const float32 anchorX, const float32 limit, const float32 maxSpeed, const Actions action, Texture *texture) : ArkanoidBody(x, y, width, height, texture), rightMovement_(false), leftMovement_(false), speed_(maxSpeed), leftAnchor_(anchorX - limit), rightAnchor_(anchorX + limit), sticky_(true), actionType_(action) { setAction(action); setBody(x, y, width, height, anchorX, limit, *Game::getWorld()); } void Paddle::setSticky(const bool sticky) { sticky_ = sticky; } // Destructor Paddle::~Paddle() { for (auto joint : joints_) { delete joint; } joints_.clear(); } // Defines the update behaviour for this instance void Paddle::update() { for (auto joint : joints_) { const auto pos = getPosition() + joint->distance_; joint->ball_->setPosition(pos.x, pos.y); } } // Defines the after update behaviour for this instance void Paddle::afterUpdate() { // Get position const auto pos = body_->GetPosition(); // If the paddle is in the walls, move it inside the area if (pos.x - size_.x / 2.0f < leftAnchor_) { setPosition(leftAnchor_ + size_.x / 2.0f, pos.y); } else if (pos.x + size_.x / 2.0f > rightAnchor_) { setPosition(rightAnchor_ - size_.x / 2.0f, pos.y); } } /// Public Virtual // Defines the render behaviour void Paddle::render() const { const auto pos = body_->GetPosition(); texture_->render({int(pos.x) - int(size_.x) / 2, int(pos.y) - int(size_.y) / 2, int(size_.x), int(size_.y)}); } // Defines the event handler behaviour void Paddle::handleEvents(const SDL_Event event) { switch (event.type) { // If it's a key press case SDL_KEYDOWN: switch (event.key.keysym.sym) { // If right arrow was pressed, set rightMovement to true case SDLK_RIGHT: rightMovement_ = true; break; // If left arrow was pressed, set leftMovement to true case SDLK_LEFT: leftMovement_ = true; break; // If space bar was pressed, call _action() case SDLK_SPACE: State::current_->addEvent(action_); break; default: break; } break; // If it's a key leave case SDL_KEYUP: switch (event.key.keysym.sym) { // If the right arrow was unpressed, set rightMovement to false case SDLK_RIGHT: rightMovement_ = false; break; // If the left arrow was unpressed, set leftMovement to false case SDLK_LEFT: leftMovement_ = false; break; default: break; } default: break; } // Set the velocity setVelocity(b2Vec2{ (rightMovement_ ? speed_ : 0) + (leftMovement_ ? -speed_ : 0), 0.0f}); } // Defines behaviour when the instance starts to have contact with an element void Paddle::onBeginContact(RigidBody *rigidBody) { Ball *ball; if (sticky_ && (ball = dynamic_cast<Ball *>(rigidBody))) { State::current_->addEvent([this, ball]() { jointTo(ball); }); } } // Defines the setWidth behaviour void Paddle::setWidth(const float32 width) { // Gets the position and linear velocity, then destroy the fixture and the // body const auto pos = body_->GetPosition(); auto vel = body_->GetLinearVelocity(); body_->DestroyFixture(fixture_); Game::getWorld()->DestroyBody(body_); // Sets the new width and creates a new body and velocity size_.x = width; setBody(pos.x, pos.y, width, size_.y, leftAnchor_ - rightAnchor_, (rightAnchor_ - leftAnchor_) / 2.0f, *Game::getWorld()); setVelocity(vel); } /// Public // Creates a joint to a ball (for the sticky paddle) void Paddle::jointTo(Ball *ball) { if (!any_of(joints_.begin(), joints_.end(), [ball](ArkanoidJoint *joint) { return joint->ball_ == ball; })) { auto a = ball->getPosition() - getPosition(); joints_.push_back(new ArkanoidJoint(ball, a)); ball->getBody()->SetActive(false); } } // Splits from a ball, releasing it to a direction away from the paddle's center void Paddle::splitFromBalls() { for (auto joint : joints_) { joint->ball_->getBody()->SetActive(true); joint->distance_ *= (1.0f / (joint->distance_.LengthSquared() * joint->ball_->getSpeed())); joint->ball_->setVelocity(joint->distance_); delete joint; } joints_.clear(); } // Defines the deserialize method behaviour to patch the instance when loading a // file save std::istream &Paddle::deserialize(std::istream &out) { texture_ = readTexture(out); float32 posx, posy, sizex, sizey; int action; out >> posx >> posy >> sizex >> sizey >> speed_ >> action; setBody(posx, posy, sizex, sizey, ArkanoidSettings::sceneUpperLeftCorner_.x + ArkanoidSettings::sceneWidth_ / 2.0f, (ArkanoidSettings::sceneWidth_) / 2 - ArkanoidSettings::wallWidth_, *Game::getWorld()); setPosition(posx, posy); size_.Set(sizex, sizey); leftAnchor_ = ArkanoidSettings::sceneUpperLeftCorner_.x + ArkanoidSettings::wallWidth_; rightAnchor_ = ArkanoidSettings::sceneUpperLeftCorner_.x + ArkanoidSettings::sceneWidth_ - ArkanoidSettings::wallWidth_; leftMovement_ = false; rightMovement_ = false; actionType_ = Actions(action); setAction(actionType_); return out; } // Defines the serialize method behaviour to save the data into a file save std::ostream &Paddle::serialize(std::ostream &is) const { return is << "Paddle " << textureIndex() << " " << getPosition().x << " " << getPosition().y << " " << getSize().x << " " << getSize().y << " " << speed_ << actionType_; } // setBody method, creates a kinematic chain shape with Box2D's API void Paddle::setBody(float32 x, float32 y, float32 width, float32 height, float32 anchorX, float32 limit, b2World &world) { // Create the body definition b2BodyDef bodyDef; bodyDef.type = b2_kinematicBody; bodyDef.fixedRotation = true; bodyDef.position.x = x; bodyDef.position.y = y; bodyDef.linearDamping = 0.0f; bodyDef.userData = static_cast<RigidBody *>(this); // Create an array of 2D vectors b2Vec2 vs[6]; vs[0].Set(-width / 2.0f, height / 2.0f); vs[1].Set(-width * 3.0f / 8.0f, -height / 4.0f); vs[2].Set(-width / 8.0f, -height / 2.0f); vs[3].Set(width / 8.0f, -height / 2.0f); vs[4].Set(width * 3.0f / 8.0f, -height / 4.0f); vs[5].Set(width / 2.0f, height / 2.0f); // Create a chain shape and set the array of vectors b2ChainShape shape; shape.CreateChain(vs, 6); // Create the fixture definition b2FixtureDef fixtureDef; fixtureDef.density = 1000000.0f; fixtureDef.filter.categoryBits = 0b0000'0000'0000'0000'0001; fixtureDef.filter.maskBits = 0b0000'0000'0000'0011'0010; fixtureDef.friction = 0.0f; fixtureDef.restitution = 1.0f; fixtureDef.shape = &shape; // Add the body definition to world body_ = world.CreateBody(&bodyDef); // Set up the shape setUp(shape, fixtureDef); } // Defines the setWidth behaviour void Paddle::setAction(const Actions action) { actionType_ = action; // Set the proper action. switch (action) { case NONE: splitFromBalls(); setSticky(false); action_ = []() {}; break; case BEGIN: splitFromBalls(); setSticky(true); action_ = [this]() { splitFromBalls(); setSticky(false); }; break; case STICKY: setSticky(true); action_ = [this]() { splitFromBalls(); }; break; case LASER: splitFromBalls(); setSticky(false); action_ = [this]() { /*Create Bullet*/ auto bullet = new Bullet(getPosition().x, getPosition().y, 10.0f, 1000.0f, Game::current_->getTextures()[BALLBLACK]); State::current_->add(*bullet); bullet->setVelocity(b2Vec2{0, -1000.0f}); }; break; default: break; } } Paddle::ArkanoidJoint::ArkanoidJoint(Ball *ball, b2Vec2 &distance) : distance_(distance), ball_(ball) {} Paddle::ArkanoidJoint::~ArkanoidJoint() = default;