blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
fa02e5faf7de60130c977137a0b4b7884df3e60a
ba8624315e0b9cbd7638d6d341dbb04b46445a1c
/wordCount/input_output.cpp
d21c58baef8d98b76022f9b75ec5757fc2fc2d13
[]
no_license
Robot-Blitzcrank/wordCount
5b5793ca67a1b0f4beaf94e493d7391920ba5361
79b9581dc52e57093a9b19511507bcc5ecf4ff2c
refs/heads/master
2020-08-21T09:40:25.116653
2019-10-20T07:10:54
2019-10-20T07:10:54
216,133,119
1
12
null
2019-10-20T07:10:55
2019-10-19T01:35:09
C++
UTF-8
C++
false
false
613
cpp
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fstream> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int m,n; string msg; int i; fstream infile(argv[2],ios::in); fstream outfile(argv[4],ios::out); infile>>msg; if(argv[6]=="-n") { n=atoi(argv[7]); m=0; } else if(argv[7]=="-n"&&argv[8]==NULL) { m=atoi(argv[6]); n=0; } else { m = atoi(argv[6]); n = atoi(argv[8]); } outfile<<msg; return 0; }
[ "noreply@github.com" ]
noreply@github.com
c2a809fe7796407d27ff8e4de9b2e45227a8eff2
18a3f93e4b94f4f24ff17280c2820497e019b3db
/geant4/G4StackManager.hh
ba7075eeeb5648f2b2b0960f7ecf901a0d9d37de
[]
no_license
jjzhang166/BOSS_ExternalLibs
0e381d8420cea17e549d5cae5b04a216fc8a01d7
9b3b30f7874ed00a582aa9526c23ca89678bf796
refs/heads/master
2023-03-15T22:24:21.249109
2020-11-22T15:11:45
2020-11-22T15:11:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,242
hh
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // // $Id: G4StackManager.hh,v 1.13 2009/08/15 15:45:50 asaim Exp $ // GEANT4 tag $Name: geant4-09-03-patch-01 $ // // #ifndef G4StackManager_h #define G4StackManager_h 1 #include "G4UserStackingAction.hh" #include "G4StackedTrack.hh" #include "G4TrackStack.hh" #include "G4SmartTrackStack.hh" #include "G4ClassificationOfNewTrack.hh" #include "G4Track.hh" #include "G4TrackStatus.hh" #include "globals.hh" #include "evmandefs.hh" class G4StackingMessenger; class G4VTrajectory; // class description: // // This is the manager class of handling stacks of G4Track objects. // This class must be a singleton and be constructed by G4EventManager. // Almost all methods must be invoked exclusively by G4EventManager. // Especially, some Clear() methods MUST NOT be invoked by the user. // Event abortion is handled by G4EventManager. // // This G4StackingManager has three stacks, the urgent stack, the // waiting stack, and the postpone to next event stack. The meanings // of each stack is descrived in the Geant4 user's manual. // class G4StackManager { public: G4StackManager(); ~G4StackManager(); private: const G4StackManager & operator= (const G4StackManager &right); G4int operator==(const G4StackManager &right) const; G4int operator!=(const G4StackManager &right) const; public: G4int PushOneTrack(G4Track *newTrack, G4VTrajectory *newTrajectory = 0); G4Track * PopNextTrack(G4VTrajectory**newTrajectory); G4int PrepareNewEvent(); public: // with description void ReClassify(); // Send all tracks stored in the Urgent stack one by one to // the user's concrete ClassifyNewTrack() method. This method // can be invoked from the user's G4UserStackingAction concrete // class, especially fron its NewStage() method. Be aware that // when the urgent stack becomes empty, all tracks in the waiting // stack are send to the urgent stack and then the user's NewStage() // method is invoked. void SetNumberOfAdditionalWaitingStacks(G4int iAdd); // Set the number of additional (optional) waiting stacks. // This method must be invoked at PreInit, Init or Idle states. // Once the user set the number of additional waiting stacks, // he/she can use the corresponding ENUM in G4ClassificationOfNewTrack. // The user should invoke G4RunManager::SetNumberOfAdditionalWaitingStacks // method, which invokes this method. void TransferStackedTracks(G4ClassificationOfNewTrack origin, G4ClassificationOfNewTrack destination); // Transfter all stacked tracks from the origin stack to the destination stack. // The destination stack needs not be empty. // If the destination is fKill, tracks are deleted. // If the origin is fKill, nothing happen. void TransferOneStackedTrack(G4ClassificationOfNewTrack origin, G4ClassificationOfNewTrack destination); // Transfter one stacked track from the origin stack to the destination stack. // The transfered track is the one which came last to the origin stack. // The destination stack needs not be empty. // If the destination is fKill, the track is deleted. // If the origin is fKill, nothing happen. private: G4UserStackingAction * userStackingAction; G4int verboseLevel; #ifdef G4_USESMARTSTACK G4SmartTrackStack * urgentStack; #else G4TrackStack * urgentStack; #endif G4TrackStack * waitingStack; G4TrackStack * postponeStack; G4StackingMessenger* theMessenger; std::vector<G4TrackStack*> additionalWaitingStacks; G4int numberOfAdditionalWaitingStacks; public: inline void clear() { ClearUrgentStack(); ClearWaitingStack(); for(int i=1;i<=numberOfAdditionalWaitingStacks;i++) {ClearWaitingStack(i);} } inline void ClearUrgentStack() { urgentStack->clear(); } inline void ClearWaitingStack(int i=0) { if(i==0) { waitingStack->clear(); } else { if(i<=numberOfAdditionalWaitingStacks) additionalWaitingStacks[i-1]->clear(); } } inline void ClearPostponeStack() { postponeStack->clear(); } inline G4int GetNTotalTrack() const { int n = urgentStack->GetNTrack() + waitingStack->GetNTrack() + postponeStack->GetNTrack(); for(int i=1;i<=numberOfAdditionalWaitingStacks;i++) {n += additionalWaitingStacks[i-1]->GetNTrack();} return n; } inline G4int GetNUrgentTrack() const { return urgentStack->GetNTrack(); } inline G4int GetNWaitingTrack(int i=0) const { if(i==0) { return waitingStack->GetNTrack(); } else { if(i<=numberOfAdditionalWaitingStacks) { return additionalWaitingStacks[i-1]->GetNTrack();} } return 0; } inline G4int GetNPostponedTrack() const { return postponeStack->GetNTrack(); } inline void SetVerboseLevel( G4int const value ) { verboseLevel = value; } inline void SetUserStackingAction(G4UserStackingAction* value) { userStackingAction = value; if(userStackingAction) userStackingAction->SetStackManager(this); } private: inline G4ClassificationOfNewTrack DefaultClassification(G4Track *aTrack) { G4ClassificationOfNewTrack classification = fUrgent; if( aTrack->GetTrackStatus() == fPostponeToNextEvent ) { classification = fPostpone; } return classification; } }; #endif
[ "r.e.deboer@students.uu.nl" ]
r.e.deboer@students.uu.nl
4ff2d301201891145ed6d4173c9aef4d3c29bb19
2c970e8367555e963c94db249ed722bd6389d0d8
/MuddyGames-gameplay-programming-i-lab-03-60ce4b8b1ccb/AnimationFSM/Left.cpp
7b326a430b0bd518bdd976ddd60624978e199ebf
[]
no_license
PaulJame5/AnimFSM
ea9e19130358085426bddc288f0d101d6e1a62e9
9e8e77c1356d7679c52474b9a40494e97abede1a
refs/heads/master
2020-04-05T08:01:14.040533
2018-11-12T10:52:28
2018-11-12T10:52:28
156,697,729
0
0
null
null
null
null
UTF-8
C++
false
false
1,110
cpp
#include <Left.h> #include <Attacking.h> #include <Climbing.h> #include <Jumping.h> #include <Right.h> #include <Idle.h> #include <Windows.h> #include <string> void Left::idle(PlayerFSM* a) { std::cout << "Left -> Idle" << std::endl; Beep(523, 500); // 523 hertz (C5) for 500 milliseconds a->setCurrent(new Idle()); delete this; } void Left::jumping(PlayerFSM* a) { std::cout << "Left -> Jump" << std::endl; Beep(523, 500); // 523 hertz (C5) for 500 milliseconds a->setCurrent(new Jumping()); delete this; } void Left::attacking(PlayerFSM* a) { std::cout << "Left -> Attacking" << std::endl; Beep(523, 500); // 523 hertz (C5) for 500 milliseconds a->setCurrent(new Attacking()); delete this; } void Left::climbing(PlayerFSM* a) { std::cout << "Left -> Climbing" << std::endl; Beep(523, 500); // 523 hertz (C5) for 500 milliseconds a->setCurrent(new Climbing()); delete this; } void Left::right(PlayerFSM * a) { std::cout << "Left -> Right" << std::endl; Beep(523, 500); // 523 hertz (C5) for 500 milliseconds a->setCurrent(new Right()); delete this; }
[ "noreply@github.com" ]
noreply@github.com
b48b175188e69d18b4c0ea886161361fc49cbd99
123fc737f01a88e58c6eb3ca7ad0e51e867ff434
/bayesbr/src/RcppExports.cpp
f1ff495afd20afaa916edad3ea62bf4e6f923fd3
[]
no_license
akhikolla/ClusterTests
e12e5486fc1a80609a956fcb7f432b47e8174b0f
1c7702ba4035511ffe7d4dd27e9021b6962718fe
refs/heads/master
2022-12-10T13:00:09.654663
2020-09-14T19:12:37
2020-09-14T19:12:37
295,513,576
2
0
null
null
null
null
UTF-8
C++
false
false
550
cpp
// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include <Rcpp.h> using namespace Rcpp; RcppExport SEXP _rcpp_module_boot_stan_fit4bayesbr_mod(); static const R_CallMethodDef CallEntries[] = { {"_rcpp_module_boot_stan_fit4bayesbr_mod", (DL_FUNC) &_rcpp_module_boot_stan_fit4bayesbr_mod, 0}, {NULL, NULL, 0} }; RcppExport void R_init_bayesbr(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); }
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
a18aad42e28f621093434a0c4ffc9d029a029825
a1932503f909f06a81862ad4eef5deaaa0a7b493
/ImagingEngineLib/include/data/data_definition.h
0d12fea249f597cc1ccae0685ea1e3fd8d634989
[]
no_license
jia1000/SvrCallImageEngine
0b8cb5d8d597243f1a1bf086c5f15b116826de8e
36a5e6076863578044cbddd043b3119df7eaf729
refs/heads/master
2020-05-29T21:16:17.765768
2019-06-27T10:11:05
2019-06-27T10:11:05
189,375,640
0
0
null
null
null
null
GB18030
C++
false
false
2,168
h
/*========================================================================= Program: ImagingEngine Module: data_definition.h author: zhangjian Brief: =========================================================================*/ #pragma once // Windows 头文件: #ifdef WIN32 #include <windows.h> #else #endif // C 运行时头文件 #include <stdlib.h> #include <malloc.h> #include <memory.h> //#include <tchar.h> #include <stdio.h> #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <stdint.h> #include <string> #include "tools/logger.h" #define UNITDATA3D unsigned char #define UNITMARK3D unsigned char #define UNITDATASHOW char #define MAXIMIUM_CT_VALUE 4096 #define MAXIMIUM_THREADS 16 #ifdef WIN32 #else typedef unsigned char BYTE; typedef int BOOL; typedef unsigned long DWORD; typedef unsigned short WORD; #endif // Error code #define RET_STATUS_IE_SUCCESS 1 #define RET_STATUS_IE_FAILURE 0 #define RET_STATUS_IE_NOT_ENOUGH_MEMORY 1 #define RET_STATUS_IE_IO_DISK_CANNOT_WRITE 1 #define RET_STATUS_IE_IO_DISK_NO_SPACE 1 #define RET_STATUS_IE_IO_FILE_EXIST 1 #define RET_STATUS_IE_INPUT_INVALID_PARAM 1 #define RET_STATUS_IE_DATA_SMALL_IMAGE_NUMBER 1 #define RET_STATUS_IE_DATA_NOT_CT_IMAGE 1 #define RET_STATUS_IE_DATA_NOT_SUPPORTED_CT_IMAGE 1 #define RET_STATUS_IE_DATA_DIFFERENCT_SPACING 1 #define RET_STATUS_IE_DATA_NOT_CONTINUOUS_POSITION 1 #define RET_STATUS_IE_LIB_NOT_FOUND 1 #define RET_STATUS_IE_LIB_WRONG_VERSION 1 #define RET_STATUS_IE_EXCEPTION_NULL_POINTER 1 #define RET_STATUS_IE_EXCEPTION_INVALID_POINTER 1 #define RET_STATUS_IE_EXCEPTION_READONLY 1 #define RET_STATUS_IE_EXCEPTION_NO_DATA 1 using namespace std; #define PI 3.14159265f //typedef enum dwRenderMode { // Slice = 0, // Slab, // MPR, // VR, // CPR //} RenderMode; struct Point3d { float x; float y; float z; }; struct Point3f { float x; float y; float z; }; struct Point3i { int x; int y; int z; }; struct Point2 { int x; int y; };
[ "" ]
4e1ee0ce4f0c991e08e84948ce7ac44387cc588f
15cfbd560bd19935fa64507750a36e4f05f0b504
/Project/ms5/IOAble.cpp
15c51f45a877d844cc100222db65c4d89f35a761
[]
no_license
Filipefreitas/OOP244
213925ef651818e02ff3f24b2c0e3c781c4620fe
8a1463cf558a311a93b800c157990ef1dd39967b
refs/heads/main
2023-04-30T04:38:57.282797
2021-05-13T19:21:54
2021-05-13T19:21:54
367,147,007
1
0
null
null
null
null
UTF-8
C++
false
false
707
cpp
/* Final Project Milestone 2 Modelue: IOAble File: IOAble.cpp Author: Filipe da Cunha de Freitas ID: 155737190 Revision History ----------------------------------------------------------- Date Reason 15/nov Developed all functions; ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. */ #include <iostream> #include "IOAble.h" using namespace std; namespace sdds { std::ostream& operator<<(std::ostream& ostr, const IOAble& I) { return I.write(ostr); } std::istream& operator>>(std::istream& istr, IOAble& I) { return I.read(istr); } }
[ "noreply@github.com" ]
noreply@github.com
c2e358c2cbd11a021614c697c61108ca4e131c68
f6fa1c14a928fb961d57a57ee6661523d64d8b99
/week2/monday/cpp03.cpp
0c3222f2b42d32a2e6df9aa3346eaf675a2d2de4
[]
no_license
greenfox-zerda-sparta/Judo3579
eeb31d14eac363aa73ee9a115c73c14db38b98cc
6e638704aeac1637afdfc5307d84ec5e0db70357
refs/heads/master
2021-01-13T07:30:25.466374
2017-02-17T13:35:25
2017-02-17T13:35:25
71,350,969
0
1
null
null
null
null
UTF-8
C++
false
false
432
cpp
//============================================================================ // Name : Hello.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <string> using namespace std; int main() { int c = 44; c *= 2; cout<< c; return 0; }
[ "istvan.judit5@gmail.com" ]
istvan.judit5@gmail.com
fa96c15a57ff45e740d7996ad89c9498ae7f1b49
c3081f8f60de5d36883b38ab789cfc7ad0bc3902
/Atom/kocka.cpp
6ad9e1572b58eee21d2f34935ef8b5ba833b447b
[]
no_license
Arrygon/atomWin7
68fe7e799eb1e47a32b8ce9ba354687407c309cc
10aa418b5cf12640934f3d79bd0e09063e11a663
refs/heads/master
2020-03-18T17:53:57.804007
2018-06-03T20:36:55
2018-06-03T20:36:55
135,058,581
0
0
null
null
null
null
UTF-8
C++
false
false
359
cpp
#include <iostream> #include <windows.h> using namespace std; int main(){ system("color 02"); int a,b; a = 1; for(int i=0; i<5; i++){ for(int j=1; j<9; j++){ cout << "\xdb"; } cout << a; a++; cout << endl; } for(int o=1; o<9; o++){ b = o; cout << b; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
a0e8b6811443959fa9e4c19168042b6e66ac52b0
ee507b3010c903ec716315f7df2ba4ef5ae5921a
/storm/storm3dv2/storm3d_terrain_groups.h
c2c507fc307d496c08848107a5860122e32ec266
[]
no_license
sopyer/Shadowgrounds
ac6b281cd95d762096dfc04ddae70d3f3e63be05
691cb389c7d8121eda85ea73409bbbb74bfdb103
refs/heads/master
2020-03-29T18:25:48.103837
2017-06-24T17:08:50
2017-06-24T17:08:50
9,700,603
0
1
null
null
null
null
UTF-8
C++
false
false
1,909
h
// Copyright 2002-2004 Frozenbyte Ltd. #ifndef INCLUDED_STORM3D_TERRAIN_GROUP_H #define INCLUDED_STORM3D_TERRAIN_GROUP_H #include "IStorm3D_Terrain.h" class Storm3D; class Storm3D_Scene; class Storm3D_Camera; class Storm3D_Model; class Storm3D_TerrainModels; struct Storm3D_TerrainGroupData; class Storm3D_TerrainGroup { Storm3D_TerrainGroupData* data; public: Storm3D_TerrainGroup(Storm3D &storm, Storm3D_TerrainModels &models); ~Storm3D_TerrainGroup(); int addModel(std::shared_ptr<Storm3D_Model> model, std::shared_ptr<Storm3D_Model> fadeModel, const std::string &bones, const std::string &idleAnimation); void removeModels(); int addInstance(int modeld, const VC3 &position, const QUAT &rotation, const COL &color); void removeInstance(int modelId, int instanceId); void setInstancePosition(int modelId, int instanceId, const VC3 &position); void setInstanceRotation(int modelId, int instanceId, const QUAT &rotation); void setInstanceLight(int modelId, int instanceId, int light, int lightId, const COL &color); void setInstanceSun(int modelId, int instanceId, const VC3 &direction, float strength); void setInstanceLightmapped(int modelId, int instanceId, bool lightmapped); void setInstanceFade(int modelId, int instanceId, float factor); void setInstanceInBuilding(int modelId, int instanceId, bool inBuilding); void setInstanceOccluded(int modelId, int instanceId, bool occluded); void removeInstances(); void setInstanceColorsToMultiplier(const COL &color); IStorm3D_Model *getInstanceModel(int modelId, int instanceId); void enableCollision(bool enable); void enableBigCollision(bool enable); void enableLightmapCollision(bool enable); void setSceneSize(const VC3 &size); std::shared_ptr<IStorm3D_TerrainModelIterator> getModelIterator(const VC3 &position, float radius); bool findObject(const VC3 &position, float radius, int &modelId, int &instanceId); }; #endif
[ "sopyer@gmail.com" ]
sopyer@gmail.com
c6036cb151c0318a6d5ee5e4c72cf0e0227fbb55
49f88ff91aa582e1a9d5ae5a7014f5c07eab7503
/gen/third_party/perfetto/protos/perfetto/trace/ftrace/mm_compaction_migratepages.pbzero.cc
e2645b2404a3ac875e48347a55a2482acc464099
[]
no_license
AoEiuV020/kiwibrowser-arm64
b6c719b5f35d65906ae08503ec32f6775c9bb048
ae7383776e0978b945e85e54242b4e3f7b930284
refs/heads/main
2023-06-01T21:09:33.928929
2021-06-22T15:56:53
2021-06-22T15:56:53
379,186,747
0
1
null
null
null
null
UTF-8
C++
false
false
1,028
cc
// Autogenerated by the ProtoZero compiler plugin. DO NOT EDIT. #include "perfetto/trace/ftrace/mm_compaction_migratepages.pbzero.h" namespace { static const ::protozero::ProtoFieldDescriptor kInvalidField = {"", ::protozero::ProtoFieldDescriptor::Type::TYPE_INVALID, 0, false}; } namespace perfetto { namespace protos { namespace pbzero { static const ::protozero::ProtoFieldDescriptor kFields_MmCompactionMigratepagesFtraceEvent[] = { {"nr_migrated", ::protozero::ProtoFieldDescriptor::Type::TYPE_UINT64, 1, 0}, {"nr_failed", ::protozero::ProtoFieldDescriptor::Type::TYPE_UINT64, 2, 0}, }; const ::protozero::ProtoFieldDescriptor* MmCompactionMigratepagesFtraceEvent::GetFieldDescriptor(uint32_t field_id) { switch (field_id) { case kNrMigratedFieldNumber: return &kFields_MmCompactionMigratepagesFtraceEvent[0]; case kNrFailedFieldNumber: return &kFields_MmCompactionMigratepagesFtraceEvent[1]; default: return &kInvalidField; } } } // Namespace. } // Namespace. } // Namespace.
[ "aoeiuv020@gmail.com" ]
aoeiuv020@gmail.com
9569eea8843d4bafaec3bc7d239cc9c2af789b6e
fae551eb54ab3a907ba13cf38aba1db288708d92
/chrome/browser/ui/webui/settings/chromeos/device_name_handler.cc
d65abda54803bc8cac83c2a96fff099555537494
[ "BSD-3-Clause" ]
permissive
xtblock/chromium
d4506722fc6e4c9bc04b54921a4382165d875f9a
5fe0705b86e692c65684cdb067d9b452cc5f063f
refs/heads/main
2023-04-26T18:34:42.207215
2021-05-27T04:45:24
2021-05-27T04:45:24
371,258,442
2
1
BSD-3-Clause
2021-05-27T05:36:28
2021-05-27T05:36:28
null
UTF-8
C++
false
false
1,168
cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/settings/chromeos/device_name_handler.h" #include <string> #include "base/check.h" #include "base/values.h" #include "chrome/browser/chromeos/device_name_store.h" #include "content/public/browser/web_ui.h" namespace chromeos { namespace settings { void DeviceNameHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( "getDeviceNameMetadata", base::BindRepeating(&DeviceNameHandler::HandleGetDeviceNameMetadata, base::Unretained(this))); } void DeviceNameHandler::HandleGetDeviceNameMetadata( const base::ListValue* args) { AllowJavascript(); CHECK_EQ(1U, args->GetSize()); std::string callback_id; CHECK(args->GetString(0, &callback_id)); base::DictionaryValue metadata; metadata.SetString("deviceName", DeviceNameStore::GetInstance()->GetDeviceName()); ResolveJavascriptCallback(base::Value(callback_id), metadata); } } // namespace settings } // namespace chromeos
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
41e2e231fc8279fd631df4e28384b23bc78e06c0
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-devicefarm/source/model/UpdateNetworkProfileRequest.cpp
2faf6a2204688c9de1c11f2067b3dc847746716e
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
2,787
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/devicefarm/model/UpdateNetworkProfileRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::DeviceFarm::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateNetworkProfileRequest::UpdateNetworkProfileRequest() : m_arnHasBeenSet(false), m_nameHasBeenSet(false), m_descriptionHasBeenSet(false), m_type(NetworkProfileType::NOT_SET), m_typeHasBeenSet(false), m_uplinkBandwidthBits(0), m_uplinkBandwidthBitsHasBeenSet(false), m_downlinkBandwidthBits(0), m_downlinkBandwidthBitsHasBeenSet(false), m_uplinkDelayMs(0), m_uplinkDelayMsHasBeenSet(false), m_downlinkDelayMs(0), m_downlinkDelayMsHasBeenSet(false), m_uplinkJitterMs(0), m_uplinkJitterMsHasBeenSet(false), m_downlinkJitterMs(0), m_downlinkJitterMsHasBeenSet(false), m_uplinkLossPercent(0), m_uplinkLossPercentHasBeenSet(false), m_downlinkLossPercent(0), m_downlinkLossPercentHasBeenSet(false) { } Aws::String UpdateNetworkProfileRequest::SerializePayload() const { JsonValue payload; if(m_arnHasBeenSet) { payload.WithString("arn", m_arn); } if(m_nameHasBeenSet) { payload.WithString("name", m_name); } if(m_descriptionHasBeenSet) { payload.WithString("description", m_description); } if(m_typeHasBeenSet) { payload.WithString("type", NetworkProfileTypeMapper::GetNameForNetworkProfileType(m_type)); } if(m_uplinkBandwidthBitsHasBeenSet) { payload.WithInt64("uplinkBandwidthBits", m_uplinkBandwidthBits); } if(m_downlinkBandwidthBitsHasBeenSet) { payload.WithInt64("downlinkBandwidthBits", m_downlinkBandwidthBits); } if(m_uplinkDelayMsHasBeenSet) { payload.WithInt64("uplinkDelayMs", m_uplinkDelayMs); } if(m_downlinkDelayMsHasBeenSet) { payload.WithInt64("downlinkDelayMs", m_downlinkDelayMs); } if(m_uplinkJitterMsHasBeenSet) { payload.WithInt64("uplinkJitterMs", m_uplinkJitterMs); } if(m_downlinkJitterMsHasBeenSet) { payload.WithInt64("downlinkJitterMs", m_downlinkJitterMs); } if(m_uplinkLossPercentHasBeenSet) { payload.WithInteger("uplinkLossPercent", m_uplinkLossPercent); } if(m_downlinkLossPercentHasBeenSet) { payload.WithInteger("downlinkLossPercent", m_downlinkLossPercent); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection UpdateNetworkProfileRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "DeviceFarm_20150623.UpdateNetworkProfile")); return headers; }
[ "sdavtaker@users.noreply.github.com" ]
sdavtaker@users.noreply.github.com
a545e69d66adbe499105d1ce97678084b3b5e738
3e07145d76d3cf0a97ddd13459a5428acf8c32a7
/px_comm/dds_msg/DDSImageSupport.cxx
67afbecbe5d2307ebf86e68460d5ace2bf80a9f5
[]
no_license
theluke55/px-ros-pkg
6adf3a9a2ecf964f47bb791e510e730fb487230d
549a78f6d0d4064a60aef79fa19ed7836d990d1d
refs/heads/master
2021-01-15T11:24:17.108019
2014-04-09T11:59:07
2014-04-09T11:59:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,820
cxx
/* WARNING: THIS FILE IS AUTO-GENERATED. DO NOT MODIFY. This file was generated from DDSImage.idl using "rtiddsgen". The rtiddsgen tool is part of the RTI Connext distribution. For more information, type 'rtiddsgen -help' at a command shell or consult the RTI Connext manual. */ #include "DDSImageSupport.h" #include "DDSImagePlugin.h" #ifdef __cplusplus #ifndef dds_c_log_impl_h #include "dds_c/dds_c_log_impl.h" #endif #endif namespace px_comm{ /* ========================================================================= */ /** <<IMPLEMENTATION>> Defines: TData, TDataWriter, TDataReader, TTypeSupport Configure and implement 'DDSImage' support classes. Note: Only the #defined classes get defined */ /* ----------------------------------------------------------------- */ /* DDSDataWriter */ /** <<IMPLEMENTATION >> Defines: TDataWriter, TData */ /* Requires */ #define TTYPENAME DDSImageTYPENAME /* Defines */ #define TDataWriter DDSImageDataWriter #define TData ::px_comm::DDSImage #ifdef __cplusplus #include "dds_cpp/generic/dds_cpp_data_TDataWriter.gen" #else #include "dds_c/generic/dds_c_data_TDataWriter.gen" #endif #undef TDataWriter #undef TData #undef TTYPENAME /* ----------------------------------------------------------------- */ /* DDSDataReader */ /** <<IMPLEMENTATION >> Defines: TDataReader, TDataSeq, TData */ /* Requires */ #define TTYPENAME DDSImageTYPENAME /* Defines */ #define TDataReader DDSImageDataReader #define TDataSeq DDSImageSeq #define TData ::px_comm::DDSImage #ifdef __cplusplus #include "dds_cpp/generic/dds_cpp_data_TDataReader.gen" #else #include "dds_c/generic/dds_c_data_TDataReader.gen" #endif #undef TDataReader #undef TDataSeq #undef TData #undef TTYPENAME /* ----------------------------------------------------------------- */ /* TypeSupport <<IMPLEMENTATION >> Requires: TTYPENAME, TPlugin_new TPlugin_delete Defines: TTypeSupport, TData, TDataReader, TDataWriter */ /* Requires */ #define TTYPENAME DDSImageTYPENAME #define TPlugin_new ::px_comm::DDSImagePlugin_new #define TPlugin_delete ::px_comm::DDSImagePlugin_delete /* Defines */ #define TTypeSupport DDSImageTypeSupport #define TData ::px_comm::DDSImage #define TDataReader DDSImageDataReader #define TDataWriter DDSImageDataWriter #ifdef __cplusplus #include "dds_cpp/generic/dds_cpp_data_TTypeSupport.gen" #else #include "dds_c/generic/dds_c_data_TTypeSupport.gen" #endif #undef TTypeSupport #undef TData #undef TDataReader #undef TDataWriter #undef TTYPENAME #undef TPlugin_new #undef TPlugin_delete } /* namespace px_comm */
[ "hengli@student.ethz.ch" ]
hengli@student.ethz.ch
6a23650315d3f833870d59152db6bee06db431b1
bc5de71a0852816d8510b9fa30207150e3d467f1
/players/players.hh
9a7802b61287de7ba226ee8ea68b9c706330369d
[ "MIT" ]
permissive
takashi-chikayama/SamurAI-Dig-Here-2020-21
b03915b65b04bf38d0223899dc6c112155db6d74
803558a7f07d39f5b637e3711f137c5789a180ea
refs/heads/master
2023-03-27T20:20:14.555996
2021-03-23T10:50:33
2021-03-23T10:50:33
295,876,171
1
4
NOASSERTION
2020-11-27T10:44:48
2020-09-15T23:53:53
HTML
UTF-8
C++
false
false
100
hh
#include "fieldMap.hh" extern int planSamurai(GameInfo &info); extern int planDog(GameInfo &info);
[ "takashi.cikayama@gmail.com" ]
takashi.cikayama@gmail.com
47b976f891113956dc926957fe9f4a2c56cb105d
7901e09d4f0827e0590fa6a7f038e7d9363e903b
/cpl/ch12/Employee.h
01a9f01c4cf0e428b905c08b4d54738ce910f709
[]
no_license
jiesoul/c_cpp_learn
32298fa21d159d3fc9a6c0c2711700548db9e4a2
cd4e411f73222dd26d22c1110ce0af4ecc60f051
refs/heads/main
2023-03-16T15:54:54.553175
2022-06-14T05:30:51
2022-06-14T05:30:51
204,853,153
0
0
null
null
null
null
UTF-8
C++
false
false
458
h
// // Created by JIESOUL on 2019/9/25. // #ifndef C_CPP_LEARN_SRC_CPL_CH12_EMPLOYEE_H #define C_CPP_LEARN_SRC_CPL_CH12_EMPLOYEE_H #include <string> using std::string; class Employee { private: string first_name, family_name; char middle_initial; public: Employee(const string& n, int d); void print() const; string full_name() const { return first_name + " " + middle_initial + " " + first_name; } }; #endif //C_CPP_LEARN_SRC_CPL_CH12_EMPLOYEE_H
[ "jiesoul@gmail.com" ]
jiesoul@gmail.com
d63433558abfe2aa32d83c241b731de1b41a60ea
ee58a1bb3f4cac0215ec3a1f753779e731c98f4e
/C-DS/有理数/复杂分数.cpp
4638e789c8e865ca068714e2907032642b5ac82c
[]
no_license
MisakiFx/DSA
e5bf5bbb00190d10f5f2ee9e26d25494655f27d0
20b862190b75eec671f1795d9585a8ccee355dc8
refs/heads/master
2020-04-05T11:07:54.591672
2020-03-12T13:40:41
2020-03-12T13:40:41
156,823,720
0
0
null
null
null
null
GB18030
C++
false
false
1,267
cpp
#include <stdio.h> #include <assert.h> typedef struct { int x; int y; }RationalNum;//有理数 typedef struct { RationalNum x; RationalNum y; }Fraction;//分数 double plus(Fraction a, Fraction b)//加 { assert(a.x.y > 0 && a.y.y > 0 && b.x.y > 0 && b.y.y > 0 && (a.y.x / a.y.y) != 0 && (b.y.x / b.y.y) != 0);//基本条件 return ((a.x.x / a.x.y) / (a.y.x / a.y.y)) + ((b.x.x / b.x.y) / (b.y.x / b.y.y));//运算 } double minus(Fraction a, Fraction b)//减 { assert(a.x.y > 0 && a.y.y > 0 && b.x.y > 0 && b.y.y > 0 && (a.y.x / a.y.y) != 0 && (b.y.x / b.y.y) != 0);//基本条件 return ((a.x.x / a.x.y) / (a.y.x / a.y.y)) - ((b.x.x / b.x.y) / (b.y.x / b.y.y));//运算 } double mul(Fraction a, Fraction b)//乘 { assert(a.x.y > 0 && a.y.y > 0 && b.x.y > 0 && b.y.y > 0 && (a.y.x / a.y.y) != 0 && (b.y.x / b.y.y) != 0);//基本条件 return ((a.x.x / a.x.y) / (a.y.x / a.y.y)) * ((b.x.x / b.x.y) / (b.y.x / b.y.y));//运算 } double div(Fraction a, Fraction b)//除 { assert(a.x.y > 0 && a.y.y > 0 && b.x.y > 0 && b.y.y > 0 && (a.y.x / a.y.y) != 0 && (b.y.x / b.y.y) != 0 && ((b.x.x / b.x.y) / (b.y.x / b.y.y)) != 0);//基本条件 return ((a.x.x / a.x.y) / (a.y.x / a.y.y)) / ((b.x.x / b.x.y) / (b.y.x / b.y.y));//运算 } int main() { }
[ "1761607418@qq.com" ]
1761607418@qq.com
ef53fcde55ae2f41a98ce4289ed09c0072e8ea52
5ee7b59b955ebde297f0dd924382a96a79771681
/plnrcmbd/PlnrExp/PlnrExpPinout.h
090e924ec82b43f750f6fca941f35d94660f0892
[]
no_license
epsitech/planar
a3b22468e6718342218143538a93e7af50debee0
e97374190feaf229dac4ec941e19f6661150e400
refs/heads/master
2021-01-21T04:25:32.542626
2016-08-07T19:20:49
2016-08-07T19:20:49
48,572,177
0
0
null
null
null
null
UTF-8
C++
false
false
2,636
h
/** * \file PlnrExpPinout.h * Plnr operation processor - (declarations) * \author Alexander Wirthmueller * \date created: 4 Dec 2015 * \date modified: 4 Dec 2015 */ #ifndef PLNREXPPINOUT_H #define PLNREXPPINOUT_H #include "PlnrExp.h" using namespace PlnrExp; // IP incl --- INSERT namespace PlnrExpPinout { DpchRetPlnr* run(XchgPlnr* xchg, DbsPlnr* dbsplnr, DpchInvPlnrExpPinout* dpchinv); // IP cust --- IBEGIN const unsigned int _RAST = 1; const unsigned int _CELLSTOP = 2; const unsigned int _RATIO = 4; const unsigned int _FRAMEW = 8; const unsigned int _PADFILL = 16; const unsigned int _BUMPD = 32; const unsigned int _WBCLR = 64; const unsigned int _WBOLP = 128; const unsigned int _CELLCLR = 256; const unsigned int _CELLOLP = 512; const unsigned int _PIOPIN_WB = 1024; const unsigned int _PIOPIN_CELL = 2048; const unsigned int _PIOPIN_KEEPOFF = 4096; const unsigned int _PIOPAD_CELL = 8192; void vtxgdfces(DbsPlnr* dbsplnr, const ubigint x1RefPlnrMDesign, const ubigint refPlnrMDevice, const double xofs, const double yofs, const int mmax, const int nmax, const double rast, const int ratio, const double framew, const bool padfill, const double bumpd, const double wbclr, const double wbolp, const double cellclr, const double cellolp, const ubigint refSruBotmet, const ubigint refSruIns, const ubigint refSruTopmet, const ubigint refSruBump); void vtxgdfces_addsq(DbsPlnr* dbsplnr, const ubigint strRefPlnrMStructure, const string sref, const ubigint refVtx1, const ubigint refLg1, const ubigint refVtx2, const ubigint refLg2, const ubigint refVtx3, const ubigint refLg3, const ubigint refVtx4, const ubigint refLg4); void piopin_loadpars(DbsPlnr* dbsplnr, const ubigint refPlnrMDevice, const ubigint x1RefPlnrMDesign, int& wb, string& cell, bool& keepoff); void piopin_gdfces(DbsPlnr* dbsplnr, const ubigint x1RefPlnrMDesign, const ubigint refSupdev, const ubigint refSubdev, const int mmax, const int nmax, const int ratio, const int wb, const string cell, const bool keepoff, const ubigint refSruBotmet, const ListPlnrMVertex& vtxs, ListPlnrMLineguide& lgs, ListPlnrMFace& fces); void piopad_loadpars(DbsPlnr* dbsplnr, const ubigint refPlnrMDevice, const ubigint x1RefPlnrMDesign, string& cell); void piopad_fces(DbsPlnr* dbsplnr, const ubigint x1RefPlnrMDesign, const ubigint refSupdev, const ubigint refSubdev, const bool padfill, const string cell, const ubigint refSruIns, const ubigint refSruTopmet, const ubigint refSruBump, const ListPlnrMVertex& vtxs, const ListPlnrMLineguide& lgs, const ListPlnrMArcguide& ags, ListPlnrMFace& fces); // IP cust --- IEND }; #endif
[ "awirthm@gmail.com" ]
awirthm@gmail.com
ed0ad363f87b93fcd3b9aa0082647dd87f0f2c41
208986c82eca620f2e0cc4226623680e9c7e15d3
/Python/regexes/100495244.re
e5615df3dc90f47a99adfddbe01b32c3047648e8
[]
no_license
libgober/campaignspending
885868902e56538894924d53e2217530ae1a14ed
34d3e506a3b118434f812bedf26fe4b4e281e9bf
refs/heads/master
2021-05-02T15:18:10.475960
2017-09-03T19:24:08
2017-09-03T19:24:08
44,576,982
0
0
null
null
null
null
UTF-8
C++
false
false
1,807
re
#### A regular expression #### # # # # #Valid keys # LINENUMBER + # ENDAIRDATE + # BEGINAIRDATE + # AIRDATE # AIRDAYS + # SPOTCOUNT_ROW # RATE # TOTAL # AIRTIME # AIRTIMERANGE (?(DEFINE) #start define block, all naems in here should be lower case, all matches are upper (?<linebegin>^\d+) #the mark that a line has begun (?<linechar>(?:(?!^\d|\Z).))#a character between lines is any one not follwed by a new line and immediately thereafter a digit or the end of character (?<datetype> # \b(?:0?[1-9]|1[012]) [/.-] (?:0?[1-9]|[12][0-9]|3[01]) [/.-] (?:19|20)?[0-9]{2}) (?<amount>(?:\d{0,3},?)+\.\d{2}) (?<trange>(?:[01]\d|2[0-4]):[0-5][0-9]-([01]\d|2[0-4]):[0-5][0-9]) ) #end define ###Regex match begins now #### #start of line (?P<LINENUMBER>)(?&linebegin) #check that the coming line characters are followed by a date range or a single date (?= (?&linechar)* (?: (?P<BEGINAIRDATE>(?&datetype)) [\s\-]+ (?P<ENDAIRDATE>(?&datetype)) ) ) #check that the coming line characters are followed by airdate,spotcount,rate,total (?= (?&linechar)* (?P<AIRDAYS>[ny]\s+[ny]\s+[ny]\s+[ny]\s+[ny]\s+[ny]\s+[ny]) \s* #prevent being too gready (?P<SPOTCOUNT_ROW>(?&amount)) \s* (?P<RATE>(?&amount)) \s* (?P<TOTAL>(?&amount)) ) #check that the coming line characters contain an air time range. (?=(?&linechar)*(?P<AIRTIMERANGE>(?&trange))) (?&linechar)* ##### TIPS ##### #(?P<linecharval>(?&linechar)), invoke saved routines and save output # (?<datetype> # # \b(?:0?[1-9]|1[012]) # [/.-] # (?:0?[1-9]|[12][0-9]|3[01]) # [/.-] # (?:19|20)?[0-9]{2}) # )
[ "libgober@users.noreply.github.com" ]
libgober@users.noreply.github.com
5b2be3283ead2678cf21044b946d21483c4b2b37
38e49c7de4daa25399907d8091e075f9c1a67d7e
/Rogalic/Rogalic.cpp
bd8e0395448b24c48dc0082b1a59dec2181c2e2c
[]
no_license
Sora20022/my-xyina
e4b51cf5766f65c67b9cc1811d77015c0bb63d3b
ee26f29f24b1f86b8b00d30740a1079c248b39bd
refs/heads/master
2020-04-16T11:26:56.270406
2019-01-13T18:01:45
2019-01-13T18:01:45
165,536,607
0
1
null
2019-01-13T19:47:16
2019-01-13T17:56:08
C++
UTF-8
C++
false
false
6,239
cpp
#include "pch.h" #include <iostream> #include "rooms.h" using namespace std; int main() { setlocale(LC_ALL, "Russian"); RoomController roomController; auto room0 = roomController.createRoom("Комната 0"); auto room1 = roomController.createRoom("Комната 1"); auto room2 = roomController.createRoom("Комната 2"); auto room3 = roomController.createRoom("Комната 3"); auto room4 = roomController.createRoom("Комната 4"); auto room10 = roomController.createRoom("Комната 10"); auto room56 = roomController.createRoom("Комнота продолжение 0"); cout << "Привет, это так-то просто тест, который должен помочь мне развиться в сфере программировани" << endl; cout << "Добро пожаловать на борт, это Эпсилон-9. Мы находимся в Галактике *Млечный Путь*, возле планеты Луна" << endl; cout << "В дальнейшем для продолжения нажимайте на 0, затем enter" << endl; int op; cin >> op; cout << "- Погодите, но луна же спутник Земли, она не может быть планетой. Ох... голова... " << endl; cout << "В 2056 году, метиор под названием Анубис, на большой скорости влетел в планету Земля, от чего погибли триллионы людей. Лишь богатые и нужные для человечества люди смогли спастись" << endl; cin >> op; cout << "Оставшиеся люди были вынуждены отправиться на Луну. К сожалению осколок от зесли через 5 лет попал и в Луну и теперь люди летят на планету под названием Земля-2" << endl; cin >> op; cout << "- Что?! Это какой-то розыгрышь? Сейчас же 2019 год." << endl; cin >> op; cout << "Сэр, на данный момент, сегодня 22 октября 2196 года. Желаете что-то?" << endl; cin >> op; cout << "- Что за... Это бред, быть этого не может... Ну а... Ну а кто ты? Почему я тебя не вижу?" << endl; cin >> op; cout << "Я бортовой ИИ (Искуственный интелект) шатла Эпсилон-9. Меня создали для помощи людям и выполнения предписанных мне указаний" << endl; cin >> op; cout << "- Я брежу..." << endl; cin >> op; cout << "Вам помочь с вашей проблемой? Голова кружится? Еслть тошнота? У меня есть вся информация по медицине." << endl; cin >> op; cout << "- Нет, спасибо, я в порядке. А где все люди и почему покруг всё в разрухе? А это по-моему кровь." << endl; cin >> op; cout << "У меня нет точного ответа, советую вам обратиться к должностным лицам. Они находятся обычно в комноте капитана" << endl; cin >> op; cout << "- Хорошо... Так как мне пройти в эту комноту? Я здесь не здешний" << endl; cin >> op; cout << "Я вам покажу карту. По пути сможете зайти в туалет, или в другие места, кроме тех, которые горят красной лампочкой" << endl; cin >> op; cout << "*Вам доступны действия, нажимайте соответсвующие клавиши, что бы продолжить дольше данную игру." << endl; cin >> op; cout << "Сэр, как прикажете вас называть?" << endl; cout << "Мне зовут... *На английском!* - "; string name; cin >> name; cout << "Хорошо сэр " << name << endl; cin >> op; cout << "*Перед вами несколько варинтов. От них будет зависить судьба вашего героя*"<< endl; cin >> op; cout << "Для начала мне нужно пойти..." << endl; room0->createVariant("На борт капитана", room1); room0->createVariant("Найти ванную комнату", room2); room0->createVariant("Осмотреть обстановку", room56); room56->createVariant("Вы находитесь в небольшой комноте. Обстановка мрачная и очень пугающая. Разбросанные вещи, пыльно и мрачно, а на стекле кровь", room0); room10->createVariant("На борт капитана", room1); room10->createVariant("Найти ванную комнату", room2); room10->createVariant("Осмотреть обстановку", room56); room2->createVariant("Вы вышли в коридор из комноты, и увидели полный разгром. Провода свисающие с потолков, стены, в которых были следы от пуль. Лужи крови и ни единого звука. Слева от себя вы увидели дверь, с надписью *Ванная комнота*. Зойдя внутрь, обстановка ничем не менялась. Вы решили посмотреть в зеркало. Не понятное чудовище, что-то похожее на инопланетное. *- Это кто?! Я?! Нет-нет-нет-нет! Что за... Эй! Компьютер или кто ты там, что это за херня! Ало?!*. Вы направляетесь на борт капитана капитана", room1); room1->createVariant("Идя на борт, вы ощущали дрожь и холод. Словно за вами наблюдали...", room4); roomController.start(); return 0; }
[ "46653974+Sora20022@users.noreply.github.com" ]
46653974+Sora20022@users.noreply.github.com
a23b254feda175a1b55bcf60f67f66cb6960a4e7
2930d8e330620a9a6f86f5c2ea9825aa4e884186
/arcanoid2/collision_system.h
bf86bf7531aa3ac7da1c1d97e155482e6887d963
[]
no_license
PollyPalindrom/arcanoid2
0365832f27763743301f80de68e9ce014dd72efb
152cf4d5a3306b78031ba9323b546e0671114664
refs/heads/master
2023-02-07T15:11:37.882430
2020-12-22T01:43:34
2020-12-22T01:43:34
317,208,617
0
0
null
null
null
null
UTF-8
C++
false
false
412
h
#pragma once #include "i_system.h" #include "transform_component.h" #include "rect_collider_component.h" class CollisionSystem : public ISystem { protected: void OnUpdate(Context& ctx) override; void Update(Context& ctx, Entity* entity) override; bool Filter(Entity* entity) const override { return entity->Contains<TransformComponent>() && entity->Contains<RectColliderComponent>(); } };
[ "polinaahrameiko@gmail.com" ]
polinaahrameiko@gmail.com
810c23cd94ad4276e6f7b65dc827b557699445fe
73b1404795f0da293139e3286d4b1072ccc2028d
/Assgn - 4/test.cpp
0634057cce931861dddb51d711437f7768511fc0
[ "MIT" ]
permissive
hemanthvhr/OS-lab
e8652ee7efcbd8b76c657c6f4c14b63c6fd9ddf2
e731d6675e34408becd90250f38fd65d9233aeae
refs/heads/master
2020-04-15T18:09:21.347995
2019-01-15T17:51:28
2019-01-15T17:51:28
164,903,244
0
0
null
null
null
null
UTF-8
C++
false
false
1,150
cpp
#include "myfs.h" void printinodevalues(char* name) { int inode = searchinodewithfilename(name); printf("%d %d %d %d\n",inode,inodelist[inode]->file_type,inodelist[inode]->file_size,inodelist[inode]->parent_inode_no); } void printdbbitmap() { for(int i=0;i<75;i++) printf("%d ",testbit(super_block->db_bitmap,i)); } void printinodebitmap() { for(int i=0;i<75;i++) printf("%d ",testbit(super_block->inode_bitmap,i)); } void printfd(int fd) { printf("%d %d %c %d\n",filetable[fd].is_occupied,filetable[fd].inode_no,filetable[fd].mode,filetable[fd].offset); } int main() { if(create_myfs(10000000)==-1) printf("Error creating file system\n"); mkdir_myfs("Directory1"); chdir_myfs("Directory1"); mkdir_myfs("Directory2"); mkdir_myfs("Directory3"); copy_pc2myfs("Text1.txt","Text1.txt"); rmdir_myfs("Directory2"); rmdir_myfs("Directory3"); int fd = open_myfs("Text1.txt",'r'); char buff[1000]; buff[999]=0; read_myfs(fd,999,buff); close_myfs(fd); ls_myfs(); fd = open_myfs("Text2.txt",'w'); write_myfs(fd,999,buff); close_myfs(fd); showfile_myfs("Text2.txt"); copy_myfs2pc("Text2.txt","text1.txt"); status_myfs(); }
[ "hemanthvhr@gmail.com" ]
hemanthvhr@gmail.com
6b9d02f15a0ad28cb3c3062a51dbf5f7c3d600dd
afc067cc21eb8058a93e9c4f9af1d648e22ce9b8
/hyphy-src/src/gui/Components/HYButton.cpp
63dd6c5fbed33112e4e2a90214068b85fcab45db
[ "MIT" ]
permissive
veg/hyphy-python
76c0ea7d6a6a30735903b1182327762d64cc104a
6f3e2d19bafe27d0b8a6626201a3326022010811
refs/heads/master
2023-05-25T19:00:26.404623
2023-05-15T19:17:33
2023-05-15T19:17:33
39,527,089
0
1
NOASSERTION
2023-05-25T02:19:32
2015-07-22T19:52:43
C++
UTF-8
C++
false
false
4,045
cpp
/* HyPhy - Hypothesis Testing Using Phylogenies. Copyright (C) 1997-now Core Developers: Sergei L Kosakovsky Pond (spond@ucsd.edu) Art FY Poon (apoon@cfenet.ubc.ca) Steven Weaver (sweaver@ucsd.edu) Module Developers: Lance Hepler (nlhepler@gmail.com) Martin Smith (martin.audacis@gmail.com) Significant contributions from: Spencer V Muse (muse@stat.ncsu.edu) Simon DW Frost (sdf22@cam.ac.uk) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "HYEventTypes.h" #include "HYButton.h" #include "HYGraphicPane.h" #ifdef __HYPHYDMALLOC__ #include "dmalloc.h" #endif //__________________________________________________________________ _HYButton::_HYButton (_HYRect r,Ptr p):_HYComponent (r,p) { backColor.R = backColor.G = backColor.B = 255; buttonFont.style = HY_FONT_PLAIN; #ifndef __HYPHY_GTK__ buttonFont.size = 12; buttonFont.face = "System Font"; #else buttonFont.size = 10; buttonFont.face = _HY_SANS_FONT; #endif alignFlags = 0; buttonKind = 0; isEnabled = true; } //__________________________________________________________________ _HYButton::~_HYButton() { } //__________________________________________________________________ void _HYButton::SetBackColor (_HYColor c) { if ((c.R!=backColor.R)||(c.G!=backColor.G)||(c.B!=backColor.B)) { backColor = c; _SetBackColor (c); _MarkForUpdate(); } } //__________________________________________________________________ _HYColor& _HYButton::GetBackColor (void) { return backColor; } //__________________________________________________________________ void _HYButton::SetText (_String newText) { buttonText = newText; _SetText (); _MarkForUpdate(); } //__________________________________________________________________ _String& _HYButton::GetText (void) { return buttonText; } //__________________________________________________________________ _HYFont& _HYButton::GetFont (void) { return buttonFont; } //__________________________________________________________________ void _HYButton::SetFont (_HYFont&f) { if ((f.face!=buttonFont.face)||(f.size!=buttonFont.size)||(f.style!=buttonFont.style)) { _SetFont (f); buttonFont.face = f.face; buttonFont.size = f.size; buttonFont.style = f.style; _MarkForUpdate(); } } //__________________________________________________________________ void _HYButton::SetVisibleSize (_HYRect rel) { _HYComponent::SetVisibleSize (rel); _HYPlatformButton::_SetVisibleSize (rel); } //__________________________________________________________________ void _HYButton::EnableButton (bool e) { if (isEnabled!=e) { isEnabled = e; _EnableButton (e); } } //__________________________________________________________________ void _HYButton::SetButtonKind (unsigned char k) { if (buttonKind != k) { buttonKind = k; _SetButtonKind (k); } }
[ "sweaver@temple.edu" ]
sweaver@temple.edu
54e88328cd1e6cf6f6c836d8ae4e083e3277f926
dfdcabfe848d89b834bee863b5555b0b5d853987
/AVR/Arduino_app/Test.cpp
298bc3bfd982e9e31be4db00de0f4da002632159
[]
no_license
WooSeok-03/Embedded-Class
aa81e718f1b51fbbb52fa8deb98dd55c5b819312
2106ed9c24dc824a146ef4fcaaa60eb22a7576cc
refs/heads/master
2023-05-14T15:11:58.122594
2021-06-07T08:00:32
2021-06-07T08:00:32
293,404,509
1
0
null
null
null
null
UTF-8
C++
false
false
77
cpp
int test_count = 0; int counting() { test_count++; return test_count; }
[ "58156742+WooSeok-03@users.noreply.github.com" ]
58156742+WooSeok-03@users.noreply.github.com
2af087460793846c61cb1b51395d86d7bfd4f5f1
f1dfa37d76f2cde5523b47668914ceb10116af53
/AtCoder Contest/B - Common Raccoon vs Monster.cpp
c1c9b883b61543f96dd5b563fbe97bed6687a47e
[]
no_license
Muzahid037/Online-Judge-Problems
d7fffd8daad60d9c5801882be1678cd851d54c29
5f14253f70c178c373f9b926a825bd82354ff10c
refs/heads/master
2022-03-15T00:45:38.384365
2022-02-24T13:56:40
2022-02-24T13:56:40
236,151,466
0
0
null
null
null
null
UTF-8
C++
false
false
235
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { ll h,n,x; cin>>h>>n; for(ll i=0;i<n;i++) { cin>>x; h-=x; } if(h>0) { cout<<"No"<<endl; } else { cout<<"Yes"<<endl; } return 0; }
[ "48602232+Muzahid037@users.noreply.github.com" ]
48602232+Muzahid037@users.noreply.github.com
a14b3493e2986f663f001836bc65dcec0bbf3234
eaaf514a11d3a64a77d73946cfac26f0d98893ed
/linked-list/0603-Solution.cpp
da1b5d1a2fd463fcca81f3011cef5ce7673a7f06
[]
no_license
yinweijie/Leetcode-Leetbook
2e63d95f1fc2245662090ada5c52fded110261b7
aeea86329a1563d856709d9cce7db9447e9e1999
refs/heads/main
2023-05-09T21:55:42.219787
2021-06-10T17:05:33
2021-06-10T17:05:33
326,009,315
1
0
null
null
null
null
UTF-8
C++
false
false
1,223
cpp
// 两数相加 // https://leetcode-cn.com/leetbook/read/linked-list/fv6w7/ /** * Definition for singly-linked list. */ struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* dummyHead = new ListNode(-1); int digit = 0; int flag = 0; // 有进位时为1,无进位为0 ListNode* pre = dummyHead; while(l1 != nullptr || l2 != nullptr) { int num1 = l1 == nullptr ? 0 : l1->val; int num2 = l2 == nullptr ? 0 : l2->val; digit = num1 + num2 + flag; flag = 0; if(digit >= 10) { digit = digit - 10; flag = 1; } pre->next = new ListNode(digit); pre = pre->next; if(l1) l1 = l1->next; if(l2) l2 = l2->next; } if(flag == 1) { pre->next = new ListNode(1); } ListNode* res = dummyHead->next; delete dummyHead; return res; } };
[ "ywj123450@gmail.com" ]
ywj123450@gmail.com
66049fb65563e6edf0680078f9832cafd5afc547
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-restbed-server/generated/model/ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiInfo.h
1dcab5abc8f3a05b456b202ffb3bf469e57df0b8
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
2,291
h
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: opensource@shinesolutions.com * * NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ /* * ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiInfo.h * * */ #ifndef ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiInfo_H_ #define ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiInfo_H_ #include <string> #include "ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiProperties.h" #include <memory> namespace org { namespace openapitools { namespace server { namespace model { /// <summary> /// /// </summary> class ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiInfo { public: ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiInfo(); virtual ~ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiInfo(); std::string toJsonString(); void fromJsonString(std::string const& jsonString); ///////////////////////////////////////////// /// ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiInfo members /// <summary> /// /// </summary> std::string getPid() const; void setPid(std::string value); /// <summary> /// /// </summary> std::string getTitle() const; void setTitle(std::string value); /// <summary> /// /// </summary> std::string getDescription() const; void setDescription(std::string value); /// <summary> /// /// </summary> std::shared_ptr<ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiProperties> getProperties() const; void setProperties(std::shared_ptr<ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiProperties> value); protected: std::string m_Pid; std::string m_Title; std::string m_Description; std::shared_ptr<ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiProperties> m_Properties; }; } } } } #endif /* ComAdobeCqSocialReviewClientEndpointsImplReviewOperationsServiInfo_H_ */
[ "cliffano@gmail.com" ]
cliffano@gmail.com
dacfd374a5cc29b8bbb2db70909dd24b44dafb8d
cc0f632f56c572bd4f50c141f048b0bc7fad4055
/UVA/11689.cpp
52a0d27e979db0a04052cfdd932b1d58641fbbe5
[]
no_license
AbuHorairaTarif/UvaProject
78517e585c668a83b99866be19b84a0a120bc617
b0688f97a7226bdd692c9ceb29e7b0c406b8a15a
refs/heads/master
2021-05-04T08:19:46.607485
2016-11-11T14:26:23
2016-11-11T14:26:23
70,333,668
0
0
null
null
null
null
UTF-8
C++
false
false
395
cpp
#include <stdio.h> int main() { int e,f,c,test,drank,empty,more; scanf("%d",&test); while(test--) { scanf("%d%d%d",&e,&f,&c); drank=0; empty=e+f; while(empty>=c) { more=empty/c; empty=empty%c; drank=drank+more; empty=empty+more; } printf("%d\n",drank); } return 0; }
[ "horaira_cse13@yahoo.com" ]
horaira_cse13@yahoo.com
07fff2c02804f79a1eff24e1b6d852aed2deed03
009614bade3cd3a7acbe75de77a5aec7dd50a8ed
/tests.h
1ee1a807c9b8a7a958c9436cf9773ab749ec9107
[]
no_license
AsaBriggs/eop-code
1d3cceb7acebeebabbc942d57b38ef3ba03796c5
fe345c9d222baf0b09e525d7ddd8d4e231ea0267
refs/heads/master
2021-01-02T09:09:38.888436
2014-09-05T14:07:06
2014-09-05T14:07:06
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
145,087
h
// tests.h // Copyright (c) 2009 Alexander Stepanov and Paul McJones // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without // fee, provided that the above copyright notice appear in all copies // and that both that copyright notice and this permission notice // appear in supporting documentation. The authors make no // representations about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. // Regression tests for algorithms from // Elements of Programming // by Alexander Stepanov and Paul McJones // Addison-Wesley Professional, 2009 // To do: move rational, polynomial to eop.h ? #ifndef EOP_TESTS #define EOP_TESTS #include "intrinsics.h" #include "type_functions.h" #include "eop.h" #include "print.h" #include "assertions.h" // Naming conventions: // property_X checks that property X is satisfied for a given set of values // concept_X checks for minimal syntactic requirements of concept X; // it also performs nominal checks of the properties corresponding to the axioms // type_X checks that a that X satisfies the minimal syntactic requirements of the corresponding concept(s) // algorithm_X (or algorithms_X) checks that an algorithm or group of algorithms // satisfies postconditions // test_X performs checks on properties, concepts, types, and algorithms in area X, // e.g., a chapter bool verbose = false; void toggle_verbose() { verbose = !verbose; if (verbose) print("verbose now true"); else print("verbose now false"); print_eol(); } // Get a compilation error if we expect_false and pass in true_type, and expect_true and pass in false_type void expect_false(false_type){} void expect_true(true_type){} void check_compile_time_not() { expect_false(not_<true_type>::type ()); expect_true(not_<false_type>::type ()); } void check_compile_time_and() { expect_false(and_<false_type, false_type, false_type>::type ()); expect_false(and_<false_type, false_type, true_type>::type ()); expect_false(and_<false_type, true_type, false_type>::type ()); expect_false(and_<true_type, false_type, false_type>::type ()); expect_false(and_<true_type, true_type, false_type>::type ()); expect_false(and_<true_type, false_type, true_type>::type ()); expect_false(and_<false_type, true_type, true_type>::type ()); expect_true(and_<true_type, true_type, true_type>::type ()); expect_false(and_<false_type, false_type>::type ()); expect_false(and_<true_type, false_type>::type ()); expect_false(and_<false_type, true_type>::type ()); expect_true(and_<true_type, true_type>::type ()); } void check_compile_time_or() { expect_true(or_<true_type, true_type, true_type>::type ()); expect_true(or_<true_type, true_type, false_type>::type ()); expect_true(or_<true_type, false_type, true_type>::type ()); expect_true(or_<false_type, true_type, true_type>::type ()); expect_true(or_<true_type, false_type, false_type>::type ()); expect_true(or_<false_type, true_type, false_type>::type ()); expect_true(or_<false_type, false_type, true_type>::type ()); expect_false(or_<false_type, false_type, false_type>::type ()); expect_true(or_<true_type, true_type>::type ()); expect_true(or_<true_type, false_type>::type ()); expect_true(or_<false_type, true_type>::type ()); expect_false(or_<false_type, false_type>::type ()); } void check_compile_time_logic() { check_compile_time_not(); check_compile_time_and(); check_compile_time_or(); } // Chapter 1. Foundations template<typename T> void concept_Regular(T& x) { // Default constructor T y; // Equality EOPAssert(x == x); // Assignment y = x; EOPAssert(y == x); // Copy constructor T x_copy(x); EOPAssert(x_copy == x); // Default total ordering less<T> lt; EOPAssert(!lt(x, x)); // Underlying type EOPUnderlyingType(T) u; (void)u; // Destructor } template<typename T> requires(TotallyOrdered(T)) void concept_TotallyOrdered(T& x0, T& x1) { // Precondition: x0 < x1 EOPAssert(x0 != x1); EOPAssert(!(x0 == x1)); // Natural total ordering EOPAssert(!(x0 < x0)); EOPAssert(x0 < x1); EOPAssert(x1 > x0); EOPAssert(x0 <= x1); EOPAssert(x1 >= x0); EOPAssert(!(x1 < x0)); EOPAssert(!(x0 > x1)); EOPAssert(!(x1 <= x0)); EOPAssert(!(x0 >= x1)); } template<typename T0, typename T1> requires(Regular(T0) && Regular(T1)) void type_pair(const T0& x00, const T0& x01, const T1& x10, const T1& x11) { // Precondition: x00 < x01 || (x00 == x01 && x10 < x11) EOPAssert(x00 < x01 || (x00 == x01 && x10 < x11)); typedef pair<T0, T1> P01; // Pair constructor P01 p0 = {x00, x10}; P01 p1 = {x01, x11}; // Regular concept_Regular(p0); concept_TotallyOrdered(p0, p1); // Member selection EOPAssert(p0.m0 == x00 && p0.m1 == x10); } template<typename T0, typename T1, typename T2> requires(Regular(T0) && Regular(T1) && Regular T2) void type_triple(const T0& x00, const T0& x01, const T1& x10, const T1& x11, const T2& x20, const T2& x21) { EOPAssert(x00 < x01 || (x00 == x01 && (x10 < x11 || (x10 == x11 && x20 < x21)))); typedef triple<T0, T1, T2> T; // Triple constructor T t0 = {x00, x10, x20}; // triple constructor T t1 = {x01, x11, x21}; // Regular concept_Regular(t0); concept_TotallyOrdered(t0, t1); // Member selection EOPAssert(t0.m0 == x00 && t0.m1 == x10 && t0.m2 == x20); } void test_tuples() { typedef pair<int, char> P; print(" pair\n"); type_pair<int, char>(0, 99, 'a', 'a'); type_pair<int, char>(0, 0, 'a', 'z'); char a[] = {'a', 'Z'}; type_pair<P, EOPpointer(char)>(make_pair(0, 'a'), make_pair(1, 'Z'), &(a[0]), &(a[1])); array<int> a0; array<int> a1(3, 3, 0); iota(3, begin(a1)); type_pair< array<int>, char >(a0, a1, 'a', 'z'); slist<int> l0; slist<int> l1(a0); type_pair< slist<int>, char >(l0, l1, 'a', 'z'); type_pair< array<int>, slist<int> >(a0, a1, l0, l1); print(" triple\n"); type_triple<int, char, double>(0, 99, 'a', 'z', 1.0, 2.0); } template<typename T> requires(MultiplicativeSemigroup(T)) struct times { typedef T input_type_0; typedef T input_type_1; typedef T codomain_type; T operator()(T const& a, T const& b) { return a * b; } }; void test_ch_1() { print(" Chapter 1\n"); int n0(0); int n1(1); concept_Regular(n0); concept_TotallyOrdered(n0, n1); // *****concept_Integer ????? // We check the most important fact in arithmetic EOPAssert(plus_0(3 * 3, 4 * 4) == 5 * 5); EOPAssert(plus_1(3 * 3, 4 * 4) == 5 * 5); int a = 3 * 3; int b = 4 * 4; int c; plus_2(&a, &b, &c); EOPAssert(c == 5 * 5); EOPAssert(square(3) == 9); EOPAssert(square(3, times<int>()) == 9); test_tuples(); } // Chapter 2. Transformations and their orbits template<typename F> requires(Transformation(F)) void concept_Transformation(F f, EOPDomain(F) x) { typedef EOPDomain(F) X; typedef EOPCodomain(F) Y; // X == Y Y y; y = x; EOPAssert(x == y); y = f(x); typedef EOPDistanceType(F) N; N n(1); (void)n; } template<typename P> requires(UnaryPredicate(P)) void concept_UnaryPredicate(P p, EOPDomain(P) x) { typedef EOPDomain(P) X; X x0; X x1; if (p(x)) x0 = x; else x1 = x; } template<typename T> requires(MultiplicativeSemigroup(T)) struct sq { typedef T input_type_0; typedef T codomain_type; T operator()(T const& x) { return x * x; } }; template<typename T> requires(MultiplicativeSemigroup(T)) struct distance_type< sq<T> > { typedef T type; }; template<typename I, typename N> requires(Integer(I) && Integer(N) && EOPDistanceType(I) = N) struct gen_orbit_predicate // definition space predicate { typedef I input_type_0; typedef bool codomain_type; I x_0; N h; N c; gen_orbit_predicate(I x_0, N h, N c) : x_0(x_0), h(h), c(c) { // Precondition: h < N(MaximumValue(I)) && c < N(MaximumValue(I)) // Precondition: !negative(h) && !negative(c) } bool operator()(const I& x) { return x_0 <= x && x < x_0 + I(h) + I(c); } }; template<typename I, typename N> requires(Integer(I) && Integer(N) && EOPDistanceType(I) = N) struct gen_orbit // transformation { typedef I input_type_0; typedef I codomain_type; gen_orbit_predicate<I, N> p; gen_orbit(I x_0, N h, N c) : p(x_0, h, c) { // Precondition: h < N(MaximumValue(I)) && c < N(MaximumValue(I)) // Precondition: !negative(h) && !negative(c) } I operator() (I x) { EOPAssert(p(x)); x = successor(x); if (x == p.x_0 + I(p.h) + I(p.c)) x = p.x_0 + I(p.h); return x; } }; template<typename I, typename N> requires(Integer(I) && Integer(N) && EOPDistanceType(I) = N) struct distance_type< gen_orbit<I, N> > { typedef N type; }; template<typename F> requires(Transformation(F)) void algorithms_orbit(EOPDomain(F) x, EOPDistanceType(F) h, EOPDistanceType(F) c) { typedef EOPDomain(F) T; typedef EOPDistanceType(F) N; F f(x, h, c); EOPAssert(zero(c) == terminating(x, f, f.p)); if (zero(h) && !zero(c)) { EOPAssert(circular(x, f, f.p)); EOPAssert(circular_nonterminating_orbit(x, f)); } else if (!zero(h)) { EOPAssert(!circular(x, f, f.p)); if (!zero(c)) EOPAssert(!circular_nonterminating_orbit(x, f)); } T y = connection_point(x, f, f.p); EOPAssert(power_unary<F>(x, h, f) == y); if (!zero(c)) EOPAssert(y == connection_point_nonterminating_orbit(x, f)); triple<unsigned, unsigned, int> t = orbit_structure(x, f, f.p); if (zero(c)) { // terminating EOPAssert(t.m0 == h); EOPAssert(zero(t.m1)); EOPAssert(t.m2 == collision_point(x, f, f.p)); } else if (zero(h)) { // circular EOPAssert(zero(t.m0)); EOPAssert(t.m1 == predecessor(c)); EOPAssert(t.m2 == x); } else { // rho-shaped EOPAssert(t.m0 == h); EOPAssert(t.m1 == predecessor(c)); EOPAssert(t.m2 == y); } if (!zero(c)) { triple<N, N, T> t = orbit_structure_nonterminating_orbit(x, f); if (zero(h)) { // circular EOPAssert(zero(t.m0)); EOPAssert(t.m1 == predecessor(c)); EOPAssert(t.m2 == x); } else { // rho-shaped EOPAssert(t.m0 == h); EOPAssert(t.m1 == predecessor(c)); EOPAssert(t.m2 == y); } } } template<typename N> requires(Integer(N)) struct hf { typedef N input_type_0; typedef N codomain_type; N operator()(N const& x) { return x / N(2); } }; template<typename N> requires(Integer(N)) struct distance_type< hf<N> > { typedef N type; }; void test_ch_2() { print(" Chapter 2\n"); for (int i = 1; i < 100000000; i = 10 * i) { EOPAssert(abs(i) == i); EOPAssert(abs(-i) == i); } EOPAssert(euclidean_norm(3., 4.) == 5.); EOPAssert(euclidean_norm(3., 4., 5.) == euclidean_norm(euclidean_norm(3., 4.), 5.)); concept_Transformation(sq<int>(), 2); concept_Transformation(gen_orbit<int, unsigned>(0, 0u, 5u), 0); concept_Transformation(hf<int>(), 16); concept_UnaryPredicate(gen_orbit<int, unsigned>(0, 0u, 5u).p, 0); for (int i = 2; i < 5; i = successor(i)) for (int j = 1; j < 5; j = successor(j)) { int tmp = power_unary(i, predecessor(j), sq<int>()); EOPAssert(power_unary(i, j, sq<int>()) == tmp * tmp); } EOPAssert(distance(2, 65536, sq<int>()) == 4); // Cyclic algorithms_orbit< gen_orbit<int, unsigned> >(0, 0u, 5u); // Rho-shaped algorithms_orbit< gen_orbit<int, unsigned> >(0, 2u, 11u); algorithms_orbit< gen_orbit<int, unsigned> >(7, 97u, 17u); algorithms_orbit< gen_orbit<int, unsigned> >(0, 4u, 2u); // Terminating algorithms_orbit< gen_orbit<int, unsigned> >(0, 101u, 0u); EOPAssert(convergent_point_guarded(1024, 64, 1, hf<int>()) == 64); EOPAssert(convergent_point_guarded(1025, 65, 1, hf<int>()) == 32); EOPAssert(convergent_point_guarded(64, 1024, 1, hf<int>()) == 64); EOPAssert(convergent_point_guarded(65, 1025, 1, hf<int>()) == 32); EOPAssert(convergent_point_guarded(1024, 2047, 1, hf<int>()) == 1); } // Chapter 3. Associative operations template<typename Op> requires(BinaryOperation(Op)) void concept_BinaryOperation(Op op, EOPDomain(Op) x) { typedef EOPDomain(Op) X; typedef EOPCodomain(Op) Y; // X == Y Y y; y = x; EOPAssert(x == y); y = op(x, x); } int minus_int(int a, int b) { return a - b; } int times_int(int a, int b) { return a * b; } void algorithm_power(int (*pow)(int, int, int (*)(int, int))) { EOPAssert(pow(1, 1, times_int) == 1); EOPAssert(pow(10, 1, times_int) == 10); EOPAssert(pow(1, 10, times_int) == 1); EOPAssert(pow(2, 2, times_int) == 4); EOPAssert(pow(2, 10, times_int) == 1024); EOPAssert(pow(10, 2, times_int) == 100); } void algorithm_power_accumulate(int (*pow)(int, int, int, int (*)(int, int))) { EOPAssert(pow(99, 1, 1, times_int) == 99 * 1); EOPAssert(pow(99, 10, 1, times_int) == 99 * 10); EOPAssert(pow(99, 1, 10, times_int) == 99 * 1); EOPAssert(pow(99, 2, 2, times_int) == 99 * 4); EOPAssert(pow(99, 2, 10, times_int) == 99 * 1024); EOPAssert(pow(99, 10, 2, times_int) == 99 * 100); EOPAssert(pow(99, 1, 0, times_int) == 99); } void algorithm_power_accumulate_positive(int (*pow)(int, int, int, int (*)(int, int))) { EOPAssert(pow(99, 1, 1, times_int) == 99 * 1); EOPAssert(pow(99, 10, 1, times_int) == 99 * 10); EOPAssert(pow(99, 1, 10, times_int) == 99 * 1); EOPAssert(pow(99, 2, 2, times_int) == 99 * 4); EOPAssert(pow(99, 2, 10, times_int) == 99 * 1024); EOPAssert(pow(99, 10, 2, times_int) == 99 * 100); } void algorithm_power_with_identity(int (*pow)(int, int, int (*)(int, int), int)) { EOPAssert(pow(1, 1, times_int, 1) == 1); EOPAssert(pow(10, 1, times_int, 1) == 10); EOPAssert(pow(1, 10, times_int, 1) == 1); EOPAssert(pow(2, 2, times_int, 1) == 4); EOPAssert(pow(2, 10, times_int, 1) == 1024); EOPAssert(pow(10, 2, times_int, 1) == 100); EOPAssert(pow(1, 0, times_int, 1) == 1); EOPAssert(pow(1, 0, times_int, 99) == 99); } template<typename I> requires(Integer(I)) void concept_Integer(I n) { I k(11); concept_Regular<I>(n); I m; m = n + k; m = m - k; m = m * k; m = m / k; m = m % k; m = I(0); // ensure m < k concept_TotallyOrdered<I>(m, k); m = successor(n); m = predecessor(m); m = twice(m); m = half_nonnegative(m); m = binary_scale_down_nonnegative(m, I(1)); m = binary_scale_up_nonnegative(m, I(1)); bool bp = positive(m); bool bn = negative(m); EOPAssert(!(bp && bn)); bool bz = zero(m); EOPAssert((bz && !(bn || bp)) || (!bz && (bn || bp))); bool b1 = one(m); EOPAssert(!(bz && b1)); EOPAssert(!b1 || bp); bool be = even(m); bool bo = odd(m); EOPAssert(be != bo); } void test_ch_3() { print(" Chapter 3\n"); concept_BinaryOperation(minus_int, 7); concept_BinaryOperation(times_int, 8); EOPAssert(power_left_associated(-2, 3, minus_int) == 2); // (-2 - -2) - -2 = 2 EOPAssert(power_left_associated(-2, 4, minus_int) == 4); // ((-2 - -2) - -2) - -2 = 4 algorithm_power(power_left_associated<int, int (*)(int, int)>); EOPAssert(power_right_associated(-2, 3, minus_int) == -2); // -2 - (-2 - -2) = -2 EOPAssert(power_right_associated(-2, 4, minus_int) == 0); // -2 - (-2 - (-2 - -2) = 0 algorithm_power(power_right_associated<int, int (*)(int, int)>); algorithm_power(power_0<int, int (*)(int, int)>); algorithm_power(power_1<int, int (*)(int, int)>); algorithm_power_accumulate(power_accumulate_0<int, int (*)(int, int)>); algorithm_power_accumulate(power_accumulate_1<int, int (*)(int, int)>); algorithm_power_accumulate(power_accumulate_2<int, int (*)(int, int)>); algorithm_power_accumulate(power_accumulate_3<int, int (*)(int, int)>); algorithm_power_accumulate(power_accumulate_4<int, int (*)(int, int)>); algorithm_power_accumulate_positive( power_accumulate_positive_0<int, int (*)(int, int)>); algorithm_power_accumulate(power_accumulate_5<int, int (*)(int, int)>); algorithm_power(power_2<int, int (*)(int, int)>); algorithm_power(power_3<int, int (*)(int, int)>); algorithm_power_accumulate_positive( power_accumulate_positive<int, int (*)(int, int)>); algorithm_power_accumulate(power_accumulate<int, int (*)(int, int)>); algorithm_power(power<int, int (*)(int, int)>); algorithm_power_with_identity(power<int, int (*)(int, int)>); typedef long long N; typedef pair<N, N> Fib; concept_Integer(N(7)); concept_BinaryOperation(fibonacci_matrix_multiply<N>, make_pair(N(1), N(0))); Fib f10 = {N(55), N(34)}; Fib f11 = {N(89), N(55)}; Fib f21 = fibonacci_matrix_multiply(f10, f11); EOPAssert(f21.m0 == 10946 && f21.m1 == 6765); EOPAssert(fibonacci<N>(10) == N(55)); EOPAssert(fibonacci<N>(20) == N(6765)); N n = 3; N nMinus1 = 2; fibonacci_next(n, nMinus1); EOPAssert(n == N(5)); EOPAssert(nMinus1 == N(3)); fibonacci_next(n, nMinus1); EOPAssert(n == N(8)); EOPAssert(nMinus1 == N(5)); fibonacci_previous(n, nMinus1); EOPAssert(n == N(5)); EOPAssert(nMinus1 == N(3)); fibonacci_previous(n, nMinus1); EOPAssert(n == N(3)); EOPAssert(nMinus1 == N(2)); } // Chapter 4. Linear orderings template<typename R> requires(Relation(R)) void concept_Relation(R r, EOPDomain(R) x) { typedef EOPDomain(R) X; X y; X z; if (r(x, x)) y = x; else z = x; } template<typename R> requires(Relation(R)) void property_transitive(R r, EOPDomain(R) x, EOPDomain(R) y, EOPDomain(R) z) { concept_Relation(r, x); EOPAssert(!r(x, y) || !r(y, z) || r(x, z)); } template<typename R> requires(Relation(R)) void property_total_ordering(R r, const EOPDomain(R)& x0, const EOPDomain(R)& x1, const EOPDomain(R)& x2) { // Precondition: total_ordering(r) /\ r(x0, x1) /\ r(x1, x2) EOPAssert(r(x0, x1) && r(x1, x2)); property_transitive(r, x0, x1, x2); EOPAssert( r(x0, x1) && !(x0 == x1) && !r(x1, x0)); // trichotomy EOPAssert(!r(x0, x0) ); // irreflexive } template<typename R> requires(Relation(R)) void property_reflexive_total_ordering(R r, const EOPDomain(R)& x0, const EOPDomain(R)& x1, const EOPDomain(R)& x2) { // Precondition: total_ordering(r) /\ r(x0, x1) /\ r(x1, x2) EOPAssert(r(x0, x1) && r(x1, x2)); property_transitive(r, x0, x1, x2); property_transitive(r, x0, x0, x1); property_transitive(r, x0, x1, x1); property_transitive(r, x0, x0, x0); EOPAssert(!r(x0, x1) || !r(x1, x0) || x0 == x1); // antisymmetric EOPAssert(r(x0, x0) ); // reflexive } template<typename T, typename U> requires(Regular(T) && Regular(U)) struct first { typedef pair<T, U> input_type_0; typedef T codomain_type; T operator()(pair<T, U> const& x) { return x.m0; } }; template <typename T0, typename T1> requires(TotallyOrdered(T0)) struct less_first { typedef pair<T0, T1> T; typedef T input_type_0; typedef T input_type_1; typedef bool codomain_type; bool operator()(T const& p0, T const& p1) const { return p0.m0 < p1.m0; } }; template <typename T0, typename T1> requires(TotallyOrdered(T0)) struct less_second { typedef pair<T0, T1> T; typedef T input_type_0; typedef T input_type_1; typedef bool codomain_type; bool operator()(T const& p0, T const& p1) const { return p0.m1 < p1.m1; } }; template<typename T0, typename T1> requires(Regular(T0)) struct eq_first { typedef pair<T0, T1> input_type_0; typedef bool codomain_type; T0 x0; eq_first(T0 x0) : x0(x0) { } bool operator()(pair<T0, T1> const& x) { return x.m0 == x0; } }; template<typename I, typename R> requires(Mutable(I) && BidirectionalIterator(I) && Relation(R)) bool next_permutation(I f, I l, R r) { // Precondition: weak_ordering(r) if (f == l || successor(f) == l) return false; I i = predecessor(l); while (true) { I ii = i; i = predecessor(i); if (r(source(i), source(ii))) { I j = l; do j = predecessor(j); while (!r(source(i), source(j))); exchange_values(i, j); reverse_bidirectional(ii, l); return true; } if (i == f) { reverse_bidirectional(f, l); return false; } } } template<typename F, typename R> requires(UnaryFunction(F) && Relation(R) && EOPCodomain(F) == EOPDomain(R)) struct key_ordering { typedef EOPDomain(F) T; typedef T input_type_0; typedef T input_type_1; typedef bool codomain_type; F f; R r; key_ordering(F f, R r) : f(f), r(r) { } bool operator()(T const& x, T const& y) { return r(f(x), f(y)); } }; void algorithm_select_1_4() { print(" select_1_4\n"); typedef pair<int, int> T; T t_1_1 = {1, 1}; T t_2_2 = {2, 2}; T t_2_3 = {2, 3}; T t_3_4 = {3, 4}; T t[] = {t_1_1, t_2_2, t_2_3, t_3_4}; EOPpointer(T) l = t + sizeof(t) / sizeof(T); do { if (verbose) { print(" 2nd of ("); print_range(t, l); print(") is "); } T r = select_1_4(t[0], t[1], t[2], t[3], key_ordering< first<int, int>, less<int> >(first<int, int>(), less<int>())); EOPpointer(T) f = find_if(t, l, eq_first<int, int>(2)); EOPAssert(f != l && source(f) == r); if (verbose) { print(r); print_eol(); } } while (next_permutation(t, l, less_second<int, int>())); } void algorithm_select_1_4_stability_indices() { print(" select_1_4 with stability indices\n"); typedef pair<int, int> T; T t_1_1 = {1, 1}; T t_2_2 = {2, 2}; T t_2_3 = {2, 3}; T t_3_4 = {3, 4}; T t[] = {t_1_1, t_2_2, t_2_3, t_3_4}; EOPpointer(T) l = t + sizeof(t) / sizeof(T); do { if (verbose) { print(" 2nd of ("); print_range(t, l); print(") is "); } T r = select_1_4<0,1,2,3>(t[0], t[1], t[2], t[3], key_ordering< first<int, int>, less<int> >(first<int, int>(), less<int>())); EOPpointer(T) f = find_if(t, l, eq_first<int, int>(2)); EOPAssert(f != l && source(f) == r); if (verbose) { print(r); print_eol(); } } while (next_permutation(t, l, less_second<int, int>())); } void algorithm_select_2_5_stability_indices() { print(" select_2_5 with stability indices\n"); typedef pair<char, int> P; typedef less_first<char, int> R; P p0 = {'x', 0}; P p1 = {'x', 1}; P p2 = {'x', 2}; P p3 = {'x', 3}; P p4 = {'x', 4}; EOPAssert((select_2_5<0,1,2,3,4>(p0,p1,p2,p3,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,1,2,4,3>(p0,p1,p2,p4,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,1,3,2,4>(p0,p1,p3,p2,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,1,3,4,2>(p0,p1,p3,p4,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,1,4,2,3>(p0,p1,p4,p2,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,1,4,3,2>(p0,p1,p4,p3,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,2,1,3,4>(p0,p2,p1,p3,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,2,1,4,3>(p0,p2,p1,p4,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,2,3,1,4>(p0,p2,p3,p1,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,2,3,4,1>(p0,p2,p3,p4,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,2,4,1,3>(p0,p2,p4,p1,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,2,4,3,1>(p0,p2,p4,p3,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,3,1,2,4>(p0,p3,p1,p2,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,3,1,4,2>(p0,p3,p1,p4,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,3,2,1,4>(p0,p3,p2,p1,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,3,2,4,1>(p0,p3,p2,p4,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,3,4,1,2>(p0,p3,p4,p1,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,3,4,2,1>(p0,p3,p4,p2,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,4,1,2,3>(p0,p4,p1,p2,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,4,1,3,2>(p0,p4,p1,p3,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,4,2,1,3>(p0,p4,p2,p1,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,4,2,3,1>(p0,p4,p2,p3,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,4,3,1,2>(p0,p4,p3,p1,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<0,4,3,2,1>(p0,p4,p3,p2,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,0,2,3,4>(p1,p0,p2,p3,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,0,2,4,3>(p1,p0,p2,p4,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,0,3,2,4>(p1,p0,p3,p2,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,0,3,4,2>(p1,p0,p3,p4,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,0,4,2,3>(p1,p0,p4,p2,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,0,4,3,2>(p1,p0,p4,p3,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,2,0,3,4>(p1,p2,p0,p3,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,2,0,4,3>(p1,p2,p0,p4,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,2,3,0,4>(p1,p2,p3,p0,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,2,3,4,0>(p1,p2,p3,p4,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,2,4,0,3>(p1,p2,p4,p0,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,2,4,3,0>(p1,p2,p4,p3,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,3,0,2,4>(p1,p3,p0,p2,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,3,0,4,2>(p1,p3,p0,p4,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,3,2,0,4>(p1,p3,p2,p0,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,3,2,4,0>(p1,p3,p2,p4,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,3,4,0,2>(p1,p3,p4,p0,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,3,4,2,0>(p1,p3,p4,p2,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,4,0,2,3>(p1,p4,p0,p2,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,4,0,3,2>(p1,p4,p0,p3,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,4,2,0,3>(p1,p4,p2,p0,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,4,2,3,0>(p1,p4,p2,p3,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,4,3,0,2>(p1,p4,p3,p0,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<1,4,3,2,0>(p1,p4,p3,p2,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,0,1,3,4>(p2,p0,p1,p3,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,0,1,4,3>(p2,p0,p1,p4,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,0,3,1,4>(p2,p0,p3,p1,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,0,3,4,1>(p2,p0,p3,p4,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,0,4,1,3>(p2,p0,p4,p1,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,0,4,3,1>(p2,p0,p4,p3,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,1,0,3,4>(p2,p1,p0,p3,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,1,0,4,3>(p2,p1,p0,p4,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,1,3,0,4>(p2,p1,p3,p0,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,1,3,4,0>(p2,p1,p3,p4,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,1,4,0,3>(p2,p1,p4,p0,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,1,4,3,0>(p2,p1,p4,p3,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,3,0,1,4>(p2,p3,p0,p1,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,3,0,4,1>(p2,p3,p0,p4,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,3,1,0,4>(p2,p3,p1,p0,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,3,1,4,0>(p2,p3,p1,p4,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,3,4,0,1>(p2,p3,p4,p0,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,3,4,1,0>(p2,p3,p4,p1,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,4,0,1,3>(p2,p4,p0,p1,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,4,0,3,1>(p2,p4,p0,p3,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,4,1,0,3>(p2,p4,p1,p0,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,4,1,3,0>(p2,p4,p1,p3,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,4,3,0,1>(p2,p4,p3,p0,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<2,4,3,1,0>(p2,p4,p3,p1,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,0,1,2,4>(p3,p0,p1,p2,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,0,1,4,2>(p3,p0,p1,p4,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,0,2,1,4>(p3,p0,p2,p1,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,0,2,4,1>(p3,p0,p2,p4,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,0,4,1,2>(p3,p0,p4,p1,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,0,4,2,1>(p3,p0,p4,p2,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,1,0,2,4>(p3,p1,p0,p2,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,1,0,4,2>(p3,p1,p0,p4,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,1,2,0,4>(p3,p1,p2,p0,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,1,2,4,0>(p3,p1,p2,p4,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,1,4,0,2>(p3,p1,p4,p0,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,1,4,2,0>(p3,p1,p4,p2,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,2,0,1,4>(p3,p2,p0,p1,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,2,0,4,1>(p3,p2,p0,p4,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,2,1,0,4>(p3,p2,p1,p0,p4,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,2,1,4,0>(p3,p2,p1,p4,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,2,4,0,1>(p3,p2,p4,p0,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,2,4,1,0>(p3,p2,p4,p1,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,4,0,1,2>(p3,p4,p0,p1,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,4,0,2,1>(p3,p4,p0,p2,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,4,1,0,2>(p3,p4,p1,p0,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,4,1,2,0>(p3,p4,p1,p2,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,4,2,0,1>(p3,p4,p2,p0,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<3,4,2,1,0>(p3,p4,p2,p1,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,0,1,2,3>(p4,p0,p1,p2,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,0,1,3,2>(p4,p0,p1,p3,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,0,2,1,3>(p4,p0,p2,p1,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,0,2,3,1>(p4,p0,p2,p3,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,0,3,1,2>(p4,p0,p3,p1,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,0,3,2,1>(p4,p0,p3,p2,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,1,0,2,3>(p4,p1,p0,p2,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,1,0,3,2>(p4,p1,p0,p3,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,1,2,0,3>(p4,p1,p2,p0,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,1,2,3,0>(p4,p1,p2,p3,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,1,3,0,2>(p4,p1,p3,p0,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,1,3,2,0>(p4,p1,p3,p2,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,2,0,1,3>(p4,p2,p0,p1,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,2,0,3,1>(p4,p2,p0,p3,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,2,1,0,3>(p4,p2,p1,p0,p3,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,2,1,3,0>(p4,p2,p1,p3,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,2,3,0,1>(p4,p2,p3,p0,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,2,3,1,0>(p4,p2,p3,p1,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,3,0,1,2>(p4,p3,p0,p1,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,3,0,2,1>(p4,p3,p0,p2,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,3,1,0,2>(p4,p3,p1,p0,p2,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,3,1,2,0>(p4,p3,p1,p2,p0,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,3,2,0,1>(p4,p3,p2,p0,p1,R()).m1 == p2.m1)); EOPAssert((select_2_5<4,3,2,1,0>(p4,p3,p2,p1,p0,R()).m1 == p2.m1)); } void algorithm_median_5() { print(" median_5\n"); int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; int i5 = 5; // ... EOPAssert((&select_2_5_ab_cd<0, 1, 2, 3, 4, less<int> >( i4, i5, i2, i3, i1, less<int>()) == &i3)); EOPAssert((&select_2_5_ab<0, 1, 2, 3, 4, less<int> >( i4, i5, i2, i3, i1, less<int>()) == &i3)); EOPAssert((&select_2_5<0, 1, 2, 3, 4, less<int> >( i4, i5, i2, i3, i1, less<int>()) == &i3)); // int p[5] = {1, 2, 3, 4, 5}; do { if (verbose) { print(" median of ("); print(p[0]); print(" "); print(p[1]); print(" "); print(p[2]); print(" "); print(p[3]); print(" "); print(p[4]); print(") is "); } int m = select_2_5<0, 1, 2, 3, 4,less<int> >( p[0], p[1], p[2], p[3], p[4], less<int>()); EOPAssert(m == 3); if (verbose) { print(m); print_eol(); } } while (next_permutation(p, p + sizeof(p) / sizeof(int), less<int>())); } typedef pair<int, int> int_pair; void test_ch_4() { print(" Chapter 4\n"); // Test derived relations less<int> lt; complement< less< int > > ge = make_complement(lt); converse< less< int > > gt = make_converse(lt); complement_of_converse< less< int > > le = make_complement_of_converse(lt); symmetric_complement< less< int> > eq = make_symmetric_complement(lt); complement< symmetric_complement< less< int> > > ne = make_complement(eq); property_total_ordering(lt, 0, 1, 2); property_reflexive_total_ordering(ge, 2, 1, 0); property_total_ordering(gt, 2, 1, 0); property_reflexive_total_ordering(le, 0, 1, 2); property_transitive(eq, 0, 0, 0); EOPAssert(ge(4, 3)); EOPAssert(gt(4, 3)); EOPAssert(le(3, 4)); EOPAssert(le(4, 4)); EOPAssert(eq(4, 4)); EOPAssert(ne(3, 4)); // Test key_ordering typedef first<int, double> F; F fst; typedef pair<int, double> PID; key_ordering< F, less<int> > ko(fst, less<int>()); PID key_1_2p0 = {1, 2.0}; PID key_2_1p0 = {2, 1.0}; PID key_1_1p0 = {1, 1.0}; EOPAssert(ko(key_1_2p0, key_2_1p0)); EOPAssert(!ko(key_1_2p0, key_1_2p0)); EOPAssert(!ko(key_1_2p0, key_1_1p0)); EOPAssert(!ko(key_1_1p0, key_1_2p0)); // clusters: != > <= >= -- see concept_TotallyOrdered // Test order selection int a = 3; int b = 3; int c = 4; int d = 4; EOPAssert(&select_0_2(a, b, less<int>()) == &a); EOPAssert(&select_0_2(b, a, less<int>()) == &b); EOPAssert(&select_0_2(a, c, less<int>()) == &a); EOPAssert(&select_0_2(c, a, less<int>()) == &a); EOPAssert(select_0_2(a, c, less<int>()) == a); EOPAssert(select_0_2(c, a, less<int>()) == a); EOPAssert(&select_1_2(a, b, less<int>()) == &b); EOPAssert(&select_1_2(b, a, less<int>()) == &a); EOPAssert(&select_1_2(a, c, less<int>()) == &c); EOPAssert(&select_1_2(c, a, less<int>()) == &c); EOPAssert(select_1_2(a, c, less<int>()) == c); EOPAssert(select_1_2(c, a, less<int>()) == c); int_pair p1 = {1, 1}; int_pair p2 = {1, 2}; typedef less_first<int, int> R; EOPAssert((select_0_2<1, 2, R>(p1, p2, R()) == p1)); EOPAssert((select_0_2<1, 2, R>(p2, p1, R()) == p2)); EOPAssert((select_1_2<1, 2, R>(p1, p2, R()) == p2)); EOPAssert((select_1_2<1, 2, R>(p2, p1, R()) == p1)); EOPAssert(&select_0_3(a, b, c, less<int>()) == &a); EOPAssert(&select_0_3(a, c, b, less<int>()) == &a); EOPAssert(&select_0_3(b, a, c, less<int>()) == &b); EOPAssert(&select_0_3(b, c, a, less<int>()) == &b); EOPAssert(&select_0_3(c, a, b, less<int>()) == &a); EOPAssert(&select_0_3(c, b, a, less<int>()) == &b); EOPAssert(select_0_3(a, c, d, less<int>()) == a); EOPAssert(select_0_3(c, a, d, less<int>()) == a); EOPAssert(select_0_3(d, c, a, less<int>()) == a); EOPAssert(&select_2_3(b, c, d, less<int>()) == &d); EOPAssert(&select_2_3(c, b, d, less<int>()) == &d); EOPAssert(&select_2_3(b, d, c, less<int>()) == &c); EOPAssert(&select_2_3(d, b, c, less<int>()) == &c); EOPAssert(&select_2_3(c, d, b, less<int>()) == &d); EOPAssert(&select_2_3(d, c, b, less<int>()) == &c); EOPAssert(select_2_3(a, c, d, less<int>()) == d); EOPAssert(select_2_3(c, a, d, less<int>()) == c); EOPAssert(select_2_3(d, c, a, less<int>()) == c); // Test select_1_3_ab EOPAssert(&select_1_3(a, b, c, less<int>()) == &b); EOPAssert(&select_1_3(a, c, b, less<int>()) == &b); EOPAssert(&select_1_3(b, a, c, less<int>()) == &a); EOPAssert(&select_1_3(b, c, a, less<int>()) == &a); EOPAssert(&select_1_3(c, a, b, less<int>()) == &b); EOPAssert(&select_1_3(c, b, a, less<int>()) == &a); EOPAssert(select_1_3(a, c, d, less<int>()) == c); EOPAssert(select_1_3(c, a, d, less<int>()) == c); EOPAssert(select_1_3(d, c, a, less<int>()) == c); // Test select_1_4_ab_cd // Test select_1_4_ab algorithm_select_1_4(); algorithm_select_1_4_stability_indices(); algorithm_select_2_5_stability_indices(); { const int ca = 1, cb = 2, cc = 3, cd = 4, ce = 5; int b = 12, d = 14; EOPAssert(median_5(1, cb, b, d, 15, less<int>()) == 12); EOPAssert(median_5(ca, cb, cc, cd, ce, less<int>()) == 3); algorithm_median_5(); } { typedef pair<char, int> P; P a_3 = {'a', 3}; P a_4 = {'a', 4}; EOPAssert(min<P>(a_3, a_4) == a_3); EOPAssert(min<P>(a_4, a_3) == a_3); EOPAssert(max<P>(a_3, a_4) == a_4); EOPAssert(max<P>(a_4, a_3) == a_4); } } // Chapter 5. Ordered algebraic structures template<typename T> requires(OrderedAdditiveSemigroup(T)) void concept_OrderedAdditiveSemigroup(T& x, T& y, T& z) { // Precondition: x < y concept_Regular(x); // + : T x T -> T EOPAssert((x + y) + z == x + (y + z)); EOPAssert(x + y == y + x); concept_TotallyOrdered(x, y); EOPAssert(x + z < y + z); } template<typename T> requires(OrderedAdditiveMonoid(T)) void concept_OrderedAdditiveMonoid(T& x, T& y, T& z) { concept_OrderedAdditiveSemigroup(x, y, z); // 0 in T EOPAssert(x + T(0) == x); } template<typename T> requires(OrderedAdditiveGroup(T)) void concept_OrderedAdditiveGroup(T& x, T& y, T& z) { // Precondition: x < y concept_OrderedAdditiveMonoid(x, y, z); // - : T -> T EOPAssert(x + (-x) == T(0)); } template<typename T> requires(OrderedAdditiveGroup(T)) void algorithm_abs(const T& something) { // We need a nonzero number to test with; OrderedAdditiveGroup doesn't guarantee one T zero(0); EOPAssert(something > zero); T x(something); T y(x + something); T z(y + something); concept_OrderedAdditiveGroup(x, y, z); // need x < y < z EOPAssert(abs(zero) == zero); EOPAssert(abs( something) == something); EOPAssert(abs(-something) == something); } template<typename T> requires(CancellableMonoid(T)) void concept_CancellableMonoid(T& x, T& y, T& z) { // Precondition: x < y concept_OrderedAdditiveMonoid(x, y, z); // - : T x T -> T if (x <= y) { T z = y - x; // defined EOPAssert(z + x == y); } } template<typename T> requires(ArchimedeanMonoid(T)) void concept_ArchimedeanMonoid(T& x, T& y, T& z, EOPQuotientType(T) n) { // Precondition: x < y concept_CancellableMonoid(x, y, z); typedef EOPQuotientType(T) N; concept_Integer<N>(n); // slow_remainder terminates for all positive arguments } template<typename T> requires(ArchimedeanGroup(T)) void concept_ArchimedeanGroup(T& x, T& y, T& z, EOPQuotientType(T) n) { // Precondition: x < y concept_ArchimedeanMonoid(x, y, z, n); T tmp = x - y; EOPAssert(tmp < 0); EOPAssert(-tmp == y - x); } template<typename T> requires(ArchimedeanMonoid(T)) // + numerals, successor void algorithms_slow_q_and_r() { typedef long Z; plus<T> plus_T; typedef EOPQuotientType(T) N; T max(1000); T a(0); while (a < max) { T b(1); while (b < max) { T r = slow_remainder(a, b); N q = slow_quotient(a, b); EOPAssert(power(b, q, plus_T, T(0)) + r == a); b = successor(b); } a = successor(a); } } template<typename T> requires(ArchimedeanMonoid(T)) // + numerals, successor void algorithms_q_and_r_nonnegative() { typedef long Z; plus<T> plus_T; typedef EOPQuotientType(T) N; T max(1000); T a(0); while (a < max) { T b(1); while (b < max) { T r = remainder_nonnegative(a, b); pair<N, T> qr = quotient_remainder_nonnegative(a, b); EOPAssert(qr.m1 == r); EOPAssert(power(b, qr.m0, plus_T, T(0)) + r == a); b = successor(b); } a = successor(a); } } template<typename T> requires(ArchimedeanMonoid(T)) // + numerals, successor void algorithms_q_and_r_nonnegative_fibonacci() { typedef long Z; plus<T> plus_T; (void)plus_T; typedef EOPQuotientType(T) N; T max(1000); T a(0); while (a < max) { T b(1); while (b < max) { T r = remainder_nonnegative_fibonacci(a, b); pair<N, T> qr = quotient_remainder_nonnegative_fibonacci(a, b); //EOPAssert(Z(r) == Z(a) % Z(b)); EOPAssert(qr.m1 == r); //EOPAssert(Z(qr.m0) == Z(a) / Z(b)); EOPAssert(power(b, qr.m0, plus_T, T(0)) + r == a); b = successor(b); } a = successor(a); } } template<typename T> requires(HalvableMonoid(T)) // + numerals, successor void algorithms_q_and_r_nonnegative_iterative() { typedef long Z; plus<T> plus_T; typedef EOPQuotientType(T) N; T max(1000); T a(0); while (a < max) { T b(1); while (b < max) { T r = remainder_nonnegative_iterative(a, b); pair<N, T> qr = quotient_remainder_nonnegative_iterative(a, b); EOPAssert(Z(r) == Z(a) % Z(b)); EOPAssert(qr.m1 == r); EOPAssert(Z(qr.m0) == Z(a) / Z(b)); EOPAssert(power(b, qr.m0, plus_T, T(0)) + r == a); b = successor(b); } a = successor(a); } } template<typename T> requires(ArchimedeanMonoid(T)) T largest_power_of_two(T a) { // Precondition: $a > 0$ T b(1); while (b <= a - b) b = b + b; return b; // Postcondition: $(\exists i \geq 0)\,b = 2^i \wedge b \leq a < b+b } template<typename T> requires(ArchimedeanMonoid(T)) // + numerals, successor void algorithm_largest_doubling() { typedef long Z; T max(1000); T a(1); while (a < max) { T b(1); while (b <= a) { T d = largest_doubling(a, b); // EOPAssert(Z(d) % Z(b) == 0); // it is an integral multiple of b // Z n = Z(d) / Z(b); // n = the integral multiple // EOPAssert(largest_power_of_two(n) == n); // n is a power of 2; it is a doubling EOPAssert(d <= a && d > a - d); // it is the largest b = successor(b); } a = successor(a); } } // remainder for double as EuclideanSemimodule double remainder(double x, double y) { return remainder_nonnegative(x, y); } // concept IntegralEOPDomain(T) means // CommutativeSemiring(T) // /\ (all a,b in T) a*b = T(0) => (a = T(0) \/ b = T(0)) // We vary from the usual definition by allowing a semiring rather than a ring. // The second condition means there are no zero divisors. // See van der Waerden, Modern Algebra, volume 1, chapter 3, section 13, // for the construction of a field of quotients from an integral domain. template<typename N> requires(IntegralEOPDomain(N)) struct rational { typedef rational T; N p; // numerator N q; // denominator rational() { } rational(const N& p, const N& q) : p(p), q(q) { EOPAssert(q != N(0)); } rational(const N& x) : p(x), q(N(1)) { } }; template<typename N> requires(IntegralEOPDomain(N)) struct quotient_type< rational<N> > { typedef N type; }; template<typename N> requires(IntegralEOPDomain(N)) rational<N> operator+(const rational<N>& x, const rational<N>& y) { return rational<N>(y.q * x.p + x.q * y.p, x.q * y.q); } template<typename N> requires(IntegralEOPDomain(N)) rational<N> operator-(const rational<N>& x) { return rational<N>(-x.p, x.q); } template<typename N> requires(IntegralEOPDomain(N)) rational<N> operator-(const rational<N>& x, const rational<N>& y) { return x + (-y); } template<typename N> requires(IntegralEOPDomain(N)) rational<N> operator*(const rational<N>& x, const rational<N>& y) { return rational<N>(x.p * y.p, x.q * y.q); } template<typename N> requires(IntegralEOPDomain(N)) rational<N> multiplicative_inverse(const rational<N>& x) { // Precondition: $x.p \neq 0$ return rational<N>(x.q, x.p); } template<typename N> requires(IntegralEOPDomain(N)) rational<N> operator/(const rational<N>& x, const rational<N>& y) { return rational<N>(x.p * y.q, x.q * y.p); // Postcondition: x * multiplicative_inverse(y) } // Multiplication for rational<N> as a semimodule over integers template<typename N> requires(IntegralEOPDomain(N)) rational<N> operator*(const N& n, const rational<N>& x) { return rational<N>(n * x.p, x.q); } template<typename N> requires(IntegralEOPDomain(N)) rational<N> remainder(const rational<N>& x, const rational<N>& y) { return remainder_nonnegative(x, y); } template<typename N> requires(IntegralEOPDomain(N)) bool operator==(const rational<N>& x, const rational<N>& y) { return x.p * y.q == y.p * x.q; } template<typename N> requires(IntegralEOPDomain(N)) bool operator<(const rational<N>& x, const rational<N>& y) { return x.p * y.q < y.p * x.q; } template<typename N> requires(IntegralEOPDomain(N)) void print(const rational<N>& x) { if (zero(x.p)) print("0"); else if (one(x.q)) print(x.p); else { print(x.p); print("/"); print(x.q); } } template<typename T> requires(ArchimedeanGroup(T)) struct ag_quotient_remainder { typedef T input_type_0; typedef T input_type_1; typedef pair<EOPQuotientType(T), T> codomain_type; codomain_type operator()(T a, T b) { EOPAssert(a >= T(0) && b > T(0)); return quotient_remainder_nonnegative(a, b); } }; template<typename T> requires(ArchimedeanGroup(T)) // + numerals, successor void algorithms_signed_q_and_r() { typedef long Z; typedef EOPQuotientType(T) N; T min(-10); T max(10); T a(min); while (a <= max) { T b(a); while (b <= max) { if (b != T(0)) { T r = remainder(a, b, remainder_nonnegative<T>); EOPAssert(abs(r) < abs(b)); pair<N, T> qr = quotient_remainder(a, b, ag_quotient_remainder<T>()); EOPAssert(qr.m1 == r); EOPAssert(qr.m0 * b + r == a); } b = successor(b); } a = successor(a); } } typedef rational<int> Q; bool operator<(const Q& x, const Q& y) { return x.p * y.q < y.p * x.q; } template<> struct quotient_type<double> { typedef long type; // ***** what should this be ????? }; // polynomial<T> is a type constructor; it models the following concept // There could be other models, such as sparse representations. // PolynomialRing(T) equals by definition // ValueType : Polynomial -> CommutativeSemiring // IndexType : Polynomial -> Integer // /\ degree : T -> IndexType(T) // /\ coefficient : T x IndexType(T) -> EOPValueType(T) // /\ lc : T –> EOPValueType(T) // a \mapsto coefficient(a, degree(a)) // /\ tc : T –> EOPValueType(T) // a \mapsto coefficient(a, 0) // /\ indeterminate : -> T // /\ evaluate : T x EOPValueType(T) -> EOPValueType(T) // /\ · : EOPValueType(T) x T -> T // /\ + : T x T -> T // /\ · : T x T -> T // /\ shift_left : T x Integer -> T // (a, n) \mapsto power(indeterminate(), n, ·) · a // /\ ... template<typename T> requires(Ring(T)) struct polynomial { typedef int IndexType; array<T> coeff; // Invariant: degree(f) = size(f.coeff) - 1 /\ // coefficient(f, i) = f.coeff[degree(f) - i] polynomial() : coeff(IndexType(1), IndexType(1), T(0)) { } // f(x) = 0 polynomial(T x_0) : coeff(IndexType(1), IndexType(1), x_0) { } // f(x) = x_0 }; template<typename T> requires(Ring(T)) struct value_type< polynomial<T> > { typedef T type; }; template<typename T> requires(Ring(T)) struct index_type; #define EOPIndexType(T) typename index_type< T >::type template<typename T> requires(Ring(T)) struct index_type< polynomial<T> > { typedef typename polynomial<T>::IndexType type; }; template<typename T> requires(Ring(T)) EOPIndexType(polynomial<T>) operator==(const polynomial<T>& f, const polynomial<T>& g) { return f.coeff == g.coeff; } template<typename T> requires(Ring(T)) EOPIndexType(polynomial<T>) operator<(const polynomial<T>& f, const polynomial<T>& g) { return degree(f) < degree(g) || (degree(g) == degree(f) && f.coeff < g.coeff); } template<typename T> requires(Ring(T)) EOPIndexType(polynomial<T>) degree(const polynomial<T>& f) { // ***** Should degree(polynomial<T>(0)) = -infinity ????? return predecessor(size(f.coeff)); } template<typename T> requires(Ring(T)) void shift_add_in_place(polynomial<T>& f, const T& x_0) { insert(back< array<T> >(f.coeff), x_0); // Postcondition: f'(x) = x * f(x) + x_0 } template<typename T> requires(Ring(T)) void shift_left_in_place(polynomial<T>& f, EOPIndexType(polynomial<T>) n) { // Precondition: n >= 0 while (count_down(n)) shift_add_in_place(f, T(0)); // Postcondition: f'(x) = x^n * f(x) } template<typename T> requires(Ring(T)) T coefficient(const polynomial<T>& f, EOPIndexType(polynomial<T>) i) { // Precondition: $0 \leq i \leq \func{degree}(f)$ return f.coeff[degree(f) - i]; // not a reference, to guarantee the invariant holds } template<typename T> requires(Ring(T)) T lc(const polynomial<T>& f) // leading coefficient { return f.coeff[0]; // Poscondition: returns coefficient(f, degree(f)) } template<typename T> requires(Ring(T)) T tc(const polynomial<T>& f) // trailing coefficient { return f.coeff[size(f.coeff) - 1]; // Poscondition: returns coefficient(f, 0) } template<typename T> requires(Ring(T)) bool monic(const polynomial<T>& f) { return lc(f) == T(1); } template<typename T> requires(Ring(T)) polynomial<T> indeterminate() { polynomial<T> f(T(1)); // f(x) = 1 shift_add_in_place(f, T(0)); // f'(x) = f(x) * x + 0 = 1 * x = x return f; // could be a static const member // Postcondition: returns f(x) = x } template<typename T> requires(Ring(T)) polynomial<T> evaluate(const polynomial<T>& f, const T& x_0) { typedef EOPIndexType(polynomial<T>) I; I n(degree(f)); // Horner's scheme T r = coefficient(f, n); while (!negative(n)) { n = predecessor(n); r = (r * x_0) + coefficient(f, n); } return r; // Postcondition: r = f(x_0) } template<typename T> requires(Ring(T)) polynomial<T> add(const polynomial<T>& f, const polynomial<T>& g, EOPIndexType(polynomial<T>) d, EOPIndexType(polynomial<T>) n_g) { // Precondition: $0 < d = degree(f) - degree(g) \wedge n_g = degree(g)$ typedef EOPIndexType(polynomial<T>) I; polynomial<T> h(lc(f)); I i(1); while (i != d) { shift_add_in_place(h, f.coeff[i]); i = successor(i); } I j(0); while (j <= n_g) { shift_add_in_place(h, f.coeff[i] + g.coeff[j]); i = successor(i); j = successor(j); } return h; // Postcondition: h(x) = f(x) + g(x) } template<typename T> requires(Ring(T)) polynomial<T> operator+(const polynomial<T>& f, const polynomial<T>& g) { typedef EOPIndexType(polynomial<T>) I; I n_f = degree(f); I n_g = degree(g); if (n_f > n_g) return add(f, g, n_f - n_g, n_g); else if (n_g > n_f) return add(g, f, n_g - n_f, n_f); I i(0); T x; while (i <= n_f) { x = f.coeff[i] + g.coeff[i]; if (x != T(0)) break; i = successor(i); } polynomial<T> h(x); while (i < n_f) { i = successor(i); shift_add_in_place(h, f.coeff[i] + g.coeff[i]); }; return h; // Postcondition: h(x) = f(x) + g(x) } template<typename T, typename F> requires(Ring(T) && Transformation(F) && T == EOPDomain(F)) void transform_coefficients_in_place(polynomial<T>& f, F trans) { typedef EOPIndexType(polynomial<T>) I; I i(0); I n = degree(f); while (i <= n) { f.coeff[i] = trans(f.coeff[i]); i = successor(i); } } template<typename T> requires(Ring(T)) polynomial<T> operator-(polynomial<T> f) // f is a copy { transform_coefficients_in_place(f, negate<T>()); return f; // Postcondition: f'(x) = -f(x) } template<typename T> requires(Ring(T)) polynomial<T> operator-(const polynomial<T>& f, const polynomial<T>& g) { return f + (-g); // Postcondition: returns h(x) = f(x) - g(x) } template<typename T> requires(Ring(T)) polynomial<T> product(const polynomial<T>& f, const polynomial<T>& g) { // Precondition: degree(f) <= degree(g) typedef EOPIndexType(polynomial<T>) I; I n_f = degree(f); I n = n_f + degree(g); polynomial<T> h(lc(f) * lc(g)); n = predecessor(n); // Invariant: shift_left(r, n) is the // (deg(f)+deg(g)-n) highest-order coefficients of the result while (!negative(n)) { T sum(0); I i_f(0); while (i_f <= min(n_f, n)) { sum = sum + coefficient(f, i_f) * coefficient(g, n - i_f); i_f = successor(i_f); } shift_add_in_place(h, sum); n = predecessor(n); } return h; // Postcondition: h(x) = f(x) * g(x) } template<typename T> requires(Ring(T)) polynomial<T> operator*(const polynomial<T>& f, const polynomial<T>& g) { if (degree(f) <= degree(g)) return product(f, g); else return product(g, f); } template<typename T> requires(Ring(T)) polynomial<T> operator*(T x_0, const polynomial<T>& f) { polynomial<T> h(f); transform_coefficients_in_place( h, multiplies_transformation< multiplies<T> >(x_0, multiplies<T>())); return h; // Postcondition: h(x) = x_0 * f(x) } template<typename T> requires(Ring(T)) polynomial<T> shift_left(const polynomial<T>& f, EOPIndexType(polynomial<T>) n) { polynomial<T> h(f); shift_left_in_place(h, n); return h; // Postcondition: h(x) = x^n * f(x) } template<typename T> requires(Ring(T)) pair< polynomial<T>, polynomial<T> > quotient_remainder(const polynomial<T>& f, const polynomial<T>&g) { // Precondition: unit(lc(g)) T u = multiplicative_inverse(lc(g)); polynomial<T> q(0); polynomial<T> r = f; while (degree(r) >= degree(g)) { // Invariant: f = q * g + r polynomial<T> q_i = shift_left(polynomial<T>(lc(r) * u), degree(r) - degree(g)); q = q + q_i; r = r - q_i * g; } return make_pair(q, r); // Postcondition: f = q * g + r /\ degree(r) < degree(g) } template<typename T> requires(Ring(T)) polynomial<T> remainder(const polynomial<T>& f, const polynomial<T>&g) { // Precondition: unit(lc(g)) return quotient_remainder(f, g).m1; } template<typename T> requires(Ring(T)) void print_coefficient(T c, EOPIndexType(polynomial<T>) i) { if (!one(c) || zero(i)) { print(c); if (positive(i)) print("*"); } if (positive(i)) { print("x"); if (i > EOPIndexType(polynomial<T>)(1)) { print("^"); print(i); } } } template<typename T> requires(Ring(T)) void print(const polynomial<T>& f) { typedef EOPIndexType(polynomial<T>) I; print("polynomial("); I i = degree(f); T c = coefficient(f, i); print_coefficient(c, i); i = predecessor(i); while (!negative(i)) { c = coefficient(f, i); if (!zero(c)) { if (negative(c)) { print(" - "); c = -c; } else print(" + "); print_coefficient(c, i); } i = predecessor(i); } print(")"); } void test_ch_5() { print(" Chapter 5\n"); algorithm_abs<int>(1); algorithm_abs<long long>(1l); algorithm_abs<double>(1.0); algorithm_abs<long double>(1.0l); algorithm_abs< rational<int> >(rational<int>(1, 2)); // type_functions.h defines EOPQuotientType for several built-in integral types { typedef int T; T x(0); T y(1); T z(2); quotient_type<T>::type n(3); concept_ArchimedeanGroup<T>(x, y, z, n); } { typedef long int T; T x(0); T y(1); T z(2); quotient_type<T>::type n(3); concept_ArchimedeanGroup<T>(x, y, z, n); } { typedef Q T; T x(0); T y(1); T z(2); quotient_type<T>::type n(3); concept_ArchimedeanGroup<T>(x, y, z, n); } { typedef double T; T x(0.0); T y(1.0); T z(2.0); quotient_type<T>::type n(3); concept_ArchimedeanGroup<T>(x, y, z, n); } algorithms_slow_q_and_r<int>(); algorithms_slow_q_and_r<long>(); algorithms_slow_q_and_r<Q>(); algorithms_q_and_r_nonnegative<int>(); algorithms_q_and_r_nonnegative<long>(); algorithms_q_and_r_nonnegative<Q>(); algorithms_q_and_r_nonnegative_fibonacci<int>(); algorithms_q_and_r_nonnegative_fibonacci<long>(); algorithms_q_and_r_nonnegative_fibonacci<Q>(); algorithms_q_and_r_nonnegative_iterative<int>(); algorithms_q_and_r_nonnegative_iterative<long>(); // algorithms_q_and_r_nonnegative_iterative<Q>(); algorithm_largest_doubling<int>(); algorithm_largest_doubling<long>(); algorithm_largest_doubling<double>(); algorithm_largest_doubling<Q>(); EOPAssert(subtractive_gcd_nonzero(1000, 990) == 10); EOPAssert(subtractive_gcd_nonzero(1000u, 990u) == 10u); EOPAssert(subtractive_gcd_nonzero(0.75, 0.5) == 0.25); EOPAssert(subtractive_gcd_nonzero(Q(3, 4), Q(1, 2)) == Q(1, 4)); EOPAssert(subtractive_gcd(1000, 990) == 10); EOPAssert(subtractive_gcd(1000, 0) == 1000); EOPAssert(subtractive_gcd(0, 990) == 990); EOPAssert(subtractive_gcd(1000u, 990u) == 10u); EOPAssert(subtractive_gcd(1000u, 0u) == 1000u); EOPAssert(subtractive_gcd(0u, 990u) == 990u); EOPAssert(subtractive_gcd(0.75, 0.5) == 0.25); EOPAssert(subtractive_gcd(0.75, 0.0) == 0.75); EOPAssert(subtractive_gcd(0.0, 0.5) == 0.5); EOPAssert(subtractive_gcd(Q(3, 4), Q(1, 2)) == Q(1, 4)); EOPAssert(subtractive_gcd(Q(3, 4), Q(0, 2)) == Q(3, 4)); EOPAssert(subtractive_gcd(Q(0, 4), Q(1, 2)) == Q(1, 2)); EOPAssert(fast_subtractive_gcd(1000, 990) == 10); EOPAssert(fast_subtractive_gcd(1000, 0) == 1000); EOPAssert(fast_subtractive_gcd(0, 990) == 990); EOPAssert(fast_subtractive_gcd(1000u, 990u) == 10u); EOPAssert(fast_subtractive_gcd(1000u, 0u) == 1000u); EOPAssert(fast_subtractive_gcd(0u, 990u) == 990u); EOPAssert(fast_subtractive_gcd(0.75, 0.5) == 0.25); EOPAssert(fast_subtractive_gcd(0.75, 0.0) == 0.75); EOPAssert(fast_subtractive_gcd(0.0, 0.5) == 0.5); EOPAssert(fast_subtractive_gcd(Q(3, 4), Q(1, 2)) == Q(1, 4)); EOPAssert(fast_subtractive_gcd(Q(3, 4), Q(0, 2)) == Q(3, 4)); EOPAssert(fast_subtractive_gcd(Q(0, 4), Q(1, 2)) == Q(1, 2)); // gcd for EuclideanSemiring EOPAssert(gcd(1000, 990) == 10); EOPAssert(gcd(1000, 0) == 1000); EOPAssert(gcd(0, 990) == 990); EOPAssert(gcd(1000u, 990u) == 10u); EOPAssert(gcd(1000u, 0u) == 1000u); EOPAssert(gcd(0u, 990u) == 990u); { typedef polynomial< rational<int> > Q_X; Q_X a = shift_left(Q_X(1), 2) - Q_X(1); // x^2 - 1 Q_X b = shift_left(Q_X(1), 1) + Q_X(1); // x + 1 if (verbose) { print(" poly 1 = "); print(Q_X(1)); print_eol(); print(" poly a = "); print(a); print_eol(); print(" poly 2*a = "); print(Q_X(2) * a); print_eol(); print(" poly b = "); print(b); print_eol(); print(" poly a * b = "); print(a * b); print_eol(); pair<Q_X, Q_X> p = quotient_remainder(a, b); print(" poly a / b = "); print(p.m0); print(" remainder "); print(p.m1); print_eol(); } EOPAssert(gcd<Q_X>(a, b) == b); } // gcd for EuclideanSemimodule EOPAssert(gcd(1000, 990) == 10); EOPAssert(gcd(1000, 0) == 1000); EOPAssert(gcd(0, 990) == 990); EOPAssert(gcd(1000u, 990u) == 10u); EOPAssert(gcd(1000u, 0u) == 1000u); EOPAssert(gcd(0u, 990u) == 990u); EOPAssert(gcd(0.75, 0.5) == 0.25); EOPAssert(gcd(0.75, 0.0) == 0.75); EOPAssert(gcd(0.0, 0.5) == 0.5); EOPAssert(gcd(Q(3, 4), Q(1, 2)) == Q(1, 4)); EOPAssert(gcd(Q(3, 4), Q(0, 2)) == Q(3, 4)); EOPAssert(gcd(Q(0, 4), Q(1, 2)) == Q(1, 2)); algorithms_signed_q_and_r<int>(); algorithms_signed_q_and_r<long>(); algorithms_signed_q_and_r<Q>(); } // Chapter 6. Iterators // "Thunk"-style iterator template<typename T> requires(Semiring(T)) struct square_of_i { T i; square_of_i(T i) : i(i) { } }; template<typename T> requires(Semiring(T)) struct value_type< square_of_i<T> > { typedef T type; }; template<typename T> requires(Semiring(T)) square_of_i<T> successor(const square_of_i<T>& x) { return square_of_i<T>(x.i + T(1)); } template<typename T> requires(Semiring(T)) T source(const square_of_i<T>& x) { return x.i * x.i; } template<typename T> requires(Semiring(T)) bool operator==(const square_of_i<T>& x, const square_of_i<T>& y) { return x.i == y.i; } template<typename Op> requires(BinaryOperation(Op)) struct accumulate { typedef EOPDomain(Op) T; typedef T input_type_0; typedef void codomain_type; Op op; T sum; accumulate(Op op, const T& x) : op(op), sum(x) { } void operator()(T const& x) { sum = op(sum, x); } }; template<typename T> requires(Regular(T)) struct identity { typedef T input_type_0; typedef T codomain_type; T operator()(T const& x) { return x; } }; void test_ch_6() { print(" Chapter 6\n"); { int i; i = int(0); increment(i); EOPAssert(i == int(1)); i = int(99); increment(i); EOPAssert(i == int(100)); double x[100]; EOPpointer(double) fx; fx = x; increment(fx); EOPAssert(fx == x + 1); fx = &x[99]; increment(fx); EOPAssert(fx == x + 100); } { typedef int Z; // Integer(Z) Z a[] = {0, 1, 2, 3, 4, 5}; slist<Z> l(counted_range<Z*>(a, sizeof(a)/sizeof(Z))); typedef iterator_type< slist<Z> >::type I; typedef distance_type< I >::type N; // Integer(N) slist_iterator<Z> f = begin(l) + N(3); EOPAssert(source(f) == Z(3)); EOPAssert(f - begin(l) == N(3)); EOPAssert(begin(l) - begin(l) == N(0)); EOPAssert(for_each(begin(l), end(l), accumulate< plus<Z> >(plus<Z>(), Z(0))).sum == 15); EOPAssert(find(begin(l), end(l), Z(-1)) == end(l)); EOPAssert(find(begin(l), end(l), Z(5)) == begin(l) + N(5)); Z b[] = {1, 1, 1}; slist<Z> lb(counted_range<Z*>(b, sizeof(b)/sizeof(Z))); EOPAssert(find_not(begin(lb), end(lb), Z(1)) == end(lb)); EOPAssert(find_not(begin(lb), end(lb), Z(0)) == begin(lb)); EOPAssert(find_if(begin(l), end(l), negative<Z>) == end(l)); EOPAssert(find_if(begin(l), end(l), make_lower_bound_predicate(3, less<Z>())) == begin(l) + N(3)); EOPAssert(find_if_not(begin(lb), end(lb), positive<Z>) == end(lb)); EOPAssert(find_if_not(begin(l), end(l), positive<Z>) == begin(l)); EOPAssert(all(begin(lb), end(lb), positive<Z>)); EOPAssert(none(begin(l), end(l), negative<Z>)); EOPAssert(some(begin(l), end(l), positive<Z>)); EOPAssert(not_all(begin(l), end(l), positive<Z>)); EOPAssert(all(Z(1), Z(100), positive<Z>)); EOPAssert(none(Z(1), Z(100), negative<Z>)); EOPAssert(some(Z(0), Z(100), odd<Z>)); EOPAssert(not_all(Z(0), Z(100), odd<Z>)); EOPAssert(count_if(begin(l), end(l), even<Z>, Z(100)) == Z(100) + Z(3)); EOPAssert(count_if(begin(l), end(l), even<Z>) == Z(3)); EOPAssert(count_if_not(begin(l), end(l), positive<Z>, Z(-1)) == Z(-1) + Z(1)); EOPAssert(count_if_not(begin(l), end(l), positive<Z>) == Z(1)); EOPAssert(count(begin(l), end(l), Z(2), Z(100)) == Z(100) + Z(1)); EOPAssert(count(begin(l), end(l), Z(2)) == Z(1)); EOPAssert(count_not(begin(l), end(l), Z(2), Z(100)) == Z(100) + Z(5)); EOPAssert(count_not(begin(l), end(l), Z(2)) == Z(5)); EOPAssert(reduce_nonempty(0, 50, plus<Z>(), identity<Z>()) == Z(49*50/2)); EOPAssert(reduce_nonempty(0, 1, plus<Z>(), identity<Z>()) == Z(0)); EOPAssert(reduce_nonempty(begin(l), end(l), plus<Z>()) == Z(15)); EOPAssert(reduce_nonempty(begin(l), successor(begin(l)), plus<Z>()) == Z(0)); EOPAssert(reduce(0, 0, plus<Z>(), identity<Z>(), Z(0)) == Z(0)); EOPAssert(reduce(0, 50, plus<Z>(), identity<Z>(), Z(0)) == Z(49*50/2)); EOPAssert(reduce(0, 1, plus<Z>(), identity<Z>(), Z(0)) == Z(0)); EOPAssert(reduce(begin(l), begin(l), plus<Z>(), Z(0)) == Z(0)); EOPAssert(reduce(begin(l), end(l), plus<Z>(), Z(0)) == Z(15)); EOPAssert(reduce(begin(l), successor(begin(l)), plus<Z>(), Z(0)) == Z(0)); Z c[] = {0, 1, 0, 2, 0, 3, 0, 4, 0, 5}; slist<Z> lc(counted_range<Z*>(c, sizeof(c)/sizeof(Z))); EOPAssert(reduce_nonzeroes(0, 0, plus<Z>(), identity<Z>(), Z(0)) == Z(0)); EOPAssert(reduce_nonzeroes(0, 50, plus<Z>(), identity<Z>(), Z(0)) == Z(49*50/2)); EOPAssert(reduce_nonzeroes(0, 1, plus<Z>(), identity<Z>(), Z(0)) == Z(0)); EOPAssert(reduce_nonzeroes(begin(lc), begin(lc), plus<Z>(), Z(0)) == Z(0)); EOPAssert(reduce_nonzeroes(begin(lc), end(lc), plus<Z>(), Z(0)) == Z(15)); EOPAssert(reduce_nonzeroes( begin(lc), successor(begin(lc)), plus<Z>(), Z(0)) == Z(0)); EOPAssert(reduce(begin(l), end(l)) == Z(15)); EOPAssert(reduce(begin(lb), end(lb)) == Z(3)); EOPAssert(reduce(begin(lc), end(lc)) == Z(15)); { pair<accumulate< plus<Z> >, iterator_type< slist<Z> >::type> p = for_each_n(begin(l), size(l), accumulate< plus<Z> >(plus<Z>(), Z(0))); EOPAssert(p.m0.sum == 15 && p.m1 == end(l)); } { pair<iterator_type< slist<Z> >::type, N> p = find_n(begin(l), size(l), Z(-1)); EOPAssert(p.m0 == end(l) && p.m1 == 0); p = find_n(begin(l), size(l), Z(5)); EOPAssert(p.m0 == begin(l) + N(5) && p.m1 == N(1)); } EOPAssert(find_if( begin(l), end(l), make_lower_bound_predicate(3, less<Z>())) != end(l)); EOPAssert(find_if_unguarded( begin(l), make_lower_bound_predicate(3, less<Z>())) == begin(l) + N(3)); EOPAssert(find_if_not(begin(l), end(l), positive<Z>) != end(l)); EOPAssert(find_if_not_unguarded(begin(l), positive<Z>) == begin(l)); { pair<I, Z> p0 = find_mismatch(begin(l), end(l), Z(0), Z(6), equal<Z>()); EOPAssert(p0.m0 == end(l) && p0.m1 == Z(6)); p0 = find_mismatch(begin(l), end(l), Z(0), Z(7), equal<Z>()); EOPAssert(p0.m0 == end(l) && p0.m1 == Z(6)); p0 = find_mismatch(begin(l), end(l), Z(0), Z(4), equal<Z>()); EOPAssert(p0.m0 == begin(l) + N(4) && p0.m1 == Z(4)); Z d[] = {0, 1, 2, 3, -4, 5}; slist<Z> ld(counted_range<Z*>(d, sizeof(d)/sizeof(Z))); pair<I, I> p1 = find_mismatch( begin(l), end(l), begin(ld), end(ld), equal<Z>()); EOPAssert(p1.m0 == begin(l) + N(4) && p1.m1 == begin(ld) + N(4)); } { EOPAssert(find_adjacent_mismatch(begin(lb), end(lb), equal<Z>()) == end(lb)); Z e[] = {0, 0, 0, 1, 0, 0}; slist<Z> le(counted_range<Z*>(e, sizeof(e)/sizeof(Z))); EOPAssert(find_adjacent_mismatch(begin(le), end(le), equal<Z>()) == begin(le) + N(3)); EOPAssert(find_adjacent_mismatch_forward( begin(lb), end(lb), equal<Z>()) == end(lb)); EOPAssert(find_adjacent_mismatch_forward( begin(le), end(le), equal<Z>()) == begin(le) + N(3)); } EOPAssert(relation_preserving(begin(l), begin(l), less<Z>())); EOPAssert(relation_preserving(begin(l), end(l), less<Z>())); EOPAssert(strictly_increasing_range(begin(l), begin(l), less<Z>())); EOPAssert(strictly_increasing_range(begin(l), end(l), less<Z>())); EOPAssert(!strictly_increasing_range(begin(lb), end(lb), less<Z>())); EOPAssert(!strictly_increasing_range(begin(lc), end(lc), less<Z>())); EOPAssert(relation_preserving( begin(l), end(l), make_complement_of_converse(less<Z>()))); { less<Z> lt; complement_of_converse< less<Z> > leq = {lt}; EOPAssert(leq(Z(0), Z(0))); EOPAssert(leq(Z(0), Z(1))); EOPAssert(!leq(Z(1), Z(0))); } EOPAssert(increasing_range(begin(l), begin(l), less<Z>())); EOPAssert(increasing_range(begin(l), end(l), less<Z>())); EOPAssert(increasing_range(begin(lb), end(lb), less<Z>())); EOPAssert(!increasing_range(begin(lc), end(lc), less<Z>())); { Z f[] = {0, 0, 1, 1, 2, 3, 5, 5}; slist<Z> lf(counted_range<Z*>(f, sizeof(f)/sizeof(Z))); EOPAssert(!strictly_increasing_range(begin(lf), end(lf), less<Z>())); EOPAssert(increasing_range(begin(lf), end(lf), less<Z>())); } EOPAssert(partitioned(begin(l), begin(l), negative<Z>)); EOPAssert(partitioned(begin(l), end(l), negative<Z>)); EOPAssert(!partitioned(begin(l), end(l), zero<Z>)); EOPAssert(partitioned(begin(lb), end(lb), even<Z>)); EOPAssert(partitioned(begin(lb), end(lb), odd<Z>)); EOPAssert(partitioned( begin(l), end(l), make_lower_bound_predicate(3, less<Z>()))); EOPAssert(partitioned( begin(l), end(l), make_upper_bound_predicate(3, less<Z>()))); { Z g[] = {0, 2, 4, 1, 3, 5}; slist<Z> lg(counted_range<Z*>(g, sizeof(g)/sizeof(Z))); EOPAssert(partitioned(begin(lg), end(lg), odd<Z>)); EOPAssert(!partitioned(begin(lg), end(lg), even<Z>)); } EOPAssert(partition_point_n(begin(lb), size(lb), zero<Z>) == end(lb)); EOPAssert(partition_point_n(begin(lb), size(lb), odd<Z>) == begin(lb)); EOPAssert(partition_point_n( begin(l), size(l), make_lower_bound_predicate(3, less<Z>())) == begin(l) + N(3)); EOPAssert(partition_point(begin(lb), end(lb), zero<Z>) == end(lb)); EOPAssert(partition_point(begin(lb), end(lb), odd<Z>) == begin(lb)); EOPAssert(partition_point( begin(l), end(l), make_lower_bound_predicate(3, less<Z>())) == begin(l) + N(3)); { // bidirectional iterators Z h[] = {0, 1, 2, 3, 4, 5}; list<Z> ah(counted_range<Z*>(h, sizeof(h)/sizeof(Z))); EOPAssert(end(ah) - 1 == begin(ah) + (size(ah) - 1)); EOPAssert(find_backward_if(begin(ah), end(ah), zero<Z>) == successor(begin(ah))); EOPAssert(find_backward_if(begin(ah), end(ah), negative<Z>) == begin(ah)); EOPAssert(find_backward_if_unguarded(end(ah), zero<Z>) == begin(ah)); EOPAssert(find_backward_if_not(begin(ah), end(ah), zero<Z>) == end(ah)); EOPAssert(find_backward_if_not(begin(ah), end(ah), positive<Z>) == successor(begin(ah))); EOPAssert(find_backward_if_not_unguarded(end(ah), positive<Z>) == begin(ah)); } { // random access iterators Z h[] = {0, 1, 2, 3, 4, 5}; array<Z> ah(counted_range<Z*>(h, sizeof(h)/sizeof(Z))); EOPAssert(end(ah) - 1 == begin(ah) + (size(ah) - 1)); EOPAssert(find_backward_if(begin(ah), end(ah), zero<Z>) == successor(begin(ah))); EOPAssert(find_backward_if(begin(ah), end(ah), negative<Z>) == begin(ah)); EOPAssert(find_backward_if_not(begin(ah), end(ah), zero<Z>) == end(ah)); EOPAssert(find_backward_if_not(begin(ah), end(ah), positive<Z>) == successor(begin(ah))); } } int a[] = {0, 1, 2, 2, 4, 4, 5}; EOPpointer(int) f = a; EOPpointer(int) l = a + sizeof(a) / sizeof(int); distance_type<int*>::type n = l - f; EOPpointer(int) m; m = lower_bound_n(f, n, 2, less<int>()); EOPAssert(m == a + 2); m = upper_bound_n(f, n, 2, less<int>()); EOPAssert(m == a + 4); m = lower_bound_n(f, n, 3, less<int>()); EOPAssert(m == a + 4); m = upper_bound_n(f, n, 3, less<int>()); EOPAssert(m == a + 4); { const int N = 9; int s0 = reduce(square_of_i<int>(0), square_of_i<int>(N + 1), plus<int>(), 0); int s1 = reduce_balanced( square_of_i<int>(0), square_of_i<int>(N + 1), plus<int>(), 0); if (verbose) { print(" reduction of thunk iterator\n"); print(" reduce(square(i), 0<=i<10, +) = "); print(s0); print_eol(); print(" reduce(square(i), 0<=i<10, +) = "); print(s1); print_eol(); } EOPAssert(s0 == s1); EOPAssert(s0 == (2 * N * N * N + 3 * N * N + N) / 6); } } // Chapter 7. Coordinate structures template<typename C> requires(BifurcateCoordinate(C)) struct count_visits { typedef visit input_type_0; typedef C input_type_1; typedef void codomain_type; int n_pre, n_in, n_post; count_visits() : n_pre(0), n_in(0), n_post(0) { } void operator()(visit v, C) { switch (v) { case pre: n_pre = successor(n_pre); break; case in: n_in = successor(n_in); break; case post: n_post = successor(n_post); break; } } }; template<typename Z, typename X> void algorithms_lexicographical() { print(" lexicographical\n"); print(" ***** to do: parameterize by range type\n"); verify_conservation<int> v(slist_node_count); Z a[] = {0, 1, 2, 3, 4, 5}; typedef EOPpointer(Z) I; I f_a = a; I l_a = f_a + (sizeof(a) / sizeof(Z)); slist<Z> la(counted_range<Z*>(a, sizeof(a) / sizeof(Z))); Z b[] = {0, 1, 2, 3, 4, -5}; I f_b = b; I l_b = f_b + (sizeof(b) / sizeof(Z)); EOPAssert(lexicographical_equivalent(f_a, l_a, begin(la), end(la), equal<Z>())); EOPAssert(lexicographical_equal(f_a, l_a, begin(la), end(la))); EOPAssert(!lexicographical_equal(f_b, l_b, begin(la), end(la))); EOPAssert((size(la) == 6 && lexicographical_equal_k<6, I, EOPIteratorType(slist<Z>)>()(f_a, begin(la)))); typedef EOPDistanceType(I) NP; EOPAssert( lexicographical_compare(f_a, f_a, f_a, l_a, less<Z>())); EOPAssert( lexicographical_compare(f_a, f_a + NP(4), f_a, l_a, less<Z>())); EOPAssert( lexicographical_compare(f_a, f_a + NP(5), f_a, l_a, less<Z>())); EOPAssert(!lexicographical_compare(f_a, f_a + NP(6), f_a, l_a, less<Z>())); EOPAssert(!lexicographical_compare(f_a, l_a, f_a, f_a + NP(4), less<Z>())); less<Z> lt; comparator_3_way< less<Z> > comp = {lt}; EOPAssert(lexicographical_compare_3way(f_a, l_a, f_b, l_b, comp) == -1); EOPAssert(lexicographical_compare_3way(f_a, l_a, f_a, l_a, comp) == 0); EOPAssert(lexicographical_compare_3way(f_b, l_b, f_a, l_a, comp) == 1); EOPAssert( lexicographical_less(f_a, f_a, f_a, l_a)); EOPAssert( lexicographical_less(f_a, f_a + NP(4), f_a, l_a)); EOPAssert( lexicographical_less(f_a, f_a + NP(5), f_a, l_a)); EOPAssert(!lexicographical_less(f_a, f_a + NP(6), f_a, l_a)); EOPAssert(!lexicographical_less(f_a, l_a, f_a, f_a + NP(4))); EOPAssert((!lexicographical_less_k<6, I, I>()(f_a, f_b))); EOPAssert((lexicographical_less_k<6, I, I>()(f_b, f_a))); } template<typename T, typename T_X> requires(Tree(T) && Tree(T_X)) void algorithms_bifurcate_coordinates() { print(" bifurcate coordinates\n"); typedef EOPCoordinateType(T) C; typedef EOPWeightType(T) N; typedef EOPCoordinateType(T_X) C_X; T t0; T t4(4); T t3_45(3, t4, T(5)); T t2_345_678(2, t3_45, T(6, T(7), T(8))); T t(1, t2_345_678, T(9, T(10, T(11), T(12)), T(13, T(14), T(15)))); if (verbose) { print("t4: "); print(t4); print_eol(); print("t3_45: "); print(t3_45); print_eol(); print("t2_345_678: "); print(t2_345_678); print_eol(); print("t: "); print(t); print_eol(); } C r = begin(t); EOPAssert(!empty(r)); EOPAssert(has_left_successor(r)); C r_l = left_successor(r); EOPAssert(!empty(r_l)); EOPAssert(has_left_successor(r_l)); C r_l_l = left_successor(r_l); EOPAssert(!empty(r_l_l)); EOPAssert(empty(begin(t0))); EOPAssert(weight_recursive(begin(t0)) == N(0)); EOPAssert(weight_recursive(begin(t4)) == N(1)); EOPAssert(weight_recursive(begin(t3_45)) == N(3)); EOPAssert(weight_recursive(begin(t2_345_678)) == N(7)); EOPAssert(weight_recursive(begin(t)) == N(15)); EOPAssert(height_recursive(begin(t0)) == N(0)); EOPAssert(height_recursive(begin(t4)) == N(1)); EOPAssert(height_recursive(begin(t3_45)) == N(2)); EOPAssert(height_recursive(begin(t2_345_678)) == N(3)); EOPAssert(height_recursive(begin(t)) == N(4)); count_visits<C> proc; proc = traverse_nonempty(begin(t), proc); EOPAssert(proc.n_pre == N(15) && proc.n_in == N(15) && proc.n_post == N(15)); //C c_r = begin(t3_45); T s4(-4); T s3_45(-3, t4, T(-5)); T s2_345_678(-2, t3_45, T(-6, T(-7), T(-8))); T s(-1, t2_345_678, T(-9, T(-10, T(-11), T(-12)), T(-13, T(-14), T(-15)))); T_X x4('d'); T_X x3_45('c', x4, T_X('e')); T_X x2_345_678('b', x3_45, T_X('f', T_X('g'), T_X('h'))); T_X x('a', x2_345_678, T_X('i', T_X('j', T_X('k'), T_X('l')), T_X('m', T_X('n'), T_X('o')))); EOPAssert(bifurcate_isomorphic_nonempty(begin(t), begin(t))); EOPAssert(bifurcate_isomorphic_nonempty(begin(t), begin(s))); EOPAssert(!bifurcate_isomorphic_nonempty(begin(t), begin(t2_345_678))); EOPAssert(bifurcate_isomorphic_nonempty(begin(t), begin(x))); EOPAssert(bifurcate_isomorphic_nonempty( left_successor(begin(t)), right_successor(begin(x)))); T u(t); if (verbose) { print("u(t): "); print(u); print_eol(); } EOPAssert(t == u); EOPAssert(bifurcate_equivalent_nonempty( begin(t), begin(u), equal<EOPValueType(T)>())); EOPAssert(!bifurcate_equivalent_nonempty( begin(t), begin(t2_345_678), equal<EOPValueType(T)>())); // These exercise bifurcate_compare_nonempty EOPAssert(!(t < u) && !(u < t)); EOPAssert(T() < T(0)); EOPAssert(!(T(0) < T())); EOPAssert(T(0) < T(1)); EOPAssert(!(T(1) < T(0))); EOPAssert(T(0, T(1, T(), T()), T()) < T(1, T(), T())); EOPAssert(!(T(1, T(), T()) < T(0, T(1, T(), T()), T()))); EOPAssert(T(0, T(), T()) < T(0, T(0), T())); EOPAssert(!(T(0, T(0), T()) < T(0, T(), T()))); EOPAssert(T(0, T(), T()) < T(0, T(), T(0))); EOPAssert(!(T(0, T(), T(0)) < T(0, T(), T()))); EOPAssert(T(0, T(0), T()) < T(0, T(0), T(0))); EOPAssert(!(T(0, T(0), T(0)) < T(0, T(0), T()))); } template <typename T, typename T_X> requires(Tree(T) && Tree(T_X) && Integer(EOPValueType(T)) && Character(EOPValueType(T_X))) void algorithms_bidirectional_bifurcate_coordinates() { print(" bidirectional bifurcate coordinates\n"); typedef EOPValueType(T) Z; typedef EOPCoordinateType(T) C; typedef EOPWeightType(T) N; typedef EOPCoordinateType(T_X) C_X; T t0; T t4(4); T t3_45(3, t4, T(5)); T t2_345_678(2, t3_45, T(6, T(7), T(8))); T t(1, t2_345_678, T(9, T(10, T(11), T(12)), T(13, T(14), T(15)))); if (verbose) { print("t4: "); print(t4); print_eol(); print("t3_45: "); print(t3_45); print_eol(); print("t2_345_678: "); print(t2_345_678); print_eol(); print("t: "); print(t); print_eol(); } C root = begin(t); EOPAssert(has_left_successor(root)); C root_l = left_successor(root); EOPAssert(is_left_successor(root_l)); EOPAssert(!is_right_successor(root_l)); EOPAssert(has_right_successor(root)); C root_r = right_successor(root); EOPAssert(is_right_successor(root_r)); EOPAssert(!is_left_successor(root_r)); EOPAssert(has_left_successor(root_l)); C root_l_l = left_successor(root_l); count_visits<C> proc; proc = traverse(begin(t), proc); EOPAssert(proc.n_pre == N(15) && proc.n_in == N(15) && proc.n_post == N(15)); C c_r = begin(t3_45); C c = c_r; typedef GetBifurcateCoordinateState<C> State; typename State::type v = State::make(); int dh; dh = traverse_step(v, c); EOPAssert(dh == 1 && c == left_successor(c_r) && state(v) == pre); dh = traverse_step(v, c); EOPAssert(dh == 0 && c == left_successor(c_r) && state(v) == in); dh = traverse_step(v, c); EOPAssert(dh == 0 && c == left_successor(c_r) && state(v) == post); dh = traverse_step(v, c); EOPAssert(dh == -1 && c == c_r && state(v) == in); dh = traverse_step(v, c); EOPAssert(dh == 1 && c == right_successor(c_r) && state(v) == pre); dh = traverse_step(v, c); EOPAssert(dh == 0 && c == right_successor(c_r) && state(v) == in); dh = traverse_step(v, c); EOPAssert(dh == 0 && c == right_successor(c_r) && state(v) == post); dh = traverse_step(v, c); EOPAssert(dh == -1 && c == c_r && state(v) == post); EOPAssert(reachable(root, root_l_l)); EOPAssert(!reachable(root_l_l, root)); EOPAssert(weight(begin(t0)) == N(0)); EOPAssert(weight(begin(t4)) == N(1)); EOPAssert(weight(begin(t3_45)) == N(3)); EOPAssert(weight(begin(t2_345_678)) == N(7)); EOPAssert(weight(begin(t)) == N(15)); EOPAssert(height(begin(t0)) == N(0)); EOPAssert(height(begin(t4)) == N(1)); EOPAssert(height(begin(t3_45)) == N(2)); EOPAssert(height(begin(t2_345_678)) == N(3)); EOPAssert(height(begin(t)) == N(4)); proc.n_pre = 0; proc.n_in = 0; proc.n_post = 0; proc = traverse(begin(t0), proc); EOPAssert(proc.n_pre == N(0) && proc.n_in == N(0) && proc.n_post == N(0)); proc = traverse(begin(t), proc); EOPAssert(proc.n_pre == N(15) && proc.n_in == N(15) && proc.n_post == N(15)); T s4(-4); T s3_45(-3, t4, T(-5)); T s2_345_678(-2, t3_45, T(-6, T(-7), T(-8))); T s(-1, t2_345_678, T(-9, T(-10, T(-11), T(-12)), T(-13, T(-14), T(-15)))); T_X x4('d'); T_X x3_45('c', x4, T_X('e')); T_X x2_345_678('b', x3_45, T_X('f', T_X('g'), T_X('h'))); T_X x('a', x2_345_678, T_X('i', T_X('j', T_X('k'), T_X('l')), T_X('m', T_X('n'), T_X('o')))); EOPAssert(bifurcate_isomorphic_nonempty(begin(t), begin(t))); EOPAssert(bifurcate_isomorphic_nonempty(begin(t), begin(s))); EOPAssert(!bifurcate_isomorphic_nonempty(begin(t), begin(t2_345_678))); EOPAssert(bifurcate_isomorphic_nonempty(begin(t), begin(x))); EOPAssert(bifurcate_isomorphic_nonempty( left_successor(begin(t)), right_successor(begin(x)))); EOPAssert(bifurcate_isomorphic(begin(t0), begin(t0))); EOPAssert(!bifurcate_isomorphic(begin(t), begin(t0))); EOPAssert(!bifurcate_isomorphic(begin(t0), begin(t))); EOPAssert(bifurcate_isomorphic(begin(t), begin(t))); EOPAssert(bifurcate_isomorphic(begin(t), begin(s))); EOPAssert(!bifurcate_isomorphic(begin(t), begin(t2_345_678))); EOPAssert(bifurcate_isomorphic(begin(t), begin(x))); EOPAssert(bifurcate_isomorphic( left_successor(begin(t)), right_successor(begin(x)))); T tt(t); EOPAssert(t == tt); EOPAssert(bifurcate_equivalent_nonempty(begin(t), begin(tt), equal<Z>())); EOPAssert(!bifurcate_equivalent_nonempty(begin(t), begin(t2_345_678), equal<Z>())); EOPAssert(bifurcate_equivalent(begin(t0), begin(t0), equal<Z>())); EOPAssert(!bifurcate_equivalent(begin(t), begin(t0), equal<Z>())); EOPAssert(!bifurcate_equivalent(begin(t0), begin(t), equal<Z>())); EOPAssert(bifurcate_equivalent(begin(t), begin(tt), equal<Z>())); EOPAssert(!bifurcate_equivalent(begin(t), begin(t2_345_678), equal<Z>())); // Test equivalence for two coordinate types typedef stree<Z> U; U u0; U u4(4); U u3_45(3, u4, U(5)); U u2_345_678(2, u3_45, U(6, U(7), U(8))); U u(1, u2_345_678, U(9, U(10, U(11), U(12)), U(13, U(14), U(15)))); EOPAssert( bifurcate_equivalent_nonempty(begin(t), begin(u), equal<Z>())); EOPAssert( bifurcate_equivalent_nonempty(begin(t), begin(u), equal<Z>())); EOPAssert(!bifurcate_equivalent_nonempty( left_successor(begin(t)), begin(u), equal<Z>())); // These exercise bifurcate_less and bifurcate_compare EOPAssert(!(t < tt) && !(tt < t)); EOPAssert(T() < T(0)); EOPAssert(!(T(0) < T())); EOPAssert(T(0) < T(1)); EOPAssert(!(T(1) < T(0))); EOPAssert(T(0, T(1, T(), T()), T()) < T(1, T(), T())); EOPAssert(!(T(1, T(), T()) < T(0, T(1, T(), T()), T()))); EOPAssert(T(0, T(), T()) < T(0, T(0), T())); EOPAssert(!(T(0, T(0), T()) < T(0, T(), T()))); EOPAssert(T(0, T(), T()) < T(0, T(), T(0))); EOPAssert(!(T(0, T(), T(0)) < T(0, T(), T()))); EOPAssert(T(0, T(0), T()) < T(0, T(0), T(0))); EOPAssert(!(T(0, T(0), T(0)) < T(0, T(0), T()))); EOPAssert( bifurcate_shape_compare(begin(t0), begin(t4))); EOPAssert(!bifurcate_shape_compare(begin(t4), begin(t0))); EOPAssert(!bifurcate_shape_compare(left_successor(begin(t)), right_successor(begin(t)))); EOPAssert(!bifurcate_shape_compare(right_successor(begin(t)), left_successor(begin(t)))); EOPAssert( bifurcate_shape_compare(begin(t2_345_678), begin(t))); EOPAssert(!bifurcate_shape_compare(begin(t), begin(t2_345_678))); } template <typename Z, typename X> requires(Integer(Z) && Regular(X)) void test_ch_7() { print(" Chapter 7\n"); algorithms_lexicographical<Z, X>(); verify_conservation<int> vs(stree_node_count); verify_conservation<int> v(tree_node_count); algorithms_bifurcate_coordinates< stree<Z>, stree<X> >(); algorithms_bifurcate_coordinates< tree<Z>, tree<X> >(); algorithms_bidirectional_bifurcate_coordinates< tree<Z>, tree<X> >(); } // Chapter 8. Coordinates with mutable successors template<typename L> requires(List(L)) void algorithms_linked() { typedef EOPValueType(L) Z; typedef EOPIteratorType(L) I; typedef EOPDistanceType(I) N; const int n = 500; array<Z> a(n, n, Z(0)); typedef EOPIteratorType(array<Z>) Ia; Ia f = begin(a); iota(n, f); Ia t; advance_tail(t, f); EOPAssert(t == begin(a) && f == successor(t)); // ***** to do: linker_to_tail L la(a); L lb; EOPAssert(size(lb) == 0); I last = find_last(begin(la), end(la)); EOPAssert(source(last) == predecessor(n) && successor(last) == end(la)); // ***** to do: split_linked, combine_linked_nonempty // ***** to do: linker_to_head // ***** rewrite these tests in terms of procedures on raw coordinates ????? reverse(la); EOPAssert(size(la) == n); equal_iota_reverse(begin(la), end(la)); reverse(la); EOPAssert(size(la) == n); EOPAssert(equal_iota(begin(la), end(la))); partition(la, lb, even<Z>); EOPAssert(size(la) + size(lb) == n); EOPAssert(all(begin(la), end(la), odd<Z>)); EOPAssert(all(begin(lb), end(lb), even<Z>)); merge(la, lb, less<Z>()); EOPAssert(size(la) == n && empty(lb)); EOPAssert(equal_iota(begin(la), end(la))); reverse(la); sort(la, less<Z>()); EOPAssert(size(la) == n); EOPAssert(equal_iota(begin(la), end(la))); } template<typename Z> requires(Integer(Z)) void algorithms_linked_iterators() { print(" linked iterators\n"); verify_conservation<int> vs(slist_node_count); verify_conservation<int> v(list_node_count); algorithms_linked< slist<Z> >(); algorithms_linked< list<Z> >(); } template<typename C> requires(Readable(C) && AdditiveMonoid(EOPValueType(C))) struct sum_source { typedef C input_type_0; typedef void codomain_type; typedef EOPValueType(C) T; T sum; sum_source() : sum(T(0)) { } void operator()(C c) { sum = sum + source(c); } }; template<typename Z> requires(Integer(Z)) void algorithms_linked_bifurcate_coordinates() { print(" linked bifurcate coordinates\n"); verify_conservation<int> v(stree_node_count); typedef stree<Z> T; typedef EOPCoordinateType(T) C; typedef EOPWeightType(C) N; // ***** to do: test tree_rotate on single-node tree { T t0_12(0, T(1), T(2)); C root = begin(t0_12); N n = weight_recursive(root); EOPAssert(n == 3); C null = C(); // empty(null) C l = left_successor(root); C r = right_successor(root); C curr = root; C prev = null; tree_rotate(curr, prev); EOPAssert(left_successor(root) == r && right_successor(root) == null && curr == l && prev == root); tree_rotate(curr, prev); tree_rotate(curr, prev); tree_rotate(curr, prev); tree_rotate(curr, prev); tree_rotate(curr, prev); tree_rotate(curr, prev); tree_rotate(curr, prev); tree_rotate(curr, prev); EOPAssert(curr == root && prev == null); EOPAssert(weight_recursive(root) == n && source(root) == Z(0) && source(left_successor(root)) == Z(1) && source(right_successor(root)) == Z(2)); // ***** to do: more verification of individual tree_rotate steps } T t4(4); T t3_45(3, t4, T(5)); T t2_345_678(2, t3_45, T(6, T(7), T(8))); T t1__15(1, t2_345_678, T(9, T(10, T(11), T(12)), T(13, T(14), T(15)))); // weight_rotating exercises counter EOPAssert(weight_rotating(begin(t3_45)) == N(3)); EOPAssert(weight_rotating(begin(t1__15)) == N(15)); // traverse_phased_rotating exercises phased_applicator EOPAssert(traverse_phased_rotating( begin(t1__15), 0, sum_source<C>() ).sum == N(120)); } template <typename Z> requires(Integer(Z)) void test_bifurcate_copy_Andrej() { typedef stree<Z> T; typedef EOPCoordinateType(T) C; typedef EOPWeightType(C) N; T tt4(4, T(5), T()); T tt2(2, T(3), tt4); T tt1(1, tt2, T(6)); T tt0(0, T(), tt1); T t(tt0); // invokes bifurcate_copy EOPAssert(t == tt0); } template<typename Z> requires(Integer(Z)) void test_ch_8() { print(" Chapter 8\n"); // ***** to do: predicate_source // ***** to do: relation_source algorithms_linked_iterators<Z>(); algorithms_linked_bifurcate_coordinates<Z>(); test_bifurcate_copy_Andrej<Z>(); } // Chapter 9. Copying template<typename S> requires(DynamicSequence(S)) void extend_sequence_n(S& s, EOPDistanceType(EOPIteratorType(S)) n, const EOPValueType(S)& x) { typedef after<S> AP; while (count_down(n)) insert(AP(s, begin(s)), x); } template<typename I> requires(Readable(I) && Iterator(I) && Integer(EOPValueType(I))) bool equal_iota_reverse(I f, I l) { EOPValueType(I) n(l - f); while (f != l) { n = predecessor(n); if (source(f) != n) return false; f = successor(f); } return true; } template<typename T> requires(Regular(T)) struct equal_to_x { typedef T input_type_0; typedef bool codomain_type; T x; equal_to_x(T const& x) : x(x) { } bool operator()(T const& y) { return x == y; } }; template<typename I0, typename I1> requires(Mutable(I0) && ForwardIterator(I0) && Mutable(I1) && ForwardIterator(I1) && EOPValueType(I0) == EOPValueType(I1) && Integer(EOPValueType(I0))) void algorithms_copy_forward(I0 f0, I0 l0, I1 f1, I1 l1) { // Precondition: $l0 - f0 <= l1 - f1$ typedef EOPValueType(I0) T; typedef EOPDistanceType(I0) N0; typedef EOPDistanceType(I1) N1; N0 n = l0 - f0; N0 n_over_2(half_nonnegative(n)); EOPAssert(n <= N0(l1 - f1)); // test fill_step (used for other tests) { { I1 f = f1; while (f != l1) { sink(f) = 0; f = successor(f); } } I1 f_o = f1; fill_step(f_o, -1); EOPAssert(f_o == successor(f1)); EOPAssert(source(f1) == -1); } // test fill { { I1 f = f1; while (f != l1) { sink(f) = T(-1); f = successor(f); } } I1 l_o = f1 + N1(n - N0(2)); I1 m1 = fill(successor(f1), l_o, T(0)); EOPAssert(m1 == l_o); EOPAssert(all(successor(f1), m1, equal_to_x<T>(T(0)))); EOPAssert(source(f1) == -1 && source(f1 + N1(n - N0(1))) == T(-1)); } // test fill_n { { I1 f = f1; while (f != l1) { sink(f) = T(-1); f = successor(f); } } N1 n1 = N1(n - N0(2)); I1 m1 = fill_n(successor(f1), n1, T(0)); EOPAssert(m1 == successor(f1) + n1); EOPAssert(all(successor(f1), m1, equal_to_x<T>(T(0)))); EOPAssert(source(f1) == -1 && source(f1 + N1(n - N0(1))) == T(-1)); } // test copy_step { I0 f_i = f0; iota(n, f0); I1 f_o = f1; fill_n(f1, l1 - f1, -1); copy_step(f_i, f_o); EOPAssert(f_i == successor(f0)); EOPAssert(f_o == successor(f1)); EOPAssert(source(f1) == source(f0)); } // test copy, not aliased { iota(n, f0); I0 m0 = f0 + (n - N0(2)); fill_n(f1, n, -1); I1 m1 = copy(f0, m0, successor(f1)); EOPAssert(m1 == f1 + N1(n - N0(1))); EOPAssert(lexicographical_equal(f0, m0, successor(f1), m1)); EOPAssert(source(f1) == -1 && source(f1 + (n - N0(1))) == -1); } // test copy, aliased backward { iota(n, f0); I1 m1 = copy(f0 + N0(2), l0, f1); // save original values I0 m0 = copy(f0 + N0(2), l0, f0); EOPAssert(m0 == f0 + (n - N0(2))); EOPAssert(lexicographical_equal(f0, m0, f1, m1)); EOPAssert(source(m0) == m0 - f0 && source(successor(m0)) == successor(m0 - f0)); } // test copy_bounded { iota(n, f0); fill_n(f1, n, -1); pair<I0, I1> pio = copy_bounded(f0, l0, f1, f1 + N1(n_over_2)); EOPAssert(pio.m0 == f0 + n_over_2 && pio.m1 == f1 + N1(n_over_2)); EOPAssert(lexicographical_equal(f0, pio.m0, f1, pio.m1)); EOPAssert(source(f1 + N1(successor(n_over_2))) == -1); } // test count_down { N0 i; N0 n; n = N0(5); i = N0(0); while (count_down(n)) i = successor(i); EOPAssert(i == N0(5)); n = N0(0); i = N0(0); while (count_down(n)) i = successor(i); EOPAssert(i == N0(0)); } // test copy_n { N0 n0 = (n - N0(2)); fill_n(f1, n, -1); pair<I0, I1> pio = copy_n(f0, n0, successor(f1)); EOPAssert(pio.m0 == f0 + n0); EOPAssert(pio.m1 == f1 + N1(n - N0(1))); EOPAssert(lexicographical_equal(f0, f0 + n0, successor(f1), pio.m1)); EOPAssert(source(f1) == -1 && source(f1 + (n - N0(1))) == -1); } // test copy_select { iota(n, f0); predicate_source< I0, bool (*)(const T&) > es = {even<T>}; I1 m1 = copy_select(f0, l0, f1, es); EOPAssert(m1 - f1 == count_if(f0, l0, even<T>)); EOPAssert(all(f1, m1, even<T>)); } // test copy_if { iota(n, f0); I1 m1 = copy_if(f0, l0, f1, odd<T>); EOPAssert(m1 - f1 == count_if(f0, l0, odd<T>)); EOPAssert(all(f1, m1, odd<T>)); } // test split_copy { iota(n, f0); I0 f_f = f0; I1 f_t = f1; predicate_source< I0, bool (*)(const T&) > es = {even<T>}; N0 n_f = count_if(f0, l0, odd<T>); N1 n_t = count_if(f0, l0, even<T>); pair<I0, I1> pft = split_copy(f0, l0, f_f, f_t, es); EOPAssert(pft.m0 - f_f == n_f); EOPAssert(pft.m1 - f_t == n_t); EOPAssert(all(f_f, pft.m0, odd<T>)); EOPAssert(all(f_t, pft.m1, even<T>)); } // test split_copy_n { iota(n, f0); I0 f_f = f0; I1 f_t = f1; predicate_source< I0, bool (*)(const T&) > es = {even<T>}; N0 n_f = count_if(f0, l0, odd<T>); N1 n_t = count_if(f0, l0, even<T>); pair<I0, I1> pft = split_copy_n(f0, n, f_f, f_t, es); EOPAssert(pft.m0 - f_f == n_f); EOPAssert(pft.m1 - f_t == n_t); EOPAssert(all(f_f, pft.m0, odd<T>)); EOPAssert(all(f_t, pft.m1, even<T>)); } // test partition_copy { iota(n, f0); I0 f_f = f0; I1 f_t = f1; N0 n_f = count_if(f0, l0, even<T>); N1 n_t = count_if(f0, l0, odd<T>); pair<I0, I1> pft = partition_copy(f0, l0, f_f, f_t, odd<T>); EOPAssert(pft.m0 - f_f == n_f); EOPAssert(pft.m1 - f_t == n_t); EOPAssert(all(f_f, pft.m0, even<T>)); EOPAssert(all(f_t, pft.m1, odd<T>)); } // test partition_copy_n { iota(n, f0); I0 f_f = f0; I1 f_t = f1; N0 n_f = count_if(f0, l0, even<T>); N1 n_t = count_if(f0, l0, odd<T>); pair<I0, I1> pft = partition_copy_n(f0, n, f_f, f_t, odd<T>); EOPAssert(pft.m0 - f_f == n_f); EOPAssert(pft.m1 - f_t == n_t); EOPAssert(all(f_f, pft.m0, even<T>)); EOPAssert(all(f_t, pft.m1, odd<T>)); } // test combine_copy { I0 m0 = iota(n_over_2, f0); iota(n - n_over_2, m0); less<EOPValueType(I0)> lt; relation_source< I0, I0, less<EOPValueType(I0)> > lts = {lt}; I1 m1 = combine_copy(f0, m0, m0, l0, f1, lts); EOPAssert(m1 - f1 == n); EOPAssert(increasing_range(f1, m1, less<T>())); } // test combine_copy_n { I0 m0 = iota(n_over_2, f0); iota(n - n_over_2, m0); less<EOPValueType(I0)> lt; relation_source< I0, I0, less<EOPValueType(I0)> > lts = {lt}; triple<I0, I0, I1> t = combine_copy_n(f0, m0 - f0, m0, l0 - m0, f1, lts); EOPAssert(t.m0 == m0 && t.m1 == l0 && t.m2 - f1 == n); EOPAssert(increasing_range(f1, t.m2, less<T>())); } // test merge_copy { I0 m0 = iota(n_over_2, f0); iota(n - n_over_2, m0); less<EOPValueType(I0)> lt; I1 m1 = merge_copy(f0, m0, m0, l0, f1, lt); EOPAssert(m1 - f1 == n); EOPAssert(increasing_range(f1, m1, less<T>())); } // test exchange_values, swap_step { I0 f_0 = f0; I1 f_1 = f1; sink(f_0) = 137; sink(f_1) = -99; exchange_values(f0, f1); EOPAssert(f_0 == f0 && f_1 == f1); EOPAssert(source(f0) == -99 && source(f1) == 137); swap_step(f_0, f_1); EOPAssert(f_0 == successor(f0) && f_1 == successor(f1)); EOPAssert(source(f0) == 137 && source(f1) == -99); } // test swap_ranges { iota(n, f0); fill_n(f1, n, T(-1)); I1 m1 = swap_ranges(f0, l0, f1); EOPAssert(m1 == f1 + N1(n)); EOPAssert(equal_iota(f1, m1)); EOPAssert(all(f0, l0, equal_to_x<T>(-1))); } // test swap_ranges_ bounded { iota(n, f0); N1 n1(n_over_2); fill_n(f1, n1, T(-1)); pair<I0, I1> p01 = swap_ranges_bounded(f0, l0, f1, f1 + n1); EOPAssert(p01.m0 == f0 + N0(n1)); EOPAssert(p01.m1 == f1 + n1); EOPAssert(equal_iota(f1, p01.m1)); EOPAssert(all(f0, p01.m0, equal_to_x<T>(-1))); } // test swap_ranges_n { iota(n, f0); fill_n(f1, n, T(-1)); pair<I0, I1> p01 = swap_ranges_n(f0, f1, n); EOPAssert(p01.m0 == f0 + n); EOPAssert(p01.m1 == f1 + N1(n)); EOPAssert(equal_iota(f1, p01.m1)); EOPAssert(all(f0, l0, equal_to_x<T>(-1))); } } template<typename I0, typename I1> requires(Readable(I0) && BidirectionalIterator(I0) && Writable(I1) && BidirectionalIterator(I1) && EOPValueType(I0) == EOPValueType(I1)) void algorithms_copy_backward(I0 f0, I0 l0, I1 f1, I1 l1) { // Precondition: $l0 - f0 <= l1 - f1$ typedef EOPValueType(I0) T; typedef EOPDistanceType(I0) N0; typedef EOPDistanceType(I1) N1; N0 n = l0 - f0; N0 n_over_2(half_nonnegative(n)); EOPAssert(n <= N0(l1 - f1)); // test copy_backward_step { I0 l_i = l0; iota(n, f0); I1 l_o = l1; fill_n(f1, l1 - f1, -1); copy_backward_step(l_i, l_o); EOPAssert(l_i == predecessor(l0)); EOPAssert(l_o == predecessor(l1)); EOPAssert(source(predecessor(l1)) == source(predecessor(l0))); } // test copy_backward { I0 m0 = l0 - (n - N0(2)); fill_n(f1, n, -1); I1 m1 = copy_backward(m0, l0, predecessor(l1)); EOPAssert(m1 == l1 - N1(n - N0(1))); EOPAssert(lexicographical_equal(m0, l0, m1, predecessor(l1))); EOPAssert(source(predecessor(m1)) == -1 && source(predecessor(l1)) == -1); } // test copy_backward_n { const N0 n_minus_2 = n - N0(2); I0 m0 = l0 - n_minus_2; fill_n(f1, n, -1); pair<I0, I1> p = copy_backward_n(l0, n_minus_2, predecessor(l1)); EOPAssert(p.m1 == l1 - N1(n - N0(1))); EOPAssert(lexicographical_equal(m0, l0, p.m1, predecessor(l1))); EOPAssert(source(predecessor(p.m1)) == -1 && source(predecessor(l1)) == -1); } // test combine_copy_backward { I0 m0 = iota(n_over_2, f0); iota(n - n_over_2, m0); less<EOPValueType(I0)> lt; relation_source< I0, I0, less<EOPValueType(I0)> > lts = {lt}; I1 m1 = combine_copy_backward(f0, m0, m0, l0, l1, lts); EOPAssert(l1 - m1 == n); EOPAssert(increasing_range(m1, l1, less<T>())); } // test combine_copy_backward_n { I0 m0 = iota(n_over_2, f0); iota(n - n_over_2, m0); less<EOPValueType(I0)> lt; relation_source< I0, I0, less<EOPValueType(I0)> > lts = {lt}; triple<I0, I0, I1> t = combine_copy_backward_n(m0, m0 - f0, l0, l0 - m0, l1, lts); EOPAssert(t.m0 == f0 && t.m1 == m0 && l1 - t.m2 == n); EOPAssert(increasing_range(t.m2, l1, less<T>())); } // test merge_copy_backward { I0 m0 = iota(n_over_2, f0); iota(n - n_over_2, m0); less<EOPValueType(I0)> lt; I1 m1 = merge_copy_backward(f0, m0, m0, l0, l1, lt); EOPAssert(l1 - m1 == n); EOPAssert(increasing_range(m1, l1, less<T>())); } // test merge_copy_backward_n { I0 m0 = iota(n_over_2, f0); iota(n - n_over_2, m0); less<EOPValueType(I0)> lt; triple<I0, I0, I1> t = merge_copy_backward_n(m0, m0 - f0, l0, l0 - m0, l1, lt); EOPAssert(t.m0 == f0 && t.m1 == m0 && l1 - t.m2 == n); EOPAssert(increasing_range(t.m2, l1, less<T>())); } } template<typename I0, typename I1> requires(Mutable(I0) && BidirectionalIterator(I0) && Mutable(I1) && BidirectionalIterator(I1) && EOPValueType(I0) == EOPValueType(I1)) void algorithms_copy_reverse(I0 f0, I0 l0, I1 f1, I1 l1) { // Precondition: $l0 - f0 == l1 - f1$ typedef EOPValueType(I0) T; typedef EOPDistanceType(I0) N0; typedef EOPDistanceType(I1) N1; N0 n = l0 - f0; N0 n_over_2(half_nonnegative(n)); EOPAssert(n == N0(l1 - f1)); // test reverse_copy_step { if (verbose) print(" reverse_copy_step\n"); I0 l_i = l0; iota(n, f0); I1 f_o = f1; fill_n(f1, l1 - f1, -1); reverse_copy_step(l_i, f_o); EOPAssert(l_i == predecessor(l0)); EOPAssert(f_o == successor(f1)); EOPAssert(source(f1) == source(predecessor(l0))); } // test reverse_copy_backward_step { if (verbose) print(" reverse_copy_backward_step\n"); I0 f_i = f0; iota(n, f0); I1 l_o = l1; fill_n(f1, l1 - f1, -1); reverse_copy_backward_step(f_i, l_o); EOPAssert(f_i == successor(f0)); EOPAssert(l_o == predecessor(l1)); EOPAssert(source(predecessor(l1)) == source(f0)); } // test reverse_copy { if (verbose) print(" reverse_copy\n"); iota(n, f0); fill_n(f1, l1 - f1, -1); I1 f_o = successor(f1); I1 l_o = reverse_copy(f0, l0 - N0(2), f_o); EOPAssert(l_o == predecessor(l1)); N1 n_o(n - N0(2)); while (count_down(n_o)) { EOPAssert(source(f_o) == n_o); f_o = successor(f_o); } EOPAssert(source(f1) == -1 && source(predecessor(l1)) == -1); } // test reverse_copy_backward { if (verbose) print(" reverse_copy_backward\n"); iota(n, f0); fill_n(f1, n, -1); I1 l_o = predecessor(l1); I1 f_o = reverse_copy_backward(f0, l0 - N0(2), l_o); EOPAssert(f_o == successor(f1)); N1 n_o(n - N0(2)); while (count_down(n_o)) { EOPAssert(source(f_o) == n_o); f_o = successor(f_o); } EOPAssert(source(f1) == -1 && source(predecessor(l1)) == -1); } // test reverse_swap_step { if (verbose) print(" reverse_swap_step\n"); I0 l_0 = l0; I1 f_1 = f1; sink(predecessor(l_0)) = 137; sink(f_1) = -99; reverse_swap_step(l_0, f_1); EOPAssert(l_0 == predecessor(l0) && f_1 == successor(f1)); EOPAssert(source(predecessor(l0)) == -99 && source(f1) == 137); } // test reverse_swap_ranges { if (verbose) print(" reverse_swap_ranges\n"); iota(n, f0); fill_n(f1, n, T(-1)); I1 m1 = reverse_swap_ranges(f0, l0, f1); EOPAssert(m1 == f1 + N1(n)); EOPAssert(equal_iota_reverse(f1, m1)); EOPAssert(all(f0, l0, equal_to_x<T>(-1))); } // test reverse_swap_ranges_bounded { if (verbose) print(" reverse_swap_ranges_bounded\n"); I0 m0 = f0 + n_over_2; iota(n_over_2, f0); fill(f1, l1, T(-1)); pair<I0, I1> p01 = reverse_swap_ranges_bounded(f0, m0, f1, l1); EOPAssert(p01.m0 == f0); EOPAssert(p01.m1 == f1 + N1(n_over_2)); EOPAssert(equal_iota_reverse(f1, p01.m1)); EOPAssert(all(f0, m0, equal_to_x<T>(-1))); } // test reverse_swap_ranges_n { if (verbose) print(" reverse_swap_ranges_n\n"); iota(n, f0); fill_n(f1, n, T(-1)); pair<I0, I1> p01 = reverse_swap_ranges_n(l0, f1, n); EOPAssert(p01.m0 == f0); EOPAssert(p01.m1 == f1 + N1(n)); EOPAssert(equal_iota_reverse(f1, p01.m1)); EOPAssert(all(f0, l0, equal_to_x<T>(-1))); } } template<typename T> requires(Regular(T)) void test_ch_9() { print(" Chapter 9\n"); print(" copy/split/combine/swap\n"); const int k = 50; array_k<k, T> ca; array<T> da(k, k, T()); slist<T> l; print(" ***** replace list with slist and list ?????\n"); int n = k; extend_sequence_n(l, n, T(-1)); EOPAssert(size(ca) == k && size(da) == k && size(l) == k); print(" forward"); print_eol(); print(" ***** to do: split into iterator and forward iterator\n"); print(" ***** to do: split into readable/writable/mutable ?????\n"); algorithms_copy_forward(begin(ca), end(ca), begin(da), end(da)); algorithms_copy_forward(begin(ca), end(ca), begin(l), end(l)); algorithms_copy_forward(begin(da), end(da), begin(ca), end(ca)); algorithms_copy_forward(begin(da), end(da), begin(l), end(l)); algorithms_copy_forward(begin(l), end(l), begin(ca), end(ca)); algorithms_copy_forward(begin(l), end(l), begin(da), end(da)); print(" ***** to do: various iterator types for split/combine/partition/merge\n"); print(" ***** to do: copy_bounded/copy_n backward overlapped\n"); print(" backward"); print_eol(); algorithms_copy_backward(begin(ca), end(ca), begin(da), end(da)); algorithms_copy_backward(begin(da), end(da), begin(ca), end(ca)); print(" ***** to do: copy_backward forward overlapped\n"); print(" reverse\n"); print(" ***** to do: split into finer iterator concept combinations\n"); print(" ***** to do: split into readable/writable/mutable ?????\n"); algorithms_copy_reverse(begin(ca), end(ca), begin(da), end(da)); algorithms_copy_reverse(begin(da), end(da), begin(ca), end(ca)); } // Chapter 10. Rearrangements template<typename I> requires(RandomAccessIterator(I)) struct successor_cyclic { typedef I input_type_0; typedef I codomain_type; I f; I l; successor_cyclic(I f, I l) : f(f), l(l) { } I operator()(I i) { i = successor(i); if (i == l) i = f; return i; } }; void algorithm_cycle_to() { typedef int N; const int k = 17; array_k<k, N> a; typedef iterator_type< array_k<k, N> >::type I; I f = begin(a); I l = end(a); iota(k, f); cycle_to(f, successor_cyclic<I>(f, l)); EOPAssert(source(f) == predecessor(k)); EOPAssert(equal_iota(successor(f), l)); } template<typename T, typename N> requires(Regular(T) && Integer(N)) void type_temporary_buffer(N n) { { temporary_buffer<T> b(n); EOPDistanceType(EOPpointer(T)) m = size(b); EOPAssert(0 < m && m <= n); if (verbose) { print("size(temporary_buffer<T>("); print(n); print(") = "); print(m); print(" where sizeof(T) = "); print(sizeof(T)); print_eol(); } } } void algorithms_reverse() { typedef int T; const int k = 50; array_k<k, int> ca; // typedef EOPDistanceType(EOPIteratorType(array<T>)) N; typedef ptrdiff_t N; array<int> da = array<int>(N(k), N(k), T(0)); slist<int> l; extend_sequence_n(l, k, T(-1)); iota(k, begin(ca)); iota(k, begin(ca)); reverse_n_indexed(begin(ca), size(ca)); equal_iota_reverse(begin(ca), end(ca)); iota(k, begin(ca)); reverse_bidirectional(begin(ca), end(ca)); equal_iota_reverse(begin(ca), end(ca)); iota(k, begin(ca)); reverse_n_bidirectional(begin(ca), end(ca), size(ca)); equal_iota_reverse(begin(ca), end(ca)); iota(k, begin(l)); reverse_n_with_buffer(begin(l), k, begin(ca)); equal_iota_reverse(begin(l), end(l)); iota(k, begin(l)); reverse_n_forward(begin(l), k); equal_iota_reverse(begin(l), end(l)); iota(k, begin(l)); reverse_n_adaptive(begin(l), k, begin(ca), half_nonnegative(k)); equal_iota_reverse(begin(l), end(l)); iota(k, begin(l)); reverse_n_adaptive(begin(l), k, begin(ca), half_nonnegative(k)); equal_iota_reverse(begin(l), end(l)); iota(k, begin(da)); reverse_indexed(begin(da), end(da)); equal_iota_reverse(begin(da), end(da)); iota(k, begin(l)); reverse_n_with_temporary_buffer(begin(l), k); equal_iota_reverse(begin(l), end(l)); } typedef EOPpointer(int) int_pointer; template<typename C> requires(IteratorConcept(C)) void algorithms_rotate_Concept(int_pointer a, int n) { EOPAssert(n != 0); fill_n(a, n, int(7)); int_pointer f = a; int_pointer l = f + n; iota(n, f); if (verbose) { print(" Initial a: "); print_range(a, a+n); print_eol(); } int_pointer c = successor(f); while (c != l) { EOPAssert(f != c && c != l); // guard required since we're invoking "inner" versions rotate_nontrivial(f, c, l, C()); c = successor(c); } if (verbose) { print(" After rotating a: "); print_range(a, a+n); print_eol(); } if (even(n)) for (int i = 0; i < n; ++i) EOPAssert(source(f + i) == (i + n / 2) % n); else for (int i = 0; i < n; ++i) EOPAssert(source(f + i) == i); } void algorithm_rotate_forward_annotated(int_pointer a, int n) { EOPAssert(n != 0); fill_n(a, n, int(7)); int_pointer f = a; int_pointer l = f + n; iota(n, f); if (verbose) { print(" Initial a: "); print_range(a, a+n); print_eol(); } int_pointer c = successor(f); while (c != l) { EOPAssert(f != c && c != l); // guard required since we're invoking "inner" versions rotate_forward_annotated(f, c, l); c = successor(c); } if (verbose) { print(" After rotating a: "); print_range(a, a+n); print_eol(); } if (even(n)) for (int i = 0; i < n; ++i) EOPAssert(source(f + i) == (i + n / 2) % n); else for (int i = 0; i < n; ++i) EOPAssert(source(f + i) == i); } template<typename I, typename B> requires(ForwardIterator(I) && ForwardIterator(B)) void algorithms_rotate_Concept_with_buffer(I f, EOPDistanceType(I) n, B f_b, I (*algo)(I, I, I, B)) { EOPAssert(n != 0); fill_n(f, n, int(7)); I l = f + n; iota(n, f); if (verbose) { print(" Initial range: "); print_range(f, l); print_eol(); } int_pointer c = successor(f); while (c != l) { EOPAssert(f != c && c != l); // guard required since we're invoking "inner" versions algo(f, c, l, f_b); c = successor(c); } if (verbose) { print(" After rotating range: "); print_range(f, l); print_eol(); } if (even(n)) for (int i = 0; i < n; ++i) EOPAssert(source(f + i) == (i + half_nonnegative(n)) % n); else for (int i = 0; i < n; ++i) EOPAssert(source(f + i) == i); } template<typename N> requires(Integer(N)) void algorithm_rotate_partial(N n) { EOPAssert(n > N(1)); array<N> a(twice(n), twice(n), N(-1)); typedef EOPIteratorType(array<N>) I; I f = begin(a) + n / N(4); I l = f + n; I m = f + 1; while (m != l) { iota(n, f); I m_prime = rotate_partial_nontrivial(f, m, l); EOPAssert(source(predecessor(f)) == N(-1) && source(l) == N(-1)); EOPAssert(m_prime + (m - f) == l); EOPAssert(equal_iota(f, m_prime, m - f)); EOPDistanceType(I) k = (l - f) % (m - f); rotate(m_prime, l - k, l); EOPAssert(equal_iota(m_prime, l)); m = successor(m); } } void algorithms_rotate() { print(" rotate\n"); // Directly or indirectly tests these algorithms: // cycle_from // k_rotate_from_permutation_random_access // k_rotate_from_permutation_indexed // rotate_cycles // rotate_indexed_nontrivial // rotate_random_access_nontrivial // rotate_bidirectional_nontrivial // rotate_forward_annotated // rotate_forward_step // rotate_forward_nontrivial // rotate_with_buffer_nontrivial // rotate_with_buffer_backward_nontrivial typedef EOPpointer(int) I; int a[8]; int b[8]; for (int n = 6; n < 8; ++n) { algorithm_rotate_forward_annotated(a, n); algorithms_rotate_Concept<forward_iterator_tag>(a, n); algorithms_rotate_Concept<bidirectional_iterator_tag>(a, n); algorithms_rotate_Concept<indexed_iterator_tag>(a, n); algorithms_rotate_Concept<random_access_iterator_tag>(a, n); algorithms_rotate_Concept_with_buffer( a, n, b, rotate_with_buffer_nontrivial<I,I>); algorithms_rotate_Concept_with_buffer( a, n, b, rotate_with_buffer_backward_nontrivial<I,I>); } int n = 41; while (n < 50) { algorithm_rotate_partial(n); n = n + 2; } } void test_ch_10() { print(" Chapter 10\n"); algorithm_cycle_to(); type_temporary_buffer< char >(1000); type_temporary_buffer< char >(100000); type_temporary_buffer< array_k<10,char> >(1000); type_temporary_buffer< array_k<10,char> >(100000); algorithms_reverse(); algorithms_rotate(); } // Chapter 11. Partition and merging void algorithms_reduce_balanced() { // tests counter_machine, add_to_counter, transpose_operation, reduce_nonzeroes typedef int Z; // Integer(Z) Z a[] = {0, 1, 2, 3, 4, 5}; slist<Z> l(counted_range<Z*>(a, sizeof(a)/sizeof(Z))); EOPAssert(reduce_balanced(0, 0, plus<Z>(), identity<Z>(), Z(0)) == Z(0)); EOPAssert(reduce_balanced(0, 50, plus<Z>(), identity<Z>(), Z(0)) == Z(49*50/2)); EOPAssert(reduce_balanced(0, 1, plus<Z>(), identity<Z>(), Z(0)) == Z(0)); EOPAssert(reduce_balanced(begin(l), begin(l), plus<Z>(), Z(0)) == Z(0)); EOPAssert(reduce_balanced(begin(l), end(l), plus<Z>(), Z(0)) == Z(15)); EOPAssert(reduce_balanced(begin(l), successor(begin(l)), plus<Z>(), Z(0)) == Z(0)); } bool even_int(int x) { return even<int>(x); } bool odd_int(int x) { return odd<int>(x); } typedef bool (*int_pred_type)(int); struct partition_algorithm_tester { typedef EOPpointer(int) I; typedef distance_type<I>::type N; EOPpointer(char const) name; array_k<6, int> a; I f; I l; N n; bool (*p)(int); slist<int> b; I m_potential; partition_algorithm_tester(EOPpointer(char const) name) : name(name), a(), f(begin(a)), l(end(a)), n(l - f), p(even_int), b(a) { EOPAssert(size(b) == n); iota(int(n), f); m_potential = potential_partition_point(f, l, even<int>); if (verbose) { print(" Before "); print(name); print(" partition with even: "); print_range(f, l); print_eol(); } } void validate(I m) { if (verbose) { print(" After "); print(name); print(" partition with even: "); print_range(f, l); print_eol(); } EOPAssert(m_potential == m); EOPAssert(partitioned(f, l, even<int>)); EOPAssert(partitioned_at_point(f, m, l, even<int>)); EOPAssert(m == partition_point(f, l, even<int>)); } void validate_false(I m) { if (verbose) { print(" After "); print(name); print(" partition with even: "); print_range(f, l); print_eol(); } EOPAssert(m_potential == m); EOPAssert(none(f, m, p)); } }; void algorithms_partition() { { int a[] = {0, 2, 4, 1, 3, 5}; EOPpointer(int) f = a; EOPpointer(int) l = a + sizeof(a) / sizeof(int); // exercise EOPpointer(int) m = potential_partition_point(f, l, odd<int>); // exercise EOPAssert(partitioned_at_point(f, m, l, odd<int>)); } { // book partition_algorithm_tester t("semistable"); t.validate(partition_semistable(t.f, t.l, t.p)); } { // exercise partition_algorithm_tester t("remove_if"); t.validate_false(remove_if(t.f, t.l, t.p)); } { // book partition_algorithm_tester t("bidirectional"); t.validate(partition_bidirectional(t.f, t.l, t.p)); } { // could have been exercise partition_algorithm_tester t("indexed"); t.validate(partition_indexed(t.f, t.l, t.p)); } { // exercise partition_algorithm_tester t("forward"); t.validate(partition_forward(t.f, t.l, t.p)); } { // exercise partition_algorithm_tester t("single_cycle"); t.validate(partition_single_cycle(t.f, t.l, t.p)); } { // exercise partition_algorithm_tester t("sentinel"); t.validate(partition_sentinel(t.f, t.l, t.p)); } // ***** to do: exercise - single_cycle_sentinel { // book partition_algorithm_tester t("stable_with_buffer"); t.validate(partition_stable_with_buffer(t.f, t.l, begin(t.b), t.p)); } { // book // uses partition_stable_singleton, partition_stable_combine partition_algorithm_tester t("stable_n_nonempty"); typedef partition_algorithm_tester::I I; pair<I, I> p = partition_stable_n_nonempty(t.f, t.l - t.f, t.p); EOPAssert(p.m1 == t.l); t.validate(p.m0); } { // book partition_algorithm_tester t("stable_n"); typedef partition_algorithm_tester::I I; pair<I, I> p; p = partition_stable_n(t.f, 0, t.p); EOPAssert(p.m0 == t.f && p.m1 == t.f); p = partition_stable_n(t.f, t.n, t.p); EOPAssert(p.m1 == t.l); t.validate(p.m0); } { // additional partition_algorithm_tester t("advanced stable_n"); typedef partition_algorithm_tester::I I; pair<I, I> p; p = advanced_partition_stable_n(t.f, 0, t.p); EOPAssert(p.m0 == t.f && p.m1 == t.f); p = advanced_partition_stable_n(t.f, t.n, t.p); EOPAssert(p.m1 == t.l); t.validate(p.m0); } { // for completeness partition_algorithm_tester t("stable"); t.validate(partition_stable(t.f, t.l, t.p)); } { // book partition_algorithm_tester t("stable iterative"); t.validate(partition_stable_iterative(t.f, t.l, t.p)); } } char force_lower(char a) { if ('A' <= a && a <= 'Z') return 'a' + (a - 'A'); return a; } struct less_ignoring_case { typedef char input_type_0; typedef char input_type_1; typedef bool codomain_type; bool operator()(char a, char b) const { return force_lower(a) < force_lower(b); } }; struct equal_ignoring_case { typedef char input_type_0; typedef char input_type_1; typedef bool codomain_type; bool operator()(char a, char b) const { return force_lower(a) == force_lower(b); } }; int size_unguarded(EOPpointer(char const) a) { int n(0); while (source(a) != char(0)) { n = successor(n); a = successor(a); } return n; } EOPpointer(char const) begin(EOPpointer(char const) a) { return a; } EOPpointer(char const) end(EOPpointer(char const) a) { return begin(a) + size_unguarded(a); } template<typename M, typename R, typename E> requires(WrappedMerger(M) && Relation(R) && EOPDomain(R) == char && Relation(E) && EOPDomain(E) == char) struct merge_case { typedef EOPpointer(const char) input_type_0; typedef EOPpointer(const char) input_type_1; typedef EOPpointer(const char) input_type_2; typedef void codomain_type; M merger; R r; E e; bool commutative; merge_case(M merger, R r, E e, bool commutative) : merger(merger), r(r), e(e), commutative(commutative) { // Precondition: $\property{weak\_ordering}(r) // Precondition: $\property{equivalence}(e) } void subcase( EOPpointer(char const) a, int n_a, EOPpointer(char const) b, int n_b, EOPpointer(char const) c, int n_c) { array<char> tmp(n_c, n_c, char(0)); EOPpointer(char) f_ab = begin(tmp); EOPpointer(char) m_ab = copy_n(begin(a), n_a, f_ab).m1; EOPpointer(char) l_ab = copy_n(begin(b), n_b, m_ab).m1; EOPAssert(l_ab == end(tmp)); merger(f_ab, n_a, m_ab, n_b, r); EOPAssert(lexicographical_equivalent(f_ab, l_ab, begin(c), end(c), e)); if (verbose) { print(" "); print(a); print(" merge "); print(b); print(" equiv "); print(c); print_eol(); } } void operator()(EOPpointer(const char) a, EOPpointer(const char) b, EOPpointer(const char) c) { int n_a = size_unguarded(a) ; int n_b = size_unguarded(b); int n_c = size_unguarded(c); EOPAssert(n_a + n_b == n_c); subcase(a, n_a, b, n_b, c, n_c); if (commutative) subcase(b, n_b, a, n_a, c, n_c); } }; template<typename M> requires(Merger(M)) void merge_cases(M m) { merge_case<M, less_ignoring_case, equal_ignoring_case> c(m, less_ignoring_case(), equal_ignoring_case(), true); merge_case<M, less_ignoring_case, equal<char> > n(m, less_ignoring_case(), equal<char>(), false); n("", "", ""); c("a", "", "a"); n("a", "A", "aA"); n("a", "a", "aa"); c("a", "b", "ab"); c("a", "bc", "abc"); c("b", "ac", "abc"); c("c", "ab", "abc"); n("ab", "AB", "aAbB"); c("ab", "cd", "abcd"); c("ac", "bd", "abcd"); c("ad", "bc", "abcd"); n("abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"); // And so on. } template<typename I, typename R> requires(Mutable(I) && ForwardIterator(I) && Relation(R) && EOPValueType(I) == EOPDomain(R)) I wrapped_merge_n_with_buffer(I f0, EOPDistanceType(I) n0, I f1, EOPDistanceType(I) n1, R r) { array<EOPValueType(I)> b(n0, n0, EOPValueType(I)()); return merge_n_with_buffer(f0, n0, f1, n1, begin(b), r); } template<typename I, typename R> requires(Mutable(I) && ForwardIterator(I) && Relation(R) && EOPValueType(I) == EOPDomain(R)) I wrapped_merge_n_adaptive(I f0, EOPDistanceType(I) n0, I f1, EOPDistanceType(I) n1, R r) { const EOPDistanceType(I) n = half_nonnegative(n0); array<EOPValueType(I)> b(n, n, EOPValueType(I)()); return merge_n_adaptive(f0, n0, f1, n1, begin(b), size(b), r); } void algorithms_merge() { typedef EOPpointer(char) I; merge_cases(wrapped_merge_n_with_buffer<I, less_ignoring_case>); merge_cases(wrapped_merge_n_adaptive<I, less_ignoring_case>); } template <typename S> requires(Sequence(S) && Integer(EOPValueType(S))) void algorithms_sort(S& s) { typedef EOPIteratorType(S) I; typedef EOPDistanceType(I) N; typedef EOPValueType(I) T; I f = begin(s); I l = end(s); N n = size(s); EOPAssert(n == l - f); I m; less<int> ls; converse< less<int> > greater = {ls}; { iota(n, f); int n_b = half_nonnegative(n); array<int> buffer(n_b, n_b, 0); m = sort_n_with_buffer(f, n, begin(buffer), greater); EOPAssert(m == l && equal_iota_reverse(f, l)); } { iota(n, f); array<int> buffer(50, 50, 0); EOPpointer(int) f_b = begin(buffer); int n_b = size(buffer); m = sort_n_adaptive(f, n, f_b, n_b, greater); EOPAssert(m == l && equal_iota_reverse(f, l)); } { iota(n, f); m = sort_n(f, n, greater); EOPAssert(m == l && equal_iota_reverse(f, l)); } { iota(n, f); m = advanced_sort_n(f, n, greater); EOPAssert(m == l && equal_iota_reverse(f, l)); } } void test_ch_11() { print(" Chapter 11\n"); print(" reduce_balanced\n"); algorithms_reduce_balanced(); print(" partition\n"); algorithms_partition(); print(" merge\n"); algorithms_merge(); const int n = 500; typedef int T; array_k<n, T> ca; array<T> a(n, n, T()); slist<T> sl(a); list<T> l(a); print(" sort\n"); algorithms_sort(ca); algorithms_sort(a); algorithms_sort(sl); algorithms_sort(l); } // Chapter 12. Composite objects template<typename T> requires(Regular(T)) void nothing(const T&) { } template<typename W> requires(Linearizable(W)) void concept_Linearizable(W& w) { // Regular concept_Regular(w); // Type functions typedef EOPIteratorType(W) I; typedef EOPValueType(W) T; typedef EOPSizeType(W) N; // Procedures and operators I f = begin(w); I l = end(w); N n = size(w); bool e = empty(w); EOPAssert(n == (l - f)); EOPAssert(e == (n == 0)); for_each(f, l, nothing<T>); N i(0); while (f != l) { EOPAssert(addressof(w[i]) == addressof(source(f))); i = successor(i); f = successor(f); } } template<typename S> requires(Sequence(S)) void concept_Sequence(S& s0, S& s1, EOPValueType(S)& x) { // Precondition: s0 < s1 /\ !empty(s1) /\ x != s1[0] EOPAssert(begin(s1) != end(s1)); EOPAssert(x != s1[0]); concept_Linearizable(s1); concept_TotallyOrdered(s0, s1); // (all s in S)(all i in [begin(s), end(s)) deref(i) is a part of s S s11(s1); EOPAssert(s11 == s1); s11[0] = x; // change the copy EOPAssert(s11 != s1); // Equality and total ordering are lexicographical } template<typename T0, typename T1> requires(ConstantSizeSequence(T0) && ConstantSizeSequence(T1) && EOPValueType(T0) == EOPValueType(T1)) void concept_ConstantSizeSequence(T0& a0, T1& a1, EOPValueType(T1)& x) { // Precondition: a0 < a1 /\ x != a1[0] if (verbose) { print(" "); print(a1); print_eol(); } concept_Sequence(a0, a1, x); // size is fixed, and agrees with Size type attribute EOPAssert(size(a0) == EOPSize(T0)); EOPAssert(size(a1) == EOPSize(T1)); // size is positive, at least for array_k EOPAssert(!empty(a0)); EOPAssert(!empty(a1)); // Iterator is EOPpointer(T) EOPAssert(begin(a0) == addressof(a0[0])); // Equality behavior EOPAssert(a0 != a1); // Total ordering behavior // ***** to do: move this to concept_Sequence ????? EOPAssert(a0 < a1); EOPAssert(!(a1 < a0)); } void type_array_k() { { array_k<10, int> a0; array_k<10, int> a1; a0[0] = -39; a1[0] = 17; // establish a0 < a1 int x(99); concept_ConstantSizeSequence(a0, a1, x); } { typedef pair<int, char> P; array_k<3, P> a0; array_k<3, P> a1; a0[0] = make_pair(0, 'a'); a1[0] = make_pair(1, 'Z'); // establish a0 < a1 P x = {2, '0'}; concept_ConstantSizeSequence(a0, a1, x); } { typedef array<int> DA; DA da0; DA da1(3, 3, 0); iota(3, begin(da1)); typedef array_k< 4, DA > A_DA; A_DA a0; A_DA a1; if (verbose) { print(" da0:"); print(da0); print_eol(); print(" da1:"); print(da1); print_eol(); } a0[0] = da0; a1[0] = da1; // establish a0 < a1 if (verbose) { print(" a0:"); print(a0); print_eol(); print(" a1:"); print(a1); print_eol(); } EOPAssert(a0 != a1); concept_ConstantSizeSequence(a0, a1, da0); { typedef slist<int> SL; SL sl0; SL sl1; extend_sequence_n(sl0, 3, 3); extend_sequence_n(sl1, 4, 4); typedef array_k< 5, SL > A_SL; A_SL a0; A_SL a1; a0[0] = sl0; a1[0] = sl1; // establish a0 < a1 concept_ConstantSizeSequence(a0, a1, sl0); } typedef slist< DA > SL; SL sl0; SL sl1; extend_sequence_n(sl0, 3, da0); extend_sequence_n(sl1, 4, da1); typedef array_k< 3, SL > A_SL; A_SL a_sl0; A_SL a_sl1; a_sl0[0] = sl0; a_sl1[0] = sl1; // establish a0 < a1 concept_ConstantSizeSequence(a_sl0, a_sl1, sl0); } } template<typename I> requires(Readable(I) && Iterator(I)) void type_bounded_range(I f, I l) { typedef bounded_range<I> T; T r(f, l); concept_Linearizable(r); // but not totally ordered } template<typename I> requires(Readable(I) && Iterator(I)) void type_counted_range(I f, EOPDistanceType(I) n) { typedef counted_range<I> T; T r(f, n); concept_Linearizable(r); // but not totally ordered } template<typename P> requires(Position(P)) void concept_Position(P p, EOPBaseType(P)& s, EOPIteratorType(P) i) { typedef EOPBaseType(P) B; typedef EOPIteratorType(P) I; typedef EOPValueType(P) T; typedef EOPSizeType(P) N; // Not regular: lacks default constructor, copy constructor, assignment B& b = base(p); EOPAssert(addressof(b) == addressof(s)); I cur = current(p); EOPAssert(cur - begin(s) >= N(0) && end(s) - cur >= N(0)); // i.e., cur \in [begin(s), end(s)) EOPAssert(begin(p) == begin(s)); EOPAssert(end(p) == end(s)); } template<typename S> requires(DynamicSequence(S)) void test_Position(S& s, EOPIteratorType(S) i) { before<S> bef(s, i); concept_Position(bef, s, i); EOPAssert(current(bef) == i); after<S> aft(s, i); concept_Position(aft, s, i); EOPAssert(current(bef) == i); front<S> fr(s); concept_Position(fr, s, i); EOPAssert(current(fr) == begin(s)); back<S> bk(s); concept_Position(bk, s, i); EOPAssert(current(bk) == end(s)); at<S> a(s, i); concept_Position(a, s, i); EOPAssert(current(bef) == i); } template<typename S> requires(DynamicSequence(S)) void concept_DynamicSequence(S& s0, S& s1, EOPValueType(S)& x) { // Precondition: s0 < s1 /\ x != s1[0] typedef EOPIteratorType(S) I; concept_Sequence(s0, s1, x); // construct from linearizable bounded_range<I> br(begin(s1), end(s1)); S s11(br); EOPAssert(s11 == s1); // insert // insert_range // erase // erase_range } template<typename L> requires(List(L) && EOPValueType(L) == int) void type_list() { const EOPSizeType(L) k0 = 10; { const EOPSizeType(L) k1 = 15; L l0; L l1; extend_sequence_n(l0, k0, 0); extend_sequence_n(l1, k1, 1); int i(2); concept_DynamicSequence(l0, l1, i); } L l0; L l1; extend_sequence_n(l0, k0, 0); // algorithms: reverse, partition, merge, sort iota(k0, begin(l0)); reverse(l0); EOPAssert(equal_iota_reverse(begin(l0), end(l0))); reverse(l0); EOPAssert(equal_iota(begin(l0), end(l0))); EOPAssert(size(l0) == k0); if (verbose) { print(" l0 before partition: "); print(l0); print_eol(); } partition(l0, l1, even<int>); if (verbose) { print(" l0 after: "); print(l0); print_eol(); } if (verbose) { print(" l1 after: "); print(l1); print_eol(); } EOPAssert(all(begin(l0), end(l0), odd<int>)); EOPAssert(all(begin(l1), end(l1), even<int>)); L l2; L l3; partition(l2, l3, even<int>); EOPAssert(empty(l2) && empty(l3)); merge(l0, l1, less<int>()); EOPAssert(equal_iota(begin(l0), end(l0)) && size(l0) == k0 && empty(l1)); reverse(l0); sort(l0, less<int>()); EOPAssert(equal_iota(begin(l0), end(l0)) && size(l0) == k0); print(" ***** to do: slist, list"); print(" (including erase, erase_first, erase_after, set_link_backward\n"); } template<typename S> requires(SingleExtentArray(S)) void type_single_extent_array(S& s0, S& s1, EOPValueType(S)& x) { // Precondition: s0 < s1 /\ x != s1[0] concept_DynamicSequence(s0, s1, x); // construct from capacity // construct from size, capacity, and value // construct from counted_range // end_of_storage // capacity // full // reserve_basic/reserve array<int> a; typedef EOPSizeType(array<int>) N; EOPAssert(empty(a)); EOPAssert(full(a)); EOPAssert(capacity(a) == N(0)); EOPAssert(end(a) == end_of_storage(a)); reserve(a, N(1)); EOPAssert(empty(a)); EOPAssert(!full(a)); EOPAssert(capacity(a) == N(1)); EOPAssert(end(a) + N(1) == end_of_storage(a)); insert(back< array<int> >(a), 1); EOPAssert(size(a) == N(1)); EOPAssert(end(a) == end_of_storage(a)); EOPAssert(full(a)); erase(back< array<int> >(a)); EOPAssert(empty(a)); EOPAssert(full(a)); // Exercises case where an empty array has non-zero capacity. // Memory used to leak. array<int> b; reserve(b, 1024*1024*1024); } void type_array() { { array<int> a0(10, 10, -39); array<int> a1(10, 10, 17); // establish a0 < a1 int x(99); type_single_extent_array(a0, a1, x); } { typedef pair<int, char> P; array<P> a0(3, 3, P()); array<P> a1(3, 3, P()); a0[0] = make_pair(0, 'a'); a1[0] = make_pair(1, 'Z'); // establish a0 < a1 P x = {2, '0'}; type_single_extent_array(a0, a1, x); } { typedef array_k<4, int> CA; CA ca0; CA ca1; fill_n(begin(ca0), size(ca0), 0); iota(4, begin(ca1)); // establish ca0 < ca1 typedef array<CA> A_CA; A_CA a0(3, 3, ca0); A_CA a1(3, 3, ca1); // establish a0 < a1 if (verbose) { print(" a0:"); print(a0); print_eol(); print(" a1:"); print(a1); print_eol(); } if (verbose) { print(" a0:"); print(a0); print_eol(); print(" a1:"); print(a1); print_eol(); } EOPAssert(a0 != a1); type_single_extent_array(a0, a1, ca0); { typedef slist<int> SL; SL sl0; SL sl1; extend_sequence_n(sl0, 3, 3); extend_sequence_n(sl1, 4, 4); typedef array< SL > A_SL; A_SL a0(2, 2, sl0); A_SL a1(2, 2, sl1); // establish a0 < a1 type_single_extent_array(a0, a1, sl0); } typedef slist< CA > SL; SL sl0; SL sl1; extend_sequence_n(sl0, 3, ca0); extend_sequence_n(sl1, 4, ca1); typedef array< SL > A_SL; A_SL a_sl0(4, 4, sl0); A_SL a_sl1(4, 4, sl1); // establish a0 < a1 type_single_extent_array(a_sl0, a_sl1, sl0); } } template<typename T, typename T0> requires(T == array<T0>) void algorithm_underlying_ref_array(T0& x) { typedef EOPUnderlyingType(T) U; T t(2, 2, x); U u = underlying_ref(t); EOPAssert(u.p == t.p); } template<typename T, typename T0> requires(T == array<T0>) void type_underlying_iterator_array(T0& x) { typedef EOPIteratorType(T) I; typedef underlying_iterator<I> UI; T t(2, 2, x); I f(begin(t)); I l(end(t)); UI uf = {f}; UI ul = {l}; EOPAssert(uf != ul); EOPAssert(predecessor(successor(uf)) == uf); EOPAssert(ul - uf == l - f); EOPAssert((uf + 1) - 1 == uf); EOPAssert(uf < ul); EOPAssert(addressof(sink(uf)) == addressof(source(uf)) && addressof(sink(uf)) == addressof(deref(uf))); EOPAssert(original(uf) == f); while (uf != ul) { EOPAssert(source(uf).p == source(f).p); f = successor(f); uf = successor(uf); } EOPAssert(f == l); } template<typename T, typename T0> requires(T == array<T0>) void algorithm_original_ref_array(T0& x) { typedef EOPUnderlyingType(T) U; T t0(2, 2, x); T t1(3, 3, x); EOPAssert(t0 < t1); U u0 = underlying_ref(t0); U u1 = underlying_ref(t1); EOPAssert(original_ref<T>(u0) < original_ref<T>(u1)); } template<typename T, typename P> requires(Predicate(P) && T == EOPDomain(P)) void algorithm_underlying_predicate(T& x0, T& x1, P p) { // Precondition: !p(x0) && p(x1) EOPAssert(!p(x0) && p(x1)); underlying_predicate<P> up = {p}; EOPAssert(!up(underlying_ref(x0)) && up(underlying_ref(x1))); } template<typename T, typename R> requires(Relation(R) && T == EOPDomain(R)) void algorithm_underlying_relation(T& x0, T& x1, R r) { // Precondition: r(x0, x1) && !r(x1, x0) typedef EOPUnderlyingType(T) U; EOPAssert(r(x0, x1) && !r(x1, x0)); underlying_relation<R> ur = {r}; U& ux0(underlying_ref(x0)); U& ux1(underlying_ref(x1)); EOPAssert(ur(ux0, ux1) && !ur(ux1, ux0)); } template<typename T> requires(Linearizable(T)) bool nonempty(const T& x) { return !empty(x); } void test_ch_12() { print(" Chapter 12\n"); print(" array_k\n"); type_array_k(); print(" bounded_range\n"); array_k<3, int> ca; type_bounded_range(begin(ca), end(ca)); array< array_k<3, int> > da(5, 5, ca); type_bounded_range(begin(da), end(da)); slist< array< array_k<3, int> > > sl; extend_sequence_n(sl, 7, da); type_bounded_range(begin(sl), end(sl)); print(" counted_range\n"); type_counted_range(begin(ca), size(ca)); type_counted_range(begin(da), size(da)); type_counted_range(begin(sl), size(sl)); { print(" before, after, front, back, at\n"); const int N = 10; array<int> da(N, N, 0); iota(N, begin(da)); slist<int> sl(da); list<int> l(da); test_Position(da, successor(begin(da))); test_Position(sl, successor(begin(sl))); test_Position(l, successor(begin(l))); } print(" slist\n"); type_list< slist<int> >(); print(" list\n"); type_list< list<int> >(); print(" ***** to do: stree, tree\n"); print(" array\n"); type_array(); print(" ***** to do: iterators/coordinates for slist, list, stree, tree, array\n"); print(" underlying type\n"); { { int i = 1; int j = 2; swap_basic(i, j); EOPAssert(i == 2 && j == 1); } { int i = 1; int j = 2; swap(i, j); EOPAssert(i == 2 && j == 1); } { int i = 1; int j = 2; int k = 3; rotate_left(i, j, k); EOPAssert(i == 2 && j == 3 && k == 1); } { int i = 1; int j = 2; int k = 3; rotate_right(i, j, k); EOPAssert(i == 3 && j == 1 && k == 2); } const int N = 10; array<int> a0(N, N, 0); array<int> a1(N, N, 1); EOPpointer(int) p0 = begin(a0); EOPpointer(int) p1 = begin(a1); swap(a0, a1); EOPAssert(all(begin(a0), end(a0), equal_to_x<int>(1))); EOPAssert(all(begin(a1), end(a1), zero<int>)); EOPAssert(p0 == begin(a1) && p1 == begin(a0)); // remote parts were swapped } int i(0); algorithm_underlying_ref_array< array<int>, int >(i); array<int> ai(1, 1, 1); algorithm_underlying_ref_array< array< array<int> > , array<int> >(ai); type_underlying_iterator_array< array< array<int> > >(ai); algorithm_original_ref_array< array< array<int> > , array<int> >(ai); array< array<int> > a_empty; array< array<int> > a_nonempty(1, 1, ai); algorithm_underlying_predicate(a_empty, a_nonempty, nonempty< array< array<int> > >); less< array< array<int> > > lt; algorithm_underlying_relation(a_empty, a_nonempty, lt); /* reverse_n_with_temporary_buffer using underlying_iterator */ } void run_tests() { // Call each procedure at least once. verify_conservation<int> vsl(slist_node_count); verify_conservation<int> vl(list_node_count); verify_conservation<int> vst(stree_node_count); verify_conservation<int> vt(tree_node_count); check_compile_time_logic(); test_ch_1(); test_ch_2(); test_ch_3(); test_ch_4(); test_ch_5(); test_ch_6(); test_ch_7<int, char>(); test_ch_8<int>(); test_ch_9<int>(); test_ch_10(); test_ch_11(); test_ch_12(); } #endif // EOP_TESTS
[ "asabriggs@fastmail.fm" ]
asabriggs@fastmail.fm
ac66e11732b0cbe70bff966c25517504cbb69d98
02541cc23351b013278c1ba4b4c5301b71e597cb
/Others/PCCA/d3/B.cpp
e2b9cdd038113ea91831cc36e1b46fa6c2a81872
[]
no_license
austin880625/problem_solving
d5ac0865405df6d613e408c996c8b875b500a85a
b76cfabcea6e750b9e97c2a66961760fe8d70cf9
refs/heads/master
2021-05-04T11:01:03.178708
2018-07-14T14:14:04
2018-07-14T14:14:04
43,396,070
0
0
null
null
null
null
UTF-8
C++
false
false
102
cpp
#include <stdio.h> #include <iostream> using namespace std; int main() { return 0; }
[ "austin880625@gmail.com" ]
austin880625@gmail.com
e1ccc1b0ea161e35bdf7d7ba6212da5beb909255
571075fc1c0eaee541c4e7aa4e63e1b6973b8f06
/Objet.cc
491604aa995782647e337a82515af241062391fe
[]
no_license
Kevin-Vu/The_Greatest
d7aa1750b228f6f249748ada80249aa44e5868f9
261af2a9a167d00878e8fe6c0d046352e4fc9933
refs/heads/master
2022-10-16T06:36:38.114256
2022-10-14T09:25:46
2022-10-14T09:25:46
167,258,552
0
1
null
2019-01-23T23:22:43
2019-01-23T21:40:56
C++
UTF-8
C++
false
false
897
cc
#include "Objet.hh" Objet::Objet(int x, int y) :Obstacle(x,y) { if(!o_text.loadFromFile("img/bulletin.png")) { std::cout << "Probleme de chargement" << std::endl; } o_text.setSmooth(true); o_sprite.setTexture(o_text); o_sprite.setPosition(sf::Vector2f(_x,_y)); o_sprite.setTextureRect(sf::IntRect(0,0,25,22)); o_rect = o_sprite.getGlobalBounds(); } void Objet::collision(Joueur& J1, int& special) { if(special == 2) { o_sprite.setPosition(sf::Vector2f(1000, 1000));//On met les objets speciaux en dehors de l'ecran updateORect(); return; } else if(special == 0) { addStat(J1);//Fait appel au addStat propre a chaque classe fille }//Dans le cas ou special = 1 ou 0, il faut deplacer dans la zone o_sprite.setPosition(sf::Vector2f(rand() % 400 + 20, rand() % 400 + 20)); updateORect(); }
[ "noreply@github.com" ]
noreply@github.com
524f6c0655e0389f2af76882991f9ea94a876a29
90ea9cc18485aa32483e5068204b42042cf36b26
/State.h
6ec40604db304fe345fb70105f58bf6d29db685a
[]
no_license
zxnrbl/micromouse
2804aff39fdccbc6bc57c9cc0dfbf7e5483a4a42
2f0b5225a1e5e4fe9354455e8b07d6ed1fa768a5
refs/heads/main
2023-02-06T06:43:05.438619
2021-01-01T03:27:56
2021-01-01T03:27:56
325,907,574
0
0
null
null
null
null
UTF-8
C++
false
false
2,519
h
#include <queue> #include "Move.h" #pragma once class Mouse; enum StateEnum { STATE_UNKNOWN, STATE_IDLE, STATE_INITIALIZING, STATE_EXPLORING, STATE_RETURNING, STATE_MAPPING, STATE_SPEEDING, STATE_COMPLETE }; class IState { public: virtual StateEnum State() const = 0; virtual void Enter( Mouse& context ); virtual void Exit( Mouse& context ); virtual void PreUpdate( Mouse& context ); virtual void Update( Mouse& context ) = 0; virtual void PostUpdate( Mouse& context ); }; class Unknown : public IState { public: static IState& Instance(); virtual StateEnum State() const; virtual void Update( Mouse& context ); private: Unknown(); ~Unknown(); }; class Idle : public IState { public: static IState& Instance(); virtual StateEnum State() const; virtual void Update( Mouse& context ); private: Idle(); ~Idle(); }; class Exploring : public IState { public: static IState& Instance(); virtual StateEnum State() const; virtual void Enter( Mouse& context ); virtual void Update( Mouse& context ); virtual void Exit( Mouse& context ); private: Exploring(); ~Exploring(); private: std::queue< MoveEnum > _queue; }; class Returning : public IState { public: static IState& Instance(); virtual StateEnum State() const; virtual void Enter( Mouse& context ); virtual void Update( Mouse& context ); virtual void Exit( Mouse& context ); private: Returning(); ~Returning(); }; class Mapping : public IState { public: static IState& Instance(); virtual StateEnum State() const; virtual void Update( Mouse& context ); virtual void Exit( Mouse& context ); private: Mapping(); ~Mapping(); }; class Speeding : public IState { public: static IState& Instance(); virtual StateEnum State() const; virtual void Enter( Mouse& context ); virtual void Update( Mouse& context ); virtual void Exit( Mouse& context ); private: Speeding(); ~Speeding(); }; class Complete : public IState { public: static IState& Instance(); virtual StateEnum State() const; virtual void Update( Mouse& context ); private: Complete(); ~Complete(); };
[ "73205278+zxnrbl@users.noreply.github.com" ]
73205278+zxnrbl@users.noreply.github.com
3c57bc397adb31c8fb5f04ccf93bd02c0e38a57d
2cf5dadd5fe8f18d6b7a107f3566913698f3f3e1
/系统模块/游戏组件/76.视频国际象棋源码/游戏客户端/GameClientDlg.h
b811d63e0fde9471911bdb8c9b0de577fdd58f15
[]
no_license
xiaokaixuan/qipai-game
319a5af77a490daf4c825ca7f54bc0b0bbf5c1a0
fce39d8192c1ea037ff34abec3d6074d56071934
refs/heads/master
2021-01-13T16:23:13.757533
2012-06-11T10:53:16
2012-06-11T10:53:16
54,963,680
1
0
null
2016-03-29T09:35:54
2016-03-29T09:35:53
null
GB18030
C++
false
false
3,551
h
#pragma once #include "Stdafx.h" #include "GameLogic.h" #include "GameClientView.h" ////////////////////////////////////////////////////////////////////////// //游戏对话框 class CGameClientDlg : public CGameFrameDlg { //游戏变量 protected: WORD m_wBlackUser; //黑棋玩家 BYTE m_cbChessColor; //棋子颜色 WORD m_wCurrentUser; //当前用户 WORD m_wLeftClock[2]; //剩余时间 //辅助变量 protected: bool m_ShamView; //预先显示 BYTE m_cbXSourcePos; //选择信息 BYTE m_cbYSourcePos; //选择信息 BYTE m_cbXTargetPos; //选择信息 BYTE m_cbYTargetPos; //选择信息 //配置变量 protected: bool m_bShowChessName; //显示名字 bool m_bAutoSaveManual; //自动保存 //控件变量 protected: CGameLogic m_GameLogic; //游戏逻辑 CGameClientView m_GameClientView; //游戏视图 //函数定义 public: //构造函数 CGameClientDlg(); //析构函数 virtual ~CGameClientDlg(); //常规继承 private: //初始函数 virtual bool InitGameFrame(); //重置框架 virtual void ResetGameFrame(); //游戏设置 virtual void OnGameOptionSet(); //时间消息 virtual bool OnTimerMessage(WORD wChairID, UINT nElapse, UINT nTimerID); //旁观状态 virtual void OnLookonChanged(bool bLookonUser, const void * pBuffer, WORD wDataSize); //网络消息 virtual bool OnGameMessage(WORD wSubCmdID, const void * pBuffer, WORD wDataSize); //游戏场景 virtual bool OnGameSceneMessage(BYTE cbGameStatus, bool bLookonOther, const void * pBuffer, WORD wDataSize); //消息处理 protected: //游戏开始 bool OnSubGameStart(const void * pBuffer, WORD wDataSize); //移动棋子 bool OnSubMoveChess(const void * pBuffer, WORD wDataSize); //悔棋请求 bool OnSubRegretReq(const void * pBuffer, WORD wDataSize); //悔棋失败 bool OnSubRegretFaile(const void * pBuffer, WORD wDataSize); //悔棋结果 bool OnSubRegretResult(const void * pBuffer, WORD wDataSize); //和棋请求 bool OnSubPeaceReq(const void * pBuffer, WORD wDataSize); //和棋应答 bool OnSubPeaceAnser(const void * pBuffer, WORD wDataSize); //游戏结束 bool OnSubGameEnd(const void * pBuffer, WORD wDataSize); //游戏棋谱 bool OnSubChessManual(const void * pBuffer, WORD wDataSize); //辅助函数 protected: //取消选择 void CancelChessSelect(); //执行走棋 void PerformMoveChess(BYTE cbSwitchChess); //保存棋谱 bool SaveChessManual(LPCTSTR pszFileName); //消息映射 protected: //定时器消息 afx_msg void OnTimer(UINT nIDEvent); //开始按钮 LRESULT OnStart(WPARAM wParam, LPARAM lParam); //悔棋按钮 LRESULT OnRegret(WPARAM wParam, LPARAM lParam); //求和按钮 LRESULT OnPeace(WPARAM wParam, LPARAM lParam); //认输按钮 LRESULT OnGiveUp(WPARAM wParam, LPARAM lParam); //保存按钮 LRESULT OnPreserve(WPARAM wParam, LPARAM lParam); //研究按钮 LRESULT OnStudy(WPARAM wParam, LPARAM lParam); //和棋应答 LRESULT OnPeaceAnswer(WPARAM wParam, LPARAM lParam); //悔棋应答 LRESULT OnRegretAnswer(WPARAM wParam, LPARAM lParam); //选择棋子 LRESULT OnSelectChess(WPARAM wParam, LPARAM lParam); //点击棋盘 LRESULT OnHitChessBorad(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() }; //////////////////////////////////////////////////////////////////////////
[ "pybmfc@gmail.com" ]
pybmfc@gmail.com
055695e4a4e5759efa782d8b91f25c812c281c08
2588b5370197ac4684b05e8d85a8f7d4e3a64a1e
/mmsjack/include/JackNetDriver.h
af137b436931417f5079ec7000d7a3d12e5875ae
[]
no_license
arthurtofani/ensemble
9fffcefcab7b87d7c9696b08a16e5d41d4701eed
18bf7510a8f8758b7730acf26371c0b15e847707
refs/heads/master
2020-12-26T02:22:17.442915
2013-04-17T02:47:23
2013-04-17T02:47:23
49,592,427
1
1
null
2016-01-13T18:13:48
2016-01-13T18:13:47
null
UTF-8
C++
false
false
3,051
h
/* Copyright (C) 2001 Paul Davis Copyright (C) 2008 Romain Moret at Grame 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. */ #ifndef __JackNetDriver__ #define __JackNetDriver__ #include "JackAudioDriver.h" #include "JackNetInterface.h" #ifdef JACK_MONITOR #include "JackFrameTimer.h" #endif namespace Jack { /** \Brief This class describes the Net Backend */ class JackNetDriver : public JackAudioDriver, public JackNetSlaveInterface { private: //jack data jack_port_id_t* fMidiCapturePortList; jack_port_id_t* fMidiPlaybackPortList; //transport int fLastTransportState; int fLastTimebaseMaster; //monitoring #ifdef JACK_MONITOR JackGnuPlotMonitor<float>* fNetTimeMon; jack_time_t fRcvSyncUst; #endif bool Initialize(); void FreeAll(); int AllocPorts(); int FreePorts(); //transport void EncodeTransportData(); void DecodeTransportData(); JackMidiBuffer* GetMidiInputBuffer ( int port_index ); JackMidiBuffer* GetMidiOutputBuffer ( int port_index ); public: JackNetDriver ( const char* name, const char* alias, JackLockedEngine* engine, JackSynchro* table, const char* ip, int port, int mtu, int midi_input_ports, int midi_output_ports, char* net_name, uint transport_sync, char network_master_mode ); ~JackNetDriver(); int Open ( jack_nframes_t frames_per_cycle, jack_nframes_t rate, bool capturing, bool playing, int inchannels, int outchannels, bool monitor, const char* capture_driver_name, const char* playback_driver_name, jack_nframes_t capture_latency, jack_nframes_t playback_latency ); int Close(); int Attach(); int Detach(); int Read(); int Write(); // BufferSize can't be changed bool IsFixedBufferSize() { return true; } int SetBufferSize ( jack_nframes_t buffer_size ) { return -1; } int SetSampleRate ( jack_nframes_t sample_rate ) { return -1; } }; } #endif
[ "lfthomaz@gmail.com" ]
lfthomaz@gmail.com
eae30747d1be0c7b6bcbc9e18be6fa2f5719bf41
bec0f727e0859afff3d592d83cb2b4661b8510e3
/src/defargs.h
a9c2f0426bac1ff91a3c1a95cbb1e65462334610
[]
no_license
pepr/doxypress
e712af4a1f25c48798594f3686f77a1a21a1ef51
a7a61abaa3051c8adda32aceadeecc151b444c2e
refs/heads/master
2021-01-18T02:57:54.351866
2016-04-18T06:45:36
2016-04-18T06:45:36
56,375,213
0
0
null
2016-04-16T09:14:15
2016-04-16T09:14:14
null
UTF-8
C++
false
false
1,028
h
/************************************************************************* * * Copyright (C) 2014-2016 Barbara Geller & Ansel Sermersheim * Copyright (C) 1997-2014 by Dimitri van Heesch. * All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation under the terms of the GNU General Public License version 2 * is hereby granted. No representations are made about the suitability of * this software for any purpose. It is provided "as is" without express or * implied warranty. See the GNU General Public License for more details. * * Documents produced by DoxyPress are derivative works derived from the * input used in their production; they are not affected by this license. * *************************************************************************/ #ifndef DEFARGS_H #define DEFARGS_H #include <QByteArray> class ArgumentList; extern void stringToArgumentList(const QString &argsString, ArgumentList *argList, QString *extraTypeChars = 0); #endif
[ "barbara@copperspice.com" ]
barbara@copperspice.com
4fe940bd770033d7f0217ab077cd8853d72de4c8
f05ea752b2260e18ccc905e53f0834040e5e5fc9
/src/gdalcubes/src/window_time.cpp
72b3a33c58a9980cc1a8a96aa588412fd122c43e
[]
no_license
cran/gdalcubes
480b13fc63e5f06ea415015bf35c77a6ea7efdd4
fcba9122505c87f8c08a9cdb944be504350ed6ea
refs/heads/master
2023-04-28T04:51:58.326642
2023-04-14T10:50:05
2023-04-14T10:50:05
201,308,945
0
0
null
null
null
null
UTF-8
C++
false
false
11,573
cpp
/* MIT License Copyright (c) 2019 Marius Appel <marius.appel@uni-muenster.de> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "window_time.h" namespace gdalcubes { std::function<double(double* buf, uint16_t n)> window_time_cube::get_default_reducer_by_name(std::string name) { if (name == "mean") { return std::function<double(double* buf, uint16_t n)>([](double* buf, uint16_t n) { double sum = 0.0; uint32_t count = 0; for (uint16_t i = 0; i < n; ++i) { if (!std::isnan(buf[i])) { sum += buf[i]; ++count; } } return sum / (double)count; }); } else if (name == "sum") { return std::function<double(double* buf, uint16_t n)>([](double* buf, uint16_t n) { double sum = 0.0; for (uint16_t i = 0; i < n; ++i) { if (!std::isnan(buf[i])) sum += buf[i]; } return sum; }); } else if (name == "count") { return std::function<double(double* buf, uint16_t n)>([](double* buf, uint16_t n) { double count = 0.0; for (uint16_t i = 0; i < n; ++i) { if (!std::isnan(buf[i])) ++count; } return count; }); } else if (name == "prod") { return std::function<double(double* buf, uint16_t n)>([](double* buf, uint16_t n) { double prod = 1.0; for (uint16_t i = 0; i < n; ++i) { if (!std::isnan(buf[i])) { prod *= buf[i]; } } return prod; }); } else if (name == "min") { return std::function<double(double* buf, uint16_t n)>([](double* buf, uint16_t n) { double min = std::numeric_limits<double>::max(); for (uint16_t i = 0; i < n; ++i) { if (!std::isnan(buf[i])) { min = std::min(min, buf[i]); } } return min; }); } else if (name == "max") { return std::function<double(double* buf, uint16_t n)>([](double* buf, uint16_t n) { double max = std::numeric_limits<double>::min(); for (uint16_t i = 0; i < n; ++i) { if (!std::isnan(buf[i])) { max = std::max(max, buf[i]); } } return max; }); } else if (name == "median") { return std::function<double(double* buf, uint16_t n)>([](double* buf, uint16_t n) { std::vector<double> val; val.assign(buf, buf+n); // TODO: handle NAN? std::sort(val.begin(), val.end()); if (val.size() % 2 == 1) { return val[val.size() / 2]; } else { return (val[val.size() / 2] + val[val.size() / 2 - 1]) / ((double)2); } }); } else { throw std::string("ERROR in window_time_cube::get_default_reducer_by_name(): Unknown reducer '" + name + "'"); } } std::function<double(double* buf, uint16_t n)> window_time_cube::get_kernel_reducer(std::vector<double> kernel) { if (kernel.size() != (uint32_t)(_win_size_l + 1 + _win_size_r)) { throw std::string("ERROR in window_time_cube::get_kernel_reducer(): Size of kernel does not match size of window"); } return std::function<double(double* buf, uint16_t n)>([kernel](double* buf, uint16_t n) -> double { double v = 0.0; for (uint16_t i = 0; i < n; ++i) { if (std::isnan(buf[i])) { return NAN; } v += buf[i] * kernel[i]; } return v; }); } std::shared_ptr<chunk_data> window_time_cube::read_chunk(chunkid_t id) { GCBS_TRACE("window_time_cube::read_chunk(" + std::to_string(id) + ")"); std::shared_ptr<chunk_data> out = std::make_shared<chunk_data>(); if (id >= count_chunks()) return out; // chunk is outside of the view, we don't need to read anything. coords_nd<uint32_t, 3> size_tyx = chunk_size(id); coords_nd<uint32_t, 4> size_btyx = {uint32_t(_bands.count()), size_tyx[0], size_tyx[1], size_tyx[2]}; out->size(size_btyx); // Fill buffers accordingly out->buf(std::calloc(size_btyx[0] * size_btyx[1] * size_btyx[2] * size_btyx[3], sizeof(double))); double* begin = (double*)out->buf(); double* end = ((double*)out->buf()) + size_btyx[0] * size_btyx[1] * size_btyx[2] * size_btyx[3]; std::fill(begin, end, NAN); uint32_t chunk_count_l = (uint32_t)std::ceil((double)_win_size_l / (double)(_in_cube->chunk_size()[0])); uint32_t chunk_count_r = (uint32_t)std::ceil((double)_win_size_r / (double)(_in_cube->chunk_size()[0])); std::shared_ptr<chunk_data> this_chunk = _in_cube->read_chunk(id); std::vector<std::shared_ptr<chunk_data>> l_chunks; std::vector<std::shared_ptr<chunk_data>> r_chunks; // Read needed chunks depending on window and chunk sizes for (uint16_t i = 1; i <= chunk_count_l; ++i) { // read l chunks int32_t tid = id - i * (_in_cube->count_chunks_x() * _in_cube->count_chunks_y()); if (tid < 0) break; l_chunks.push_back(_in_cube->read_chunk(tid)); } for (uint16_t i = 1; i <= chunk_count_r; ++i) { // read l chunks int32_t tid = id + i * (_in_cube->count_chunks_x() * _in_cube->count_chunks_y()); if (tid >= (int32_t)_in_cube->count_chunks()) break; r_chunks.push_back(_in_cube->read_chunk(tid)); } // buffer for a single time series including data from adjacent chunks for all used input bands uint32_t cur_ts_length = _win_size_l + size_tyx[0] + _win_size_r; double* cur_ts = (double*)std::calloc(cur_ts_length * _bands.count(), sizeof(double)); std::fill(cur_ts, cur_ts + cur_ts_length * _bands.count(), NAN); for (uint32_t ixy = 0; ixy < size_tyx[1] * size_tyx[2]; ++ixy) { // fill values from l chunks int32_t tsidx = _win_size_l - 1; for (uint16_t i = 0; i < chunk_count_l; ++i) { if (i >= l_chunks.size()) { // fill NA for (uint32_t ic = 0; ic < _in_cube->chunk_size()[0]; ++ic) { if (tsidx >= 0 && tsidx < (int32_t)cur_ts_length) { for (uint16_t ib = 0; ib < _bands.count(); ++ib) { cur_ts[ib * cur_ts_length + tsidx] = NAN; } tsidx--; } } } else { for (uint32_t ic = 0; ic < l_chunks[i]->size()[1]; ++ic) { if (tsidx >= 0 && tsidx < (int32_t)cur_ts_length) { // read only up to window size even if current chunk is larger for (uint16_t ib = 0; ib < _bands.count(); ++ib) { if (l_chunks[i]->empty()) { cur_ts[ib * cur_ts_length + tsidx] = NAN; } else { cur_ts[ib * cur_ts_length + tsidx] = ((double*)(l_chunks[i]->buf()))[_band_idx_in[ib] * (l_chunks[i]->size()[1] * l_chunks[i]->size()[2] * l_chunks[i]->size()[3]) + (l_chunks[i]->size()[1] - 1 - ic) * (l_chunks[i]->size()[2] * l_chunks[i]->size()[3]) + ixy]; } } tsidx--; } } } } // fill values from current chunk tsidx = _win_size_l; for (uint32_t ic = 0; ic < this_chunk->size()[1]; ++ic) { if (tsidx >= 0 && tsidx < (int32_t)cur_ts_length) { // read only up to window size even if current chunk is larger for (uint16_t ib = 0; ib < _bands.count(); ++ib) { if (this_chunk->empty()) { cur_ts[ib * cur_ts_length + tsidx] = NAN; } else { cur_ts[ib * cur_ts_length + tsidx] = ((double*)(this_chunk->buf()))[_band_idx_in[ib] * (this_chunk->size()[1] * this_chunk->size()[2] * this_chunk->size()[3]) + ic * (this_chunk->size()[2] * this_chunk->size()[3]) + ixy]; } tsidx++; } } } // fill values from r chunks for (uint16_t i = 0; i < chunk_count_r; ++i) { if (i >= r_chunks.size()) { // fill NA for (uint32_t ic = 0; ic < _in_cube->chunk_size()[0]; ++ic) { if (tsidx >= 0 && tsidx < (int32_t)cur_ts_length) { for (uint16_t ib = 0; ib < _bands.count(); ++ib) { cur_ts[ib * cur_ts_length + tsidx] = NAN; } tsidx++; } } } else { for (uint32_t ic = 0; ic < r_chunks[i]->size()[1]; ++ic) { if (tsidx >= 0 && tsidx < (int32_t)cur_ts_length) { // read only up to window size even if current chunk is larger for (uint16_t ib = 0; ib < _bands.count(); ++ib) { if (r_chunks[i]->empty()) { cur_ts[ib * cur_ts_length + tsidx] = NAN; } else { cur_ts[ib * cur_ts_length + tsidx] = ((double*)(r_chunks[i]->buf()))[_band_idx_in[ib] * (r_chunks[i]->size()[1] * r_chunks[i]->size()[2] * r_chunks[i]->size()[3]) + ic * (r_chunks[i]->size()[2] * r_chunks[i]->size()[3]) + ixy]; } } tsidx++; } } } } // compute new value for (uint32_t ic = 0; ic < size_tyx[0]; ++ic) { // call function over all windows for (uint16_t ib = 0; ib < _bands.count(); ++ib) { ((double*)out->buf())[ib * (size_tyx[0] * size_tyx[1] * size_tyx[2]) + ic * size_tyx[1] * size_tyx[2] + ixy] = _f[ib](&(cur_ts[ic]), _win_size_l + 1 + _win_size_r); } } } std::free(cur_ts); // check if chunk is completely NAN and if yes, return empty chunk if (out->all_nan()) { out = std::make_shared<chunk_data>(); } return out; } } // namespace gdalcubes
[ "csardi.gabor+cran@gmail.com" ]
csardi.gabor+cran@gmail.com
08333faef0788ef438ee0209609e39f9c64e9e8c
97e04772570141a5671e3c1ddef3c916a17f1ee6
/XPlay/app/src/main/cpp/IDecode.h
1a98cf33e3ab6a43c6300ca87eb13766f7fbdcab
[]
no_license
GJP1106/FFmpegXplay
695ba3236653b0fc20141db21ff7e974e9fe3272
86dcc4d04db8dcc2b0e2769412423d3e4d814fcf
refs/heads/master
2021-04-10T21:48:30.254792
2020-03-29T03:26:23
2020-03-29T03:26:23
248,969,418
0
0
null
null
null
null
UTF-8
C++
false
false
966
h
// // Created by GJP on 2020/3/22. // #ifndef XPLAY_IDECODE_H #define XPLAY_IDECODE_H #include "XParameter.h" #include "IObserver.h" #include <list> //解码接口,支持硬解码 class IDecode :public IObserver{ public: //打开解码器 virtual bool Open(XParameter para, bool isHard = false) = 0; virtual void Close() = 0; virtual void Clear(); //future模型 发送数据到线程解码 virtual bool SendPacket(XData pkt) = 0; //从线程中获取解码结果 再次调用会复用上次空间。线程不安全 virtual XData RecvFrame() = 0; //由主体notify的数据 阻塞 virtual void Update(XData pkt); bool isAudio = false; //最大的队列缓冲 int maxList = 100; //同步时间,再次打开文件要清理 int synPts = 0; int pts = 0; protected: virtual void Main(); //读取缓冲 std::list<XData> packs; std::mutex packsMutex; }; #endif //XPLAY_IDECODE_H
[ "gjp1106@outlook.com" ]
gjp1106@outlook.com
20bb099e5bb9747a395480db201e8c6a37f6ff2e
9824d607fab0a0a827abff255865f320e2a7a692
/界面资源/[XTreme.Toolkit.9.6.MFC].Xtreme.Toolkit.Pro.v9.60/Include/Controls/Common.Include/XTColorPopup.h
ea04eaf5d75a6deae19c2e35ae794779de572263
[]
no_license
tuian/pcshare
013b24af954b671aaf98604d6ab330def675a561
5d6455226d9720d65cfce841f8d00ef9eb09a5b8
refs/heads/master
2021-01-23T19:16:44.227266
2014-09-18T02:31:05
2014-09-18T02:31:05
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
8,613
h
// XTColorPopup.h : interface for the CXTColorPopup class. // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // ©1998-2005 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// //{{AFX_CODEJOCK_PRIVATE #if !defined(__XTCOLORPOPUP_H__) #define __XTCOLORPOPUP_H__ //}}AFX_CODEJOCK_PRIVATE #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //=========================================================================== // Summary: // CXTColorPopup is a CXTColorSelectorCtrl derived class. It is used // to create a CXTColorPopup window that will allow a user to select // colors and add custom colors to a color list. //=========================================================================== class _XT_EXT_CLASS CXTColorPopup : public CXTColorSelectorCtrl { public: //----------------------------------------------------------------------- // Summary: // Constructs a CXTColorPopup object. // Parameters: // bAutoDelete - TRUE if the color picker window is to be self deleting. // callerParam - Caller parameter; it will be reported back as an LPARAM of // color popup notification messages. //----------------------------------------------------------------------- CXTColorPopup(BOOL bAutoDelete=FALSE, LPARAM callerParam = 0); //----------------------------------------------------------------------- // Summary: // Destroys a CXTColorPopup object, handles cleanup and deallocation //----------------------------------------------------------------------- virtual ~CXTColorPopup(); public: //----------------------------------------------------------------------- // Summary: // This member function will add a color to the user defined color // list. // Parameters: // clrColor - An RGB value that represents the user defined color // to be displayed in // the recent color list. //----------------------------------------------------------------------- static void AddUserColor(COLORREF clrColor); // --------------------------------------------------------------------------- // Summary: // Resets the recently used color list. // Remarks: // Call this member function to reset the user defined color list. Calling // this function will remove all user defined colors from the MRU // list. // --------------------------------------------------------------------------- static void ResetUserColors(); // ----------------------------------------------------------------------------- // Summary: // This member function handles the creation of the color popup // window. // Parameters: // rect - A reference to a <i>CRect</i> object that represents the // size of the color popup window. // pParentWnd - Points to the parent window for the color popup. // dwPopup - Style for the popup window. See the Remarks section for a // complete list of available styles. // clrColor - An <i>RGB</i> value that represents the currently selected // color for the popup window. // clrDefault - Specifies the default color for the color popup. If the // current style includes CPS_NOFILL, this parameter is // ignored. // Remarks: // Styles to be added or removed can be combined by using the bitwise // OR (|) operator. It can be one or more of the following: // * <b>CPS_XT_NOFILL</b> The color picker will display a No Fill // button rather than the default Automatic Color button. // * <b>CPS_XT_EXTENDED</b> The color picker will display 40 // extended colors rather than the default 16 colors. // * <b>CPS_XT_MORECOLORS</b> The color picker will display a // More Colors button which will display a CXTColorDialog. // * <b>CPS_XT_SHOW3DSELECTION</b> Displays the color selection // box with a 3D raised border in CXTColorDialog. // * <b>CPS_XT_SHOWHEXVALUE</b> Displays the hex equivalent of // the selected color. // Returns: // TRUE if successful, otherwise returns FALSE. // See Also: // CXTColorPicker::ModifyCPStyle, CXTColorSelectorCtrl::Create // ----------------------------------------------------------------------------- virtual BOOL Create(CRect& rect,CWnd* pParentWnd,DWORD dwPopup,COLORREF clrColor,COLORREF clrDefault=CLR_DEFAULT); // --------------------------------------------------------------------- // Summary: // This member function adds a window that picker notifications are // sent to. // Parameters: // hwndListener - A handle to the listener window. Messages will be // sent to it. // --------------------------------------------------------------------- void AddListener(HWND hwndListener); // -------------------------------------------------------------------------- // Summary: // Enables or disables popup window shadow. // Parameters: // bDisplayShadow - Flag that tells if the shadow is to be displayed. // Remarks: // This member function enables or disables the drawing of popup shadows. // Call this function after instantiating the color popup as a part // \of an object's initialization. Do not call it after popup // creation because doing so may cause unpredictable results. // -------------------------------------------------------------------------- void DisplayShadow(BOOL bDisplayShadow = TRUE); protected: //----------------------------------------------------------------------- // Summary: // This member function will finish the selection process for the color // box or button in the color popup window. // Parameters: // nCurSel - Current index of the selected color box or button // in the color popup window. //----------------------------------------------------------------------- virtual void EndSelection(int nCurSel); protected: //{{AFX_CODEJOCK_PRIVATE DECLARE_MESSAGE_MAP() //{{AFX_VIRTUAL(CXTColorPopup) virtual BOOL PreTranslateMessage(MSG* pMsg); virtual void PostNcDestroy(); //}}AFX_VIRTUAL //{{AFX_MSG(CXTColorPopup) afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized); afx_msg void OnDestroy(); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnPaint(); afx_msg void OnKillFocus(CWnd* pNewWnd); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnNcPaint(); afx_msg void OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp); //}}AFX_MSG #if _MSC_VER > 1200 //MFC 7.0 afx_msg void OnActivateApp(BOOL bActive, DWORD dwThreadID); #else afx_msg void OnActivateApp(BOOL bActive, HTASK hTask); #endif //MFC 7.0 //}}AFX_CODEJOCK_PRIVATE private: BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL); protected: BOOL m_bAutoDelete; // TRUE if the popup window is to be self deleting. BOOL m_bDisplayShadow; // TRUE if the popup window will render its shadow. CRect m_rcExclude; // Area to exclude from shadow display. const LPARAM m_callerParam; // Caller parameter that will be reported back as an LPARAM of all notification messages. }; ////////////////////////////////////////////////////////////////////// AFX_INLINE void CXTColorPopup::AddUserColor(COLORREF clrColor) { m_arUserDefColors.Add( clrColor ); } AFX_INLINE BOOL CXTColorPopup::Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext) { return CWnd::Create(lpszClassName, lpszWindowName, dwStyle, rect, pParentWnd, nID, pContext); } AFX_INLINE void CXTColorPopup::ResetUserColors() { m_arUserDefColors.RemoveAll(); } AFX_INLINE void CXTColorPopup::DisplayShadow( BOOL bDisplayShadow/* = TRUE*/) { m_bDisplayShadow = bDisplayShadow; } #endif //#if !defined(__XTCOLORPOPUP_H__)
[ "sincoder@vip.qq.com" ]
sincoder@vip.qq.com
5b5a5c7258d45a598ed3ffb450a122d873fde241
9ad7957f285a8cff3efb10e14dc2602f532f9c39
/gas/lcd.cpp
19a811b916735847ea44b0c8eebdaebc1f52110b
[ "MIT" ]
permissive
jeannekamikaze/gas
b8fd27075c0450c15d595e7008685b964c0ed38a
d914a5ff45d4d7ae93fc7cd6ae3db00356875f8b
refs/heads/master
2021-01-01T04:04:39.519950
2017-07-14T17:02:28
2017-07-14T17:02:28
97,119,540
0
0
null
null
null
null
UTF-8
C++
false
false
227
cpp
#include "lcd.h" void print2 (LiquidCrystal& lcd, int x) { if (x < 10) lcd.print(0); lcd.print(x); } void print3 (LiquidCrystal& lcd, int x) { if (x < 100) lcd.print(0); if (x < 10) lcd.print(0); lcd.print(x); }
[ "jeannekamikaze@gmail.com" ]
jeannekamikaze@gmail.com
af5a9e40e7d4f14dd294e67ad29a183f79bfffdc
b9d486e0986f04bc112e59b16fa2510509f5c6fd
/uva/uva1225_fast.cpp
ec7b1c6d993633ded16314e089537ff2e469f243
[]
no_license
yqbeyond/Algorithms
8adb96b41248772762d71b9b652ac1065bfc364e
fd36261cff8d842a11a76ed167beda074c215794
refs/heads/master
2021-07-06T08:43:41.581046
2021-05-15T05:35:47
2021-05-15T05:35:47
55,763,481
0
0
null
null
null
null
UTF-8
C++
false
false
1,370
cpp
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int len(int n) { int res = 0; if (n == 0) return 1; while(n) { n /= 10; res++; } return res; } void print(long long *times) { for (int i = 0 ; i < 9; i++) printf("%lld ", times[i]); printf("%lld\n", times[9]); } int main() { long long times[10][10] = { {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1} }; for (int i = 2; i < 10; i++) { times[i][0] = times[i-1][0] + times[i-1][1] * 9; for (int j = 1; j <= 9; j++) times[i][j] = (long long)(pow(10, i - 1)) + times[i - 1][j] * 10; } int T; scanf("%d", &T); while(T--) { int n; scanf("%d", &n); int _len = len(n); long long res[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int tmp = 9; for (int i = 1; i < _len; i++) { res[0] += tmp * i; tmp *= 10; } res[0] += (n - (long long)(pow(10, _len-1)) + 1) * _len; while(n) { int first = n / (long long)(pow(10, _len - 1)); for (int i = 1; i < 10; i++) { res[i] += times[_len - 1][i] * first; if (i < first) res[i] += (long long)(pow(10, _len - 1)); if (i == first) res[i] += 1; } n %= (long long)(pow(10, _len - 1)); if (first != 0) res[first] += n; _len -= 1; } for (int i = 1; i < 10; i++) { res[0] -= res[i]; } print(res); } return 0; }
[ "yqqbeyond@gmail.com" ]
yqqbeyond@gmail.com
eaf7db64b14eb6a64eef248ec1079d7b5bfbf781
b3c47795e8b6d95ae5521dcbbb920ab71851a92f
/ZOJ/3630.cc
28288235835d763e0c9e715f8e34575d3141f8e0
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Wizmann/ACM-ICPC
6afecd0fd09918c53a2a84c4d22c244de0065710
7c30454c49485a794dcc4d1c09daf2f755f9ecc1
refs/heads/master
2023-07-15T02:46:21.372860
2023-07-09T15:30:27
2023-07-09T15:30:27
3,009,276
51
23
null
null
null
null
UTF-8
C++
false
false
2,796
cc
//Result:2012-07-30 16:57:06 Accepted 3630 C++ 510 616 Wizmann #include <cstdio> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <bitset> using namespace std; #define print(x) cout<<x<<endl #define input(x) cin>>x #define SIZE 10000 #define INF 1<<25 struct node { int v; int next; node(){} node(int iv,int inext) { v=iv;next=inext; } }; int head[SIZE]; node g[SIZE]; int ind; int n,m; int low[SIZE],dfn[SIZE]; int scc[SIZE],num[SIZE]; vector<int> tmpG[SIZE]; int sccnr=0; stack<int> st; bitset<SIZE> instack; int nr; int inG[SIZE]; inline void add_edge(int a,int b) { g[ind]=node(b,head[a]); head[a]=ind; ind++; } void init(bool all=true) { if(all) { memset(head,-1,sizeof(head)); memset(g,0,sizeof(g)); ind=0; } instack.reset(); memset(dfn,0,sizeof(dfn)); memset(scc,0,sizeof(scc)); memset(num,0,sizeof(num)); memset(low,0,sizeof(low)); while(!st.empty()) st.pop(); nr=1;sccnr=0; } void tarjan(int pos) { low[pos]=dfn[pos]=nr++; st.push(pos); instack[pos]=1; for(int i=head[pos];i!=-1;i=g[i].next) { int j=g[i].v; if(!dfn[j]) { tarjan(j); low[pos]=min(low[pos],low[j]); } else if(instack[j]) { low[pos]=min(low[pos],dfn[j]); } } if(dfn[pos]==low[pos]) { sccnr++; while(1) { int t=st.top(); instack[t]=0; st.pop(); scc[t]=sccnr; num[sccnr]++; if(t==pos) break; } } } int slove(int sec,int ptr) { int tmp=0; memset(inG,-1,sizeof(inG)); for(int i=0;i<SIZE;i++) tmpG[i].clear(); for(int i=0;i<n;i++) { if(scc[i]==ptr) inG[i]=tmp++; } for(int i=0;i<n;i++) { if(scc[i]==ptr) { int now=inG[i]; for(int j=head[i];j!=-1;j=g[j].next) { int next=g[j].v; if(inG[next]>=0) { next=inG[next]; tmpG[now].push_back(next); } } } } init(); n=tmp; for(int i=0;i<tmp;i++) { for(int j=0;j<(int)tmpG[i].size();j++) { add_edge(i,tmpG[i][j]); } } int ans=INF; for(int i=0;i<tmp;i++) { init(false); int t=head[i]; head[i]=-1; for(int j=0;j<tmp;j++) { if(!dfn[j]) tarjan(j); } int maxi=-1; for(int j=0;j<tmp;j++) { maxi=max(maxi,num[j]); } ans=min(ans,max(maxi,sec)); head[i]=t; } return ans>1?ans:0; } int main() { freopen("input.txt","r",stdin); int a,b; while(input(n>>m)) { init(); for(int i=0;i<m;i++) { scanf("%d%d",&a,&b); add_edge(a,b); } for(int i=0;i<n;i++) { if(!dfn[i]) tarjan(i); } priority_queue<int> pq; int max_scc=-1,ptr=-1; for(int i=1;i<=sccnr;i++) { pq.push(num[i]); if(num[i]>max_scc) { max_scc=num[i]; ptr=i; } } //print(">>"<<' '<<max_scc); pq.pop(); int sec=0; if(!pq.empty()) sec=pq.top(); print(slove(sec,ptr)); } return 0; }
[ "kuuy@foxmail.com" ]
kuuy@foxmail.com
a6150b078c3501943d10472b0c4bcb5b5bdf89c7
39eac74fa6a244d15a01873623d05f480f45e079
/ImportWizardTypeDlg.cpp
9f01db39c2973f732ec6f80240230bc6f124ac53
[]
no_license
15831944/Practice
a8ac8416b32df82395bb1a4b000b35a0326c0897
ae2cde9c8f2fb6ab63bd7d8cd58701bd3513ec94
refs/heads/master
2021-06-15T12:10:18.730367
2016-11-30T15:13:53
2016-11-30T15:13:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
37,125
cpp
// ImportWizardTypeDlg.cpp : implementation file // #include "stdafx.h" #include "ImportWizardDlg.h" #include "ImportWizardTypeDlg.h" #include "Globalutils.h" // (j.politis 2015-04-27 14:12) - PLID 65524 - Allow the import wizard to be resizable #include "GlobalDrawingUtils.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif using namespace NXDATALIST2Lib; enum FileTypeValues{ ftvCSV=0, ftvTab, ftvOther, }; ///////////////////////////////////////////////////////////////////////////// // CImportWizardTypeDlg dialog // (b.savon 2015-04-28 15:19) - PLID 65485 - Derive from our CNxPropertyPage IMPLEMENT_DYNCREATE(CImportWizardTypeDlg, CNxPropertyPage) CImportWizardTypeDlg::CImportWizardTypeDlg() : CNxPropertyPage(CImportWizardTypeDlg::IDD) { Construct(IDD_IMPORT_WIZARD_TYPE); m_psp.dwFlags |= PSP_USETITLE; m_psp.pszTitle = "Import File Wizard"; //{{AFX_DATA_INIT(CImportWizardTypeDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT // (j.politis 2015-04-27 14:12) - PLID 65524 - Allow the import wizard to be resizable m_bNeedInit = TRUE; } void CImportWizardTypeDlg::OnFinalRelease() { // When the last reference for an automation object is released // OnFinalRelease is called. The base class will automatically // deletes the object. Add additional cleanup required for your // object before calling the base class. CDialog::OnFinalRelease(); } void CImportWizardTypeDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CImportWizardTypeDlg) // NOTE: the ClassWizard will add DDX and DDV calls here DDX_Control(pDX, IDC_IMPORT_FILE_NAME, m_nxeditImportFileName); DDX_Control(pDX, IDC_IMPORT_FIELD_DELIMITER, m_nxeditImportFieldDelimiter); DDX_Control(pDX, IDC_IMPORT_TEXT_QUALIFIER, m_nxeditImportTextQualifier); DDX_Control(pDX, IDC_IMPORT_DELIMITER_LABEL, m_nxstaticImportDelimiterLabel); DDX_Control(pDX, IDC_IMPORT_TYPE_GROUPBOX, m_btnImportTypeGroupbox); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CImportWizardTypeDlg, CNxPropertyPage) //{{AFX_MSG_MAP(CImportWizardTypeDlg) ON_BN_CLICKED(IDC_IMPORT_PATIENT_FILE, OnImportPatientFile) ON_BN_CLICKED(IDC_IMPORT_PROVIDER_FILE, OnImportProviderFile) ON_BN_CLICKED(IDC_IMPORT_REF_PHYS_FILE, OnImportRefPhysFile) ON_BN_CLICKED(IDC_IMPORT_USER_FILE, OnImportUserFile) ON_BN_CLICKED(IDC_IMPORT_SUPPLIER_FILE, OnImportSupplierFile) ON_BN_CLICKED(IDC_IMPORT_OTHER_CONTACT_FILE, OnImportOtherContactFile) ON_BN_CLICKED(IDC_IMPORT_MEDINOTES_FILE, OnImportMedinotesFile) ON_BN_CLICKED(IDC_IMPORT_SERVICE_CODE_FILE, OnImportServiceCodeFile) ON_BN_CLICKED(IDC_IMPORT_RESOURCE_FILE, OnImportResourceCodeFile) ON_BN_CLICKED(IDC_IMPORT_PRODUCT_FILE, OnImportProductCodeFile) ON_BN_CLICKED(IDC_IMPORT_INSCO_FILE, OnImportInsCoCodeFile) ON_EN_CHANGE(IDC_IMPORT_FILE_NAME, OnChangeImportFileName) ON_BN_CLICKED(IDC_IMPORT_FILE_BROWSE, OnImportFileBrowse) ON_BN_CLICKED(IDC_IMPORT_USE_TEXT_QUALIFIER, OnImportUseTextQualifier) //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_IMPORT_PATIENT_NOTE_FILE, &CImportWizardTypeDlg::OnImportmportPatientNoteFile) ON_BN_CLICKED(IDC_IMPORT_RECALL_FILE, &CImportWizardTypeDlg::OnBnClickedImportRecallFile) ON_BN_CLICKED(IDC_IMPORT_APPTS_FILE, &CImportWizardTypeDlg::OnBnClickedImportApptsFile) ON_BN_CLICKED(IDC_IMPORT_INSURED_PARTIES, &CImportWizardTypeDlg::OnBnClickedImportInsuredParties) // (j.politis 2015-04-27 14:12) - PLID 65524 - Allow the import wizard to be resizable ON_WM_SIZE() ON_BN_CLICKED(IDC_IMPORT_RACES_FILE, &CImportWizardTypeDlg::OnBnClickedImportRacesFile) END_MESSAGE_MAP() BEGIN_DISPATCH_MAP(CImportWizardTypeDlg, CNxPropertyPage) //{{AFX_DISPATCH_MAP(CImportWizardTypeDlg) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_DISPATCH_MAP END_DISPATCH_MAP() // Note: we add support for IID_IImportWizardTypeDlg to support typesafe binding // from VBA. This IID must match the GUID that is attached to the // dispinterface in the .ODL file. // {31DD5896-CBAC-4FB4-86D6-0111F33AAEF6} static const IID IID_IImportWizardTypeDlg = { 0x31dd5896, 0xcbac, 0x4fb4, { 0x86, 0xd6, 0x1, 0x11, 0xf3, 0x3a, 0xae, 0xf6 } }; BEGIN_INTERFACE_MAP(CImportWizardTypeDlg, CNxPropertyPage) INTERFACE_PART(CImportWizardTypeDlg, IID_IImportWizardTypeDlg, Dispatch) END_INTERFACE_MAP() ///////////////////////////////////////////////////////////////////////////// // CImportWizardTypeDlg message handlers BOOL CImportWizardTypeDlg::OnInitDialog() { try{ CNxPropertyPage::OnInitDialog(); //(s.dhole 4/8/2015 10:26 AM ) - PLID 65229 Proirity preference // (j.politis 2015-04-06 14:17) - PLID 65232 - Limit all note imports to a maximum of 100k records. //(s.dhole 4/29/2015 2:18 PM ) - PLID 65712 added AllowedParagraphPerColumnInImport g_propManager.CachePropertiesInBulk("CImportWizardTypeDlg", propNumber, "(Username = '<None>' OR Username = '%s') AND (" "Name = 'MyDefaultNotesPriority' OR " "Name = 'MaxNumOfNoteRecordsToImport' OR " "Name = 'AllowedParagraphPerColumnInImport' " ")", _Q(GetCurrentUserName())); m_pFileType = BindNxDataList2Ctrl(this, IDC_IMPORT_FILE_TYPE, NULL, false); //(e.lally 2007-06-18) PLID 26364 - (Labeling the parsing part of the import wizard, split from 5288) //(e.lally 2007-06-07) PLID 26251 - Add ability to parse input files with text qualifier // (b.savon 2015-07-06 11:16) - PLID 66491 - The text qualifier checkbox on the import should default to be checked CheckDlgButton(IDC_IMPORT_USE_TEXT_QUALIFIER, BST_CHECKED); OnImportUseTextQualifier(); IRowSettingsPtr pRow = m_pFileType->GetNewRow(); pRow->PutValue(0, (long)ftvCSV); pRow->PutValue(1, "Comma Separated Values (.csv)"); m_pFileType->AddRowAtEnd(pRow, NULL); pRow = m_pFileType->GetNewRow(); pRow->PutValue(0, (long)ftvTab); pRow->PutValue(1, "Tab Delimited (.txt)"); m_pFileType->AddRowAtEnd(pRow, NULL); pRow = m_pFileType->GetNewRow(); pRow->PutValue(0, (long)ftvOther); pRow->PutValue(1, "Other"); m_pFileType->AddRowAtEnd(pRow, NULL); // (j.jones 2010-10-19 08:43) - PLID 34571 - disable options that they do // not have permissions to create entries for /* IF ANY CHANGES ARE MADE TO THE FOLLOWING PERMISSIONS CHECKS, THEN PLEASE REVIEW CMainFrame::ImportShouldBeEnabled() IF NECESSARY, MAKE SURE YOUR CHANGES ARE APPLIED THERE AS WELL. */ //the Medinotes import is also a patient import if(!(GetCurrentUserPermissions(bioPatient) & SPT____C_______ANDPASS)) { GetDlgItem(IDC_IMPORT_PATIENT_FILE)->EnableWindow(FALSE); GetDlgItem(IDC_IMPORT_MEDINOTES_FILE)->EnableWindow(FALSE); } //all contact creation is controlled by only one permission if(!(GetCurrentUserPermissions(bioContact) & SPT____C_______ANDPASS)) { GetDlgItem(IDC_IMPORT_PROVIDER_FILE)->EnableWindow(FALSE); GetDlgItem(IDC_IMPORT_REF_PHYS_FILE)->EnableWindow(FALSE); GetDlgItem(IDC_IMPORT_USER_FILE)->EnableWindow(FALSE); GetDlgItem(IDC_IMPORT_SUPPLIER_FILE)->EnableWindow(FALSE); GetDlgItem(IDC_IMPORT_OTHER_CONTACT_FILE)->EnableWindow(FALSE); } if(!(GetCurrentUserPermissions(bioServiceCodes) & SPT____C_______ANDPASS)) { GetDlgItem(IDC_IMPORT_SERVICE_CODE_FILE)->EnableWindow(FALSE); } // (r.farnworth 2015-03-30 12:26) - PLID 65197 - Add a new import type, Resources, to the import utility if (!(GetCurrentUserPermissions(bioAdminScheduler) & SPT___W________ANDPASS)) { GetDlgItem(IDC_IMPORT_RESOURCE_FILE)->EnableWindow(FALSE); } // (r.farnworth 2015-03-30 12:28) - PLID 65238 - Add a new import type, Products, to the't import utility if (!(GetCurrentUserPermissions(bioInvItem) & SPT____C_______ANDPASS)) { GetDlgItem(IDC_IMPORT_PRODUCT_FILE)->EnableWindow(FALSE); } // (b.savon 2015-03-30 15:48) - PLID 65231 - Add a new import type, Recalls, to the import utility if (!(GetCurrentUserPermissions(bioRecallSystem) & SPT____C_______ANDPASS)){ GetDlgItem(IDC_IMPORT_RECALL_FILE)->EnableWindow(FALSE); } // (r.farnworth 2015-04-01 12:45) - PLID 65166 - Add new import type, Insurance Companies, to the import utility if (!(GetCurrentUserPermissions(bioInsuranceCo) & SPT____C_______ANDPASS)) { GetDlgItem(IDC_IMPORT_INSCO_FILE)->EnableWindow(FALSE); } // (b.savon 2015-04-06 08:59) - PLID 65215 - Add a new import type, Appointments, to the import utility if (!(GetCurrentUserPermissions(bioAppointment) & SPT____C_______ANDPASS)){ GetDlgItem(IDC_IMPORT_APPTS_FILE)->EnableWindow(FALSE); } //(s.dhole 4/8/2015 1:50 PM ) - PLID 65224 Add new patient note utility if (!(GetCurrentUserPermissions(bioPatientNotes) & SPT____C_______ANDPASS)) { GetDlgItem(IDC_IMPORT_PATIENT_NOTE_FILE)->EnableWindow(FALSE); } //(s.dhole 4/13/2015 3:07 PM ) - PLID 65190 - Add a new import type, Insure Party, to the import utility if (!(GetCurrentUserPermissions(bioPatientInsurance) & SPT____C_______ANDPASS)) { GetDlgItem(IDC_IMPORT_INSURED_PARTIES)->EnableWindow(FALSE); } // (j.politis 2015-04-27 14:12) - PLID 65524 - Allow the import wizard to be resizable //Get our current size { CRect rc; GetClientRect(&rc); //Remember our current size m_ClientSize = rc.Size(); } //Remember that we no longer need to be initialized m_bNeedInit = FALSE; return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }NxCatchAll("Error in CImportWizardTypeDlg::OnInitDialog"); return FALSE; } BOOL CImportWizardTypeDlg::OnSetActive() { // (j.politis 2015-04-30 10:49) - PLID 65524 - Allow the import wizard to be resizable //When we become active, tell our parent CImportWizardDlg *pSheet = dynamic_cast<CImportWizardDlg *>(GetParentSheet()); if (pSheet != NULL) { pSheet->OnPageSetActive(this); } //Fill things in from our parent. // (j.jones 2010-10-19 08:43) - PLID 34571 - don't set a value if they don't have permission, // also don't set a value by default if they need to enter a password //the Medinotes import is also a patient import if((((CImportWizardDlg*)GetParent())->m_irtRecordType == irtPatients || ((CImportWizardDlg*)GetParent())->m_irtRecordType == irtMediNotes) && (!(GetCurrentUserPermissions(bioPatient) & SPT____C_______ANDPASS) || (GetCurrentUserPermissions(bioPatient) & sptCreateWithPass))) { UpdateWizardButtons(); return CNxPropertyPage::OnSetActive(); } //all contact creation is controlled by only one permission if((((CImportWizardDlg*)GetParent())->m_irtRecordType == irtProviders || ((CImportWizardDlg*)GetParent())->m_irtRecordType == irtReferringPhysicians || ((CImportWizardDlg*)GetParent())->m_irtRecordType == irtUsers || ((CImportWizardDlg*)GetParent())->m_irtRecordType == irtSuppliers || ((CImportWizardDlg*)GetParent())->m_irtRecordType == irtOtherContacts) && (!(GetCurrentUserPermissions(bioContact) & SPT____C_______ANDPASS) || (GetCurrentUserPermissions(bioContact) & sptCreateWithPass))) { UpdateWizardButtons(); return CNxPropertyPage::OnSetActive(); } if(((CImportWizardDlg*)GetParent())->m_irtRecordType == irtServiceCodes && (!(GetCurrentUserPermissions(bioServiceCodes) & SPT____C_______ANDPASS) || (GetCurrentUserPermissions(bioServiceCodes) & sptCreateWithPass))) { UpdateWizardButtons(); return CNxPropertyPage::OnSetActive(); } // (r.farnworth 2015-03-16 16:02) - PLID 65197 - Add a new import type, Resources, to the import utility if (((CImportWizardDlg*)GetParent())->m_irtRecordType == irtResources && (!(GetCurrentUserPermissions(bioAdminScheduler) & SPT___W________ANDPASS) || (GetCurrentUserPermissions(bioAdminScheduler) & sptWriteWithPass))) { UpdateWizardButtons(); return CNxPropertyPage::OnSetActive(); } // (r.farnworth 2015-03-19 11:17) - PLID 65238 - Add a new import type, Products, to the't import utility if (((CImportWizardDlg*)GetParent())->m_irtRecordType == irtProducts && (!(GetCurrentUserPermissions(bioInvItem) & SPT____C_______ANDPASS) || (GetCurrentUserPermissions(bioInvItem) & sptCreateWithPass))) { UpdateWizardButtons(); return CNxPropertyPage::OnSetActive(); } //(s.dhole 3/30/2015 11:19 AM ) - PLID 65224 if (((CImportWizardDlg*)GetParent())->m_irtRecordType == irtPatientNotes && (!(GetCurrentUserPermissions(bioPatientNotes) & SPT____C_______ANDPASS) || (GetCurrentUserPermissions(bioPatientNotes) & sptCreateWithPass))) { UpdateWizardButtons(); return CNxPropertyPage::OnSetActive(); } // (b.savon 2015-03-30 15:48) - PLID 65231 - Add a new import type, Recalls, to the import utility if (((CImportWizardDlg*)GetParent())->m_irtRecordType == irtRecalls && (!(GetCurrentUserPermissions(bioRecallSystem) & SPT____C_______ANDPASS) || (GetCurrentUserPermissions(bioRecallSystem) & sptCreateWithPass))) { UpdateWizardButtons(); return CNxPropertyPage::OnSetActive(); } // (r.farnworth 2015-04-01 17:15) - PLID 65166 - Add new import type, Insurance Companies, to the import utility if (((CImportWizardDlg*)GetParent())->m_irtRecordType == irtInsuranceCos && (!(GetCurrentUserPermissions(bioInsuranceCo) & SPT____C_______ANDPASS) || (GetCurrentUserPermissions(bioInsuranceCo) & sptCreateWithPass))) { UpdateWizardButtons(); return CNxPropertyPage::OnSetActive(); } // (b.savon 2015-04-06 09:01) - PLID 65215 - Add a new import type, Appointments, to the import utility if (((CImportWizardDlg*)GetParent())->m_irtRecordType == irtAppointments && (!(GetCurrentUserPermissions(bioAppointment) & SPT____C_______ANDPASS) || (GetCurrentUserPermissions(bioAppointment) & sptCreateWithPass))){ UpdateWizardButtons(); return CNxPropertyPage::OnSetActive(); } //(s.dhole 4/13/2015 3:07 PM ) - PLID 65190 - Add a new import type, Insure Party, to the import utility if (((CImportWizardDlg*)GetParent())->m_irtRecordType == irtInsuredParties && (!(GetCurrentUserPermissions(bioPatientInsurance) & SPT____C_______ANDPASS) || (GetCurrentUserPermissions(bioPatientInsurance) & sptCreateWithPass))) { UpdateWizardButtons(); return CNxPropertyPage::OnSetActive(); } UINT idcToCheck; switch(((CImportWizardDlg*)GetParent())->m_irtRecordType) { default: case irtPatients: idcToCheck = IDC_IMPORT_PATIENT_FILE; break; case irtProviders: idcToCheck = IDC_IMPORT_PROVIDER_FILE; break; case irtReferringPhysicians: idcToCheck = IDC_IMPORT_REF_PHYS_FILE; break; case irtUsers: idcToCheck = IDC_IMPORT_USER_FILE; break; case irtSuppliers: idcToCheck = IDC_IMPORT_SUPPLIER_FILE; break; case irtOtherContacts: idcToCheck = IDC_IMPORT_OTHER_CONTACT_FILE; break; case irtMediNotes: idcToCheck = IDC_IMPORT_MEDINOTES_FILE; break; case irtServiceCodes: // (j.jones 2010-03-30 08:52) - PLID 16717 - added support for service codes idcToCheck = IDC_IMPORT_SERVICE_CODE_FILE; break; case irtResources: // (r.farnworth 2015-03-16 16:06) - PLID 65197 - Add a new import type, Resources, to the import utility idcToCheck = IDC_IMPORT_RESOURCE_FILE; break; case irtProducts: idcToCheck = IDC_IMPORT_PRODUCT_FILE; break; case irtPatientNotes: //(s.dhole 3/30/2015 10:49 AM ) - PLID 65224 Patient note import idcToCheck = IDC_IMPORT_PATIENT_NOTE_FILE; break; case irtRecalls: // (b.savon 2015-03-30 16:11) - PLID 65231 - Add a new import type, Recalls, to the import utility idcToCheck = IDC_IMPORT_RECALL_FILE; break; case irtInsuranceCos: // (r.farnworth 2015-04-01 12:49) - PLID 65166 - Add new import type, Insurance Companies, to the import utility idcToCheck = IDC_IMPORT_INSCO_FILE; break; case irtAppointments: // (b.savon 2015-04-06 09:01) - PLID 65215 - Add a new import type, Appointments, to the import utility idcToCheck = IDC_IMPORT_APPTS_FILE; break; case irtInsuredParties: //(s.dhole 4/13/2015 3:07 PM ) - PLID 65190 - Add a new import type, Insure Party, to the import utility idcToCheck = IDC_IMPORT_INSURED_PARTIES; break; case irtRaces: // (r.goldschmidt 2016-02-09 14:59) - PLID 68163 - Add new import type, Races, to the import utility idcToCheck = IDC_IMPORT_RACES_FILE; break; } CheckRadioButton(IDC_IMPORT_PATIENT_FILE, IDC_IMPORT_RACES_FILE, idcToCheck); HandleRadioButton(); UpdateWizardButtons(); return CNxPropertyPage::OnSetActive(); } //(j.politis 2015-04-02 13:30) PLID 65232 - Bounce note imports with over 100k records BOOL CImportWizardTypeDlg::IsFileValid(const CString &strFileName) { CFile fImportFile; fImportFile.SetFilePath(strFileName); if (!fImportFile.Open(strFileName, CFile::modeRead | CFile::shareCompat)) { MessageBox("Could not read the specified filename. Please enter a valid filename for this import."); return FALSE; } if (DoesRecordTypeHaveFileLengthLimit()){ return IsFileLengthValid(fImportFile); } return TRUE; } //(j.politis 2015-04-02 13:30) PLID 65232 - Bounce note imports with over 100k records BOOL CImportWizardTypeDlg::DoesRecordTypeHaveFileLengthLimit() { switch (((CImportWizardDlg*)GetParent())->m_irtRecordType){ case irtPatientNotes: { return TRUE; } default: { return FALSE; } } } //(j.politis 2015-04-02 13:30) PLID 65232 - Bounce note imports with over 100k records long CImportWizardTypeDlg::GetFileLengthLimitForRecordType() { switch (((CImportWizardDlg*)GetParent())->m_irtRecordType){ case irtPatientNotes: { return GetRemotePropertyInt("MaxNumOfNoteRecordsToImport", 100000, 0, "<None>", true); } default: { //If you get here, you must handle the record type you added in DoesRecordTypeHaveFileLengthLimit() ASSERT(FALSE); return -1; } } } //(j.politis 2015-04-02 13:30) PLID 65232 - Bounce note imports with over 100k records CString CImportWizardTypeDlg::GetFileLengthLimitWarningMessage(long nMaxLimit) { CString strNMax = FormatNumberForInterface(nMaxLimit, FALSE, TRUE, 0); return FormatString("There are too many records in your file, the maximum allowed is %s.\r\n\r\n" "Please split your file into multiple files with %s records or less and try again.", strNMax, strNMax); } //(j.politis 2015-04-02 13:30) PLID 65232 - Bounce note imports with over 100k records BOOL CImportWizardTypeDlg::IsFileLengthValid(CFile &fImportFile) { CArchive ar(&fImportFile, CArchive::load); //easier to read whole lines with archives //Construct the error message long nMaxLimit = GetFileLengthLimitForRecordType(); //Count how many lines we read in, stop just 1 after our max CString strIn; int nCount = 0; while (ar.ReadString(strIn)){ //If we read in more than our max, display an error message and return if (++nCount > nMaxLimit){ CString strMessage = GetFileLengthLimitWarningMessage(nMaxLimit); MessageBox(strMessage, "Nextech Practice", MB_OK | MB_ICONEXCLAMATION); return FALSE; } } return TRUE; } BOOL CImportWizardTypeDlg::OnKillActive() { try { //(e.lally 2007-06-18) PLID 26364 - (Labeling the parsing part of the import wizard, split from 5288) //They have a filename, check if it is valid CString strFileName; GetDlgItemText(IDC_IMPORT_FILE_NAME, strFileName); if(strFileName.IsEmpty()){ MessageBox("You must enter a filename for this import"); return FALSE; } //(j.politis 2015-04-02 13:30) PLID 65232 - Bounce note imports with over 100k records if (!IsFileValid(strFileName)) { return FALSE; } //All is well, set the filename ((CImportWizardDlg*)GetParent())->m_strFileName = strFileName; //Make sure a file format was selected IRowSettingsPtr pRow = m_pFileType->GetCurSel(); if(pRow == NULL){ MessageBox("A File Format must be specified before continuing."); return FALSE; } //Check what type of file it is and see if we need to set the delimiter if(VarLong(pRow->GetValue(0)) == (long)ftvOther){ CString strDelimiter; GetDlgItemText(IDC_IMPORT_FIELD_DELIMITER, strDelimiter); ((CImportWizardDlg*)GetParent())->m_strFieldSeparator = strDelimiter; //we should force a delimiter to be specified if(strDelimiter.IsEmpty()){ MessageBox("The Field Delimiter must be specified with the 'Other' file format."); return FALSE; } } //(e.lally 2007-06-07) PLID 26251 - Add ability to parse input files with text qualifier //check if we need the field qualifier CString strQualifier = ""; //empty/none if(IsDlgButtonChecked(IDC_IMPORT_USE_TEXT_QUALIFIER)){ GetDlgItemText(IDC_IMPORT_TEXT_QUALIFIER, strQualifier); //we should force a text qualifier to be specified if(strQualifier.IsEmpty()){ MessageBox("The Text Qualifier may not be blank if it is checked to be in use."); return FALSE; } } ((CImportWizardDlg*)GetParent())->m_strTextQualifier = strQualifier; return CNxPropertyPage::OnKillActive(); }NxCatchAll("Error in CImportWizardTypeDlg::OnKillActive"); return FALSE; } void CImportWizardTypeDlg::UpdateWizardButtons() { //They can't go Back (we're the first page), and they can only go Next if // -they have filled in a file name // -they have specified the type of import being performed //(s.dhole 3/30/2015 10:51 AM ) - PLID 65224 Added IDC_IMPORT_PATIENT_NOTE_FILE // (b.savon 2015-03-30 16:18) - PLID 65231 - Add a new import type, Recalls, to the import utility // (b.savon 2015-04-06 09:01) - PLID 65215 - Add a new import type, Appointments, to the import utility //(s.dhole 4/13/2015 3:07 PM ) - PLID 65190 - Add a new import type, Insure Party, to the import utility // (r.goldschmidt 2016-02-09 14:59) - PLID 68163 - Add new import type, Races, to the import utility CString strFileName; GetDlgItemText(IDC_IMPORT_FILE_NAME, strFileName); if(strFileName.IsEmpty()) { ((CImportWizardDlg*)GetParent())->SetWizardButtons(0); } else if(!IsDlgButtonChecked(IDC_IMPORT_PATIENT_FILE) && !IsDlgButtonChecked(IDC_IMPORT_PROVIDER_FILE) && !IsDlgButtonChecked(IDC_IMPORT_REF_PHYS_FILE) && !IsDlgButtonChecked(IDC_IMPORT_USER_FILE) && !IsDlgButtonChecked(IDC_IMPORT_SUPPLIER_FILE) && !IsDlgButtonChecked(IDC_IMPORT_OTHER_CONTACT_FILE) && !IsDlgButtonChecked(IDC_IMPORT_MEDINOTES_FILE) && !IsDlgButtonChecked(IDC_IMPORT_SERVICE_CODE_FILE) && !IsDlgButtonChecked(IDC_IMPORT_RESOURCE_FILE) && !IsDlgButtonChecked(IDC_IMPORT_PRODUCT_FILE) && !IsDlgButtonChecked(IDC_IMPORT_PATIENT_NOTE_FILE) && !IsDlgButtonChecked(IDC_IMPORT_RECALL_FILE) && !IsDlgButtonChecked(IDC_IMPORT_INSCO_FILE) && !IsDlgButtonChecked(IDC_IMPORT_APPTS_FILE) && !IsDlgButtonChecked(IDC_IMPORT_INSURED_PARTIES) && !IsDlgButtonChecked(IDC_IMPORT_RACES_FILE) ) { ((CImportWizardDlg*)GetParent())->SetWizardButtons(0); } else { //they have a type of import selected //enable the next button ((CImportWizardDlg*)GetParent())->SetWizardButtons(PSWIZB_NEXT); } } void CImportWizardTypeDlg::OnImportPatientFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Patient File"); } void CImportWizardTypeDlg::OnImportProviderFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Provider File"); } void CImportWizardTypeDlg::OnImportRefPhysFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Referring Physician File"); } void CImportWizardTypeDlg::OnImportUserFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: User File"); } void CImportWizardTypeDlg::OnImportSupplierFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Supplier File"); } void CImportWizardTypeDlg::OnImportOtherContactFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Other Contact File"); } void CImportWizardTypeDlg::OnImportMedinotesFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: MediNotes File"); } // (j.jones 2010-04-05 10:07) - PLID 16717 - supported service codes void CImportWizardTypeDlg::OnImportServiceCodeFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Service Code File"); } // (r.farnworth 2015-03-16 16:51) - PLID 65197 - Add a new import type, Resources, to the import utility void CImportWizardTypeDlg::OnImportResourceCodeFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Resource Code File"); } // (r.farnworth 2015-03-19 11:30) - PLID 65238 - Add a new import type, Products, to the't import utility void CImportWizardTypeDlg::OnImportProductCodeFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Product Code File"); } // (r.farnworth 2015-04-01 14:41) - PLID 65166 - Add new import type, Insurance Companies, to the import utility void CImportWizardTypeDlg::OnImportInsCoCodeFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Insurance Companies Code File"); } //(s.dhole 3/30/2015 10:54 AM ) - PLID 65224 void CImportWizardTypeDlg::OnImportmportPatientNoteFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Patient Note File"); } // (b.savon 2015-03-30 16:01) - PLID 65231 - Add a new import type, Recalls, to the import utility void CImportWizardTypeDlg::OnBnClickedImportRecallFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Recall File"); } // (b.savon 2015-04-06 09:03) - PLID 65215 - Add a new import type, Appointments, to the import utility void CImportWizardTypeDlg::OnBnClickedImportApptsFile() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Appointment File"); } // (r.goldschmidt 2016-02-09 14:50) - PLID 68163 - added races import void CImportWizardTypeDlg::OnBnClickedImportRacesFile() { try { HandleRadioButton(); }NxCatchAll("Error selecting import file type: Races File"); } void CImportWizardTypeDlg::HandleRadioButton() { bool bChanged = false; if(IsDlgButtonChecked(IDC_IMPORT_PATIENT_FILE)) { // (j.jones 2010-10-19 08:43) - PLID 34571 - check create permission if(!CheckCurrentUserPermissions(bioPatient, sptCreate)) { CheckDlgButton(IDC_IMPORT_PATIENT_FILE, FALSE); UpdateWizardButtons(); return; } bChanged = (((CImportWizardDlg*)GetParent())->m_irtRecordType != irtPatients); ((CImportWizardDlg*)GetParent())->m_irtRecordType = irtPatients; } else if(IsDlgButtonChecked(IDC_IMPORT_PROVIDER_FILE)) { // (j.jones 2010-10-19 08:43) - PLID 34571 - check create permission if(!CheckCurrentUserPermissions(bioContact, sptCreate)) { CheckDlgButton(IDC_IMPORT_PROVIDER_FILE, FALSE); UpdateWizardButtons(); return; } bChanged = (((CImportWizardDlg*)GetParent())->m_irtRecordType != irtProviders); ((CImportWizardDlg*)GetParent())->m_irtRecordType = irtProviders; } else if(IsDlgButtonChecked(IDC_IMPORT_REF_PHYS_FILE)) { // (j.jones 2010-10-19 08:43) - PLID 34571 - check create permission if(!CheckCurrentUserPermissions(bioContact, sptCreate)) { CheckDlgButton(IDC_IMPORT_REF_PHYS_FILE, FALSE); UpdateWizardButtons(); return; } bChanged = (((CImportWizardDlg*)GetParent())->m_irtRecordType != irtReferringPhysicians); ((CImportWizardDlg*)GetParent())->m_irtRecordType = irtReferringPhysicians; } else if(IsDlgButtonChecked(IDC_IMPORT_USER_FILE)) { // (j.jones 2010-10-19 08:43) - PLID 34571 - check create permission if(!CheckCurrentUserPermissions(bioContact, sptCreate)) { CheckDlgButton(IDC_IMPORT_USER_FILE, FALSE); UpdateWizardButtons(); return; } bChanged = (((CImportWizardDlg*)GetParent())->m_irtRecordType != irtUsers); ((CImportWizardDlg*)GetParent())->m_irtRecordType = irtUsers; } else if(IsDlgButtonChecked(IDC_IMPORT_SUPPLIER_FILE)) { // (j.jones 2010-10-19 08:43) - PLID 34571 - check create permission if(!CheckCurrentUserPermissions(bioContact, sptCreate)) { CheckDlgButton(IDC_IMPORT_SUPPLIER_FILE, FALSE); UpdateWizardButtons(); return; } bChanged = (((CImportWizardDlg*)GetParent())->m_irtRecordType != irtSuppliers); ((CImportWizardDlg*)GetParent())->m_irtRecordType = irtSuppliers; } else if(IsDlgButtonChecked(IDC_IMPORT_OTHER_CONTACT_FILE)) { // (j.jones 2010-10-19 08:43) - PLID 34571 - check create permission if(!CheckCurrentUserPermissions(bioContact, sptCreate)) { CheckDlgButton(IDC_IMPORT_OTHER_CONTACT_FILE, FALSE); UpdateWizardButtons(); return; } bChanged = (((CImportWizardDlg*)GetParent())->m_irtRecordType != irtOtherContacts); ((CImportWizardDlg*)GetParent())->m_irtRecordType = irtOtherContacts; } else if(IsDlgButtonChecked(IDC_IMPORT_MEDINOTES_FILE)) { // (j.jones 2010-10-19 08:43) - PLID 34571 - check create permission if(!CheckCurrentUserPermissions(bioPatient, sptCreate)) { CheckDlgButton(IDC_IMPORT_MEDINOTES_FILE, FALSE); UpdateWizardButtons(); return; } bChanged = (((CImportWizardDlg*)GetParent())->m_irtRecordType != irtMediNotes); ((CImportWizardDlg*)GetParent())->m_irtRecordType = irtMediNotes; } // (j.jones 2010-03-30 08:52) - PLID 16717 - added support for service codes else if(IsDlgButtonChecked(IDC_IMPORT_SERVICE_CODE_FILE)) { // (j.jones 2010-10-19 08:43) - PLID 34571 - check create permission if(!CheckCurrentUserPermissions(bioServiceCodes, sptCreate)) { CheckDlgButton(IDC_IMPORT_SERVICE_CODE_FILE, FALSE); UpdateWizardButtons(); return; } bChanged = (((CImportWizardDlg*)GetParent())->m_irtRecordType != irtServiceCodes); ((CImportWizardDlg*)GetParent())->m_irtRecordType = irtServiceCodes; } // (r.farnworth 2015-03-17 09:00) - PLID 65197 - Add a new import type, Resources, to the import utility else if (IsDlgButtonChecked(IDC_IMPORT_RESOURCE_FILE)) { if (!CheckCurrentUserPermissions(bioAdminScheduler, sptWrite)) { CheckDlgButton(IDC_IMPORT_RESOURCE_FILE, FALSE); UpdateWizardButtons(); return; } bChanged = (((CImportWizardDlg*)GetParent())->m_irtRecordType != irtResources); ((CImportWizardDlg*)GetParent())->m_irtRecordType = irtResources; } // (r.farnworth 2015-03-19 11:30) - PLID 65238 - Add a new import type, Products, to the't import utility else if (IsDlgButtonChecked(IDC_IMPORT_PRODUCT_FILE)) { if (!CheckCurrentUserPermissions(bioInvItem, sptCreate)) { CheckDlgButton(IDC_IMPORT_PRODUCT_FILE, FALSE); UpdateWizardButtons(); return; } bChanged = (((CImportWizardDlg*)GetParent())->m_irtRecordType != irtProducts); ((CImportWizardDlg*)GetParent())->m_irtRecordType = irtProducts; } // (r.farnworth 2015-04-01 14:43) - PLID 65166 - Add new import type, Insurance Companies, to the import utility else if (IsDlgButtonChecked(IDC_IMPORT_INSCO_FILE)) { if (!CheckCurrentUserPermissions(bioInsuranceCo, sptCreate)) { CheckDlgButton(IDC_IMPORT_INSCO_FILE, FALSE); UpdateWizardButtons(); return; } bChanged = (((CImportWizardDlg*)GetParent())->m_irtRecordType != irtInsuranceCos); ((CImportWizardDlg*)GetParent())->m_irtRecordType = irtInsuranceCos; } //(s.dhole 3/30/2015 11:13 AM ) - PLID 65224 patient note import else if (IsDlgButtonChecked(IDC_IMPORT_PATIENT_NOTE_FILE) && HandleRadioButtonEx(IDC_IMPORT_PATIENT_NOTE_FILE, irtPatientNotes, bioPatientNotes, sptCreate) == FALSE) { return; } else if (IsDlgButtonChecked(IDC_IMPORT_RECALL_FILE) && HandleRadioButtonEx(IDC_IMPORT_RECALL_FILE, irtRecalls, bioRecallSystem, sptCreate) == FALSE) { // (b.savon 2015-03-30 16:18) - PLID 65231 - Add a new import type, Recalls, to the import utility return; } else if (IsDlgButtonChecked(IDC_IMPORT_APPTS_FILE) && HandleRadioButtonEx(IDC_IMPORT_APPTS_FILE, irtAppointments, bioAppointment, sptCreate) == FALSE){ // (b.savon 2015-04-06 09:03) - PLID 65215 - Add a new import type, Appointments, to the import utility return; } else if (IsDlgButtonChecked(IDC_IMPORT_INSURED_PARTIES) && HandleRadioButtonEx(IDC_IMPORT_INSURED_PARTIES, irtInsuredParties , bioPatientInsurance, sptCreate) == FALSE){ //(s.dhole 4/13/2015 3:07 PM ) - PLID 65190 - Add a new import type, Insure Party, to the import utility return; } else if (IsDlgButtonChecked(IDC_IMPORT_RACES_FILE)) { // (r.goldschmidt 2016-02-09 14:59) - PLID 68163 - Add new import type, Races, to the import utility ((CImportWizardDlg*)GetParent())->m_irtRecordType = irtRaces; } UpdateWizardButtons(); } //(s.dhole 3/30/2015 11:10 AM ) - PLID 65224 BOOL CImportWizardTypeDlg::HandleRadioButtonEx(UINT RedioButtonId, ImportRecordType RecordType, EBuiltInObjectIDs oBuiltInObjectID, ESecurityPermissionType SecurityPermissionType) { if (!CheckCurrentUserPermissions(oBuiltInObjectID, SecurityPermissionType)) { CheckDlgButton(RedioButtonId, FALSE); UpdateWizardButtons(); return FALSE ; } ((CImportWizardDlg*)GetParent())->m_irtRecordType = RecordType; return TRUE; } void CImportWizardTypeDlg::OnChangeImportFileName() { try{ UpdateWizardButtons(); }NxCatchAll("Error changing import file name"); } BOOL CImportWizardTypeDlg::GetImportFileName(CString &strFileName) { CFileDialog dlgBrowse(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_NOREADONLYRETURN, "Comma Separated Values (*.csv)|*.csv|Tab Delimited Text Files (*.txt)|*.txt;*.tab|All Files|*.*|"); // (b.savon 2015-07-06 14:29) - PLID 66489 - It appears to not remember by design. It's overwriting the "last path" with the shared path. // Removed explicity set. if (dlgBrowse.DoModal() == IDOK) { // If the user clicked okay, that means he or she selected a file so remember it strFileName = dlgBrowse.GetPathName(); return TRUE; } else { //they cancelled so we are not going to do anything return FALSE; } } void CImportWizardTypeDlg::OnImportFileBrowse() { try{ CString strImportFileName; if(GetImportFileName(strImportFileName)){ SetDlgItemText(IDC_IMPORT_FILE_NAME, strImportFileName); if(strImportFileName.Right(4).CompareNoCase(".txt") == 0){ //Set file type to tab m_pFileType->SetSelByColumn(0, (long)ftvTab); HandleSelectedFileType(ftvTab); } else if(strImportFileName.Right(4).CompareNoCase(".csv") ==0){ //Set file type to csv m_pFileType->SetSelByColumn(0, (long)ftvCSV); HandleSelectedFileType(ftvCSV); } } }NxCatchAll("Error browsing for import file"); } BEGIN_EVENTSINK_MAP(CImportWizardTypeDlg, CNxPropertyPage) //{{AFX_EVENTSINK_MAP(CImportWizardTypeDlg) ON_EVENT(CImportWizardTypeDlg, IDC_IMPORT_FILE_TYPE, 2 /* SelChanged */, OnSelChangedImportFileType, VTS_DISPATCH VTS_DISPATCH) ON_EVENT(CImportWizardTypeDlg, IDC_IMPORT_FILE_TYPE, 16 /* SelChosen */, OnSelChosenImportFileType, VTS_DISPATCH) //}}AFX_EVENTSINK_MAP END_EVENTSINK_MAP() void CImportWizardTypeDlg::OnSelChangedImportFileType(LPDISPATCH lpOldSel, LPDISPATCH lpNewSel) { } void CImportWizardTypeDlg::OnSelChosenImportFileType(LPDISPATCH lpRow) { try{ IRowSettingsPtr pRow(lpRow); long nFileType = VarLong(pRow->GetValue(0), -1); HandleSelectedFileType(nFileType); }NxCatchAll("Error selecting Import File type"); } //(e.lally 2007-06-18) PLID 26364 - (Labeling the parsing part of the import wizard, split from 5288) void CImportWizardTypeDlg::HandleSelectedFileType(long nFileType) { switch(nFileType){ case ftvCSV: ((CImportWizardDlg*)GetParent())->m_strFieldSeparator = ","; break; case ftvTab: ((CImportWizardDlg*)GetParent())->m_strFieldSeparator = "\t"; break; case ftvOther: GetDlgItem(IDC_IMPORT_FIELD_DELIMITER)->ShowWindow(TRUE); GetDlgItem(IDC_IMPORT_DELIMITER_LABEL)->ShowWindow(TRUE); return;// we can stop here } GetDlgItem(IDC_IMPORT_FIELD_DELIMITER)->ShowWindow(FALSE); GetDlgItem(IDC_IMPORT_DELIMITER_LABEL)->ShowWindow(FALSE); } void CImportWizardTypeDlg::OnImportUseTextQualifier() { //(e.lally 2007-06-07) PLID 26251 - Add ability to parse input files with text qualifier try{ BOOL bEnabled = FALSE; if(IsDlgButtonChecked(IDC_IMPORT_USE_TEXT_QUALIFIER)){ bEnabled = TRUE; CString strQualifier; GetDlgItemText(IDC_IMPORT_TEXT_QUALIFIER, strQualifier); if(strQualifier.IsEmpty()) SetDlgItemText(IDC_IMPORT_TEXT_QUALIFIER, "\""); //double quote } else{ bEnabled = FALSE; } GetDlgItem(IDC_IMPORT_TEXT_QUALIFIER)->EnableWindow(bEnabled); }NxCatchAll("Error enabling the use of a Text Qualifier"); } //(s.dhole 4/13/2015 3:07 PM ) - PLID 65190 - Add a new import type, Insure Party, to the import utility void CImportWizardTypeDlg::OnBnClickedImportInsuredParties() { try{ HandleRadioButton(); }NxCatchAll("Error selecting import file type: Insured Party File"); } // (j.politis 2015-04-27 14:12) - PLID 65524 - Allow the import wizard to be resizable void CImportWizardTypeDlg::OnSize(UINT nType, int cx, int cy) { CPropertyPage::OnSize(nType, cx, cy); if (m_bNeedInit) { return; } //Get the delta, the difference in size int dx = cx - m_ClientSize.cx; int dy = cy - m_ClientSize.cy; //Rember the new size m_ClientSize.cx = cx; m_ClientSize.cy = cy; //Change the positions of each of the items, according to their anchors try{ ChangeDlgItemPos(this, IDC_IMPORT_FILE_NAME, dx, dy, EChangeDlgItemPosAnchor::LeftTopRight); ChangeDlgItemPos(this, IDC_IMPORT_FILE_BROWSE, dx, dy, EChangeDlgItemPosAnchor::TopRight); }NxCatchAllIgnore(); }
[ "h.shah@WALD" ]
h.shah@WALD
8aeda434c47803b96d238edb8ad2642d772de670
20805224c698e9260cc5b9f3f51a3290fafec386
/common/comm/player_base.cpp
d56fc97d6602b1fe72b61cce1bbf5fd989598301
[]
no_license
jyqiu1216/bob
bacd14472a3b5f19b52fbf9747c1e2d5b0f29ee2
5a58c17deaa953a48df512c29ed1557276ef3608
refs/heads/master
2020-06-18T17:56:26.416382
2017-01-03T01:16:49
2017-01-03T01:16:49
74,750,647
0
0
null
null
null
null
GB18030
C++
false
false
37,426
cpp
#include "player_base.h" #include "common_base.h" #include "common_func.h" #include "activities_logic.h" #include "service_key.h" #include "quest_logic.h" #include "city_base.h" #include "action_base.h" #include "item_base.h" #include "msg_base.h" #include "conf_base.h" #include "sendmessage_base.h" TBOOL CPlayerBase::HasEnoughGem(TbLogin *ptbLogin, TUINT32 udwGemNum) { if (ptbLogin->m_nGem >= udwGemNum) { return TRUE; } return FALSE; } TVOID CPlayerBase::CostGem(SUserInfo *pstUser, TUINT32 udwGemNum) { TbLogin *ptbLogin = &pstUser->m_tbLogin; if (ptbLogin->m_nGem > udwGemNum) { ptbLogin->m_nGem -= udwGemNum; } else { ptbLogin->m_nGem = 0; } CActivitesLogic::ComputeCostGemScore(pstUser, udwGemNum); ptbLogin->m_mFlag[TbLOGIN_FIELD_GEM] = UPDATE_ACTION_TYPE_PUT; } TVOID CPlayerBase::AddGem(TbLogin *ptbLogin, TUINT32 udwGemNum) { ptbLogin->m_nGem += udwGemNum; ptbLogin->m_mFlag[TbLOGIN_FIELD_GEM] = UPDATE_ACTION_TYPE_PUT; } TVOID CPlayerBase::SetGem(TbLogin *ptbLogin, TUINT32 udwGemNum) { ptbLogin->m_nGem = udwGemNum; ptbLogin->m_mFlag[TbLOGIN_FIELD_GEM] = UPDATE_ACTION_TYPE_PUT; } TBOOL CPlayerBase::IsDeadPlayer(TbPlayer *ptbPlayer, TUINT32 udwTime) { if (udwTime - ptbPlayer->m_nUtime > MAX_PLAYER_DEAD_TIME) { return TRUE; } else { return FALSE; } } TBOOL CPlayerBase::HasChangePlayerName(const TbPlayer* ptbPlayer) { if (NULL == strstr(ptbPlayer->m_sUin.c_str(), "Player")) { return TRUE; } return FALSE; } TVOID CPlayerBase::AddLordExp(SUserInfo *pstUser, SCityInfo *pstCity, TUINT32 udwExp, TBOOL bNeedBuff) { TbPlayer* ptbPlayer = &pstUser->m_tbPlayer; if (bNeedBuff) { udwExp *= 1 + 1.0 * pstUser->m_stPlayerBuffList[EN_BUFFER_INFO_LORD_EXP_BONUS].m_ddwBuffTotal / 10000; } ptbPlayer->Set_Exp(ptbPlayer->m_nExp + udwExp); CQuestLogic::SetTaskCurValue(pstUser, pstCity, EN_TASK_TYPE_ING_ADD_HERO_EXP, udwExp); if(ptbPlayer->m_nExp > CPlayerBase::GetMaxLordExp()) { ptbPlayer->Set_Exp(CPlayerBase::GetMaxLordExp()); } } TVOID CPlayerBase::AddDragonExp(SUserInfo *pstUser, TUINT32 udwExp, TBOOL bNeedBuff) { TbPlayer* ptbPlayer = &pstUser->m_tbPlayer; TINT64 ddwMaxExp = CPlayerBase::GetMaxDragonExp(ptbPlayer->m_nDragon_max_lv); if (ptbPlayer->m_nDragon_exp < ddwMaxExp) { if (bNeedBuff) { udwExp *= 1 + 1.0 * pstUser->m_stPlayerBuffList[EN_BUFFER_INFO_DRAGON_EXP_BONUS].m_ddwBuffTotal / 10000; } ptbPlayer->Set_Dragon_exp(ptbPlayer->m_nDragon_exp + udwExp); if (ptbPlayer->m_nDragon_exp > ddwMaxExp) { ptbPlayer->Set_Dragon_exp(ddwMaxExp); } } } TINT64 CPlayerBase::GetRawVipLevelPoint(TINT32 dwLevel) { //dwLevel = (dwLevel <= 1) ? 1 : dwLevel; //const Json::Value& oJsonVip = CGameInfo::GetInstance()->m_oJsonRoot["game_vip"]; //if(dwLevel > static_cast<TINT32>(oJsonVip["a"].size())) //{ // return oJsonVip["a"][oJsonVip["a"].size() - 1].asInt64(); //} //return oJsonVip["a"][dwLevel - 1].asInt64(); dwLevel = (dwLevel <= 1) ? 1 : dwLevel; const Json::Value& oJsonVip = CGameInfo::GetInstance()->m_oJsonRoot["game_vip_new"]; if (dwLevel > static_cast<TINT32>(oJsonVip.size())) { return oJsonVip[oJsonVip.size() - 1]["a"][0u].asInt64(); } return oJsonVip[dwLevel - 1]["a"][0u].asInt64(); } TINT32 CPlayerBase::GetRawVipLevel(TbPlayer* ptbPlayer, TINT64 ddwVipPoint) { //const Json::Value& oJsonVip = CGameInfo::GetInstance()->m_oJsonRoot["game_vip"]; //TUINT32 dwVipLevel = 0; //for(dwVipLevel = 0; dwVipLevel < oJsonVip["a"].size(); ++dwVipLevel) //{ // if(ddwVipPoint < oJsonVip["a"][dwVipLevel].asInt64()) // { // break; // } //} //return dwVipLevel; const Json::Value& oJsonVip = CGameInfo::GetInstance()->m_oJsonRoot["game_vip_new"]; TINT32 dwVipLevel = 0; for (dwVipLevel = 0; dwVipLevel < oJsonVip.size(); dwVipLevel++) { if (ddwVipPoint < oJsonVip[dwVipLevel]["a"][0u].asInt64() || ptbPlayer->m_nVip_stage < oJsonVip[dwVipLevel]["a"][1u].asInt64()) { break; } } return dwVipLevel; } TINT32 CPlayerBase::GetRawVipStage(TINT32 dwLevel) { //const Json::Value& oJsonVip = CGameInfo::GetInstance()->m_oJsonRoot["game_vip_new"]; //TINT32 dwVipStage; //TUINT32 udwIdx; //for (udwIdx = 0; udwIdx < oJsonVip.size(); udwIdx++) //{ // if (ddwVipPoint < oJsonVip[udwIdx]["a"][0u].asInt64()) // { // break; // } //} //dwVipStage = oJsonVip[udwIdx-1]["a"][1u].asUInt(); //return dwVipStage; dwLevel = (dwLevel <= 1) ? 1 : dwLevel; const Json::Value& oJsonVip = CGameInfo::GetInstance()->m_oJsonRoot["game_vip_new"]; if (dwLevel > static_cast<TINT32>(oJsonVip.size())) { return oJsonVip[oJsonVip.size() - 1]["a"][1u].asInt64(); } return oJsonVip[dwLevel - 1]["a"][1u].asInt64(); } TINT64 CPlayerBase::GetMaxVipPoint(TbPlayer* ptbPlayer) { //当前阶段最大vip点数 TUINT32 udwVipStage = ptbPlayer->m_nVip_stage; TUINT32 udwIdx; const Json::Value& oJsonVip = CGameInfo::GetInstance()->m_oJsonRoot["game_vip_new"]; for (udwIdx = 0; udwIdx < oJsonVip.size(); udwIdx++) { if (udwVipStage < oJsonVip[udwIdx]["a"][1u].asUInt()) { udwIdx--; break; } } return oJsonVip[udwIdx]["a"][0u].asInt64(); } TINT64 CPlayerBase::GetMaxVipPoint() { const Json::Value& oJsonVip = CGameInfo::GetInstance()->m_oJsonRoot["game_vip_new"]; return oJsonVip[oJsonVip.size() - 1]["a"][0u].asInt64(); } TINT32 CPlayerBase::GetMaxVipStage() { const Json::Value& oJsonVip = CGameInfo::GetInstance()->m_oJsonRoot["game_vip_new"]; return oJsonVip[oJsonVip.size() - 1]["a"][1u].asInt(); } TINT32 CPlayerBase::GetVipLevel(TbPlayer* ptbPlayer) { if(ptbPlayer->m_nVip_etime < CTimeUtils::GetUnixTime()) { return 0; } return CPlayerBase::GetRawVipLevel(ptbPlayer, ptbPlayer->m_nVip_point); } TINT32 CPlayerBase::ComputePlayerLevel(TbPlayer* ptbPlayer) { TUINT32 dwLevel = 0; const Json::Value& oJsonExp = CGameInfo::GetInstance()->m_oJsonRoot["game_lord_exp"]; for(; dwLevel < oJsonExp.size(); ++dwLevel) { if(ptbPlayer->m_nExp < oJsonExp[dwLevel][0u].asInt64()) { break; } } dwLevel = dwLevel > 0 ? dwLevel - 1 : dwLevel; return dwLevel; } TINT32 CPlayerBase::ComputeDragonLevel(TINT64 ddwExp) { TUINT32 dwLevel = 0; const Json::Value& oJsonExp = CGameInfo::GetInstance()->m_oJsonRoot["game_dragon_exp"]; for (; dwLevel < oJsonExp.size(); ++dwLevel) { if (ddwExp < oJsonExp[dwLevel][0u].asInt64()) { break; } } dwLevel = dwLevel > 0 ? dwLevel - 1 : dwLevel; return dwLevel; } TINT32 CPlayerBase::GetLeftLordSkillPoint(TbPlayer* ptbPlayer, TbUser_stat* ptbUserStat) { TUINT32 dwLevel = ptbPlayer->m_nLevel; const Json::Value& oJsonExp = CGameInfo::GetInstance()->m_oJsonRoot["game_lord_exp"]; if (dwLevel >= oJsonExp.size()) { dwLevel = oJsonExp.size() - 1; } TINT32 dwTotalPoint = oJsonExp[dwLevel][1u].asInt(); TINT32 dwUsedPoints = 0; for (TUINT32 udwIdx = 0; udwIdx < EN_SKILL_TYPE__END; ++udwIdx) { dwUsedPoints += ptbUserStat->m_bLord_skill[0].m_addwLevel[udwIdx]; } return dwTotalPoint > dwUsedPoints ? dwTotalPoint - dwUsedPoints : 0; return 0; } TINT32 CPlayerBase::GetLeftLordSkillPoint( SUserInfo *pstUserInfo ) { TINT32 dwTotalPoint = pstUserInfo->m_stPlayerBuffList[EN_BUFFER_INFO_INCREACE_LORD_SKILL_POINT].m_ddwBuffTotal; TINT32 dwUsedPoints = GetUsedLoadSkillPoint(&pstUserInfo->m_tbUserStat); return dwTotalPoint > dwUsedPoints ? dwTotalPoint - dwUsedPoints : 0; } TINT32 CPlayerBase::GetUsedLoadSkillPoint( TbUser_stat* ptbUserStat ) { TINT32 dwUsedPoints = 0; for (TUINT32 udwIdx = 0; udwIdx < EN_SKILL_TYPE__END; ++udwIdx) { dwUsedPoints += ptbUserStat->m_bLord_skill[0].m_addwLevel[udwIdx]; } return dwUsedPoints; } TINT32 CPlayerBase::GetLordSkillPointLimit(TINT32 dwSkillId) { const Json::Value& oJsonSkill = CGameInfo::GetInstance()->m_oJsonRoot["game_lord_skill"]; string strSkillId = CCommonFunc::NumToString(dwSkillId); if (oJsonSkill.isMember(strSkillId) == FALSE) { return 0; } return oJsonSkill[strSkillId]["a"]["a0"].asInt(); } TINT32 CPlayerBase::GetLeftDragonSkillPoint(TbPlayer* ptbPlayer, TbUser_stat* ptbUserStat) { TUINT32 dwLevel = ptbPlayer->m_nDragon_level; const Json::Value& oJsonExp = CGameInfo::GetInstance()->m_oJsonRoot["game_dragon_exp"]; if(dwLevel >= oJsonExp.size()) { dwLevel = oJsonExp.size() - 1; } TINT32 dwTotalPoint = oJsonExp[dwLevel][1u].asInt(); TINT32 dwUsedPoints = 0; for(TUINT32 udwIdx = 0; udwIdx < EN_SKILL_TYPE__END; ++udwIdx) { dwUsedPoints += ptbUserStat->m_bDragon_skill[0].m_addwLevel[udwIdx]; } return dwTotalPoint > dwUsedPoints ? dwTotalPoint - dwUsedPoints : 0; } TINT32 CPlayerBase::GetLeftDragonSkillPoint( SUserInfo *pstUserInfo ) { TbUser_stat *ptbUserStat = &pstUserInfo->m_tbUserStat; TINT32 dwTotalPoint = pstUserInfo->m_stPlayerBuffList[EN_BUFFER_INFO_INCREACE_DRAGON_SKILL_POINT].m_ddwBuffTotal; TINT32 dwUsedPoints = 0; for(TUINT32 udwIdx = 0; udwIdx < EN_SKILL_TYPE__END; ++udwIdx) { dwUsedPoints += ptbUserStat->m_bDragon_skill[0].m_addwLevel[udwIdx]; } return dwTotalPoint > dwUsedPoints ? dwTotalPoint - dwUsedPoints : 0; } TINT32 CPlayerBase::GetDragonSkillPointLimit(TINT32 dwSkillId) { const Json::Value& oJsonSkill = CGameInfo::GetInstance()->m_oJsonRoot["game_dragon_skill"]; string strSkillId = CCommonFunc::NumToString(dwSkillId); if(oJsonSkill.isMember(strSkillId) == FALSE) { return 0; } return oJsonSkill[strSkillId]["a"]["a0"].asInt(); } TINT32 CPlayerBase::GetLeftDragonMonsterSkillPoint(TbPlayer* ptbPlayer, TbUser_stat* ptbUserStat) { TUINT32 dwLevel = ptbPlayer->m_nDragon_level; const Json::Value& oJsonExp = CGameInfo::GetInstance()->m_oJsonRoot["game_dragon_exp"]; if(dwLevel >= oJsonExp.size()) { dwLevel = oJsonExp.size() - 1; } TINT32 dwTotalPoint = oJsonExp[dwLevel][2u].asInt(); TINT32 dwUsedPoints = 0; for (TUINT32 udwIdx = 0; udwIdx < EN_SKILL_TYPE__END; ++udwIdx) { dwUsedPoints += ptbUserStat->m_bDragon_monster_skill[0].m_addwLevel[udwIdx]; } return dwTotalPoint > dwUsedPoints ? dwTotalPoint - dwUsedPoints : 0; } TINT32 CPlayerBase::GetLeftDragonMonsterSkillPoint( SUserInfo *pstUserInfo ) { TbUser_stat *ptbUserStat = &pstUserInfo->m_tbUserStat; TINT32 dwTotalPoint = pstUserInfo->m_stPlayerBuffList[EN_BUFFER_INFO_INCREACE_MONSTER_SKILL_POINT].m_ddwBuffTotal; TINT32 dwUsedPoints = 0; for (TUINT32 udwIdx = 0; udwIdx < EN_SKILL_TYPE__END; ++udwIdx) { dwUsedPoints += ptbUserStat->m_bDragon_monster_skill[0].m_addwLevel[udwIdx]; } return dwTotalPoint > dwUsedPoints ? dwTotalPoint - dwUsedPoints : 0; } TINT32 CPlayerBase::GetDragonMonsterSkillPointLimit(TINT32 dwSkillId) { const Json::Value& oJsonSkill = CGameInfo::GetInstance()->m_oJsonRoot["game_dragon_skill_monster"]; string strSkillId = CCommonFunc::NumToString(dwSkillId); if(oJsonSkill.isMember(strSkillId) == FALSE) { return 0; } return oJsonSkill[strSkillId]["a"]["a0"].asInt(); } TBOOL CPlayerBase::IsMeetLordSkillReliance(SUserInfo* pstUser, TINT32 dwSkillId, TINT32 dwSKillLevel) { const Json::Value& oJsonSkill = CGameInfo::GetInstance()->m_oJsonRoot["game_lord_skill"]; string strSkillId = CCommonFunc::NumToString(dwSkillId); SSkill* pstSkill = &pstUser->m_tbUserStat.m_bLord_skill[0]; const Json::Value& oJsonSkillReliance = oJsonSkill[strSkillId]["r"]["r1"][dwSKillLevel - 1]; for (TUINT32 udwIdx = 0; udwIdx < oJsonSkillReliance.size(); ++udwIdx) { //可以在此处扩展依赖的类型 TINT32 dwRelySkillId = oJsonSkillReliance[udwIdx][1u].asInt(); TINT32 dwRelySkillLevel = oJsonSkillReliance[udwIdx][2u].asInt(); if (pstSkill->m_addwLevel[dwRelySkillId] < dwRelySkillLevel) { return FALSE; } } return TRUE; } TBOOL CPlayerBase::IsMeetDragonSkillReliance(SUserInfo* pstUser, TINT32 dwSkillId, TINT32 dwSKillLevel) { const Json::Value& oJsonSkill = CGameInfo::GetInstance()->m_oJsonRoot["game_dragon_skill"]; string strSkillId = CCommonFunc::NumToString(dwSkillId); SSkill* pstSkill = &pstUser->m_tbUserStat.m_bDragon_skill[0]; const Json::Value& oJsonSkillReliance = oJsonSkill[strSkillId]["r"]["r1"][dwSKillLevel - 1]; for (TUINT32 udwIdx = 0; udwIdx < oJsonSkillReliance.size(); ++udwIdx) { //可以在此处扩展依赖的类型 TINT32 dwRelySkillId = oJsonSkillReliance[udwIdx][1u].asInt(); TINT32 dwRelySkillLevel = oJsonSkillReliance[udwIdx][2u].asInt(); if (pstSkill->m_addwLevel[dwRelySkillId] < dwRelySkillLevel) { return FALSE; } } return TRUE; } TBOOL CPlayerBase::IsMeetDragonMonsterSkillReliance(SUserInfo* pstUser, TINT32 dwSkillId, TINT32 dwSKillLevel) { const Json::Value& oJsonSkill = CGameInfo::GetInstance()->m_oJsonRoot["game_dragon_skill_monster"]; string strSkillId = CCommonFunc::NumToString(dwSkillId); SSkill* pstSkill = &pstUser->m_tbUserStat.m_bDragon_monster_skill[0]; const Json::Value& oJsonSkillReliance = oJsonSkill[strSkillId]["r"]["r1"][dwSKillLevel - 1]; for (TUINT32 udwIdx = 0; udwIdx < oJsonSkillReliance.size(); ++udwIdx) { //可以在此处扩展依赖的类型 TINT32 dwRelySkillId = oJsonSkillReliance[udwIdx][1u].asInt(); TINT32 dwRelySkillLevel = oJsonSkillReliance[udwIdx][2u].asInt(); if (pstSkill->m_addwLevel[dwRelySkillId] < dwRelySkillLevel) { return FALSE; } } return TRUE; } TINT32 CPlayerBase::AddLoyality(TbPlayer *pstPlayer, TUINT32 udwNum) { if(pstPlayer->m_nAlid != 0 && pstPlayer->m_nAlpos != EN_ALLIANCE_POS__REQUEST) { pstPlayer->Set_Loy_all(udwNum + pstPlayer->Get_Loy_all()); pstPlayer->Set_Loy_cur(udwNum + pstPlayer->Get_Loy_cur()); } return 0; } TINT32 CPlayerBase::CostLoyality(TbPlayer *pstPlayer, TUINT32 udwNum) { pstPlayer->Set_Loy_all(pstPlayer->Get_Loy_all() > udwNum ? pstPlayer->Get_Loy_all() - udwNum : 0); pstPlayer->Set_Loy_cur(pstPlayer->Get_Loy_cur() > udwNum ? pstPlayer->Get_Loy_cur() - udwNum : 0); return 0; } TINT32 CPlayerBase::HasEnoughLoyality(TbPlayer *pstPlayer, TUINT32 udwNum) { if(pstPlayer->Get_Loy_cur() > udwNum) { return TRUE; } return FALSE; } TINT64 CPlayerBase::GetMaxDragonExp(TINT64 ddwMaxLv) { CGameInfo *poGameInfo = CGameInfo::GetInstance(); const Json::Value& oJson = poGameInfo->m_oJsonRoot["game_dragon_exp"]; TUINT32 udwLv = ddwMaxLv; if (oJson.size() == 0) { return 0; } if (udwLv == 0 || udwLv > oJson.size() - 1) { udwLv = oJson.size() - 1; } return oJson[udwLv][0U].asInt64(); } TINT64 CPlayerBase::GetMaxLordExp() { CGameInfo *poGameInfo = CGameInfo::GetInstance(); const Json::Value& oJson = poGameInfo->m_oJsonRoot["game_lord_exp"]; if (oJson.size() > 0) { return oJson[oJson.size() - 1][0U].asInt64(); } return 0; } TUINT32 CPlayerBase::GetDragonExcuteTime(TUINT32 udwLevel) { CGameInfo *pstGameInfo = CGameInfo::GetInstance(); const Json::Value& oJson = pstGameInfo->m_oJsonRoot["game_dragon_exp"]; return oJson[udwLevel][4u].asUInt(); } TUINT32 CPlayerBase::GetAltarBuffTime(TUINT32 udwHerolv) { CGameInfo *pstGameInfo = CGameInfo::GetInstance(); const Json::Value& oJson = pstGameInfo->m_oJsonRoot["game_dragon_exp"]; return oJson[udwHerolv][5u].asUInt(); } TINT32 CPlayerBase::CheckUpdtDragonEnergy(SUserInfo *pstUser) { TINT32 dwRetCode = 1; TbPlayer *ptbPlayer = &pstUser->m_tbPlayer; if(ptbPlayer->m_nHas_dragon == 0) //没有龙时直接返回 { return dwRetCode; } TINT64 ddwMaxEnergy = GetCurDragonMaxEnergy(pstUser); const Json::Value &jDragon = CGameInfo::GetInstance()->m_oJsonRoot["game_dragon"]; if (ptbPlayer->m_nDragon_max_energy == 0) { ptbPlayer->Set_Dragon_max_energy(ddwMaxEnergy); } else if (ptbPlayer->m_nDragon_max_energy != ddwMaxEnergy) { TINT64 ddwCurEnergy = ptbPlayer->m_nDragon_cur_energy; ddwCurEnergy = ceil(ddwCurEnergy * 1.0 / ptbPlayer->m_nDragon_max_energy * ddwMaxEnergy); if (ddwCurEnergy > ddwMaxEnergy) { ddwCurEnergy = ddwMaxEnergy; } ptbPlayer->Set_Dragon_cur_energy(ddwCurEnergy); ptbPlayer->Set_Dragon_max_energy(ddwMaxEnergy); } TINT64 ddwCurTime = CTimeUtils::GetUnixTime(); if (ptbPlayer->m_nDragon_recovery_time != 0 && ddwCurTime > ptbPlayer->m_nDragon_recovery_time) { ptbPlayer->Set_Dragon_cur_energy(ddwMaxEnergy); ptbPlayer->Set_Dragon_recovery_time(0); //ADD NOTIFICATION SNoticInfo stNoticInfo; stNoticInfo.Reset(); stNoticInfo.SetValue(EN_NOTI_ID__HERO_ENERGY_RECOVERED, "", "", 0, 0, 0, 0, 0, "", 0); CMsgBase::SendNotificationPerson(CConfBase::GetString("tbxml_project"), pstUser->m_tbPlayer.m_nSid, pstUser->m_tbPlayer.m_nUid, stNoticInfo); dwRetCode = 0; } if (ptbPlayer->m_nDragon_cur_energy < ddwMaxEnergy && ptbPlayer->m_nDragon_recovery_time == 0) { if (ptbPlayer->m_nDragon_begin_recovery_time + jDragon["a5"].asInt64() < ddwCurTime) { ptbPlayer->Set_Dragon_recovery_count(0); } assert(jDragon["a4"].size()); ptbPlayer->Set_Dragon_recovery_time(CTimeUtils::GetUnixTime() + jDragon["a4"][(TINT32)ptbPlayer->m_nDragon_recovery_count].asInt64()); ptbPlayer->Set_Dragon_recovery_count(ptbPlayer->m_nDragon_recovery_count + 1); if (ptbPlayer->m_nDragon_recovery_count >= jDragon["a4"].size()) { ptbPlayer->m_nDragon_recovery_count = jDragon["a4"].size() - 1; } } return dwRetCode; } TINT32 CPlayerBase::AddLordImage(TbLord_image *ptbLord_image, TUINT32 udwImageId) { Json::Value& jTmp = ptbLord_image->m_jLord_image; for (TUINT32 udwIdx = 0; udwIdx < jTmp.size(); udwIdx++) { if (udwImageId == jTmp[udwIdx]["id"].asUInt()) { return 0; } } Json::Value jImage = Json::Value(Json::objectValue); jImage["id"] = udwImageId; jTmp.append(jImage); ptbLord_image->SetFlag(TbLORD_IMAGE_FIELD_LORD_IMAGE); return 0; } TINT32 CPlayerBase::AddDecoration(TbDecoration *ptbDecoration, TUINT32 udwDecoId, TUINT32 udwItemNum /*=1*/) { Json::Value& jTmp = ptbDecoration->m_jDecoration_list; string strDecoid; ostringstream oss; oss << udwDecoId; strDecoid = oss.str(); if (jTmp.isMember(strDecoid)) { jTmp[strDecoid]["still_have_num"] = jTmp[strDecoid]["still_have_num"].asInt() + udwItemNum; jTmp[strDecoid]["total_num"] = jTmp[strDecoid]["total_num"].asInt() + udwItemNum; } else { //种类数量限制 TUINT32 udwMax = CCommonBase::GetGameBasicVal(EN_GAME_BASIC_DECORATION_UPPER_LIMIT); //TUINT32 udwMax = 3; Json::Value::Members jMember = ptbDecoration->m_jDecoration_list.getMemberNames(); if (jMember.size() + udwItemNum > udwMax) { return EN_RET_CODE__DECORATION_OVREFLOW; } Json::Value jNewDeco = Json::Value(Json::objectValue); jNewDeco["get_time"] = CTimeUtils::GetUnixTime(); jNewDeco["still_have_num"] = udwItemNum; jNewDeco["total_num"] = udwItemNum; jTmp[strDecoid] = jNewDeco; } ptbDecoration->SetFlag(TbDECORATION_FIELD_DECORATION_LIST); return 0; } TINT32 CPlayerBase::SetDecoration(TbDecoration *ptbDecoration, string strDecoId, TUINT32 udwItemNum) { Json::Value jTmp = ptbDecoration->m_jDecoration_list; if (!jTmp.isMember(strDecoId) || jTmp[strDecoId]["total_num"].asUInt() < udwItemNum) { return EN_RET_CODE__REQ_PARAM_ERROR; } jTmp[strDecoId]["still_have_num"] = jTmp[strDecoId]["total_num"].asUInt() - udwItemNum; ptbDecoration->Set_Decoration_list(jTmp); return 0; } TINT32 CPlayerBase::HasEnoughDecoration(TbDecoration *ptbDecoration, TUINT32 udwDecoId, TUINT32 udwNum /*=1*/) { Json::Value& jTmp = ptbDecoration->m_jDecoration_list; string strDecoid; ostringstream oss; oss << udwDecoId; strDecoid = oss.str(); if (!jTmp.isMember(strDecoid)) { return -1; } if (jTmp[strDecoid]["still_have_num"].asInt() < udwNum) { return -2; } return 0; } TINT32 CPlayerBase::CostDecoration(TbDecoration *ptbDecoration, TUINT32 udwDecoId) { Json::Value& jTmp = ptbDecoration->m_jDecoration_list; string strDecoid; ostringstream oss; oss << udwDecoId; strDecoid = oss.str(); if (!jTmp.isMember(strDecoid)) { return -1; } if (jTmp[strDecoid]["still_have_num"].asInt() <= 0) { return -2; } jTmp[strDecoid]["still_have_num"] = jTmp[strDecoid]["still_have_num"].asInt() - 1; ptbDecoration->Set_Decoration_list(jTmp); return 0; } TINT32 CPlayerBase::PickUpDecoration(TbDecoration *ptbDecoration, TUINT32 udwDecoId) { Json::Value& jTmp = ptbDecoration->m_jDecoration_list; string strDecoid; ostringstream oss; oss << udwDecoId; strDecoid = oss.str(); if (!jTmp.isMember(strDecoid)) { return -1; } jTmp[strDecoid]["still_have_num"] = jTmp[strDecoid]["still_have_num"].asInt() + 1; ptbDecoration->Set_Decoration_list(jTmp); return 0; } TINT32 CPlayerBase::AddDragonEnergy(SUserInfo *pstUser, TUINT32 udwNum) { TbPlayer *ptbPlayer = &pstUser->m_tbPlayer; TINT64 ddwMaxEnergy = CPlayerBase::GetCurDragonMaxEnergy(pstUser); TINT64 ddwCurEnergy = ptbPlayer->m_nDragon_cur_energy; ddwCurEnergy += udwNum; if(ddwCurEnergy > ddwMaxEnergy) { ddwCurEnergy = ddwMaxEnergy; } ptbPlayer->Set_Dragon_cur_energy(ddwCurEnergy); return 0; } TINT32 CPlayerBase::AddDragonShard(SUserInfo *pstUser, TUINT32 udwNum) { TbPlayer *ptbPlayer = &pstUser->m_tbPlayer; ptbPlayer->Set_Dragon_shard(ptbPlayer->m_nDragon_shard + udwNum); return 0; } TINT32 CPlayerBase::SetDragonShard(SUserInfo *pstUser, TUINT32 udwNum) { TbPlayer *ptbPlayer = &pstUser->m_tbPlayer; ptbPlayer->Set_Dragon_shard(udwNum); return 0; } TINT32 CPlayerBase::CostDragonShard(SUserInfo *pstUser, TUINT32 udwNum) { TbPlayer *ptbPlayer = &pstUser->m_tbPlayer; if (udwNum == 0) { return 0; } TINT64 ddwDragonShard = ptbPlayer->m_nDragon_shard; if (udwNum > ddwDragonShard) { ptbPlayer->Set_Dragon_shard(0); } else { ptbPlayer->Set_Dragon_shard(ddwDragonShard - udwNum); } return 0; } TBOOL CPlayerBase::HasEnoughDragonShard(SUserInfo *pstUser, TUINT32 udwNum) { TbPlayer *ptbPlayer = &pstUser->m_tbPlayer; if (ptbPlayer->m_nDragon_shard >= udwNum) { return TRUE; } else { return FALSE; } } TVOID CPlayerBase::GetTrialAttackCost(SUserInfo *pstUser, TUINT32 udwAtkNum, TUINT32 &udwItemNum, TUINT32 &udwShardNum) { udwItemNum = 0; udwShardNum = 0; TUINT32 udwItemId = 836; // 免费攻击道具 TUINT32 udwHasItemNum = CItemBase::GetItemNum(&pstUser->m_tbBackpack, udwItemId); TUINT32 udwShardCost = CCommonBase::GetGameBasicVal(EN_GAME_BASIC_TRIAL_NORMAL_DRAGON_SHARD_COST); if (pstUser->m_tbPlayer.m_nTrial_rage_mode == 1) { udwShardCost = CCommonBase::GetGameBasicVal(EN_GAME_BASIC_TRIAL_RAGE_DRAGON_SHARD_COST); } if (udwHasItemNum >= udwAtkNum) { udwItemNum = udwAtkNum; } else { udwItemNum = udwHasItemNum; udwShardNum = (udwAtkNum - udwHasItemNum) * udwShardCost; } } TINT64 CPlayerBase::GetCurDragonMaxEnergy(SUserInfo *pstUser) { TINT64 ddwMaxEnergy = CCommonBase::GetGameBasicVal(EN_GAME_BASIC_HERO_ENERGY_DEFAULT); TFLOAT64 fHeroStaminaLimitRate = pstUser->m_stPlayerBuffList.m_astPlayerBuffInfo[EN_BUFFER_INFO_HERO_STAMINA_LIMIT].m_ddwBuffTotal / 10000.0; ddwMaxEnergy = ceil(ddwMaxEnergy*(1.0 + fHeroStaminaLimitRate)); return ddwMaxEnergy; } TVOID CPlayerBase::CheckAndUpdtKnightInfo( SUserInfo *pstUser ) { TbCity_Knight& knight = pstUser->m_stCityInfo.m_stTblData.m_bKnight; TUINT32 udwNum = pstUser->m_stPlayerBuffList.m_astPlayerBuffInfo[EN_BUFFER_INFO_KNIGHT_NUM].m_ddwBuffTotal; //TUINT32 udwNum = CCityBase::GetBuildingLevelByFuncType(&pstUser->m_stCityInfo, EN_BUILDING_TYPE__KNIGHT_HALL); if(udwNum > knight.m_udwNum) { for(TUINT32 idx = knight.m_udwNum; idx < udwNum; idx++) { knight[idx].Reset(); } knight.m_udwNum = udwNum; pstUser->m_stCityInfo.m_stTblData.SetFlag(TbCITY_FIELD_KNIGHT); } //容错处理 for(TUINT32 idx = 0; idx < knight.m_udwNum; idx++) { if(knight[idx].ddwPos == EN_KNIGHT_POS__UNASSIGN) { if(knight[idx].ddwStatus == EN_KNIGHT_STATUS__ASSIGNING) { knight[idx].ddwStatus = EN_KNIGHT_STATUS__NORMAL; pstUser->m_stCityInfo.m_stTblData.SetFlag(TbCITY_FIELD_KNIGHT); } } if(knight[idx].ddwPos != EN_KNIGHT_POS__UNASSIGN) { if(knight[idx].ddwStatus != EN_KNIGHT_STATUS__ASSIGNING) { knight[idx].ddwStatus = EN_KNIGHT_STATUS__ASSIGNING; pstUser->m_stCityInfo.m_stTblData.SetFlag(TbCITY_FIELD_KNIGHT); } } if(knight[idx].ddwStatus == EN_KNIGHT_STATUS__MARCHING) { if(knight[idx].ddwTid == 0) { knight[idx].ddwStatus = EN_KNIGHT_STATUS__NORMAL; pstUser->m_stCityInfo.m_stTblData.SetFlag(TbCITY_FIELD_KNIGHT); } else { TINT32 dwIndex = CActionBase::GetMarchIndex(pstUser->m_atbMarch, pstUser->m_udwMarchNum, knight[idx].ddwTid); if(dwIndex < 0) { knight[idx].ddwStatus = EN_KNIGHT_STATUS__NORMAL; pstUser->m_stCityInfo.m_stTblData.SetFlag(TbCITY_FIELD_KNIGHT); } } } } } TVOID CPlayerBase::AutoUnassignKnight( SUserInfo *pstUser ) { TINT32 dwUnassignId = -1; TbCity_Knight& knight = pstUser->m_stCityInfo.m_stTblData.m_bKnight; for(TUINT32 idx = 0; idx < knight.m_udwNum; idx++) { if(knight[idx].ddwPos != EN_KNIGHT_POS__UNASSIGN) { knight[idx].ddwStatus = EN_KNIGHT_STATUS__NORMAL; knight[idx].ddwPos = EN_KNIGHT_POS__UNASSIGN; dwUnassignId = idx; pstUser->m_stCityInfo.m_stTblData.SetFlag(TbCITY_FIELD_KNIGHT); } } if(dwUnassignId >= 0) { //ADD NOTIFICATION SNoticInfo stNoticInfo; stNoticInfo.Reset(); stNoticInfo.SetValue(EN_NOTI_ID__KNIGHT_BE_DISMISSED, "", "", 0, 0, 0, 0, 0, "", 0); CMsgBase::SendNotificationPerson(CConfBase::GetString("tbxml_project"), pstUser->m_tbPlayer.m_nSid, pstUser->m_tbPlayer.m_nUid, stNoticInfo); // tips CSendMessageBase::AddTips(pstUser, EN_TIPS_TYPE__KNIGHT_DISMISS, pstUser->m_tbPlayer.m_nUid, FALSE, dwUnassignId, 0, 0, pstUser->m_tbPlayer.m_sUin.c_str()); } } TINT32 CPlayerBase::GetCurPersonGuide( SUserInfo *pstUser ) { // vip道具累计5个以上,三天没有使用 //if(CheckPersonGuideVIP(pstUser, EN_PERSON_GUIDE_VIP)) //{ // return EN_PERSON_GUIDE_VIP; //} // 领主到了8级一直没有分配过技能点 //if(CheckPersonGuidePlayerSkill(pstUser, EN_PERSON_GUIDE_PLAYER_SKILL)) //{ // return EN_PERSON_GUIDE_PLAYER_SKILL; //} // 清除所有树木,TODO:新建建筑没有空间的情况下 //if(CheckPersonGuideBuilding(pstUser, EN_PERSON_GUIDE_BUILDING)) //{ // return EN_PERSON_GUIDE_BUILDING; //} // 当有箱子未开启,指引玩家开箱 if(CheckPersonGuideChest(pstUser, EN_PERSON_GUIDE_CHEST)) { return EN_PERSON_GUIDE_CHEST; } // 玩家还没有加入联盟 if(CheckPersonGuideJoinAlliance(pstUser, EN_PERSON_GUIDE_JOIN_ALLIANCE)) { return EN_PERSON_GUIDE_JOIN_ALLIANCE; } //// 用户开始了一份队列时间大于1小时的任务 //if(CheckPersonGuideNeverUseSpeedItem(pstUser, EN_PERSON_GUIDE_NEVER_USE_SPEED_ITEM)) //{ // return EN_PERSON_GUIDE_NEVER_USE_SPEED_ITEM; //} return 0; } TBOOL CPlayerBase::CheckPersonGuideVIP( SUserInfo *pstUser, TUINT32 udwKey ) { if(BITTEST(pstUser->m_tbPlayer.m_bPerson_guide[0].m_bitGuide, udwKey)) { return FALSE; } TUINT32 udwItemNum = 0; CGameInfo *poGameInfo = CGameInfo::GetInstance(); for(TUINT32 idx = 0; idx < pstUser->m_tbBackpack.m_bItem.m_udwNum; idx++) { TUINT32 udwFuncType = poGameInfo->m_oJsonRoot["game_item"][CCommonFunc::NumToString(pstUser->m_tbBackpack.m_bItem[idx].m_ddwItemId)]["a2"].asUInt(); if(udwFuncType == 10024) { udwItemNum += pstUser->m_tbBackpack.m_bItem[idx].m_ddwItemNum; } } if(udwItemNum > 5) { return TRUE; } return FALSE; } TBOOL CPlayerBase::CheckPersonGuidePlayerSkill(SUserInfo *pstUser, TUINT32 udwKey) { if(BITTEST(pstUser->m_tbPlayer.m_bPerson_guide[0].m_bitGuide, udwKey)) { return FALSE; } TINT32 dwUsedPoints = CPlayerBase::GetUsedLoadSkillPoint(&pstUser->m_tbUserStat); if(pstUser->m_tbPlayer.Get_Level() >= 8 && 0 == dwUsedPoints) { return TRUE; } else { return FALSE; } } TBOOL CPlayerBase::CheckPersonGuideBuilding(SUserInfo *pstUser, TUINT32 udwKey) { if(BITTEST(pstUser->m_tbPlayer.m_bPerson_guide[0].m_bitGuide, udwKey)) { return FALSE; } TBOOL bRetCode = TRUE; SCityBuildingNode *pstBuilding = NULL; //check还有无树木 for(TUINT32 idx = 0; idx < pstUser->m_stCityInfo.m_stTblData.m_bBuilding.m_udwNum; idx++) { pstBuilding = &pstUser->m_stCityInfo.m_stTblData.m_bBuilding[idx]; if(pstBuilding->m_ddwType >= 46 && pstBuilding->m_ddwType <= 58) { bRetCode = FALSE; break; } } //check 有无空间放建筑 //todo return bRetCode; } TBOOL CPlayerBase::CheckPersonGuideChest(SUserInfo *pstUser, TUINT32 udwKey) { if(BITTEST(pstUser->m_tbPlayer.m_bPerson_guide[0].m_bitGuide, udwKey)) { return FALSE; } TUINT32 udwItemNum = 0; CGameInfo *poGameInfo = CGameInfo::GetInstance(); for(TUINT32 idx = 0; idx < pstUser->m_tbBackpack.m_bItem.m_udwNum; idx++) { TUINT32 udwFuncType = poGameInfo->m_oJsonRoot["game_item"][CCommonFunc::NumToString(pstUser->m_tbBackpack.m_bItem[idx].m_ddwItemId)]["a1"].asUInt(); if(udwFuncType == EN_ITEM_CATEGORY__CHEST && pstUser->m_tbBackpack.m_bItem[idx].m_ddwItemId == 403) //chest { udwItemNum += pstUser->m_tbBackpack.m_bItem[idx].m_ddwItemNum; break; } } //有箱子, 且大于等于第三个时代 if(udwItemNum >= 1 && pstUser->m_tbPlayer.m_nAge >= 2) { return TRUE; } return FALSE; } TBOOL CPlayerBase::CheckPersonGuideJoinAlliance(SUserInfo *pstUser, TUINT32 udwKey) { if(BITTEST(pstUser->m_tbPlayer.m_bPerson_guide[0].m_bitGuide, udwKey)) { return FALSE; } //TUINT8 ucCastleLv = CCityBase::GetBuildingLevelByFuncType(&pstUser->m_stCityInfo, EN_BUILDING_TYPE__CASTLE); TUINT8 ucEmbassyLv = CCityBase::GetBuildingLevelByFuncType(&pstUser->m_stCityInfo, EN_BUILDING_TYPE__EMBASSY); if(ucEmbassyLv >= 1 && 0 == pstUser->m_tbLogin.m_nAl_time && 0 == pstUser->m_tbPlayer.m_nAlid && EN_ALLIANCE_POS__REQUEST == pstUser->m_tbPlayer.m_nAlpos) { return TRUE; } return FALSE; } TBOOL CPlayerBase::CheckPersonGuideNeverUseSpeedItem(SUserInfo *pstUser, TUINT32 udwKey) { if(BITTEST(pstUser->m_tbPlayer.m_bPerson_guide[0].m_bitGuide, udwKey)) { return FALSE; } TUINT32 udwSpeedupItem = 11; //15fenzhong jiasu if(CItemBase::GetItemNum(&pstUser->m_tbBackpack, udwSpeedupItem) == 0) { return FALSE; } TBOOL bRetCode = FALSE; TUINT32 idx = 0; const TUINT32 udwTimeThrd = 3600; TUINT32 udwCurTime = CTimeUtils::GetUnixTime(); for(idx = 0; idx < pstUser->m_udwSelfAlActionNum; idx++) { if(pstUser->m_atbSelfAlAction[idx].m_nSuid != pstUser->m_tbPlayer.m_nUid) { continue; } if(pstUser->m_atbSelfAlAction[idx].m_nEtime > udwCurTime + udwTimeThrd) { bRetCode = TRUE; break; } } return bRetCode; } TINT32 CPlayerBase::AddDragon(TbPlayer *ptbPlayer, TINT64 ddwMaxEnergy) { ptbPlayer->Set_Has_dragon(2L); ptbPlayer->Set_Dragon_exp(0); ptbPlayer->Set_Dragon_level(1); ptbPlayer->Set_Dragon_cur_energy(ddwMaxEnergy); ptbPlayer->Set_Dragon_max_energy(ddwMaxEnergy); ptbPlayer->Set_Dragon_recovery_time(0); ptbPlayer->Set_Dragon_recovery_count(0); ptbPlayer->Set_Dragon_begin_recovery_time(0); ptbPlayer->Set_Dragon_tid(0); ptbPlayer->Set_Dragon_status(EN_DRAGON_STATUS_NORMAL); ostringstream oss; TCHAR szUIntToString[MAX_TABLE_NAME_LEN]; //龙名字 oss.str(""); oss << CGameInfo::GetInstance()->m_oJsonRoot["game_init_data"]["r"]["a2"].asString().c_str(); if (ptbPlayer->m_nUid) { CCommonFunc::UIntToString(ptbPlayer->m_nUid, szUIntToString); oss << szUIntToString; } ptbPlayer->Set_Dragon_name(oss.str()); //龙头像 TUINT32 udwDragonUi = 0; TUINT32 udwDragonUiSize = CGameInfo::GetInstance()->m_oJsonRoot["game_init_data"]["r"]["a4"].size(); if (udwDragonUiSize != 0) { udwDragonUi = rand() % udwDragonUiSize; } ptbPlayer->Set_Dragon_avatar(udwDragonUi); return 0; } TBOOL CPlayerBase::CheckDeadPlayerBaseCondForClear( SUserInfo *pstUser ) { TbPlayer *ptbPlayer = &pstUser->m_tbPlayer; SCityInfo *pstCity = &pstUser->m_stCityInfo; TUINT32 udwCurTime = CTimeUtils::GetUnixTime(); if(ptbPlayer->m_nDead_flag > 0) { return FALSE; } //if((ptbPlayer->m_nStatus & EN_CITY_STATUS__NEW_PROTECTION) || (ptbPlayer->m_nStatus & EN_CITY_STATUS__AVOID_WAR)) if(ptbPlayer->m_nStatus & EN_CITY_STATUS__AVOID_WAR) { return FALSE; } TUINT32 udwCastleLevel = CCityBase::GetBuildingLevelByFuncType(pstCity, EN_BUILDING_TYPE__CASTLE); TBOOL bDeadTime = FALSE; if(udwCastleLevel <= 2) { if(udwCurTime - ptbPlayer->m_nUtime > 8 * 3600) { bDeadTime = TRUE; } } else if(udwCastleLevel <= 4) { if(udwCurTime - ptbPlayer->m_nUtime > 24 * 3600) { bDeadTime = TRUE; } } else if(udwCastleLevel <= 7) { if(udwCurTime - ptbPlayer->m_nUtime > 36 * 3600) { bDeadTime = TRUE; } } else if(udwCastleLevel <= 13) { if(udwCurTime - ptbPlayer->m_nUtime > 96 * 3600) { bDeadTime = TRUE; } } else { if(udwCurTime - ptbPlayer->m_nUtime > 192 * 3600) { bDeadTime = TRUE; } } if(bDeadTime == FALSE) { return FALSE; } return TRUE; } TUINT32 CPlayerBase::GetAllianceId( TbPlayer *ptbPlayer ) { TUINT32 udwAlId = 0; if(ptbPlayer->m_nUid && ptbPlayer->m_nAlpos && ptbPlayer->m_nAlid) { udwAlId = ptbPlayer->m_nAlid / PLAYER_ALLIANCE_ID_OFFSET; } return udwAlId; }
[ "jyqiu1216@163.com" ]
jyqiu1216@163.com
728b552e70e7cc0688a2acd01b7142dbb749850a
9cb7aa24936d5b22941808b28745833107497cad
/week11/communication/communication.ino
df195458144292ac58d4b9cfdf60ade8fb0b4f49
[]
no_license
CluckeyMcCormick/Comp469-RoboBrain
00b994437c729ef644b5df8688c5c181b01b0096
4f28bc86c7e8bbf0181bbcb616ca2967566c10b2
refs/heads/master
2021-05-15T12:25:16.627005
2017-12-12T18:05:34
2017-12-12T18:05:34
108,441,859
0
0
null
null
null
null
UTF-8
C++
false
false
3,336
ino
/* Encoder Test for Robo-team 1 * Nicolas Fredrickson * Steven Coronel * November 16th, 2017 */ // we can achieve a 90 degree turn via 450/1088 turns //The sample code for driving one way motor encoder const byte encoder0pinA = 2;//2;//A pin -> the interrupt pin 2 const byte encoder0pinB = 3;//3;//B pin -> the digital pin 3 const byte encoder1pinA = 18;//18;//A pin -> the interrupt pin 18 const byte encoder1pinB = 19;//19;//B pin -> the digital pin 19 byte encoder0PinALast; int duration0;//the number of the pulses boolean Direction0;//the rotation Direction0 byte encoder1PinALast; int duration1;//the number of the pulses boolean Direction1;//the rotation Direction0 int loops; #include <Servo.h> //#define ROTATION 663 // According to manual //#define ROTATION 398 // According to tests? #define ROTATION 1326 //1326????? // .413603 #define ROTATIONS_PER_90_DEGREES 450/1088 #define CIRC 136 * PI // .322051 #define PIP_DIST (CIRC) / ROTATION #define PRINT_EVERY 5000//25 #define ENC_0_NEG_SLOW 90 #define ENC_0_NEG_FAST 180//180 #define ENC_0_POS_SLOW 80 #define ENC_0_POS_FAST 0//0 #define FORWARD_BYTECODE 'f' #define BACKWARD_BYTECODE 'b' #define STOP_BYTECODE 's' Servo ST0, ST1; char gotByt; void setup() { Serial.begin(9600);//Initialize the serial port EncoderInit();//Initialize the module ST0.attach( 9, 1000, 2000); ST1.attach(10, 1000, 2000); loops = 0; ST0.write(85); ST1.write(85); delay(10); } void loop() { if (Serial.available() > 0) { gotByt = Serial.read(); if(gotByt == FORWARD_BYTECODE){ Serial.println("FORWARD MOTION!"); forward(); } else if(gotByt == BACKWARD_BYTECODE){ Serial.println("BACKWARD MOTION!"); backward(); } else if(gotByt == STOP_BYTECODE){ Serial.println("NO MOTION!"); stopAll(); } else if(gotByt != -1){ Serial.print("Invalid bytecode: "); Serial.println( gotByt ); } } } void backward(){ ST0.write(65); ST1.write(65); delay(10); } void forward(){ ST0.write(105); ST1.write(105); delay(10); } void stopAll(){ ST0.write(85); ST1.write(85); delay(10); } void EncoderInit() { Direction0 = true;//default -> Forward Direction1 = true;//default -> Forward pinMode(encoder0pinB,INPUT); pinMode(encoder1pinB,INPUT); attachInterrupt(digitalPinToInterrupt(encoder0pinA), wheelSpeed0, CHANGE); attachInterrupt(digitalPinToInterrupt(encoder1pinA), wheelSpeed1, CHANGE); } void wheelSpeed0() { int Lstate0 = digitalRead(encoder0pinA); if((encoder0PinALast == LOW) && Lstate0==HIGH) { int val0 = digitalRead(encoder0pinB); if(val0 == LOW && Direction0) Direction0 = false; //Reverse else if(val0 == HIGH && !Direction0) Direction0 = true; //Forward } encoder0PinALast = Lstate0; if(!Direction0) duration0++; else duration0--; } void wheelSpeed1() { int Lstate1 = digitalRead(encoder1pinA); if((encoder1PinALast == LOW) && Lstate1==HIGH) { int val1 = digitalRead(encoder1pinB); if(val1 == LOW && Direction1) Direction1 = false; //Reverse else if(val1 == HIGH && !Direction1) Direction1 = true; //Forward } encoder1PinALast = Lstate1; if(!Direction1) duration1++; else duration1--; }
[ "fredricksonnicolas@gmail.com" ]
fredricksonnicolas@gmail.com
da083fdb23e6f13f5effcddc3fe2c61488b04cdd
0cb85cd0c88a9b9f0cca4472742c2bf9febef2d8
/Windows/Hook/TestProjects/MBRLog/MBRLog.cpp
4179b247d05b8455b1e22e53a987717d432fa26b
[]
no_license
seth1002/antivirus-1
9dfbadc68e16e51f141ac8b3bb283c1d25792572
3752a3b20e1a8390f0889f6192ee6b851e99e8a4
refs/heads/master
2020-07-15T00:30:19.131934
2016-07-21T13:59:11
2016-07-21T13:59:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
356
cpp
// MBRLog.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "jobs.h" int main(int argc, char* argv[]) { Job_Process m_JobProcesses; m_JobProcesses.Start(); m_JobProcesses.ChangeActiveStatus(true); SuspendThread(GetCurrentThread()); m_JobProcesses.ChangeActiveStatus(false); return 0; }
[ "idrez.mochamad@gmail.com" ]
idrez.mochamad@gmail.com
9e7b90d48ba6b4bf8c18eb513e06a3b6653bf93a
1bb6a0b3692b5468f7d148788298320ac3ba2a23
/Real_Contests/ACPC_2021/o_pizza.cpp
af549969ce61be53bab36edf1b09aac3af3d5e2c
[]
no_license
ablondal/comp-prog
ee6ea5c0b32d7fbe0321a4b9919a9cec23fe85f6
725e369476993307874f9f5d6e2e7299918251a0
refs/heads/master
2022-10-08T05:40:39.206721
2022-09-25T22:29:49
2022-09-25T22:29:49
243,620,860
0
0
null
null
null
null
UTF-8
C++
false
false
989
cpp
#include <bits/stdc++.h> using namespace std; // incomplete #define rep(i, a, b) for(int i = a; i < (b); ++i) #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<ll> vll; const double PI = acos(-1); double alph, bet, N; double ab; // Area from 0 to ang double arrr(double ang){ double aa = 0.5 * bet * bet * ang; aa += 0.25 * bet * (ab / PI) * ang * ang; aa += ((ab*ab)/(24*PI*PI))*ang*ang*ang; return aa; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> alph >> bet >> N; alph = alph + bet; ab = alph - bet; double tota = arrr(2*PI); rep(i,1,(int)N){ double ii = i; double lo = 0, hi = 2*PI; while(hi-lo > 1e-9){ double md = (hi+lo)/2; if (arrr(md) <= tota * (ii/N)) { lo = md; } else { hi = md; } // cout << md << " " << area(md) << endl; } cout << setprecision(15) << lo << endl; } // cout << area(2*PI) << endl; }
[ "ari.blondal@gmail.com" ]
ari.blondal@gmail.com
19c1c302a0de1bc9df33ab0302d2ebd32e30aaca
accd5545df6c1fe34da58b9aef97e7329c55f9c5
/吉田学園情報ビジネス専門学校_増澤 未来/01_electro/02_開発環境/01_game/Electro/7.7/spawneffect.h
fd0ab483cc5d4c655cc5163e8b743bfae4de7e5f
[]
no_license
miraika4400/MiraiMasuzawa
41fff5ce74c285f230f390bd355530f139dff949
4473fc3821a244f9b7270410b178cbad59e3d185
refs/heads/master
2023-03-12T01:09:30.264778
2021-02-27T20:56:45
2021-02-27T20:56:45
305,336,083
0
1
null
2020-10-22T01:04:47
2020-10-19T09:47:08
C++
SHIFT_JIS
C++
false
false
1,695
h
//============================================================================= // // enemyヘッダ [enemy.h] // Author : 増澤 未来 // //============================================================================= //二重インクルード防止 #ifndef _ENEMYSPAWN_H_ #define _ENEMYSPAWN_H_ //***************************** // インクルード //***************************** #include "main.h" #include "scene3d.h" #include "enemy.h" //***************************** // 前方宣言 //***************************** class CParticle; //***************************** // マクロ定義 //***************************** #define ENEMYSPAWN_PARTICLE_NUM 6 // 一回のスポーンで使うパーティクル数 //***************************** // クラス定義 //***************************** // エネミースポーン演出のクラス class CEnemySpawn : public CScene { public: //============ // メンバ関数 //============ CEnemySpawn(); ~CEnemySpawn(); static CEnemySpawn *Create(const D3DXVECTOR3 pos, const CEnemy::ENEMYTYPE type); // クラス生成 HRESULT Init(void); // 初期化 void Uninit(void); // 終了 void Update(void); // 更新 void Draw(void); // 描画 private: //============ // メンバ変数 //============ D3DXVECTOR3 m_pos; // 座標 CParticle*m_pParticle[ENEMYSPAWN_PARTICLE_NUM]; // パーティクルのポインタ CEnemy::ENEMYTYPE m_enemyType; // エネミータイプ int m_nCntFrame; // フレームカウント用 D3DXCOLOR m_col; // 色 }; #endif
[ "mirai4400@yahoo.co.jp" ]
mirai4400@yahoo.co.jp
a9c21f1b783147450c5ea00c0da569c2979c7442
bca2526232680c443f244bc66a59a0b3db971d4f
/main.cpp
68a20b4752dd24e4370858215db1be0eb15b4776
[ "MIT" ]
permissive
rushup/kitra520-linux-iap
071a07a48c036fa7ff59d450b40db6b3dcd7c3b0
bc563a658f6043926334a440771f0c0ef7249fbe
refs/heads/master
2021-01-12T07:27:39.154853
2017-01-11T07:37:13
2017-01-11T07:37:13
76,964,063
1
0
null
null
null
null
UTF-8
C++
false
false
6,578
cpp
#include <stdint.h> #include <stdio.h> #include <iostream> #include <fstream> #include <time.h> #include "serial.h" #include "kitra_input.h" #include "kitra_output.h" using namespace std; #define KITRA_LINUX_IAP_VER 2 serial k_serial; char* buffer; int buffer_index = 0; int size; bool wait_version = false; void loop_boot(); int main (int argc, char **argv) { ifstream in_file; if(argc < 2) { printf("Missing params\n"); printf("Ex: /dev/tty0 fw.bin\n"); return -1; } printf("Kitra firmwre upgrade V%d \n",KITRA_LINUX_IAP_VER); printf("Opening %s\n",argv[1]); if(k_serial.serialOpen(argv[1],115200) != -1) { printf("Serial found\n"); if(argc == 3) { printf("Reading %s\n",argv[2]); in_file.open(argv[2],ios::binary); in_file.seekg(0,ios::end); size = in_file.tellg(); in_file.seekg(0); if(size > 0) { buffer = new char[size]; in_file.read(buffer,size); in_file.close(); loop_boot(); } else printf("File not found"); } else { printf("No file specified \n"); buffer = NULL; loop_boot(); } } else printf("Serial error\n"); /**/ return 0; } void k_output_iap_whoiam_handler(t_cmd_holder* cmd) { k_input_iap_start k_obj; k_obj.id = K_INPUT_IAP_START; k_obj.size = size; buffer_index = 0; k_serial.serialPuts(k_send_packet(&k_obj,0)); printf("Device found \n"); printf("Clearing flash\n"); } void k_output_iap_ack_handler(t_cmd_holder* cmd, bool nack) { char packet[2048]; char chks[10]; int psize = 0; static int last_size = 0; if(nack && buffer_index > 1024) buffer_index -= last_size; if((size - buffer_index) >= 1024) { psize = 1024; } else psize = size - buffer_index; if(psize > 0) { sprintf(packet,"$KITRA,%d,%d,",K_INPUT_IAP_NEW_PACKET,psize); int presize = strlen(packet); memcpy(packet + strlen(packet), buffer + buffer_index,psize); buffer_index += psize; last_size = psize; k_get_checksum(packet + 1,presize + psize - 1,chks); psize = presize + psize; packet[psize++] = '*'; packet[psize++] = chks[0]; packet[psize++] = chks[1]; packet[psize++] = '\r'; packet[psize++] = '\n'; packet[psize] = 0; for(int i=0;i<psize;i++) k_serial.serialPutchar(packet[i]); } printf("\rProgress %d%%",((buffer_index * 100)/size)); fflush( stdout ); } void k_output_iap_nack_handler(t_cmd_holder* cmd) { k_output_iap_ack_handler(cmd,1); } void k_output_iap_new_end_handler(t_cmd_holder* cmd) { printf("\nUpdate done\n"); printf("Reboot the system and kitra\n"); exit(0); } void ask_switch_app() { int c; printf("Kitra is in bootloader mode, switch to application (system will be rebooted) ? (y/n) \n"); while(1) { c = getchar(); if(c == 'y') { k_input_iap_boot k_obj_res; k_obj_res.id = K_INPUT_IAP_BOOT; char* ptr = k_send_packet(&k_obj_res,0); k_serial.serialPrintf(ptr); printf("\n Rebooting system..."); system("shutdown now"); exit(-1); } else exit(0); } } void k_output_get_firmware_response_handler(t_cmd_holder* cmd) { int c; k_output_get_fw_response* k_obj = (k_output_get_fw_response*)cmd->obj; printf("Kitra HW_%d FW_%d EXTRA_%d \n",k_obj->hw_version,k_obj->fw_version,k_obj->extra); if(k_obj->extra != 0xFFFF) { wait_version = true; printf("Do you want to switch to bootloader mode (Will reboot system) ? (y/n): "); while(1) { c = getchar(); if( c == 'y') { k_input_start_fw_upgrade k_obj_res; k_obj_res.id = K_INPUT_START_FW_UPGRADE; char* ptr = k_send_packet(&k_obj_res,0); k_serial.serialPrintf(ptr); printf("\n Rebooting system..."); system("shutdown now"); exit(-1); } else exit(0); } } else if(buffer == NULL) { ask_switch_app(); } } void loop_boot() { /* If the device answers to the GET FIRMWARE request it is in application mode * if it doesn't it is in bootloader mode */ clock_t start, end; char* ptr; k_input_get_firmware k_obj_get_fw; k_obj_get_fw.id = K_INPUT_GET_FIRMWARE; ptr = k_send_packet(&k_obj_get_fw,0); k_serial.serialPrintf(ptr); start = clock(); while(1) { t_cmd_holder* cmd; cmd = k_get_last_cmd(); if(cmd != 0) { uint32_t id = ((k_input_iap_whoiam*) cmd->obj)->id; //just get id switch(id) { case K_OUTPUT_IAP_WHOIAM: k_output_iap_whoiam_handler(cmd); break; case K_OUTPUT_IAP_ACK: k_output_iap_ack_handler(cmd,0); break; case K_OUTPUT_IAP_NACK: k_output_iap_nack_handler(cmd); break; case K_OUTPUT_IAP_END: k_output_iap_new_end_handler(cmd); break; case K_OUTPUT_GET_FW_RESPONSE: printf("Got version\n"); k_output_get_firmware_response_handler(cmd); break; } } end = clock(); if(wait_version == false && ((end - start)/CLOCKS_PER_SEC) > 2) { wait_version = true; if(buffer == NULL) { printf("We are in boot mode, no file specified \n"); ask_switch_app(); exit(0); } k_input_iap_whoiam k_obj_whoiam; k_obj_whoiam.id = K_INPUT_IAP_WHOIAM; ptr = k_send_packet(&k_obj_whoiam,0); k_serial.serialPrintf(ptr); } int n = k_serial.serialDataAvail(); for(int i=0; i<n;i++) { int ris = k_serial.serialGetchar(); if(ris >= 0 && ris <= 127) { k_process_input((char) ris); } } } }
[ "matteofumagalli1275@gmail.com" ]
matteofumagalli1275@gmail.com
d28cfd20202cc0e7fca2e17190a6c9ac9ef0376f
c0caed81b5b3e1498cbca4c1627513c456908e38
/src/protocols/qsar/scoring_grid/HbaGrid.fwd.hh
48025b4251639d13e2c6459ff434df43a0dde830
[]
no_license
malaifa/source
5b34ac0a4e7777265b291fc824da8837ecc3ee84
fc0af245885de0fb82e0a1144422796a6674aeae
refs/heads/master
2021-01-19T22:10:22.942155
2017-04-19T14:13:07
2017-04-19T14:13:07
88,761,668
0
2
null
null
null
null
UTF-8
C++
false
false
883
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu. /// @file src/protocols/ligand_docking/scoring_grid/HbaGrid.fwd.hh /// @author Sam DeLuca #ifndef INCLUDED_protocols_qsar_scoring_grid_HbaGrid_fwd_hh #define INCLUDED_protocols_qsar_scoring_grid_HbaGrid_fwd_hh namespace protocols { namespace qsar { namespace scoring_grid { class HbaGrid; } } } #endif /* HBAGRID_FWD_HH_ */
[ "malaifa@yahoo.com" ]
malaifa@yahoo.com
f5c708f17d3cba79f88f434d7be865497d8910fd
05ace75fffe21a2d375e3611571f1a815d3c0fbc
/4.0.6/Core/src/server/shared/Utilities/Util.h
43f28f5e4ae742866555c7071564e2f8f7f1ac25
[]
no_license
DeKaDeNcE/Project-WoW
97fcf9b505f2cd87e2fb17b27d92d960cdc12668
9307425445316cc4e88c73e116d4ea4d440d5ac2
refs/heads/master
2021-05-27T09:11:53.994059
2014-02-20T06:29:42
2014-02-20T06:29:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,497
h
/* * Copyright (C) 2005-2011 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008-2011 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010-2011 Project SkyFire <http://www.projectskyfire.org/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _UTIL_H #define _UTIL_H #include "Common.h" #include <string> #include <vector> // Searcher for map of structs template<typename T, class S> struct Finder { T val_; T S::* idMember_; Finder(T val, T S::* idMember) : val_(val), idMember_(idMember) {} bool operator()(const std::pair<int, S> &obj) { return obj.second.*idMember_ == val_; } }; struct Tokens: public std::vector<char*> { Tokens(const std::string &src, const char sep, uint32 vectorReserve = 0); ~Tokens() { delete[] m_str; } char* m_str; }; void stripLineInvisibleChars(std::string &src); std::string secsToTimeString(uint64 timeInSecs, bool shortText = false, bool hoursOnly = false); uint32 TimeStringToSecs(const std::string& timestring); std::string TimeToTimestampStr(time_t t); inline uint32 secsToTimeBitFields(time_t secs) { tm* lt = localtime(&secs); return (lt->tm_year - 100) << 24 | lt->tm_mon << 20 | (lt->tm_mday - 1) << 14 | lt->tm_wday << 11 | lt->tm_hour << 6 | lt->tm_min; } /* Return a random number in the range min..max; (max-min) must be smaller than 32768. */ int32 irand(int32 min, int32 max); /* Return a random number in the range min..max (inclusive). For reliable results, the difference * between max and min should be less than RAND32_MAX. */ uint32 urand(uint32 min, uint32 max); /* Return a random number in the range 0 .. RAND32_MAX. */ int32 rand32(); /* Return a random double from 0.0 to 1.0 (exclusive). Floats support only 7 valid decimal digits. * A double supports up to 15 valid decimal digits and is used internally (RAND32_MAX has 10 digits). * With an FPU, there is usually no difference in performance between float and double. */ double rand_norm(void); /* Return a random double from 0.0 to 99.9999999999999. Floats support only 7 valid decimal digits. * A double supports up to 15 valid decimal digits and is used internaly (RAND32_MAX has 10 digits). * With an FPU, there is usually no difference in performance between float and double. */ double rand_chance(void); /* Return true if a random roll fits in the specified chance (range 0-100). */ inline bool roll_chance_f(float chance) { return chance > rand_chance(); } /* Return true if a random roll fits in the specified chance (range 0-100). */ inline bool roll_chance_i(int chance) { return chance > irand(0, 99); } inline void ApplyModUInt32Var(uint32& var, int32 val, bool apply) { int32 cur = var; cur += (apply ? val : -val); if (cur < 0) cur = 0; var = cur; } inline void ApplyModFloatVar(float& var, float val, bool apply) { var += (apply ? val : -val); if (var < 0) var = 0; } inline void ApplyPercentModFloatVar(float& var, float val, bool apply) { if (val == -100.0f) // prevent set var to zero val = -99.99f; var *= (apply ? (100.0f + val) / 100.0f : 100.0f / (100.0f + val)); } // Percentage calculation template <class T> inline T CalculatePctF(T base, float pct) { return T(base * pct / 100.0f); } template <class T> inline T CalculatePctN(T base, int32 pct) { return T(base * float(pct) / 100.0f); } template <class T> inline T CalculatePctU(T base, uint32 pct) { return T(base * float(pct) / 100.0f); } template <class T> inline T AddPctF(T& base, float pct) { return base += CalculatePctF(base, pct); } template <class T> inline T AddPctN(T& base, int32 pct) { return base += CalculatePctN(base, pct); } template <class T> inline T AddPctU(T& base, uint32 pct) { return base += CalculatePctU(base, pct); } template <class T> inline T ApplyPctF(T& base, float pct) { return base = CalculatePctF(base, pct); } template <class T> inline T ApplyPctN(T& base, int32 pct) { return base = CalculatePctN(base, pct); } template <class T> inline T ApplyPctU(T& base, uint32 pct) { return base = CalculatePctU(base, pct); } template <class T> inline T RoundToInterval(T& num, T floor, T ceil) { return num = std::min(std::max(num, floor), ceil); } // UTF8 handling bool Utf8toWStr(const std::string& utf8str, std::wstring& wstr); // in wsize==max size of buffer, out wsize==real string size bool Utf8toWStr(char const* utf8str, size_t csize, wchar_t* wstr, size_t& wsize); inline bool Utf8toWStr(const std::string& utf8str, wchar_t* wstr, size_t& wsize) { return Utf8toWStr(utf8str.c_str(), utf8str.size(), wstr, wsize); } bool WStrToUtf8(std::wstring wstr, std::string& utf8str); // size==real string size bool WStrToUtf8(wchar_t* wstr, size_t size, std::string& utf8str); size_t utf8length(std::string& utf8str); // set string to "" if invalid utf8 sequence void utf8truncate(std::string& utf8str, size_t len); inline bool isBasicLatinCharacter(wchar_t wchar) { if (wchar >= L'a' && wchar <= L'z') // LATIN SMALL LETTER A - LATIN SMALL LETTER Z return true; if (wchar >= L'A' && wchar <= L'Z') // LATIN CAPITAL LETTER A - LATIN CAPITAL LETTER Z return true; return false; } inline bool isExtendedLatinCharacter(wchar_t wchar) { if (isBasicLatinCharacter(wchar)) return true; if (wchar >= 0x00C0 && wchar <= 0x00D6) // LATIN CAPITAL LETTER A WITH GRAVE - LATIN CAPITAL LETTER O WITH DIAERESIS return true; if (wchar >= 0x00D8 && wchar <= 0x00DF) // LATIN CAPITAL LETTER O WITH STROKE - LATIN CAPITAL LETTER THORN return true; if (wchar == 0x00DF) // LATIN SMALL LETTER SHARP S return true; if (wchar >= 0x00E0 && wchar <= 0x00F6) // LATIN SMALL LETTER A WITH GRAVE - LATIN SMALL LETTER O WITH DIAERESIS return true; if (wchar >= 0x00F8 && wchar <= 0x00FE) // LATIN SMALL LETTER O WITH STROKE - LATIN SMALL LETTER THORN return true; if (wchar >= 0x0100 && wchar <= 0x012F) // LATIN CAPITAL LETTER A WITH MACRON - LATIN SMALL LETTER I WITH OGONEK return true; if (wchar == 0x1E9E) // LATIN CAPITAL LETTER SHARP S return true; return false; } inline bool isCyrillicCharacter(wchar_t wchar) { if (wchar >= 0x0410 && wchar <= 0x044F) // CYRILLIC CAPITAL LETTER A - CYRILLIC SMALL LETTER YA return true; if (wchar == 0x0401 || wchar == 0x0451) // CYRILLIC CAPITAL LETTER IO, CYRILLIC SMALL LETTER IO return true; return false; } inline bool isEastAsianCharacter(wchar_t wchar) { if (wchar >= 0x1100 && wchar <= 0x11F9) // Hangul Jamo return true; if (wchar >= 0x3041 && wchar <= 0x30FF) // Hiragana + Katakana return true; if (wchar >= 0x3131 && wchar <= 0x318E) // Hangul Compatibility Jamo return true; if (wchar >= 0x31F0 && wchar <= 0x31FF) // Katakana Phonetic Ext. return true; if (wchar >= 0x3400 && wchar <= 0x4DB5) // CJK Ideographs Ext. A return true; if (wchar >= 0x4E00 && wchar <= 0x9FC3) // Unified CJK Ideographs return true; if (wchar >= 0xAC00 && wchar <= 0xD7A3) // Hangul Syllables return true; if (wchar >= 0xFF01 && wchar <= 0xFFEE) // Halfwidth forms return true; return false; } inline bool isNumeric(wchar_t wchar) { return (wchar >= L'0' && wchar <=L'9'); } inline bool isNumeric(char c) { return (c >= '0' && c <='9'); } inline bool isNumeric(char const* str) { for (char const* c = str; *c; ++c) if (!isNumeric(*c)) return false; return true; } inline bool isNumericOrSpace(wchar_t wchar) { return isNumeric(wchar) || wchar == L' '; } inline bool isBasicLatinString(std::wstring wstr, bool numericOrSpace) { for (size_t i = 0; i < wstr.size(); ++i) if (!isBasicLatinCharacter(wstr[i]) && (!numericOrSpace || !isNumericOrSpace(wstr[i]))) return false; return true; } inline bool isExtendedLatinString(std::wstring wstr, bool numericOrSpace) { for (size_t i = 0; i < wstr.size(); ++i) if (!isExtendedLatinCharacter(wstr[i]) && (!numericOrSpace || !isNumericOrSpace(wstr[i]))) return false; return true; } inline bool isCyrillicString(std::wstring wstr, bool numericOrSpace) { for (size_t i = 0; i < wstr.size(); ++i) if (!isCyrillicCharacter(wstr[i]) && (!numericOrSpace || !isNumericOrSpace(wstr[i]))) return false; return true; } inline bool isEastAsianString(std::wstring wstr, bool numericOrSpace) { for (size_t i = 0; i < wstr.size(); ++i) if (!isEastAsianCharacter(wstr[i]) && (!numericOrSpace || !isNumericOrSpace(wstr[i]))) return false; return true; } inline wchar_t wcharToUpper(wchar_t wchar) { if (wchar >= L'a' && wchar <= L'z') // LATIN SMALL LETTER A - LATIN SMALL LETTER Z return wchar_t(uint16(wchar)-0x0020); if (wchar == 0x00DF) // LATIN SMALL LETTER SHARP S return wchar_t(0x1E9E); if (wchar >= 0x00E0 && wchar <= 0x00F6) // LATIN SMALL LETTER A WITH GRAVE - LATIN SMALL LETTER O WITH DIAERESIS return wchar_t(uint16(wchar)-0x0020); if (wchar >= 0x00F8 && wchar <= 0x00FE) // LATIN SMALL LETTER O WITH STROKE - LATIN SMALL LETTER THORN return wchar_t(uint16(wchar)-0x0020); if (wchar >= 0x0101 && wchar <= 0x012F) // LATIN SMALL LETTER A WITH MACRON - LATIN SMALL LETTER I WITH OGONEK (only %2=1) { if (wchar % 2 == 1) return wchar_t(uint16(wchar)-0x0001); } if (wchar >= 0x0430 && wchar <= 0x044F) // CYRILLIC SMALL LETTER A - CYRILLIC SMALL LETTER YA return wchar_t(uint16(wchar)-0x0020); if (wchar == 0x0451) // CYRILLIC SMALL LETTER IO return wchar_t(0x0401); return wchar; } inline wchar_t wcharToUpperOnlyLatin(wchar_t wchar) { return isBasicLatinCharacter(wchar) ? wcharToUpper(wchar) : wchar; } inline wchar_t wcharToLower(wchar_t wchar) { if (wchar >= L'A' && wchar <= L'Z') // LATIN CAPITAL LETTER A - LATIN CAPITAL LETTER Z return wchar_t(uint16(wchar)+0x0020); if (wchar >= 0x00C0 && wchar <= 0x00D6) // LATIN CAPITAL LETTER A WITH GRAVE - LATIN CAPITAL LETTER O WITH DIAERESIS return wchar_t(uint16(wchar)+0x0020); if (wchar >= 0x00D8 && wchar <= 0x00DE) // LATIN CAPITAL LETTER O WITH STROKE - LATIN CAPITAL LETTER THORN return wchar_t(uint16(wchar)+0x0020); if (wchar >= 0x0100 && wchar <= 0x012E) // LATIN CAPITAL LETTER A WITH MACRON - LATIN CAPITAL LETTER I WITH OGONEK (only %2=0) { if (wchar % 2 == 0) return wchar_t(uint16(wchar)+0x0001); } if (wchar == 0x1E9E) // LATIN CAPITAL LETTER SHARP S return wchar_t(0x00DF); if (wchar == 0x0401) // CYRILLIC CAPITAL LETTER IO return wchar_t(0x0451); if (wchar >= 0x0410 && wchar <= 0x042F) // CYRILLIC CAPITAL LETTER A - CYRILLIC CAPITAL LETTER YA return wchar_t(uint16(wchar)+0x0020); return wchar; } inline void wstrToUpper(std::wstring& str) { std::transform( str.begin(), str.end(), str.begin(), wcharToUpper ); } inline void wstrToLower(std::wstring& str) { std::transform( str.begin(), str.end(), str.begin(), wcharToLower ); } std::wstring GetMainPartOfName(std::wstring wname, uint32 declension); bool utf8ToConsole(const std::string& utf8str, std::string& conStr); bool consoleToUtf8(const std::string& conStr, std::string& utf8str); bool Utf8FitTo(const std::string& str, std::wstring search); void utf8printf(FILE *out, const char *str, ...); void vutf8printf(FILE *out, const char *str, va_list* ap); bool IsIPAddress(char const* ipaddress); uint32 CreatePIDFile(const std::string& filename); void hexEncodeByteArray(uint8* bytes, uint32 arrayLen, std::string& result); #endif //handler for operations on large flags #ifndef _FLAG96 #define _FLAG96 #ifndef PAIR64_HIPART #define PAIR64_HIPART(x) (uint32)((uint64(x) >> 32) & UI64LIT(0x00000000FFFFFFFF)) #define PAIR64_LOPART(x) (uint32)(uint64(x) & UI64LIT(0x00000000FFFFFFFF)) #endif // simple class for not-modifyable list template <typename T> class HookList { typedef typename std::list<T>::iterator ListIterator; private: typename std::list<T> m_list; public: HookList<T> & operator+=(T t) { m_list.push_back(t); return *this; } HookList<T> & operator-=(T t) { m_list.remove(t); return *this; } size_t size() { return m_list.size(); } ListIterator begin() { return m_list.begin(); } ListIterator end() { return m_list.end(); } }; class flag96 { private: uint32 part[3]; public: flag96(uint32 p1=0, uint32 p2=0, uint32 p3=0) { part[0]=p1; part[1]=p2; part[2]=p3; } flag96(uint64 p1, uint32 p2) { part[0]=PAIR64_LOPART(p1); part[1]=PAIR64_HIPART(p1); part[2]=p2; } inline bool IsEqual(uint32 p1=0, uint32 p2=0, uint32 p3=0) const { return ( part[0]==p1 && part[1]==p2 && part[2]==p3); }; inline bool HasFlag(uint32 p1=0, uint32 p2=0, uint32 p3=0) const { return ( part[0]&p1 || part[1]&p2 || part[2]&p3); }; inline void Set(uint32 p1=0, uint32 p2=0, uint32 p3=0) { part[0]=p1; part[1]=p2; part[2]=p3; }; template<class type> inline bool operator < (type & right) { for (uint8 i=3; i > 0; --i) { if (part[i-1]<right.part[i-1]) return 1; else if (part[i-1]>right.part[i-1]) return 0; } return 0; }; template<class type> inline bool operator < (type & right) const { for (uint8 i = 3; i > 0; --i) { if (part[i-1]<right.part[i-1]) return 1; else if (part[i-1]>right.part[i-1]) return 0; } return 0; }; template<class type> inline bool operator != (type & right) { if (part[0]!=right.part[0] || part[1]!=right.part[1] || part[2]!=right.part[2]) return true; return false; } template<class type> inline bool operator != (type & right) const { if (part[0]!=right.part[0] || part[1]!=right.part[1] || part[2]!=right.part[2]) return true; return false; }; template<class type> inline bool operator == (type & right) { if (part[0]!=right.part[0] || part[1]!=right.part[1] || part[2]!=right.part[2]) return false; return true; }; template<class type> inline bool operator == (type & right) const { if (part[0]!=right.part[0] || part[1]!=right.part[1] || part[2]!=right.part[2]) return false; return true; }; template<class type> inline void operator = (type & right) { part[0]=right.part[0]; part[1]=right.part[1]; part[2]=right.part[2]; }; template<class type> inline flag96 operator & (type & right) { flag96 ret(part[0] & right.part[0],part[1] & right.part[1],part[2] & right.part[2]); return ret; }; template<class type> inline flag96 operator & (type & right) const { flag96 ret(part[0] & right.part[0],part[1] & right.part[1],part[2] & right.part[2]); return ret; }; template<class type> inline void operator &= (type & right) { *this=*this & right; }; template<class type> inline flag96 operator | (type & right) { flag96 ret(part[0] | right.part[0],part[1] | right.part[1],part[2] | right.part[2]); return ret; }; template<class type> inline flag96 operator | (type & right) const { flag96 ret(part[0] | right.part[0],part[1] | right.part[1],part[2] | right.part[2]); return ret; }; template<class type> inline void operator |= (type & right) { *this=*this | right; }; inline void operator ~ () { part[2]=~part[2]; part[1]=~part[1]; part[0]=~part[0]; }; template<class type> inline flag96 operator ^ (type & right) { flag96 ret(part[0] ^ right.part[0],part[1] ^ right.part[1],part[2] ^ right.part[2]); return ret; }; template<class type> inline flag96 operator ^ (type & right) const { flag96 ret(part[0] ^ right.part[0],part[1] ^ right.part[1],part[2] ^ right.part[2]); return ret; }; template<class type> inline void operator ^= (type & right) { *this=*this^right; }; inline operator bool() const { return( part[0] != 0 || part[1] != 0 || part[2] != 0); }; inline operator bool() { return( part[0] != 0 || part[1] != 0 || part[2] != 0); }; inline bool operator ! () const { return( part[0] == 0 && part[1] == 0 && part[2] == 0); }; inline bool operator ! () { return( part[0] == 0 && part[1] == 0 && part[2] == 0); }; inline uint32 & operator[](uint8 el) { return (part[el]); }; inline const uint32 & operator[](uint8 el) const { return (part[el]); }; }; /* Select a random element from a container. Note: make sure you explicitly empty check the container */ template <class C> typename C::value_type const& SelectRandomContainerElement(C const& container) { typename C::const_iterator it = container.begin(); std::advance(it, urand(0, container.size() - 1)); return *it; } #endif
[ "pat_66696@hotmail.com" ]
pat_66696@hotmail.com
d5a692209fc0c70d1fd0b0749cdd970652e3f18b
b278695d3f1b411f3bf10fb2adf9a8baf11542d3
/Solutions/longestProblems/longestConsecutiveSequence.cpp
a388b3e4fb523cf668fa898563936178ebf59b53
[]
no_license
VenkataAnilKumar/LeetCode
445f62dc8e8eec430b6ea0709dc77cbdb7494621
df6d9e4b7172266bef4bc1f771fce3abb2216298
refs/heads/master
2021-06-25T07:56:54.217539
2020-12-18T05:54:59
2020-12-18T05:54:59
176,710,300
1
0
null
null
null
null
UTF-8
C++
false
false
1,951
cpp
// Source : https://oj.leetcode.com/problems/longest-consecutive-sequence/ // Author : Venkata Anil Kumar /********************************************************************************** * * Given an unsorted array of integers, find the length of the longest consecutive elements sequence. * * For example, * Given [100, 4, 200, 1, 3, 2], * The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. * * Your algorithm should run in O(n) complexity. * * **********************************************************************************/ // // Obviously, the easist way is sort the array, however the run-time complexity is O(nlogn) // // If we cannot use the sort algorithm, then it seems we have to use O(n^2) solution. // // That's fine, let's take a look the O(n^2) soultion // // 1) for each item num[i] in the array // 2) for loop to seach ...... num[i-2], num[i-1], num[i]+1, num[i]+2 ...... // // We can see, the search is really heavy, and the best data structure for seaching is HashMap. // hash map is O(1) run-time complexity for seaching. // // So, we can have the following solution by using Hash Map. // class Solution { public: int longestConsecutive(vector<int> &num) { map<int, int> m; for (int i=0; i<num.size(); i++){ m[num[i]]=i; } int max_seq=0; for (int i=0; i<num.size(); i++){ int cnt=1; for(int n = num[i]+1;m.find(n)!=m.end();n++){ m.erase(m.find(n)); cnt++; } for(int n = num[i]-1;m.find(n)!=m.end();n--){ m.erase(m.find(n)); cnt++; } if (max_seq < cnt){ max_seq = cnt; } if (m.size()==0){ break; } } return max_seq; } };
[ "25908037+VenkataAnilKumar@users.noreply.github.com" ]
25908037+VenkataAnilKumar@users.noreply.github.com
2ef12e0d2e3cac569ce59f074365019457f7a05c
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_repos_function_5746_last_repos.cpp
a993575f450ee24b4b80a1fbea2b07e5be3717dd
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,860
cpp
void Auth::Negotiate::UserRequest::startHelperLookup(HttpRequest *, AccessLogEntry::Pointer &al, AUTHCB * handler, void *data) { static char buf[MAX_AUTHTOKEN_LEN]; assert(data); assert(handler); assert(user() != NULL); assert(user()->auth_type == Auth::AUTH_NEGOTIATE); if (static_cast<Auth::Negotiate::Config*>(Auth::Config::Find("negotiate"))->authenticateProgram == NULL) { debugs(29, DBG_CRITICAL, "ERROR: No Negotiate authentication program configured."); handler(data); return; } debugs(29, 8, HERE << "credentials state is '" << user()->credentials() << "'"); const char *keyExtras = helperRequestKeyExtras(request, al); int printResult = 0; if (user()->credentials() == Auth::Pending) { if (keyExtras) printResult = snprintf(buf, sizeof(buf), "YR %s %s\n", client_blob, keyExtras); else printResult = snprintf(buf, sizeof(buf), "YR %s\n", client_blob); //CHECKME: can ever client_blob be 0 here? } else { if (keyExtras) printResult = snprintf(buf, sizeof(buf), "KK %s %s\n", client_blob, keyExtras); else printResult = snprintf(buf, sizeof(buf), "KK %s\n", client_blob); } if (printResult < 0 || printResult >= (int)sizeof(buf)) { if (printResult < 0) debugs(29, DBG_CRITICAL, "ERROR: Can not build negotiate authentication helper request"); else debugs(29, DBG_CRITICAL, "ERROR: Negotiate authentication helper request too big for the " << sizeof(buf) << "-byte buffer"); handler(data); return; } waiting = 1; safe_free(client_blob); helperStatefulSubmit(negotiateauthenticators, buf, Auth::Negotiate::UserRequest::HandleReply, new Auth::StateData(this, handler, data), authserver); }
[ "993273596@qq.com" ]
993273596@qq.com
79863d3b2e4d17132289991edd2b9193f97b5917
2782c2fc4eb2448ee5d4f82c1e2ca9265722b8d1
/region_growing/regionGrowing.cpp
12cf1de156b8f05d47ca76e17726544f6060514e
[]
no_license
MarkusEich/semantic_perception
2fa7854f165f97cef63de8f4e25d8adb2d79aff6
df9c879cb78a6b8dcda339a727870ed2f8b258f4
refs/heads/master
2021-01-02T23:13:23.856242
2013-08-21T18:28:17
2013-08-21T18:28:17
10,883,195
3
0
null
null
null
null
UTF-8
C++
false
false
8,185
cpp
/***************************************** ** Markus Eich (2013) ** Malgosia Goldhorn (2010) ** DFKI GmbH ** ** */ #include "regionGrowing.h" #include <iostream> #include <math.h> #include <fstream> #include <stdlib.h> #include <string.h> #include "hull.h" #include "kdtree.hpp" #include "plane.h" #ifdef USE_OPENMP #include <omp.h> #endif using namespace Gamera::Kdtree; using namespace std; int RegionGrowing::neighbours_count; RegionGrowing::RegionGrowing() : delta(0), gamma(0), epsilon(0), theta(0), n_p (0), neighboursCalculated(false), funcPtr(0) { } RegionGrowing::~RegionGrowing(){ points.clear(); } /** * Chooses starting points. */ void RegionGrowing::selectP1P2(Shared_Plane pl) { //only if there are two points existing while(n_p<=points.size()-2) { //add point to the plane, take the nearest neighbors of the point, then move the point to the end of the point set, //that future planes not from this point sample pl->mergeNearestNeighbours(points[0]); pl->addPoint(points[0]); moveToEnd(0); //search nearest neighbors to the point, which still is not in the plane Shared_Point p2 = pl->findNearestNeighbour(); if(p2) { movePtrToEnd(p2); pl->addPoint(p2); pl->mergeNearestNeighbours(p2); return; } } } /** * Sets the pointcloud, which should be processed. */ void RegionGrowing::setPointcloud(std::vector<Shared_Point>& points){ mutex.lock(); this->points=points; mutex.unlock(); } /** * Sets the pointcloud as Point_3d array, which should be processed. */ void RegionGrowing::setPointcloud(Pointcloud::Point_3d* points, const int count){ mutex.lock(); neighboursCalculated=false; for(int i=0; i<this->points.size(); i++){ this->points[i].reset(); } this->points.clear(); for(int i=0; i<count; i++){ Shared_Point p(new Point(points[i].x, points[i].y, points[i].z)); this->points.push_back(p); } mutex.unlock(); } /** * Sets the callback function. */ /** * Moves a point to the end of the point array, move the local point to the old position of the point. */ void RegionGrowing::movePtrToEnd(Shared_Point p) { moveToEnd(p->index); } void RegionGrowing::moveToEnd(size_t i) { size_t tmpi = points.size()-n_p-1; bool f_point = false; Shared_Point tmpp = points[i]; points[i] = points[tmpi]; points[tmpi] = tmpp; points[tmpi]->index = tmpi; points[i]->index = i; n_p++; } void RegionGrowing::calculateNeighbours(std::vector<Shared_Point> &points, double delta){ //all points entered in the tree, they need to be converted to the internal messaging format gamera KdnodeVector nodes; nodes.reserve(points.size()); std::vector<Shared_Point>::iterator it; size_t ind = 0; for(it = points.begin(); it != points.end(); it++) { //register index of the point in the point array, this will make a mapping of the points on their array position possible //(necessary for the reordering of the points) (*it)->index = ind++; CoordPoint p; p.reserve(3); for(int i = 0; i < 3; i++) p.push_back((*it)->p[i]); //in the node element can also store a pointer to the point in our format, //we may find that after the calculation quickly nodes.push_back(kdnode(p, &(*it))); } //create tree of the above assembled nodes kdtree tree(&nodes); //iterating over all the points and find its nearest neighbors //the first one is (probably) always be the point itself for(it = points.begin(); it != points.end(); it++) { KdnodeVector neighbours; CoordPoint ref; ref.reserve(3); for(int i = 0; i < 3; i++) ref.push_back((*it)->p[i]); tree.k_nearest_neighbors(ref, neighbours_count, &neighbours); KdnodeVector::iterator rit; //going throught neighbors to consider, whether they really are not the reference point and whether the distance is actually //smaller than delta //if so, it will be added to the list of nearby points of the point for(rit = neighbours.begin(); rit != neighbours.end(); rit++) { Shared_Point p2 = *reinterpret_cast<Shared_Point*>(rit->data); if(p2 != *it && (*it)->distance(*p2) < delta) { (*it)->nearestNeighbours.push_back(Point::Neighbour(p2, (*it)->distance(*p2))); } } } } /** * Precomputation of the nearest neighbors by k-d tree. */ void RegionGrowing::precomputeNearestNeighbours() { if(neighboursCalculated){ return; } RegionGrowing::calculateNeighbours(points, delta); neighboursCalculated = true; //std::cout << "finished precomputing nearest neighbours" << std::endl; } /** * Actual search function, gets a reference to a list handed over by planes. */ bool RegionGrowing::regionFind(std::list<Shared_Plane>& result) { if(!mutex.try_lock()){ //Only sucsessful if no setters are active, so it prevent race-conditidions on the pointlists. printf("Cannot lock lists, so skipping RegionGrowing\n"); return false; } std::cout<< "Using following paramters: delta , epsilon , theta , gamma , KNN "<<std::endl; std::cout<< delta << " " << epsilon << " "<< epsilon<< " "<< theta << " "<< gamma <<" "<< neighbours_count<<std::endl; if(points.empty()){ mutex.unlock(); printf("Points are Empty, cannot start\n"); return false; } n_p = 0; //precalculate neighbors of the points std::cout << "Start Calculation of N.N."<< std::endl; precomputeNearestNeighbours(); std::cout << "Start computing of " << points.size() << " points " << std::endl; //as long as enough points are available #ifdef USE_OPENMP #pragma omp parallel { #pragma omp signle private(n_p,maxiter,) { #endif while(n_p <= points.size()-2) { int maxiter = points.size(); Shared_Plane cur_plane(new Plane); //first point from the vector select, this is by no means in a pre-existing plane //(due to reordering of the points in the array!) selectP1P2(cur_plane); //as long as the plane does not nearest neighbors and not all points were processed while(cur_plane->knowNeighbours() && n_p < points.size() && maxiter--) { //read nearest neighbors (in constant time) and check whether this is already contained in the plane //if such a point exists, it is added to the plane Shared_Point pprime = cur_plane->findNearestNeighbour(); if(pprime.get()!=0 && pprime->index < points.size()-n_p) { //has the point maximum gamma distance to the plane? if(cur_plane->planeDist(pprime) < gamma) { //save the state of the plane and add point, because of the stored state, we can afterward go back to the old state, //if the point not fit to the plane (MSE is too large) //simple backtracking cur_plane->saveState(); cur_plane->mergeNearestNeighbours(pprime); cur_plane->addPoint(pprime); //check with the added data, if MSE is too large, if so, remove the point again and saved the state //and restore plane if(cur_plane->mse() >= epsilon) { cur_plane->removePoint(pprime); cur_plane->restoreState(); } else { //if not, the point will be moved to the end of the point list and its neighbors in the queue of the plane movePtrToEnd(pprime); } } } } //calculation of a plane is completed, check that it contains enough points, //if so, add to the result, if not, discard if(cur_plane->points.size() > theta) { static int planecount = 0; //std::cout << "Found plane with " << cur_plane->points.size() << " points." << std::endl; result.push_back(cur_plane); if(funcPtr!=0) (*funcPtr)(cur_plane); //same as above but with proper boost if(callback_!=0) callback_(cur_plane); } } #ifdef USE_OPENMP } } #endif //printf("Calculation ended\n"); mutex.unlock(); return true; } void RegionGrowing::setDelta(double v){ neighboursCalculated=false; delta = v; fprintf(stdout,"New Delta %f\n",v); } void RegionGrowing::setGamma(double v){ gamma = v; fprintf(stdout,"New Gamma %f\n",v); } void RegionGrowing::setEpsilon(double v){ epsilon = v; fprintf(stdout,"New Epsilon %f\n",v); } void RegionGrowing::setTheta(int v){ theta = v; fprintf(stdout,"New Theta %i\n",v); } void RegionGrowing::setNeighbours(int v){ neighboursCalculated=false; RegionGrowing::neighbours_count = v; fprintf(stdout,"New Neighnour Count %i\n",v); }
[ "markus.eich@dfki.de" ]
markus.eich@dfki.de
057ecdcd03a6f16a515c72772ed30b815ad20732
e2714a029d43d19faf18b7a7dcdf931d4bc612b2
/Morphs/Importers/CoreUtils/Shared/CanvasTex/cpp/Source/Android-Mac/ScratchImage.cpp
41672099da931aed48c1d6cd23e7e23900a0a47e
[ "MIT" ]
permissive
PolygonalSun/BabylonPolymorph
a12abf65f94c0e8bc72d79a2d851929991854cd0
c9d65884215063a449195fe06b50a86e5149ae69
refs/heads/master
2022-08-04T13:39:11.753031
2020-05-05T03:07:49
2020-05-05T03:07:49
257,961,313
0
0
MIT
2020-04-22T16:42:11
2020-04-22T16:42:11
null
UTF-8
C++
false
false
5,826
cpp
#include <CanvasTex/ScratchImage.h> #include "ScratchImage.h" #include "ImageMac.h" #include <vector> #include <gli/texture2d_array.hpp> #include <gli/texture_cube.hpp> namespace CanvasTex { //--------------------------------------------------------------------------------------------------------------------- ScratchImage::ScratchImage() : m_impl(std::make_shared<ScratchImageImplementation>()) { } //--------------------------------------------------------------------------------------------------------------------- ScratchImage::~ScratchImage() = default; //--------------------------------------------------------------------------------------------------------------------- ScratchImage::ScratchImage(ScratchImage&& other) : m_impl(std::move(other.m_impl)) { } //--------------------------------------------------------------------------------------------------------------------- ScratchImage& ScratchImage::operator=(ScratchImage&& other) { if(this != &other) { m_impl = std::move(other.m_impl); } return *this; } //--------------------------------------------------------------------------------------------------------------------- void ScratchImage::InitializeFromImage(const Image& srcImage) { m_impl->InitializeFromImage(srcImage.CGetImplementation()); } //--------------------------------------------------------------------------------------------------------------------- void ScratchImage::Release() { } //--------------------------------------------------------------------------------------------------------------------- ConstTextureMetadata ScratchImage::GetMetadata() const { auto metaImpl = static_cast<const ConstTextureMetadata::TextureMetadataImplementation*>(&m_impl->GetMetadata()); return ConstTextureMetadata(std::shared_ptr<const TextureMetadataBase::TextureMetadataImplementation>(m_impl, metaImpl)); } // //--------------------------------------------------------------------------------------------------------------------- ConstImage ScratchImage::GetImage(size_t item, size_t mip) const { gli::texture& texture = m_impl->m_texture; // It seems that the behaviour of CanvasTex is that the item is an index into layers or faces. // ScratchImage does not directly support arrays of cubemaps. if (texture.layers() > 1 && texture.faces() > 1) { throw Babylon::Utils::BabylonException(std::string("ScratchImage::GetImage - Does not support arrays of cubemaps")); } switch (m_impl->m_texture.target()) { case gli::TARGET_1D: case gli::TARGET_2D: { if (item != 0) { throw Babylon::Utils::BabylonException(std::string("ScratchImage::GetImage - Non-zero 'item' for non-array texture")); } // index == miplevel auto t2d = gli::texture2d(texture); auto gliImage = t2d[mip]; Image image; ImageBase::ImageImplementation& imageImpl = image.GetImplementation(); imageImpl.SetGliImage(gliImage); return ConstImage(image); } break; case gli::TARGET_1D_ARRAY: case gli::TARGET_2D_ARRAY: { auto t2da = gli::texture2d_array(texture); auto gliImage = t2da[item][mip]; Image image; ImageBase::ImageImplementation& imageImpl = image.GetImplementation(); imageImpl.SetGliImage(gliImage); return ConstImage(image); } break; case gli::TARGET_CUBE: { auto cube = gli::texture_cube(texture); auto gliImage = cube[item][mip]; Image image; ImageBase::ImageImplementation& imageImpl = image.GetImplementation(); imageImpl.SetGliImage(gliImage); return ConstImage(image); } break; case gli::TARGET_3D: throw Babylon::Utils::BabylonException("ScratchImage::GetImage - Not implemented for 3D textures"); break; default: throw Babylon::Utils::BabylonException(std::string("ScratchImage::GetImage - Unknown texture target ") + std::to_string(m_impl->m_texture.target())); } } //--------------------------------------------------------------------------------------------------------------------- size_t ScratchImage::GetImageCount() const { if (m_impl->m_texture.layers() > 1 && m_impl->m_texture.faces() > 1) { throw Babylon::Utils::BabylonException(std::string("ScratchImage::GetImageCount - Does not support arrays of cubemaps")); } return std::max(m_impl->m_texture.layers(), m_impl->m_texture.faces()) * m_impl->m_texture.levels(); } //--------------------------------------------------------------------------------------------------------------------- const uint8_t* ScratchImage::GetPixels() const { return m_impl->GetPixels(); } //--------------------------------------------------------------------------------------------------------------------- uint8_t* ScratchImage::GetPixels() { return m_impl->GetPixels(); } //--------------------------------------------------------------------------------------------------------------------- size_t ScratchImage::GetPixelsSize() const { return m_impl->GetPixelsSize(); } //--------------------------------------------------------------------------------------------------------------------- ScratchImage::ScratchImageImplementation& ScratchImage::GetImplementation() { return *m_impl; } //--------------------------------------------------------------------------------------------------------------------- const ScratchImage::ScratchImageImplementation& ScratchImage::CGetImplementation() const { return *m_impl; } } // namespace CanvasTex
[ "dasolare@microsoft.com" ]
dasolare@microsoft.com
5732729f59c227882c35d87a0ab04a953edceebd
3d9a2a802548a8257c02d1009b9e5f5e4ad5542e
/Coin.h
98f39f3a4c952d8822741fc9c57999163522df3d
[]
no_license
GeorgeVicarey/TSoTM
dae3a15de37a1e9241359aab2ad7357c44155315
c234fdcb1af6729a28662db89c6696fecc121af8
refs/heads/master
2021-01-22T07:39:06.341751
2014-05-04T19:03:55
2014-05-04T19:03:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
511
h
/* * Coin.h * * Created on: 28 Apr 2014 * Author: George */ #ifndef COIN_H_ #define COIN_H_ class Coin { private: //The X and Y offsets of the tony //The velocity of the tony int xVel, yVel; public: int x, y; //Initializes the variables Coin(int Px, int Py); Coin(); //Shows the tony on the screen void show(); void setPos(int px, int pY); void hide(); int getX(); int getY(); }; #endif /* COIN_H_ */ extern SDL_Surface *coin;
[ "g.vicarey@hotmail.co.uk" ]
g.vicarey@hotmail.co.uk
3558cfc76362a844cb3314a049fe0ad914902fc5
9a6036d2f5b0a9d56c8e8bc55d78758409f6cd72
/CAsyncSocketEx/CBase64Coding.cpp
ecefef8f8654864fc57cc048e11d5bbfa1140080
[]
no_license
Ciapas-Linux/PinkCard2
7c5c58ea496f9af3de00a7254ba56a1518cd67b6
9891266c9e5886de215594fd42d71e59241cf62b
refs/heads/main
2023-08-16T14:34:52.381673
2021-09-28T10:59:31
2021-09-28T10:59:31
411,242,448
0
0
null
null
null
null
UTF-8
C++
false
false
7,822
cpp
#include "stdafx.h" #include "CBase64Coding.hpp" #pragma hdrstop #define CARRIAGE_RETURN (13) #define LINE_FEED (10) /* ** Author: Samuel R. Blackburn ** Internet: wfc@pobox.com ** ** You can use it any way you like as long as you don't try to sell it. ** ** Any attempt to sell WFC in source code form must have the permission ** of the original author. You can produce commercial executables with ** WFC but you can't sell WFC. ** ** Copyright, 2000, Samuel R. Blackburn ** ** $Workfile: CBase64Coding.cpp $ ** $Revision: 14 $ ** $Modtime: 5/12/00 3:39p $ ** $Reuse Tracing Code: 1 $ */ //Modified for use with CAsyncProxySocket, removed tracing code #if defined( _DEBUG ) && ! defined( WFC_STL ) #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif // _DEBUG #define END_OF_BASE64_ENCODED_DATA ('=') #define BASE64_END_OF_BUFFER (0xFD) #define BASE64_IGNORABLE_CHARACTER (0xFE) #define BASE64_UNKNOWN_VALUE (0xFF) #define BASE64_NUMBER_OF_CHARACTERS_PER_LINE (72) static inline BYTE __get_character( const BYTE * buffer, const BYTE * decoder_table, int& index, int size_of_buffer ) { BYTE return_value = 0; do { if ( index >= size_of_buffer ) { return( BASE64_END_OF_BUFFER ); } return_value = buffer[ index ]; index++; } while( return_value != END_OF_BASE64_ENCODED_DATA && decoder_table[ return_value ] == BASE64_IGNORABLE_CHARACTER ); return( return_value ); } CBase64Coding::CBase64Coding() { } CBase64Coding::~CBase64Coding() { } BOOL CBase64Coding::Encode( const char * source, int len, char * destination_string ) { const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int loop_index = 0; int number_of_bytes_to_encode = len; BYTE byte_to_add = 0; BYTE byte_1 = 0; BYTE byte_2 = 0; BYTE byte_3 = 0; DWORD number_of_bytes_encoded = (DWORD) ( (double) number_of_bytes_to_encode / (double) 0.75 ) + 1; // Now add in the CR/LF pairs, each line is truncated at 72 characters // 2000-05-12 // Thanks go to Ilia Golubev (ilia@varicom.co.il) for finding a bug here. // I was using number_of_bytes_to_encode rather than number_of_bytes_encoded. number_of_bytes_encoded += (DWORD)( ( ( number_of_bytes_encoded / BASE64_NUMBER_OF_CHARACTERS_PER_LINE ) + 1 ) * 2 ); char * destination = destination_string; number_of_bytes_encoded = 0; while( loop_index < number_of_bytes_to_encode ) { // Output the first byte byte_1 = source[ loop_index ]; byte_to_add = alphabet[ ( byte_1 >> 2 ) ]; destination[ number_of_bytes_encoded ] = static_cast< TCHAR >( byte_to_add ); number_of_bytes_encoded++; loop_index++; if ( loop_index >= number_of_bytes_to_encode ) { // We're at the end of the data to encode byte_2 = 0; byte_to_add = alphabet[ ( ( ( byte_1 & 0x03 ) << 4 ) | ( ( byte_2 & 0xF0 ) >> 4 ) ) ]; destination[ number_of_bytes_encoded ] = byte_to_add; number_of_bytes_encoded++; destination[ number_of_bytes_encoded ] = END_OF_BASE64_ENCODED_DATA; number_of_bytes_encoded++; destination[ number_of_bytes_encoded ] = END_OF_BASE64_ENCODED_DATA; // 1999-09-01 // Thanks go to Yurong Lin (ylin@dial.pipex.com) for finding a bug here. // We must NULL terminate the string before letting CString have the buffer back. destination[ number_of_bytes_encoded + 1 ] = 0; return( TRUE ); } else { byte_2 = source[ loop_index ]; } byte_to_add = alphabet[ ( ( ( byte_1 & 0x03 ) << 4 ) | ( ( byte_2 & 0xF0 ) >> 4 ) ) ]; destination[ number_of_bytes_encoded ] = byte_to_add; number_of_bytes_encoded++; loop_index++; if ( loop_index >= number_of_bytes_to_encode ) { // We ran out of bytes, we need to add the last half of byte_2 and pad byte_3 = 0; byte_to_add = alphabet[ ( ( ( byte_2 & 0x0F ) << 2 ) | ( ( byte_3 & 0xC0 ) >> 6 ) ) ]; destination[ number_of_bytes_encoded ] = byte_to_add; number_of_bytes_encoded++; destination[ number_of_bytes_encoded ] = END_OF_BASE64_ENCODED_DATA; // 1999-09-01 // Thanks go to Yurong Lin (ylin@dial.pipex.com) for finding a bug here. // We must NULL terminate the string before letting CString have the buffer back. destination[ number_of_bytes_encoded + 1 ] = 0; return( TRUE ); } else { byte_3 = source[ loop_index ]; } loop_index++; byte_to_add = alphabet[ ( ( ( byte_2 & 0x0F ) << 2 ) | ( ( byte_3 & 0xC0 ) >> 6 ) ) ]; destination[ number_of_bytes_encoded ] = byte_to_add; number_of_bytes_encoded++; byte_to_add = alphabet[ ( byte_3 & 0x3F ) ]; destination[ number_of_bytes_encoded ] = byte_to_add; number_of_bytes_encoded++; if ( ( number_of_bytes_encoded % BASE64_NUMBER_OF_CHARACTERS_PER_LINE ) == 0 ) { destination[ number_of_bytes_encoded ] = CARRIAGE_RETURN; number_of_bytes_encoded++; destination[ number_of_bytes_encoded ] = LINE_FEED; number_of_bytes_encoded++; } } destination[ number_of_bytes_encoded ] = END_OF_BASE64_ENCODED_DATA; // 1999-09-01 // Thanks go to Yurong Lin (ylin@dial.pipex.com) for finding a bug here. // We must NULL terminate the string before letting CString have the buffer back. destination[ number_of_bytes_encoded + 1 ] = 0; return( TRUE ); } // End of source #if 0 <HTML> <HEAD> <TITLE>WFC - CBase64Coding</TITLE> <META name="keywords" content="WFC, MFC extension library, freeware class library, Win32, MIME encoding, base 64, source code"> <META name="description" content="This C++ class let's you MIME encode bytes to text using base64."> </HEAD> <BODY> <H1>CBase64Coding</H1> $Revision: 14 $<BR><HR> <H2>Description</H2> This class gives you the ability to encode/decode data using base64. <H2>Constructors</H2> <DL COMPACT> <DT><PRE><B>CBase64Coding</B>()<DD> Constructs this object. </DL> <H2>Methods</H2> <DL COMPACT> <DT><PRE>BOOL <B><A NAME="Decode">Decode</A></B>( const CByteArray&amp; source, CByteArray&amp; destination ) BOOL <B>Decode</B>( const CString&amp; source, CByteArray&amp; destination )</PRE><DD> This method takes base64 encoded text and produces the bytes. It decodes the base64 encoding. <DT><PRE>BOOL <B><A NAME="Encode">Encode</A></B>( const CByteArray&amp; source, CByteArray&amp; destination ) BOOL <B>Encode</B>( const CByteArray&amp; source, CString&amp; destination )</PRE><DD> This method takes bytes and turns them into base64 text. </DL> <H2>Example</H2> <PRE><CODE>#include &lt;wfc.h&gt; int _tmain( int number_of_command_line_arguments, LPCTSTR command_line_arguments[] ) { <A HREF="WfcTrace.htm">WFCTRACEINIT</A>( TEXT( &quot;_tmain()&quot; ) ); CByteArray bytes; get_file_contents( command_line_arguments[ 0 ], bytes ); <B>CBase64Coding</B> encoder; CString encoded_data; if ( encoder.Encode( bytes, encoded_data ) != FALSE ) { _tprintf( TEXT( &quot;%s\n&quot;, (LPCTSTR) encoded_data ); } }</CODE></PRE> <HR><I>Copyright, 2000, <A HREF="mailto:wfc@pobox.com">Samuel R. Blackburn</A></I><BR> $Workfile: CBase64Coding.cpp $<BR> $Modtime: 5/12/00 3:39p $ </BODY> </HTML> #endif
[ "maxgon@o2.pl" ]
maxgon@o2.pl
7bf91e082fab10841e9961ac451d40350d0332c0
f78501e74e26b6c3702c649097d9b7426ae0506b
/Lab7 Wireless network and ESP32/Lab7_5_ESP32_TCPServer/Lab7_5_ESP32_TCPServer.ino
e90431703c2354b8708906bee41f17315939621f
[]
no_license
noppadolp/IoT-codelabs
200a7cc2f63f0ea62e054db71211599a01a715f9
b939fa7363af22ab237901ad3725201b95731ddb
refs/heads/master
2023-08-24T05:43:27.059434
2021-10-26T13:54:33
2021-10-26T13:54:33
408,972,865
1
3
null
null
null
null
UTF-8
C++
false
false
867
ino
#include <WiFi.h> #define SERVER_PORT 9999 const char* ssid = "IEE-IoT"; const char* password = "ieenopassword"; WiFiServer my_server(SERVER_PORT); void setup() { Serial.begin(115200); WiFi.begin(ssid,password); while(WiFi.status() != WL_CONNECTED){ delay(500); Serial.print("."); } Serial.println("WiFi Connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); my_server.begin(); Serial.println("Server started"); } void loop() { WiFiClient my_client = my_server.available(); if(my_client){ Serial.println("New client connected"); while(true){ while(my_client.available()){ uint8_t data = my_client.read(); Serial.write(data); my_client.write(data); } if(my_server.hasClient()){ Serial.println("Client disconnected"); return; } } } }
[ "noppadol.p@eng.kmutnb.ac.th" ]
noppadol.p@eng.kmutnb.ac.th
db4b40cf71eafa5468061c427d18c4b66bbb7e1a
a1a8b69b2a24fd86e4d260c8c5d4a039b7c06286
/build/iOS/Debug/include/Fuse.Scripting.EventEmitterModule.h
b077839a7d1e2930e5fdec137b4debc31f8f64de
[]
no_license
epireve/hikr-tute
df0af11d1cfbdf6e874372b019d30ab0541c09b7
545501fba7044b4cc927baea2edec0674769e22c
refs/heads/master
2021-09-02T13:54:05.359975
2018-01-03T01:21:31
2018-01-03T01:21:31
115,536,756
0
0
null
null
null
null
UTF-8
C++
false
false
1,010
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Scripting/1.4.2/EventEmitterModule.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.h namespace g{namespace Fuse{namespace Scripting{struct Context;}}} namespace g{namespace Fuse{namespace Scripting{struct EventEmitterModule;}}} namespace g{namespace Fuse{namespace Scripting{struct Function;}}} namespace g{ namespace Fuse{ namespace Scripting{ // internal static class EventEmitterModule :7 // { uClassType* EventEmitterModule_typeof(); void EventEmitterModule__GetConstructor_fn(::g::Fuse::Scripting::Context* c, ::g::Fuse::Scripting::Function** __retval); struct EventEmitterModule : uObject { static uSStrong< ::g::Fuse::Scripting::Function* _instance_; static uSStrong< ::g::Fuse::Scripting::Function* & _instance() { return _instance_; } static ::g::Fuse::Scripting::Function* GetConstructor(::g::Fuse::Scripting::Context* c); }; // } }}} // ::g::Fuse::Scripting
[ "i@firdaus.my" ]
i@firdaus.my
55eb4ef073230b749f7da75c8736b5b3b6f6fdf8
2af943fbfff74744b29e4a899a6e62e19dc63256
/MistSlicer/Modules/Meshing/Widgets/vtkMimxExtractEdgeWidget.cxx
72d7f78aead79bf0abd4a4d66b725452c72a26a2
[ "LicenseRef-scancode-3dslicer-1.0", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lheckemann/namic-sandbox
c308ec3ebb80021020f98cf06ee4c3e62f125ad9
0c7307061f58c9d915ae678b7a453876466d8bf8
refs/heads/master
2021-08-24T12:40:01.331229
2014-02-07T21:59:29
2014-02-07T21:59:29
113,701,721
2
1
null
null
null
null
UTF-8
C++
false
false
23,158
cxx
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkMimxExtractEdgeWidget.cxx,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMimxExtractEdgeWidget.h" #include "vtkActor.h" #include "vtkAssemblyNode.h" #include "vtkAssemblyPath.h" #include "vtkCallbackCommand.h" #include "vtkCamera.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkCellPicker.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPlanes.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkSphereSource.h" #include "vtkTransform.h" #include "vtkUnstructuredGrid.h" vtkCxxRevisionMacro(vtkMimxExtractEdgeWidget, "$Revision: 1.3 $"); vtkStandardNewMacro(vtkMimxExtractEdgeWidget); vtkMimxExtractEdgeWidget::vtkMimxExtractEdgeWidget() { this->State = vtkMimxExtractEdgeWidget::Start; this->EventCallbackCommand->SetCallback(vtkMimxExtractEdgeWidget::ProcessEvents); // Enable/disable the translation, rotation, and scaling of the widget // this->TranslationEnabled = 1; // this->RotationEnabled = 1; // this->ScalingEnabled = 1; //Build the representation of the widget //int i; // Control orientation of normals /* this->InsideOut = 0; this->OutlineFaceWires = 0; this->OutlineCursorWires = 1;*/ // Construct the poly data representing the hex this->EdgePolyData = vtkPolyData::New(); this->EdgeMapper = vtkPolyDataMapper::New(); this->EdgeMapper->SetInput(EdgePolyData); this->EdgeActor = vtkActor::New(); this->EdgeActor->SetMapper(this->EdgeMapper); // Construct initial points //this->Points = vtkPoints::New(VTK_DOUBLE); //this->Points->SetNumberOfPoints(15);//8 corners; 6 faces; 1 center //this->HexPolyData->SetPoints(this->Points); // Construct connectivity for the faces. These are used to perform // the picking. /* vtkIdType pts[4]; vtkCellArray *cells = vtkCellArray::New(); cells->Allocate(cells->EstimateSize(6,4)); pts[0] = 3; pts[1] = 0; pts[2] = 4; pts[3] = 7; cells->InsertNextCell(4,pts); pts[0] = 1; pts[1] = 2; pts[2] = 6; pts[3] = 5; cells->InsertNextCell(4,pts); pts[0] = 0; pts[1] = 1; pts[2] = 5; pts[3] = 4; cells->InsertNextCell(4,pts); pts[0] = 2; pts[1] = 3; pts[2] = 7; pts[3] = 6; cells->InsertNextCell(4,pts); pts[0] = 0; pts[1] = 3; pts[2] = 2; pts[3] = 1; cells->InsertNextCell(4,pts); pts[0] = 4; pts[1] = 5; pts[2] = 6; pts[3] = 7; cells->InsertNextCell(4,pts); this->HexPolyData->SetPolys(cells); cells->Delete(); this->HexPolyData->BuildCells();*/ // The face of the hexahedra //cells = vtkCellArray::New(); //cells->Allocate(cells->EstimateSize(1,4)); //cells->InsertNextCell(4,pts); //temporary, replaced later //this->HexFacePolyData = vtkPolyData::New(); //this->HexFacePolyData->SetPoints(this->Points); //this->HexFacePolyData->SetPolys(cells); //this->HexFaceMapper = vtkPolyDataMapper::New(); //this->HexFaceMapper->SetInput(HexFacePolyData); //this->HexFace = vtkActor::New(); //this->HexFace->SetMapper(this->HexFaceMapper); //cells->Delete(); //// Create the outline for the hex //this->OutlinePolyData = vtkPolyData::New(); //this->OutlinePolyData->SetPoints(this->Points); //this->OutlineMapper = vtkPolyDataMapper::New(); //this->OutlineMapper->SetInput(this->OutlinePolyData); //this->HexOutline = vtkActor::New(); //this->HexOutline->SetMapper(this->OutlineMapper); //cells = vtkCellArray::New(); //cells->Allocate(cells->EstimateSize(15,2)); //this->OutlinePolyData->SetLines(cells); //cells->Delete(); //// Set up the initial properties //this->CreateDefaultProperties(); //// Create the outline //this->GenerateOutline(); //// Create the handles //this->Handle = new vtkActor* [7]; //this->HandleMapper = new vtkPolyDataMapper* [7]; //this->HandleGeometry = new vtkSphereSource* [7]; //for (i=0; i<7; i++) // { // this->HandleGeometry[i] = vtkSphereSource::New(); // this->HandleGeometry[i]->SetThetaResolution(16); // this->HandleGeometry[i]->SetPhiResolution(8); // this->HandleMapper[i] = vtkPolyDataMapper::New(); // this->HandleMapper[i]->SetInput(this->HandleGeometry[i]->GetOutput()); // this->Handle[i] = vtkActor::New(); // this->Handle[i]->SetMapper(this->HandleMapper[i]); // } // //// Define the point coordinates //double bounds[6]; //bounds[0] = -0.5; //bounds[1] = 0.5; //bounds[2] = -0.5; //bounds[3] = 0.5; //bounds[4] = -0.5; //bounds[5] = 0.5; //// Points 8-14 are down by PositionHandles(); //this->PlaceWidget(bounds); //Manage the picking stuff this->EdgePicker = vtkCellPicker::New(); this->EdgePicker->SetTolerance(0.001); /* for (i=0; i<7; i++) { this->HandlePicker->AddPickList(this->Handle[i]); }*/ this->EdgePicker->AddPickList(this->EdgeActor); this->EdgePicker->PickFromListOn(); //this->HexPicker = vtkCellPicker::New(); //this->HexPicker->SetTolerance(0.001); //this->HexPicker->AddPickList(HexActor); //this->HexPicker->PickFromListOn(); // //this->CurrentHandle = NULL; //this->Transform = vtkTransform::New(); this->InputActor = NULL; } vtkMimxExtractEdgeWidget::~vtkMimxExtractEdgeWidget() { this->EdgeActor->Delete(); this->EdgeMapper->Delete(); this->EdgePolyData->Delete(); //this->Points->Delete(); //this->HexFace->Delete(); //this->HexFaceMapper->Delete(); //this->HexFacePolyData->Delete(); //this->HexOutline->Delete(); //this->OutlineMapper->Delete(); //this->OutlinePolyData->Delete(); // //for (int i=0; i<7; i++) // { // this->HandleGeometry[i]->Delete(); // this->HandleMapper[i]->Delete(); // this->Handle[i]->Delete(); // } //delete [] this->Handle; //delete [] this->HandleMapper; //delete [] this->HandleGeometry; this->EdgePicker->Delete(); /* this->HexPicker->Delete(); this->Transform->Delete(); this->HandleProperty->Delete(); this->SelectedHandleProperty->Delete(); this->FaceProperty->Delete(); this->SelectedFaceProperty->Delete(); this->OutlineProperty->Delete(); this->SelectedOutlineProperty->Delete();*/ } void vtkMimxExtractEdgeWidget::SetEnabled(int enabling) { if ( ! this->Interactor ) { vtkErrorMacro(<<"The interactor must be set prior to enabling/disabling widget"); return; } if ( enabling ) //------------------------------------------------------------ { vtkDebugMacro(<<"Enabling widget"); if ( this->Enabled ) //already enabled, just return { return; } if ( ! this->CurrentRenderer ) { this->SetCurrentRenderer(this->Interactor->FindPokedRenderer( this->Interactor->GetLastEventPosition()[0], this->Interactor->GetLastEventPosition()[1])); if (this->CurrentRenderer == NULL) { return; } } this->Enabled = 1; // listen to the following events vtkRenderWindowInteractor *i = this->Interactor; i->AddObserver(vtkCommand::MouseMoveEvent, this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::LeftButtonPressEvent, this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::LeftButtonReleaseEvent, this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::MiddleButtonPressEvent, this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::MiddleButtonReleaseEvent, this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::RightButtonPressEvent, this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::RightButtonReleaseEvent, this->EventCallbackCommand, this->Priority); // Add the various actors // Add the outline this->CurrentRenderer->AddActor(this->EdgeActor); if(this->InputActor) this->CurrentRenderer->RemoveActor(this->InputActor); //this->CurrentRenderer->AddActor(this->HexOutline); //this->HexActor->SetProperty(this->OutlineProperty); //this->HexOutline->SetProperty(this->OutlineProperty); // Add the hex face //this->CurrentRenderer->AddActor(this->HexFace); //this->HexFace->SetProperty(this->FaceProperty); // turn on the handles /* for (int j=0; j<7; j++) { this->CurrentRenderer->AddActor(this->Handle[j]); this->Handle[j]->SetProperty(this->HandleProperty); }*/ this->InvokeEvent(vtkCommand::EnableEvent,NULL); } else //disabling------------------------------------------------------------- { vtkDebugMacro(<<"Disabling widget"); if ( ! this->Enabled ) //already disabled, just return { return; } this->Enabled = 0; // don't listen for events any more this->Interactor->RemoveObserver(this->EventCallbackCommand); // turn off the outline this->CurrentRenderer->RemoveActor(this->EdgeActor); if(this->InputActor) this->CurrentRenderer->AddActor(this->InputActor); // this->CurrentRenderer->RemoveActor(this->HexOutline); // turn off the hex face // this->CurrentRenderer->RemoveActor(this->HexFace); // turn off the handles /* for (int i=0; i<7; i++) { this->CurrentRenderer->RemoveActor(this->Handle[i]); }*/ this->InvokeEvent(vtkCommand::DisableEvent,NULL); this->SetCurrentRenderer(NULL); } this->Interactor->Render(); } void vtkMimxExtractEdgeWidget::ProcessEvents(vtkObject* vtkNotUsed(object), unsigned long event, void* clientdata, void* vtkNotUsed(calldata)) { vtkMimxExtractEdgeWidget* self = reinterpret_cast<vtkMimxExtractEdgeWidget *>( clientdata ); //okay, let's do the right thing switch(event) { case vtkCommand::LeftButtonPressEvent: self->OnLeftButtonDown(); break; case vtkCommand::LeftButtonReleaseEvent: self->OnLeftButtonUp(); break; case vtkCommand::MiddleButtonPressEvent: self->OnMiddleButtonDown(); break; case vtkCommand::MiddleButtonReleaseEvent: self->OnMiddleButtonUp(); break; case vtkCommand::RightButtonPressEvent: self->OnRightButtonDown(); break; case vtkCommand::RightButtonReleaseEvent: self->OnRightButtonUp(); break; case vtkCommand::MouseMoveEvent: self->OnMouseMove(); break; } } void vtkMimxExtractEdgeWidget::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } void vtkMimxExtractEdgeWidget::OnLeftButtonDown() { int X = this->Interactor->GetEventPosition()[0]; int Y = this->Interactor->GetEventPosition()[1]; // Okay, we can process this. Try to pick handles first; // if no handles picked, then pick the bounding box. if (!this->CurrentRenderer || !this->CurrentRenderer->IsInViewport(X, Y)) { this->State = vtkMimxExtractEdgeWidget::Outside; return; } vtkAssemblyPath *path; this->EdgePicker->Pick(X,Y,0.0,this->CurrentRenderer); path = this->EdgePicker->GetPath(); if ( path != NULL ) { this->State = vtkMimxExtractEdgeWidget::Moving; vtkIdType PickedCell = this->EdgePicker->GetCellId(); if(PickedCell != -1) { /* if(this->EdgePolyData->GetCellData()->GetScalars()) { this->EdgePolyData->GetCellData()->GetScalars()->Delete(); }*/ vtkIntArray *intarray = vtkIntArray::New(); intarray->SetNumberOfValues(this->EdgePolyData->GetNumberOfCells()); this->EdgePolyData->GetCellData()->SetScalars(intarray); for(int i=0; i < this->EdgePolyData->GetNumberOfCells(); i++) intarray->SetValue(i,0.0); intarray->SetValue(PickedCell,1.0); intarray->Delete(); vtkIdType t; this->EdgePolyData->GetCellPoints(PickedCell,t,this->EdgePoints); } } else { this->State = vtkMimxExtractEdgeWidget::Outside; return; } this->EventCallbackCommand->SetAbortFlag(1); this->StartInteraction(); this->InvokeEvent(vtkCommand::StartInteractionEvent, NULL); this->Interactor->Render(); } void vtkMimxExtractEdgeWidget::OnLeftButtonUp() { if ( this->State == vtkMimxExtractEdgeWidget::Outside || this->State == vtkMimxExtractEdgeWidget::Start ) { return; } this->State = vtkMimxExtractEdgeWidget::Start; /* this->HighlightFace(this->HighlightHandle(NULL)); this->SizeHandles();*/ this->EventCallbackCommand->SetAbortFlag(1); this->EndInteraction(); this->InvokeEvent(vtkCommand::EndInteractionEvent, NULL); this->Interactor->Render(); } void vtkMimxExtractEdgeWidget::OnMiddleButtonDown() { //int X = this->Interactor->GetEventPosition()[0]; //int Y = this->Interactor->GetEventPosition()[1]; //// Okay, we can process this. Try to pick handles first; //// if no handles picked, then pick the bounding box. //if (!this->CurrentRenderer || !this->CurrentRenderer->IsInViewport(X, Y)) // { // this->State = vtkMimxExtractEdgeWidget::Outside; // return; // } // //vtkAssemblyPath *path; //this->HandlePicker->Pick(X,Y,0.0,this->CurrentRenderer); //path = this->HandlePicker->GetPath(); //if ( path != NULL ) // { // this->State = vtkMimxExtractEdgeWidget::Moving; // this->CurrentHandle = this->Handle[6]; // this->HighlightOutline(1); // this->HandlePicker->GetPickPosition(this->LastPickPosition); // this->ValidPick = 1; // } //else // { // this->HexPicker->Pick(X,Y,0.0,this->CurrentRenderer); // path = this->HexPicker->GetPath(); // if ( path != NULL ) // { // this->State = vtkMimxExtractEdgeWidget::Moving; // this->CurrentHandle = this->Handle[6]; // this->HighlightOutline(1); // this->HexPicker->GetPickPosition(this->LastPickPosition); // this->ValidPick = 1; // } // else // { // this->HighlightFace(this->HighlightHandle(NULL)); // this->State = vtkMimxExtractEdgeWidget::Outside; // return; // } // } // //this->EventCallbackCommand->SetAbortFlag(1); //this->StartInteraction(); //this->InvokeEvent(vtkCommand::StartInteractionEvent, NULL); //this->Interactor->Render(); } void vtkMimxExtractEdgeWidget::OnMiddleButtonUp() { /*if ( this->State == vtkMimxExtractEdgeWidget::Outside || this->State == vtkMimxExtractEdgeWidget::Start ) { return; } this->State = vtkMimxExtractEdgeWidget::Start; this->HighlightFace(this->HighlightHandle(NULL)); this->SizeHandles(); this->EventCallbackCommand->SetAbortFlag(1); this->EndInteraction(); this->InvokeEvent(vtkCommand::EndInteractionEvent, NULL); this->Interactor->Render();*/ } void vtkMimxExtractEdgeWidget::OnRightButtonDown() { // int X = this->Interactor->GetEventPosition()[0]; // int Y = this->Interactor->GetEventPosition()[1]; // // // Okay, we can process this. Try to pick handles first; // // if no handles picked, then pick the bounding box. // if (!this->CurrentRenderer || !this->CurrentRenderer->IsInViewport(X, Y)) // { // this->State = vtkMimxExtractEdgeWidget::Outside; // return; // } // // vtkAssemblyPath *path; // this->HandlePicker->Pick(X,Y,0.0,this->CurrentRenderer); // path = this->HandlePicker->GetPath(); // if ( path != NULL ) // { // this->State = vtkMimxExtractEdgeWidget::Scaling; // this->HighlightOutline(1); // this->HandlePicker->GetPickPosition(this->LastPickPosition); // this->ValidPick = 1; // } // else // { // this->HexPicker->Pick(X,Y,0.0,this->CurrentRenderer); // path = this->HexPicker->GetPath(); // if ( path != NULL ) // { // this->State = vtkMimxExtractEdgeWidget::Scaling; // this->HighlightOutline(1); // this->HexPicker->GetPickPosition(this->LastPickPosition); // this->ValidPick = 1; // } // else // { // this->State = vtkMimxExtractEdgeWidget::Outside; // return; // } // } // // this->EventCallbackCommand->SetAbortFlag(1); // this->StartInteraction(); // this->InvokeEvent(vtkCommand::StartInteractionEvent, NULL); // this->Interactor->Render(); //} // //void vtkMimxExtractEdgeWidget::OnRightButtonUp() //{ // if ( this->State == vtkMimxExtractEdgeWidget::Outside ) // { // return; // } // // this->State = vtkMimxExtractEdgeWidget::Start; // this->HighlightOutline(0); // this->SizeHandles(); // // this->EventCallbackCommand->SetAbortFlag(1); // this->EndInteraction(); // this->InvokeEvent(vtkCommand::EndInteractionEvent, NULL); // this->Interactor->Render(); } void vtkMimxExtractEdgeWidget::OnMouseMove() { //// See whether we're active //if ( this->State == vtkMimxExtractEdgeWidget::Outside || // this->State == vtkMimxExtractEdgeWidget::Start ) // { // return; // } // //int X = this->Interactor->GetEventPosition()[0]; //int Y = this->Interactor->GetEventPosition()[1]; //// Do different things depending on state //// Calculations everybody does //double focalPoint[4], pickPoint[4], prevPickPoint[4]; //double z, vpn[3]; //vtkCamera *camera = this->CurrentRenderer->GetActiveCamera(); //if ( !camera ) // { // return; // } //// Compute the two points defining the motion vector //this->ComputeWorldToDisplay(this->LastPickPosition[0], this->LastPickPosition[1], // this->LastPickPosition[2], focalPoint); //z = focalPoint[2]; //this->ComputeDisplayToWorld(double(this->Interactor->GetLastEventPosition()[0]), // double(this->Interactor->GetLastEventPosition()[1]), // z, prevPickPoint); //this->ComputeDisplayToWorld(double(X), double(Y), z, pickPoint); //// Process the motion //if ( this->State == vtkMimxExtractEdgeWidget::Moving ) // { // // Okay to process // if ( this->CurrentHandle ) // { // if ( this->RotationEnabled && this->CurrentHandle == this->HexFace ) // { // camera->GetViewPlaneNormal(vpn); // this->Rotate(X, Y, prevPickPoint, pickPoint, vpn); // } // else if ( this->TranslationEnabled && this->CurrentHandle == this->Handle[6] ) // { // this->Translate(prevPickPoint, pickPoint); // } // else if ( this->TranslationEnabled && this->ScalingEnabled ) // { // if ( this->CurrentHandle == this->Handle[0] ) // { // this->MoveMinusXFace(prevPickPoint, pickPoint); // } // else if ( this->CurrentHandle == this->Handle[1] ) // { // this->MovePlusXFace(prevPickPoint, pickPoint); // } // else if ( this->CurrentHandle == this->Handle[2] ) // { // this->MoveMinusYFace(prevPickPoint, pickPoint); // } // else if ( this->CurrentHandle == this->Handle[3] ) // { // this->MovePlusYFace(prevPickPoint, pickPoint); // } // else if ( this->CurrentHandle == this->Handle[4] ) // { // this->MoveMinusZFace(prevPickPoint, pickPoint); // } // else if ( this->CurrentHandle == this->Handle[5] ) // { // this->MovePlusZFace(prevPickPoint, pickPoint); // } // } // } // } //else if ( this->ScalingEnabled && this->State == vtkMimxExtractEdgeWidget::Scaling ) // { // this->Scale(prevPickPoint, pickPoint, X, Y); // } //// Interact, if desired //this->EventCallbackCommand->SetAbortFlag(1); //this->InvokeEvent(vtkCommand::InteractionEvent, NULL); //this->Interactor->Render(); } void vtkMimxExtractEdgeWidget::ExtractEdge() { // the unstructured grid is converted to polydata with each edge // stored as a cell in polydata vtkIdType* pts=0; vtkIdType t=0; this->UGrid->GetCells()->InitTraversal(); vtkPoints* points = vtkPoints::New(); points->SetNumberOfPoints(this->UGrid->GetNumberOfPoints()); for(int i=0; i <this->UGrid->GetNumberOfPoints(); i++) points->SetPoint(i,this->UGrid->GetPoint(i)); this->EdgePolyData->SetPoints(points); vtkCell* cell; vtkCellArray* edgelist = vtkCellArray::New(); edgelist->InitTraversal(); for(int i=0; i < this->UGrid->GetNumberOfCells(); i++) { if(i >0) { cell = this->UGrid->GetCell(i); // loop through all the edges in the hexahedron cell for(int j=0; j < cell->GetNumberOfEdges(); j++) { vtkCell* edgecell = cell->GetEdge(j); vtkIdList* pointlist = edgecell->GetPointIds(); vtkIdType pt1 = pointlist->GetId(0); vtkIdType pt2 = pointlist->GetId(1); bool status = false; edgelist->InitTraversal(); edgelist->GetNextCell(t,pts); do { // check if the edge is already present in the edge list if((pts[0] == pt1 && pts[1] == pt2) || (pts[0] == pt2 && pts[1] == pt1)) { status = true; } } while(!status && edgelist->GetNextCell(t,pts)); if(!status) {edgelist->InsertNextCell(2); edgelist->InsertCellPoint(pt1); edgelist->InsertCellPoint(pt2); } } } else { cell = this->UGrid->GetCell(i); for(int j=0; j < cell->GetNumberOfEdges(); j++) { vtkCell* edgecell = cell->GetEdge(j); vtkIdList* pointlist = edgecell->GetPointIds(); vtkIdType pt1 = pointlist->GetId(0); vtkIdType pt2 = pointlist->GetId(1); bool status = false; edgelist->InsertNextCell(2); edgelist->InsertCellPoint(pt1); edgelist->InsertCellPoint(pt2); } } } this->EdgePolyData->SetLines(edgelist); this->EdgePolyData->Modified(); this->EdgeActor->GetProperty()->SetLineWidth(3); edgelist->Delete(); points->Delete(); } void vtkMimxExtractEdgeWidget::Initialize() { if(this->UGrid) { // if the input data changes if(this->EdgePolyData->GetPoints()) this->EdgePolyData->GetPoints()->Delete(); if (this->EdgePolyData->GetPolys()) this->EdgePolyData->GetPolys()->Delete(); this->EdgePolyData->Initialize(); this->ExtractEdge(); this->EdgePicker->AddPickList(this->EdgeActor); this->EdgePicker->PickFromListOn(); } } void vtkMimxExtractEdgeWidget::OnRightButtonUp() { } void vtkMimxExtractEdgeWidget::PlaceWidget(double bounds[6]) { } void vtkMimxExtractEdgeWidget::SetInput(vtkDataSet *Input) { this->UGrid = vtkUnstructuredGrid::SafeDownCast(Input); this->Initialize(); this->InputActor = NULL; }
[ "yhayashi@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8" ]
yhayashi@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8
d3ded27591f216c2c172fd7aca19f9a6aa62382c
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir521/dir522/dir572/dir595/file676.cpp
5bfe208a848fe3772ed39e395ae9b0cf0ea3aca5
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
107
cpp
#ifndef file676 #error "macro file676 must be defined" #endif static const char* file676String = "file676";
[ "tgeng@google.com" ]
tgeng@google.com
9ade7806f56991989aa3bedea2d02804b1c2042d
2248e62ab73c5b36e31ab5306eec47252ed3671b
/Chapter 3/3_28.cpp
ea47decfe9ca539ac9313ab2d4b42b33284c9221
[]
no_license
ShadowHu/CppPrimer5th
845c9e9478ea4133adbae1b14e508db8d8420163
849263129dadea6743b759a79175a105cabc415c
refs/heads/master
2021-01-01T05:24:23.295908
2017-05-11T09:22:49
2017-05-11T09:22:49
57,224,274
0
0
null
null
null
null
UTF-8
C++
false
false
476
cpp
/************************************************************************* > File Name: 3_28.cpp > Author: > Mail: > Created Time: 2014年08月17日 星期日 21时45分59秒 ************************************************************************/ #include<iostream> using namespace std; string sa[10]; int ia[10]; int main(){ string sa2[10]; int ia2[10]; cout<<*sa<<endl; cout<<*ia<<endl; cout<<*sa2<<endl; cout<<*ia2<<endl; return 0; }
[ "shadow_hu1441@163.com" ]
shadow_hu1441@163.com
a7eedc8e8abf903e41d48b40043ef7c42ed77f5a
42810b5e3bb8c6983c37a8d695cac351511ed681
/ScoreState.h
78e34b4447a4100d7fb1f640e0195014af76bf7e
[ "MIT" ]
permissive
Deadvard/Tetris
746504d2b19564c57c5261d6f586662761c11cfd
b018d134239339f46de2f1218f2477786968c581
refs/heads/master
2020-03-08T05:56:28.522370
2018-04-03T19:39:34
2018-04-03T19:39:34
127,959,490
0
0
null
null
null
null
UTF-8
C++
false
false
813
h
#ifndef SCORESTATE_H #define SCORESTATE_H #include "GameState.h" #include "Button.h" class ScoreState : public GameState { public: ScoreState(sf::RenderWindow& window, InputHandler* ih, ResourceHandler* rh); virtual ~ScoreState(); //Updates current state void update(sf::RenderWindow& window, sf::Time timeSinceLastUpdate); //Draws current state void draw(sf::RenderWindow& window); private: //Draws a specific button void drawButton(sf::RenderWindow& window, Button& button); //Tests if a button is pressed void isButtonPressed(sf::Vector2f mouse); //Uses the result of the button press to change gamestate if button was pressed void result(sf::RenderWindow& window); bool startMenu; sf::Text text; Button backButton; }; #endif // !SCORESTATE_H
[ "noreply@github.com" ]
noreply@github.com
549babf42ed2965d8972fe5a3013899ac54d9d0c
4bd36dae2e4e69e9d04438b9197ae23bbab255e1
/Status/Core/Client/Teacher/MainWindow/t_functionButtonWidget.cpp
2f0d1d07d2c709e669460d1443fb396349cccf2a
[]
no_license
StatusOnIineEducationDev/status-desktop
6b40704a25b8082a22bb16ea923dacd2f20e6938
f8632fa835306a8ec34d5324cd1f44406b1dcdb5
refs/heads/master
2020-07-30T19:29:04.119987
2019-12-30T11:22:54
2019-12-30T11:22:54
210,332,367
0
0
null
null
null
null
UTF-8
C++
false
false
222
cpp
#include "t_functionButtonWidget.h" TeacherFunctionButtonWidget::TeacherFunctionButtonWidget(QWidget *parent) : QWidget(parent) { m_ui.setupUi(this); } TeacherFunctionButtonWidget::~TeacherFunctionButtonWidget() { }
[ "lanyangbo@foxmail.com" ]
lanyangbo@foxmail.com
f26a862cc2cbd9bd57e88577c00badfed0c5b452
82c19ae7828b2ca07a631f19868c1320d4da419b
/mf1836_hw7_q1.cpp
d19a901209d11e7bd4c12856c1e772b65becf355
[]
no_license
mf3129/NYU_Work
4d6f72a5b511ac86240cd254f179e828e6b51a68
147222c821b8072657615df2655dd6d7278a3b69
refs/heads/master
2020-06-11T19:10:20.430957
2019-09-18T03:10:20
2019-09-18T03:10:20
194,057,086
0
0
null
null
null
null
UTF-8
C++
false
false
3,085
cpp
/* Implement a function: int printMonthCalender(int numOfDays, int startingDay) This function is given two parameters: numOfDays - The number of days in the month startingDay – a number 1-7 that represents the day in the week of the first day in that month (1 for Monday, 2 for Tuesday, 3 for Wednesday, etc.). */ #include <iostream> using namespace std; //Declaring Function Prototype int printMonthCalendar(int numOfDays, int startingDay); bool isALeapYear(int year); void printYearCalendar(int year, int startingDay); int main() { // Part A - printMonthCalendar(31, 4); int yearNumber; int tabNumber; cout << "Enter a year: "; cin >> yearNumber; cout << "Enter the number of spaces: "; cin >> tabNumber ; printYearCalendar(yearNumber, tabNumber); return 0; } //Defining Functions /***************************** Part A **********************************/ int printMonthCalendar(int numOfDays, int startingDay) { //Printing the header cout << "Mon" << '\t' << "Tue" << '\t' << "Wed" << '\t' << "Thr" << '\t' << "Fri" << '\t' << "Sat" << '\t' << "Sun" << endl; int currentDay = 0, finalDay, positionNumber = 1; for (positionNumber; positionNumber < numOfDays + startingDay; positionNumber++) { if (positionNumber < startingDay) { cout << "\t"; } if (positionNumber >= startingDay && currentDay <= numOfDays) { currentDay++; cout << currentDay << "\t"; if (positionNumber % 7 == 0) { cout << endl; } } } finalDay = (positionNumber - 1) % 7; cout << endl; return finalDay; } /***************************** Part B **********************************/ bool isALeapYear(int year) { if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { return true; } else { return false; } } /***************************** Part C **********************************/ void printYearCalendar(int year, int startingDay) { string month [12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; int daysInMonth [12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int finalDay; if (isALeapYear(year)) { //Accouting for the leap year daysInMonth [1] = 29; //Looping through the array for (int i = 0; i < 12; i++) { //Print the header for each month cout << month[i] << " " << year << endl; finalDay = printMonthCalendar(daysInMonth[i], startingDay); startingDay = finalDay + 1; cout << endl; } } }
[ "noreply@github.com" ]
noreply@github.com
ed58980c23b72fc92e0a09518ed9711f3df4293c
80a8477d098b4d86063d1a60570b57bd03c034a8
/tst/mov_avg_tst/mov_avg_tst.cc
67614276bee6cb62cad32cdaf985f856f8f1019c
[]
no_license
ratatech/RatatechSynth
a67bd273d60b8a4f06f5067915a44ed5d1be34aa
6406165d8c1c9041cfff5c767ca97cff988cc90c
refs/heads/master
2021-01-11T14:55:47.081445
2018-10-05T22:19:01
2018-10-05T22:19:01
80,235,732
0
0
null
null
null
null
UTF-8
C++
false
false
5,348
cc
/* @file mov_avg_tst.cc @brief Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. @ Created by Jordi Hidalgo, Ratatech, Jun 13, 2017 This file is part of XXXXXXX XXXXXXX is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. XXXXXXX 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 XXXXXXX. If not, see <http://www.gnu.org/licenses/> */ #include <stdio.h> #include "unity.h" #include "oscillator.h" #include "mov_avg.h" #include "tst_utils.h" /** * Size of reference and output buffers */ #define BUFF_SIZE 256 /** * Moving average unit test reference buffer */ q15_t buff_mov_avg_ref[BUFF_SIZE] = { 1255,2462,3623,4739,5813,6846,7839,8794,9712,10595,11445,12261,13047,13802,14529,15228,15899,16546,17167,17765,18339,18892,19424,19935, 20426,20899,21354,21791,22211,22616,23005,23379,23738,24084,24417,24737,25044,25340,25625,25898,26161,26414,26658,26892,27117,27333,27541, 27742,27934,28119,28297,28468,28633,28791,28944,29090,29231,29366,29497,29622,29742,29858,29970,30077,30180,30279,30374,30466,30554,30639, 30720,30799,30874,30947,31016,31083,31148,31210,31269,31327,31382,31435,31486,31535,31582,31628,31671,31713,31754,31792,31830,31866,31900, 31933,31965,31996,32025,32054,32081,32107,32133,32157,32180,32203,32224,32245,32265,32284,32303,32321,32338,32354,32370,32385,32400,32414, 32427,32440,32453,32465,32476,32487,32498,32508,32518,32528,32537,32546,32554,32562,32570,32578,32585,32592,32599,32605,32611,32617,32623, 32628,32634,32639,32644,32648,32653,32657,32661,32665,32669,32673,32677,32680,32683,32687,32690,32693,32695,32698,32701,32703,32706,32708, 32710,32712,32714,32716,32718,32720,32722,32724,32725,32727,32728,32730,32731,32733,32734,32735,32736,32738,32739,32740,32741,32742,32743, 32744,32744,32745,32746,32747,32748,32748,32749,32750,32750,32751,32752,32752,32753,32753,32754,32754,32755,32755,32756,32756,32756,32757, 32757,32758,32758,32758,32759,32759,32759,32759,32760,32760,32760,32760,32761,32761,32761,32761,32762,32762,32762,32762,32762,32762,32763, 32763,32763,32763,32763,32763,32763,32763,32764,32764,32764,32764,32764,32764,32764,32764,32764,32764,32765,32765,32765,32765,32765,32765, 32765,32765, }; /** * Moving average input data * */ q15_t pIn[FRAME_SIZE] = { 0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff, 0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff,0x7fff, }; /** * Dummy object pool */ object_pool_t object_pool; /** * Structure holding the main synth parameters */ synth_params_t synth_params; /** * Moving average filter class instance */ MovAvg mov_avg; /** * Oscillator class instance */ Oscillator osc; /** * Unit test output buffer */ q15_t pMovAvgOut[BUFF_SIZE]; /** * Moving average filter unit test */ void test_mov_avg_out(void){ /** Pointer to moving average filter frame **/ q15_t pMovAvg[FRAME_SIZE]; /** Init moving average filter with default settings */ mov_avg.init(&synth_params.mov_avg_params); /** Specify the total number of frames */ uint8_t _NFRAMES = BUFF_SIZE/FRAME_SIZE; /** Specifically set beta coefficient for the test */ mov_avg.beta = 2065214841; // tau = 0.1, fs=256hz /** Get moving average frames */ for(int i=0; i< _NFRAMES; i++){ mov_avg.process_frame(&synth_params,pIn,pMovAvg); /** Store frames in outuput buffer */ arm_copy_q15(pMovAvg,&pMovAvgOut[i*FRAME_SIZE],FRAME_SIZE); }; /** Print output buffer */ printOutBuff("buff_mov_avg_out", pMovAvgOut, BUFF_SIZE); /** Compare output vs reference */ TEST_ASSERT_EQUAL_INT16_ARRAY(buff_mov_avg_ref,pMovAvgOut,BUFF_SIZE); } int main(void) { /** Init system and peripherals */ ratatech_init(&synth_params); /** Load initial default settings */ init_settings(&synth_params,object_pool); /** Turn off buffers, so IO occurs immediately */ setvbuf(stdin, NULL, _IONBF, 0); setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); /** Wait usart confirmation to start the test */ wait_usart_ready(); /** Ready to start test */ iprintf("\nTEST: Moving Average Filter\n-----------------------"); /** Start unity and trigger tests */ UNITY_BEGIN(); RUN_TEST(test_mov_avg_out); /** FInish unity */ return UNITY_END(); }
[ "jhidalgo87@gmail.com" ]
jhidalgo87@gmail.com
bccd9a538d8baae6a06a6bab9177d99e35520923
30e1dc84fe8c54d26ef4a1aff000a83af6f612be
/src/external/boost/boost_1_68_0/libs/bimap/test/compile_fail/test_bimap_info_2.cpp
d3b2007fcbb94eaf2eac0b89cc89b161a5dc22e6
[ "BSL-1.0", "BSD-3-Clause" ]
permissive
Sitispeaks/turicreate
0bda7c21ee97f5ae7dc09502f6a72abcb729536d
d42280b16cb466a608e7e723d8edfbe5977253b6
refs/heads/main
2023-05-19T17:55:21.938724
2021-06-14T17:53:17
2021-06-14T17:53:17
385,034,849
1
0
BSD-3-Clause
2021-07-11T19:23:21
2021-07-11T19:23:20
null
UTF-8
C++
false
false
1,196
cpp
// Boost.Bimap // // Copyright (c) 2006-2007 Matias Capeletto // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // VC++ 8.0 warns on usage of certain Standard Library and API functions that // can be cause buffer overruns or other possible security issues if misused. // See http://msdn.microsoft.com/msdnmag/issues/05/05/SafeCandC/default.aspx // But the wording of the warning is misleading and unsettling, there are no // portable alternative functions, and VC++ 8.0's own libraries use the // functions in question. So turn off the warnings. #define _CRT_SECURE_NO_DEPRECATE #define _SCL_SECURE_NO_DEPRECATE #include <boost/config.hpp> // Boost.Test #include <boost/test/minimal.hpp> // Boost.Bimap #include <boost/bimap/bimap.hpp> #include <boost/bimap/list_of.hpp> void test_bimap_info_2() { using namespace boost::bimaps; typedef bimap< int, list_of<int> > bm_type; bm_type bm; bm.insert( bm_type::value_type(1,1) ); // fail test { bm.begin()->info; } } int test_main( int, char* [] ) { test_bimap_info_2(); return 0; }
[ "znation@apple.com" ]
znation@apple.com
162bfc47d76242370b8ae1ae15f514a8d841b3ff
de852231b562c3e423ebc24bc0a68fe04653d2cc
/Arduino Code/Lap_Counter_LED_8x32_v17/Lap_Counter_LED_8x32_v17.ino
5cde42d2a7562ed109cfc564bdb0561c741c33ad
[]
no_license
bespokegear/lapcounter
c31f70f4092d492f5c7e7a47b58bf2b6b366e585
610d943bbc886d8734fc4b31142dcbb6c6aaa747
refs/heads/master
2020-03-27T19:51:06.960480
2018-09-01T16:52:30
2018-09-01T16:52:30
147,015,972
0
0
null
null
null
null
UTF-8
C++
false
false
16,129
ino
/******************************************************** /****** Scalextric Lap Counter Unit ******************** /****** by Matt Little ********************************** /****** Date: 18/7/18 ********************************** /****** info@re-innovation.co.uk ************************ /****** www.re-innovation.co.uk ************************* /******************************************************** /* Code for Sure 8 x 32 LED matrix HT1632 controller board This reads data from two lap counter switches. This is for player 1 and 2 timers. These work with interrupts 1 and 2 which control the timers. Two additional buttons are added: Green is Start Red is edit: change the number of laps (puts into edit mode) Usual operation: When powered on it will show two numbers - this is how many laps to count down from. Start button will reset these. When Start button is pressed: Show "Ready Set GO!" Then display number of laps and max lap count (adjustable - stored in EEPROM) for each track Wach time a track interrupt happens then the display will show the lap time for 1 second (adjustable). At end (laps = 0) then the display shows the winner and their fastest time on the display. Press edit button: Then set number of laps (0-50 available) Use green button to scroll through. This needs to be stored in EEPROM for next time. The display is updated often, but only out of the interrupt loop. Interrupts: They will go low when triggered. The cause the timer to stop and reset. It will also decrement the lap counter The lap is then reduced and the previous time displayed Pin allocations: D2: Track 1 interrupt D3: Track 2 interrupt LED matrix connections: D4: CS1 D5: CS2 D6: CS3 D7: CS4 B8: WR B9: DATA D10: RD D11: D12: Button 1: Start D13: Button 2: Edit / Status LED This is code for a plug-in board for these Sure Electronics LED displays. http://www.sureelectronics.net/goods.php?id=1119 The PCB has been developed by Renewable Energy Innovation. http://www.re-innovation.co.uk/ The HT1632 code was obtained from here: https://github.com/gauravmm/HT1632-for-Arduino The HT1632.h file must ensure that the USE_NMOS was set to 1. This was for my Sure displays. // Note: I've had to updated HT1632.cpp to change the line: #if defined TYPE_3208_MONO //writeCommand(HT1632_CMD_COMS00); // For HT1632c writeCommand(HT1632_CMD_COMS10); // Changed for HT1632 Code started: 18/7/18 By: Matt Little (matt@re-innovation.co.uk) TO DO: */ #include <HT1632.h> #include <font_5x4.h> #include <images.h> #include <stdlib.h> #include <EEPROM.h> // For writing values to the EEPROM #include <avr/eeprom.h> // For writing values to EEPROM #include <avr/interrupt.h> #include <avr/io.h> // constants won't change. They're used here to set pin numbers: const int buttonStart = 12; // Start button (will be D11 - D3 for testing) const int buttonEdit = 13; // Edit Button const int debounceDelay = 5; // // This is for the HT1632 LED display //Initialise with //HT1632.begin(pinCS1 [, pinCS2 [, pinCS3 [, pinCS4]]], pinWR, pinDATA); // HT1632.begin(4, 8, 9); // ******* Variables ************* int lapMax = 5; // Holds the number of laps to count down (stored in EEPROM when adjusted) int lapCount1; // Holds the actual number of laps so far int lapCount2; // Holds the actual number of laps so far volatile float lap1time; float lap1timeAct; // This is the actual lap time in mS float lap1timeMin = 999999; // Stores minimum time for laps float lap1timeOld; // for comparison volatile bool track1flag = LOW; // Set on track 1 interrupt volatile float lap2time; float lap2timeAct; // This is the actual lap time in mS float lap2timeMin = 999999; // stores minimum time for laps float lap2timeOld; // for comparison volatile bool track2flag = LOW; // Set on track 2 interrupt bool endRaceFlag = LOW; // Set to show the winner bool raceRunningFlag = LOW; bool buttonValue; bool lastButtonAState = LOW; int debounceACounter = 0; bool buttonValueB; bool lastButtonBState = LOW; int debounceBCounter = 0; //int wd; // for display? int displayCounterMax = 50; // This is how often (in multiples of 5mS) the display will update int displayCounter = 0; int displayMode = 0; // Initial display mode bool editFlag = LOW; // For the edit button bool startFlag = LOW; // For the start flag unsigned long enterMillis = 0; int winner = 0; // Stores the winner number char result[8] = ""; // Buffer big enough for 7-character float bool setInt1flag = LOW; //static unsigned long last_interrupt_time1 = 0; //unsigned long interrupt_time1; //static unsigned long last_interrupt_time2 = 0; //unsigned long interrupt_time2; // ******* END Variables ************* // Need to put ISR here x 2 void track1Interupt(void) { static unsigned long last_interrupt_time1 = 0; unsigned long interrupt_time1 = millis(); // If interrupts come faster than 200ms, assume it's a bounce and ignore if (interrupt_time1 - last_interrupt_time1 > 2) { //detachInterrupt(0); track1flag = HIGH; lap1time = millis(); Serial.println("int1!"); } last_interrupt_time1 = interrupt_time1; // Does this on interrupt so code can continue } void track2Interupt(void) { static unsigned long last_interrupt_time2 = 0; unsigned long interrupt_time2 = millis(); // If interrupts come faster than 200ms, assume it's a bounce and ignore if (interrupt_time2 - last_interrupt_time2 > 50) { //detachInterrupt(1); track2flag = HIGH; lap2time = millis(); Serial.println("int2!"); } last_interrupt_time2 = interrupt_time2; // Does this on interrupt so code can continue } void setup() { // initialize the pushbutton pins as an input: // DEBUG!! pinMode(buttonStart, INPUT_PULLUP); pinMode(buttonStart, INPUT_PULLUP); pinMode(buttonEdit, INPUT_PULLUP); pinMode(2, INPUT); pinMode(3, INPUT); // // For battery voltage measurement // analogReference(INTERNAL); // Sets the voltage ref to the internal 1.1V Serial.begin(115200); // Set up a serial output for data display and changing parameters Serial.flush(); // Want to read in any saved value of Max Laps from EEPROM // This is saved into space 0 // EEPROM.write(0, lapMax); // Example of writing to EEPROM lapMax = EEPROM.read(0); Serial.print("Max Laps is: "); Serial.println(lapMax); //Initialise with //HT1632.begin(pinCS1 [, pinCS2 [, pinCS3 [, pinCS4]]], pinWR, pinDATA); // HT1632 pin connections: // CS1: D4 // CS2: D5 // CS3: D6 // CS4: D7 // WR: D8 // RD: D10 // DATA:D9 // OSC: NC // SYNC:NC HT1632.begin(4, 5, 8, 9); // Set pin 2 & 3 as interrupt and attach handler: //attachInterrupt(0, track1Interupt, FALLING); //attachInterrupt(1, track2Interupt, FALLING); } void loop () { // Start of main loop // Check track flags and deal with them if (raceRunningFlag == HIGH) { checkFlags(); } // Check switches checkButton(); // Update display, if required (every 0.25 seconds in this example) if (displayCounter >= displayCounterMax) { updateDisplay(); //Reset the display counter displayCounter = 0; } displayCounter++; // increment the counter // Delay and slow things down delay(5); // Slow things down } void checkButton() { //******** SWITCH CHECK ******************************************* // Check the button A and debounce it and latch it buttonValue = digitalRead(buttonStart); if (buttonValue != lastButtonAState && debounceACounter >= debounceDelay) { //buttonPressed=HIGH; // set the button pressed flag. // Button Start has been pressed startFlag = HIGH; raceRunningFlag = LOW; // Just in case we wer halfway through before reset Serial.print("START:"); Serial.println(startFlag); } else if (buttonValue == LOW) { debounceACounter = 0; } lastButtonAState = buttonValue; debounceACounter++; // Check the button B and debounce it and latch it buttonValueB = digitalRead(buttonEdit); if (buttonValueB != lastButtonBState && debounceBCounter >= debounceDelay) { //buttonPressed=HIGH; // set the button pressed flag. // Button Start has been pressed Serial.print("EDIT:"); if (editFlag == LOW) { editFlag = HIGH; displayMode = 6; // Go into Edit Mode } else { editFlag = LOW; enterMillis = millis(); // Display for one second that it has saved displayMode = 7; // write data to EEPROM } Serial.println(editFlag); } else if (buttonValueB == LOW) { debounceBCounter = 0; } lastButtonBState = buttonValueB; debounceBCounter++; // Sort out the start of the race: if (startFlag == HIGH && editFlag == LOW) { displayMode = 1; enterMillis = millis(); startFlag = LOW; } } void checkFlags() { if (endRaceFlag == HIGH) { track1flag = LOW; track2flag = LOW; } // Check track flag 1 if (track1flag == HIGH && endRaceFlag == LOW) { // Lap one has been completed lap1timeAct = lap1time - lap1timeOld; lapCount1++; // Increment the lap counter Serial.print("Time1:"); Serial.println(lap1timeAct); Serial.print("Lap: "); Serial.print(lapCount1); Serial.print(" of "); Serial.println(lapMax); if ( lap1timeAct < lap1timeMin) { // This is a new miniumum time lap1timeMin = lap1timeAct; Serial.print("Min:"); Serial.println(lap1timeMin); } if (lapCount1 >= lapMax) { // Here track 1 is the winner Serial.println("Track 1 wins!"); Serial.print("Min:"); Serial.println(lap1timeMin); endRaceFlag = HIGH; winner = 1; startFlag = LOW; // Reset the start flag Serial.print("START:"); Serial.println(startFlag); } lap1timeOld = lap1time; track1flag = LOW; } // Check track flag 2 if (track2flag == HIGH && endRaceFlag == LOW) { // Lap one has been completed lap2timeAct = lap2time - lap2timeOld; lapCount2++; // Increment the lap counter Serial.print("Time2:"); Serial.println(lap2timeAct); Serial.print("Lap: "); Serial.print(lapCount2); Serial.print(" of "); Serial.println(lapMax); if (lap2timeAct < lap2timeMin) { // This is a new miniumum time lap2timeMin = lap2timeAct; Serial.print("Min:"); Serial.println(lap2timeMin); } if (lapCount2 >= lapMax) { // Here track 2 is the winner Serial.println("Track 2 wins!"); Serial.print("Min:"); Serial.println(lap2timeMin); endRaceFlag = HIGH; winner = 2; startFlag = LOW; // Reset the start flag Serial.print("START:"); Serial.println(startFlag); } lap2timeOld = lap2time; track2flag = LOW; } } void updateDisplay() { switch (displayMode) { case 0: // Initial display mode // Display "ready" and blank rest of screen HT1632.renderTarget(0); HT1632.clear(); HT1632.drawText("READY" , 6, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.render(); HT1632.renderTarget(1); HT1632.clear(); HT1632.render(); break; case 1: if (millis() >= (enterMillis + 1000)) { displayMode = 2; enterMillis = millis(); } HT1632.renderTarget(0); HT1632.clear(); HT1632.drawText("READY" , 6, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.render(); HT1632.renderTarget(1); HT1632.clear(); HT1632.render(); break; case 2: if (millis() >= (enterMillis + 1000)) { displayMode = 3; enterMillis = millis(); } HT1632.renderTarget(0); HT1632.clear(); HT1632.drawText("SET" , 9, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.render(); HT1632.renderTarget(1); HT1632.clear(); HT1632.render(); break; case 3: if (millis() >= (enterMillis + 1000)) { displayMode = 4; } HT1632.renderTarget(0); HT1632.clear(); HT1632.drawText("GO!!!" , 9, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.render(); HT1632.renderTarget(1); HT1632.clear(); HT1632.render(); // Here we start the race and set all the starting variables winner = 0; lap1timeAct = 0; lap2timeAct = 0; // Reset all the values lapCount1 = 0; lapCount2 = 0; endRaceFlag = LOW; lap1timeMin = 999999; lap1timeOld = millis(); // Set the start time lap2timeMin = 999999; lap2timeOld = millis(); // Set the start time raceRunningFlag = HIGH; // Start the actual timers attachInterrupt(0, track1Interupt, FALLING); attachInterrupt(1, track2Interupt, FALLING); break; case 4: // In this section the displayMode number is used to show what is to be displayed // The race is running here // Display number of laps for each track if (lap1timeAct > 0) { HT1632.renderTarget(0); HT1632.clear(); dtostrf(lapCount1, 2, 0, result); HT1632.drawText(result , 1, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.drawText("of" , 11, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); dtostrf(lapMax, 2, 0, result); HT1632.drawText(result , 21, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.render(); } if (lap2timeAct > 0) { HT1632.renderTarget(1); HT1632.clear(); dtostrf(lapCount2, 2, 0, result); HT1632.drawText(result , 1, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.drawText("of" , 11, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); dtostrf(lapMax, 2, 0, result); HT1632.drawText(result , 21, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.render(); } if (endRaceFlag == HIGH) { displayMode = 5; raceRunningFlag = LOW; // Stop the timers } break; case 5: // We have a winner! detachInterrupt(0); detachInterrupt(1); // Display "WINNER:?" // Then min lap time for winner dtostrf(winner, 1, 0, result); HT1632.renderTarget(0); HT1632.clear(); HT1632.drawText(result, 1, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.drawText("WINS!" , 7, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.render(); if (winner == 1) { dtostrf(lap1timeMin / 1000.0, 6, 2, result); // Leave room for too large numbers! } else if (winner == 2) { dtostrf(lap2timeMin / 1000.0, 6, 2, result); // Leave room for too large numbers! } HT1632.renderTarget(1); HT1632.clear(); HT1632.drawText(result , 1, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.render(); break; case 6: // Edit button has been pressed // Check Start button to increment max laps HT1632.renderTarget(0); HT1632.clear(); HT1632.drawText("MAX LAPS" , 1, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.render(); HT1632.renderTarget(1); HT1632.clear(); dtostrf(lapMax, 2, 0, result); HT1632.drawText(result , 1, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.render(); if (startFlag == HIGH) { lapMax++; if (lapMax > 50) { lapMax = 1; // Roll over } startFlag = LOW; } break; case 7: if (millis() >= (enterMillis + 1000)) { // Here we write to EEPROM on leaving, so just done once EEPROM.write(0, lapMax); // Example of writing to EEPROM displayMode = 0; } HT1632.renderTarget(0); HT1632.clear(); HT1632.drawText("SAVED" , 1, 1, FONT_5X4, FONT_5X4_END, FONT_5X4_HEIGHT); HT1632.render(); break; default: // In case things have gone wrong break; } }
[ "matt@re-innovation.co.uk" ]
matt@re-innovation.co.uk
ac9f910d129a8d5eb023e551c2e7628d84dd4c75
10c67c4beef52d4afc3b7935a698059e37cffc30
/GUARDCOS.cpp
257fd5443ba22dc9bd15af3f83cd71ea4a2526b6
[]
no_license
ronaldo-k/Solutions
00e6bb321e677bcf6061099aa64ff870f6f18e53
3cc63cd1d9ff88654691b6a6f4afbbde902cb306
refs/heads/master
2020-07-29T15:50:45.905274
2019-11-27T00:39:06
2019-11-27T00:39:06
209,868,438
0
0
null
null
null
null
UTF-8
C++
false
false
472
cpp
#include <stdio.h> int d, vf, vg, pf, pg, df; bool valid; int main() { while(scanf("%d %d %d", &d, &vf, &vg) != EOF) { df = vg - vf; valid = false; if(d >= 12 || df <= 0) valid = false; pg = 0; pf = d; for(int i = 0; vf * i < 12; i++) { valid = false; pf += vf; pg += vg; if(pg >= pf) { valid = true; break; } } if(d >= 12 - df && !(d >= 12) && !(df <= 0) ) valid = true; if(valid) printf("S\n"); else printf("N\n"); } }
[ "ronaldo.kanegae@gmail.com" ]
ronaldo.kanegae@gmail.com
f3e2af10173ee6fa07652e2327f16c14ee35015f
e28e5e34a399c49ec61409dfb66a33d3c033498f
/9469-vonneumann/9469-vonneumann.cpp
7d4a024551c7026e060167fb0f34c3fff235e71a
[]
no_license
rupc/boj
e72f2e8ec1a69da7d735ac1723273b977cf2155e
281ce9561c152a7330acc31ded83198a1d0c34c7
refs/heads/master
2020-07-02T08:07:00.618675
2017-01-24T05:56:32
2017-01-24T05:56:32
66,392,534
0
0
null
null
null
null
UTF-8
C++
false
false
1,564
cpp
// input, output #include <iostream> #include <iomanip> // container #include <vector> #include <array> #include <list> #include <map> #include <set> #include <string> // container adaper #include <stack> #include <queue> // STL algorithm related #include <algorithm> #include <iterator> #include <functional> #include <numeric> #include <memory> #include <utility> // C standard library #include <cmath> #include <cstdlib> // // #define DEBUG using namespace std; // Declaration of variables // Declaration of auxiliary function class genProbSolver { public: genProbSolver(string s) : name(s) {} void process_input(istream &); void process_solution(); void process_output(ostream &); void echo_input(); private: string name; }; void genProbSolver::process_input(istream &pin) { int P, N; double D, A, B, F; pin >> P; for (int i = 0; i < P; i++) { pin >> N >> D >> A >> B >> F; double flying_time = D / (A+B); double move_dist = flying_time * F; cout << i+1 << " " << setprecision(2) << fixed << move_dist << endl; } } void genProbSolver::echo_input() { } void genProbSolver::process_solution() { } void genProbSolver::process_output(ostream &pout) { } int main(int argc, const char *argv[]) { genProbSolver probsolver(""); probsolver.process_input(std::cin); probsolver.echo_input(); probsolver.process_solution(); probsolver.process_output(std::cout); return 0; }
[ "neurosilver@gmail.com" ]
neurosilver@gmail.com
67aa61a0b101ab904c072de906911ec00601b628
3fb01b66b695d57871ce33328c494669a97276e5
/src/simple_uv/config.cpp
cc6862d13eedaae67da9d45a8b7d54c7f5197af4
[]
no_license
HONGJICAI/coflow_in_hrrn
21cfa3265eb37fbb75e0e9a725901f5e3bdb7465
4d07edf52ad40ae2f8a2cd66556c363b36eab91e
refs/heads/master
2020-03-13T20:18:47.998815
2018-05-21T14:57:47
2018-05-21T14:57:47
131,271,237
0
0
null
null
null
null
UTF-8
C++
false
false
3,393
cpp
// Config.cpp #include "config.h" using namespace std; Config::Config(string filename, string delimiter, string comment) : m_Delimiter(delimiter), m_Comment(comment) { // Construct a Config, getting keys and values from given file std::ifstream in(filename.c_str()); if (!in) throw File_not_found(filename); in >> (*this); } Config::Config() : m_Delimiter(string(1, '=')), m_Comment(string(1, '#')) { // Construct a Config without a file; empty } bool Config::KeyExists(const string& key) const { // Indicate whether key is found mapci p = m_Contents.find(key); return (p != m_Contents.end()); } /* static */ void Config::Trim(string& inout_s) { // Remove leading and trailing whitespace static const char whitespace[] = " \n\t\v\r\f"; inout_s.erase(0, inout_s.find_first_not_of(whitespace)); inout_s.erase(inout_s.find_last_not_of(whitespace) + 1U); } std::ostream& operator<<(std::ostream& os, const Config& cf) { // Save a Config to os for (Config::mapci p = cf.m_Contents.begin(); p != cf.m_Contents.end(); ++p) { os << p->first << " " << cf.m_Delimiter << " "; os << p->second << std::endl; } return os; } void Config::Remove(const string& key) { // Remove key and its value m_Contents.erase(m_Contents.find(key)); return; } std::istream& operator >> (std::istream& is, Config& cf) { // Load a Config from is // Read in keys and values, keeping internal whitespace typedef string::size_type pos; const string& delim = cf.m_Delimiter; // separator const string& comm = cf.m_Comment; // comment const pos skip = delim.length(); // length of separator string nextline = ""; // might need to read ahead to see where value ends while (is || nextline.length() > 0) { // Read an entire line at a time string line; if (nextline.length() > 0) { line = nextline; // we read ahead; use it now nextline = ""; } else { std::getline(is, line); } // Ignore comments line = line.substr(0, line.find(comm)); // Parse the line if it contains a delimiter pos delimPos = line.find(delim); if (delimPos < string::npos) { // Extract the key string key = line.substr(0, delimPos); line.replace(0, delimPos + skip, ""); // See if value continues on the next line // Stop at blank line, next line with a key, end of stream, // or end of file sentry bool terminate = false; while (!terminate && is) { std::getline(is, nextline); terminate = true; string nlcopy = nextline; Config::Trim(nlcopy); if (nlcopy == "") continue; nextline = nextline.substr(0, nextline.find(comm)); if (nextline.find(delim) != string::npos) continue; nlcopy = nextline; Config::Trim(nlcopy); if (nlcopy != "") line += "\n"; line += nextline; terminate = false; } // Store key and value Config::Trim(key); Config::Trim(line); cf.m_Contents[key] = line; // overwrites if key is repeated } } return is; } bool Config::FileExist(std::string filename) { bool exist = false; std::ifstream in(filename.c_str()); if (in) exist = true; return exist; } void Config::ReadFile(string filename, string delimiter, string comment) { m_Delimiter = delimiter; m_Comment = comment; std::ifstream in(filename.c_str()); if (!in) throw File_not_found(filename); in >> (*this); }
[ "464580613@qq.com" ]
464580613@qq.com
03d1d9eb83ccf8f7b754672e64c3c994fc13febf
00efb44a653d5e05997ca1dde50c58a6df8549d7
/src/CryptoNoteCore/Account.cpp
2c1a707dda52a8701742ed245cd8340580c50037
[]
no_license
askmeboy/sld
8a635183482ecdd3d8351d84389bb2f3211a3021
2755bcc27e27d9e437c5eb5b025184d16c9eb7f0
refs/heads/master
2020-04-18T01:33:52.691066
2018-12-07T20:48:37
2018-12-07T20:48:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,913
cpp
// Copyright (c) 2011-2016 The Cryptonote developers // Copyright (c) 2014-2017 XDN-project developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "Account.h" #include "CryptoNoteSerialization.h" namespace CryptoNote { //----------------------------------------------------------------- AccountBase::AccountBase() { setNull(); } //----------------------------------------------------------------- void AccountBase::setNull() { m_keys = AccountKeys(); } //----------------------------------------------------------------- void AccountBase::generate() { Crypto::generate_keys(m_keys.address.spendPublicKey, m_keys.spendSecretKey); Crypto::generate_keys(m_keys.address.viewPublicKey, m_keys.viewSecretKey); m_creation_timestamp = 1509321600; } //----------------------------------------------------------------- const AccountKeys &AccountBase::getAccountKeys() const { return m_keys; } //----------------------------------------------------------------- void AccountBase::setAccountKeys(const AccountKeys &keys) { m_keys = keys; } //----------------------------------------------------------------- void AccountBase::serialize(ISerializer &s) { s(m_keys, "m_keys"); s(m_creation_timestamp, "m_creation_timestamp"); } //----------------------------------------------------------------- Crypto::SecretKey AccountBase::generate_or_recover(const Crypto::SecretKey& recovery_key, const Crypto::SecretKey& secondary_key, bool is_recovery, bool is_copy, bool is_deterministic) { Crypto::SecretKey like_seed = generate_keys_or_recover( m_keys.address.spendPublicKey, m_keys.spendSecretKey, recovery_key, is_recovery); //rng for generating second set of keys is hash of like_seed rng //means only one set of electrum-style words needed for recovery // is_recovery = 0 >> Gen RND spendSecretKey ELSE use recovery_key // is_copy = 0 >> secondary_key=KECCAK ELSE secondary_key untouched // is_deterministic = 0 >> Gen RND viewSecretKey else use secondary_key if (!is_copy) { keccak((uint8_t *)&like_seed, sizeof(Crypto::SecretKey), (uint8_t *)&secondary_key, sizeof(Crypto::SecretKey)); } else { is_deterministic = 1; } generate_keys_or_recover( m_keys.address.viewPublicKey, m_keys.viewSecretKey, secondary_key, is_deterministic); m_creation_timestamp = 1509321600; return like_seed; } //----------------------------------------------------------------- void AccountBase::create_read_only(const CryptoNote::AccountPublicAddress& address, const Crypto::SecretKey& viewkey) { Crypto::SecretKey zero; memset(&zero, 0, sizeof(zero)); m_keys.address = address; m_keys.spendSecretKey = zero; m_keys.viewSecretKey = viewkey; m_creation_timestamp = 1509321600; } //----------------------------------------------------------------- }
[ "32670449+monselice@users.noreply.github.com" ]
32670449+monselice@users.noreply.github.com
fa8603c109e150ed1656be307d71714416086c46
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/curl/gumtree/curl_repos_function_2454_last_repos.cpp
7f6ccbc9053d7cc1fe8724fcf6196043b46f889e
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
185
cpp
static void Curl_gskit_close(struct connectdata *conn, int sockindex) { close_one(&conn->ssl[sockindex], conn, sockindex); close_one(&conn->proxy_ssl[sockindex], conn, sockindex); }
[ "993273596@qq.com" ]
993273596@qq.com
551d1c1aff78cb1c97d83c4a8fa1675f44ae883b
1203ede9b2b6a2a0016467da79824a5e804bcdaa
/DefineVarCommand.h
12b4436f2a3b2e81c301c3174b2ee0218a9f0229
[]
no_license
GalSeidner/Flight-Gear-Simulator-Controller
a2ca24784ea3a5b0fa6f327651b109f824e5a1a6
eeadc617c1cee40b6c43a56617e9bae7db24d6af
refs/heads/master
2021-01-02T05:48:54.454020
2020-11-03T16:29:00
2020-11-03T16:29:00
239,516,649
0
0
null
null
null
null
UTF-8
C++
false
false
341
h
// // Created by gal on 22/12/2019. // #ifndef EX3_NEW__DEFINEVARCOMMAND_H_ #define EX3_NEW__DEFINEVARCOMMAND_H_ #include "Command.h" #include <iostream> class DefineVarCommand : public Command { public: /** * constructor */ DefineVarCommand(); int execute(vector<string>::iterator); }; #endif //EX3_NEW__DEFINEVARCOMMAND_H_
[ "noreply@github.com" ]
noreply@github.com
7488ade2239c85c989803b64d6dc4b5cc25f0f91
dcb68c87482166c15576e798a01b1880034c620c
/cpp_indie_studio/src/Graphics/AScene.hpp
1e0ea0cdb8c666721185ea48db45a0ffb18186d8
[]
no_license
Toinoux/Epitech
7a5cc1b954c951f765c424c176e128b6ce6f60ae
bdb86c9e679f7121890ec07f2405a0c1afa12c68
refs/heads/master
2020-03-22T21:49:13.546508
2019-03-12T16:17:49
2019-03-12T16:17:49
140,710,308
0
0
null
null
null
null
UTF-8
C++
false
false
478
hpp
/* ** EPITECH PROJECT, 2018 ** Untitled (Workspace) ** File description: ** AScene */ #pragma once #include <irr/irrlicht.h> #include "Graphics/Event.hpp" // #include "SocketManager.hpp" namespace bbm { class AScene { public: AScene(irr::IrrlichtDevice *device, MyEventReceiver &event) : _device(device), _event(event) {} virtual ~AScene() = default; virtual const std::string run() = 0; protected: irr::IrrlichtDevice *_device; MyEventReceiver &_event; }; }
[ "antoine.yvroud@epitech.eu" ]
antoine.yvroud@epitech.eu
6ff534beeeb5b6130226566f8aa61963a214e465
3019cc02f3738fafb71dc53e1764401501ea8475
/dev/so_5/rt/agent.cpp
961058fb21bbe382c85e3e87cf7eddabf82e9c4a
[ "BSD-3-Clause", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
eao197/so-5-5
a341ac895298e08479f01ac42be15b14ad11af6b
fa0c31c84d2637dce04e13a155040150d505fbbd
refs/heads/master
2021-06-11T03:38:26.141983
2020-07-04T08:39:56
2020-07-04T08:39:56
32,193,560
78
21
NOASSERTION
2018-10-15T05:38:09
2015-03-14T03:11:06
C++
UTF-8
C++
false
false
37,861
cpp
/* SObjectizer 5. */ #include <so_5/rt/h/agent.hpp> #include <so_5/rt/h/mbox.hpp> #include <so_5/rt/h/enveloped_msg.hpp> #include <so_5/rt/h/environment.hpp> #include <so_5/rt/impl/h/internal_env_iface.hpp> #include <so_5/rt/impl/h/state_listener_controller.hpp> #include <so_5/rt/impl/h/subscription_storage_iface.hpp> #include <so_5/rt/impl/h/process_unhandled_exception.hpp> #include <so_5/rt/impl/h/message_limit_internals.hpp> #include <so_5/rt/impl/h/delivery_filter_storage.hpp> #include <so_5/rt/impl/h/msg_tracing_helpers.hpp> #include <so_5/rt/impl/h/enveloped_msg_details.hpp> #include <so_5/details/h/abort_on_fatal_error.hpp> #include <so_5/h/spinlocks.hpp> #include <so_5/h/stdcpp.hpp> #include <algorithm> #include <sstream> #include <cstdlib> namespace so_5 { namespace { /*! * \since * v.5.4.0 * * \brief A helper class for temporary setting and then dropping * the ID of the current working thread. * * \note New working thread_id is set only if it is not an * null thread_id. */ struct working_thread_id_sentinel_t { so_5::current_thread_id_t & m_id; working_thread_id_sentinel_t( so_5::current_thread_id_t & id_var, so_5::current_thread_id_t value_to_set ) : m_id( id_var ) { if( value_to_set != null_current_thread_id() ) m_id = value_to_set; } ~working_thread_id_sentinel_t() { if( m_id != null_current_thread_id() ) m_id = null_current_thread_id(); } }; /*! * \since * v.5.4.0 * */ std::string create_anonymous_state_name( const agent_t * agent, const state_t * st ) { std::ostringstream ss; ss << "<state:target=" << agent << ":this=" << st << ">"; return ss.str(); } } /* namespace anonymous */ // NOTE: Implementation of state_t is moved to that file in v.5.4.0. // // state_t::time_limit_t // struct state_t::time_limit_t { struct timeout : public signal_t {}; duration_t m_limit; const state_t & m_state_to_switch; mbox_t m_unique_mbox; timer_id_t m_timer; time_limit_t( duration_t limit, const state_t & state_to_switch ) : m_limit( limit ) , m_state_to_switch( state_to_switch ) {} void set_up_limit_for_agent( agent_t & agent, const state_t & current_state ) SO_5_NOEXCEPT { // Because this method is called from on_enter handler it can't // throw exceptions. Any exception will lead to abort of the application. // So we don't care about exception safety. so_5::details::invoke_noexcept_code( [&] { // New unique mbox is necessary for time limit. m_unique_mbox = impl::internal_env_iface_t{ agent.so_environment() } // A new MPSC mbox will be used for that. .create_mpsc_mbox( // New MPSC mbox will be directly connected to target agent. &agent, // Message limits will not be used. nullptr ); // A subscription must be created for timeout signal. agent.so_subscribe( m_unique_mbox ) .in( current_state ) .event< timeout >( [&agent, this] { agent.so_change_state( m_state_to_switch ); } ); // Delayed timeout signal must be sent. m_timer = agent.so_environment().schedule_timer< timeout >( m_unique_mbox, m_limit, duration_t::zero() ); } ); } void drop_limit_for_agent( agent_t & agent, const state_t & current_state ) SO_5_NOEXCEPT { // Because this method is called from on_exit handler it can't // throw exceptions. Any exception will lead to abort of the application. // So we don't care about exception safety. so_5::details::invoke_noexcept_code( [&] { m_timer.release(); if( m_unique_mbox ) { // Old subscription must be removed. agent.so_drop_subscription< timeout >( m_unique_mbox, current_state ); // Unique mbox is no more needed. m_unique_mbox = mbox_t{}; } } ); } }; // // state_t // state_t::state_t( agent_t * target_agent, std::string state_name, state_t * parent_state, std::size_t nested_level, history_t state_history ) : m_target_agent{ target_agent } , m_state_name( std::move(state_name) ) , m_parent_state{ parent_state } , m_initial_substate{ nullptr } , m_state_history{ state_history } , m_last_active_substate{ nullptr } , m_nested_level{ nested_level } , m_substate_count{ 0 } { if( parent_state ) { // We should check the deep of nested states. if( m_nested_level >= max_deep ) SO_5_THROW_EXCEPTION( rc_state_nesting_is_too_deep, "max nesting deep for agent states is " + std::to_string( max_deep ) ); // Now we can safely mark parent state as composite. parent_state->m_substate_count += 1; } } state_t::state_t( agent_t * agent ) : state_t{ agent, history_t::none } { } state_t::state_t( agent_t * agent, history_t state_history ) : state_t{ agent, std::string(), nullptr, 0, state_history } { } state_t::state_t( agent_t * agent, std::string state_name ) : state_t{ agent, std::move(state_name), history_t::none } {} state_t::state_t( agent_t * agent, std::string state_name, history_t state_history ) : state_t{ agent, std::move(state_name), nullptr, 0, state_history } {} state_t::state_t( initial_substate_of parent ) : state_t{ parent, std::string(), history_t::none } {} state_t::state_t( initial_substate_of parent, std::string state_name ) : state_t{ parent, std::move(state_name), history_t::none } {} state_t::state_t( initial_substate_of parent, std::string state_name, history_t state_history ) : state_t{ parent.m_parent_state->m_target_agent, std::move(state_name), parent.m_parent_state, parent.m_parent_state->m_nested_level + 1, state_history } { if( m_parent_state->m_initial_substate ) SO_5_THROW_EXCEPTION( rc_initial_substate_already_defined, "initial substate for state " + m_parent_state->query_name() + " is already defined: " + m_parent_state->m_initial_substate->query_name() ); m_parent_state->m_initial_substate = this; } state_t::state_t( substate_of parent ) : state_t{ parent, std::string(), history_t::none } {} state_t::state_t( substate_of parent, std::string state_name ) : state_t{ parent, std::move(state_name), history_t::none } {} state_t::state_t( substate_of parent, std::string state_name, history_t state_history ) : state_t{ parent.m_parent_state->m_target_agent, std::move(state_name), parent.m_parent_state, parent.m_parent_state->m_nested_level + 1, state_history } {} state_t::state_t( state_t && other ) : m_target_agent( other.m_target_agent ) , m_state_name( std::move( other.m_state_name ) ) , m_parent_state{ other.m_parent_state } , m_initial_substate{ other.m_initial_substate } , m_state_history{ other.m_state_history } , m_last_active_substate{ other.m_last_active_substate } , m_nested_level{ other.m_nested_level } , m_substate_count{ other.m_substate_count } , m_on_enter{ std::move(other.m_on_enter) } , m_on_exit{ std::move(other.m_on_exit) } { if( m_parent_state && m_parent_state->m_initial_substate == &other ) m_parent_state->m_initial_substate = this; } state_t::~state_t() { } bool state_t::operator == ( const state_t & state ) const { return &state == this; } std::string state_t::query_name() const { auto getter = [this]() -> std::string { if( m_state_name.empty() ) return create_anonymous_state_name( m_target_agent, this ); else return m_state_name; }; if( m_parent_state ) return m_parent_state->query_name() + "." + getter(); else return getter(); } namespace { #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexit-time-destructors" #pragma clang diagnostic ignored "-Wglobal-constructors" #endif /*! * \since * v.5.4.0 * * \brief A special object for the state in which agent is awaiting * for deregistration after unhandled exception. * * This object will be shared between all agents. */ const state_t awaiting_deregistration_state( nullptr, "<AWAITING_DEREGISTRATION_AFTER_UNHANDLED_EXCEPTION>" ); /*! * \since * v.5.5.21 * * \brief A special object to be used as state for make subscriptions * for deadletter handlers. * * This object will be shared between all agents. */ const state_t deadletter_state( nullptr, "<DEADLETTER_STATE>" ); #if defined(__clang__) #pragma clang diagnostic pop #endif } /* namespace anonymous */ bool state_t::is_target( const agent_t * agent ) const { if( m_target_agent ) return m_target_agent == agent; else if( this == &awaiting_deregistration_state ) return true; else return false; } void state_t::activate() const { m_target_agent->so_change_state( *this ); } state_t & state_t::time_limit( duration_t timeout, const state_t & state_to_switch ) { if( duration_t::zero() == timeout ) SO_5_THROW_EXCEPTION( rc_invalid_time_limit_for_state, "zero can't be used as time limit for state: " + query_name() ); // Old time limit must be dropped if it exists. { // As a defense from exception create new time_limit object first. auto fresh_limit = stdcpp::make_unique< time_limit_t >( timeout, std::cref(state_to_switch) ); drop_time_limit(); m_time_limit = std::move(fresh_limit); } // If this state is active then new time limit must be activated. if( is_active() ) so_5::details::do_with_rollback_on_exception( [&] { m_time_limit->set_up_limit_for_agent( *m_target_agent, *this ); }, [&] { // Time limit must be dropped because it is not activated // for the current state. drop_time_limit(); } ); return *this; } state_t & state_t::drop_time_limit() { if( m_time_limit ) { m_time_limit->drop_limit_for_agent( *m_target_agent, *this ); m_time_limit.reset(); } return *this; } const state_t * state_t::actual_state_to_enter() const { const state_t * s = this; while( 0 != s->m_substate_count ) { if( s->m_last_active_substate ) // Note: for states with shallow history m_last_active_substate // can point to composite substate. This substate must be // processed usual way with checking for substate count, presence // of initial substate and so on... s = s->m_last_active_substate; else if( !s->m_initial_substate ) SO_5_THROW_EXCEPTION( rc_no_initial_substate, "there is no initial substate for composite state: " + query_name() ); else s = s->m_initial_substate; } return s; } void state_t::update_history_in_parent_states() const { auto p = m_parent_state; // This pointer will be used for update states with shallow history. // This pointer will be changed on every iteration. auto c = this; while( p ) { if( history_t::shallow == p->m_state_history ) p->m_last_active_substate = c; else if( history_t::deep == p->m_state_history ) p->m_last_active_substate = this; c = p; p = p->m_parent_state; } } void state_t::handle_time_limit_on_enter() const { m_time_limit->set_up_limit_for_agent( *m_target_agent, *this ); } void state_t::handle_time_limit_on_exit() const { m_time_limit->drop_limit_for_agent( *m_target_agent, *this ); } // // agent_t // agent_t::agent_t( environment_t & env ) : agent_t( env, tuning_options() ) { } agent_t::agent_t( environment_t & env, agent_tuning_options_t options ) : agent_t( context_t( env, std::move( options ) ) ) { } agent_t::agent_t( context_t ctx ) : m_current_state_ptr( &st_default ) , m_current_status( agent_status_t::not_defined_yet ) , m_state_listener_controller( new impl::state_listener_controller_t ) , m_handler_finder( // Actual handler finder is dependent on msg_tracing status. impl::internal_env_iface_t( ctx.env() ).is_msg_tracing_enabled() ? &agent_t::handler_finder_msg_tracing_enabled : &agent_t::handler_finder_msg_tracing_disabled ) , m_subscriptions( ctx.options().query_subscription_storage_factory()( self_ptr() ) ) , m_message_limits( message_limit::impl::info_storage_t::create_if_necessary( ctx.options().giveout_message_limits() ) ) , m_env( ctx.env() ) , m_event_queue( nullptr ) , m_direct_mbox( impl::internal_env_iface_t( ctx.env() ).create_mpsc_mbox( self_ptr(), m_message_limits.get() ) ) // It is necessary to enable agent subscription in the // constructor of derived class. , m_working_thread_id( so_5::query_current_thread_id() ) , m_agent_coop( nullptr ) , m_priority( ctx.options().query_priority() ) { } agent_t::~agent_t() { // Sometimes it is possible that agent is destroyed without // correct deregistration from SO Environment. drop_all_delivery_filters(); m_subscriptions.reset(); } void agent_t::so_evt_start() { // Default implementation do nothing. } void agent_t::so_evt_finish() { // Default implementation do nothing. } bool agent_t::so_is_active_state( const state_t & state_to_check ) const { state_t::path_t path; m_current_state_ptr->fill_path( path ); auto e = begin(path) + static_cast< state_t::path_t::difference_type >( m_current_state_ptr->nested_level() ) + 1; return e != std::find( begin(path), e, &state_to_check ); } const std::string & agent_t::so_coop_name() const { if( nullptr == m_agent_coop ) throw exception_t( "agent isn't bound to cooperation yet", rc_agent_has_no_cooperation ); return m_agent_coop->query_coop_name(); } void agent_t::so_add_nondestroyable_listener( agent_state_listener_t & state_listener ) { m_state_listener_controller->so_add_nondestroyable_listener( state_listener ); } void agent_t::so_add_destroyable_listener( agent_state_listener_unique_ptr_t state_listener ) { m_state_listener_controller->so_add_destroyable_listener( std::move( state_listener ) ); } exception_reaction_t agent_t::so_exception_reaction() const { if( m_agent_coop ) return m_agent_coop->exception_reaction(); else // This is very strange case. So it would be better to abort. return abort_on_exception; } void agent_t::so_switch_to_awaiting_deregistration_state() { so_change_state( awaiting_deregistration_state ); } const mbox_t & agent_t::so_direct_mbox() const { return m_direct_mbox; } const state_t & agent_t::so_default_state() const { return st_default; } namespace impl { class state_switch_guard_t { agent_t & m_agent; agent_t::agent_status_t m_previous_status; public : state_switch_guard_t( agent_t & agent ) : m_agent( agent ) , m_previous_status( agent.m_current_status ) { if( agent_t::agent_status_t::state_switch_in_progress == agent.m_current_status ) SO_5_THROW_EXCEPTION( rc_another_state_switch_in_progress, "an attempt to switch agent state when another state " "switch operation is in progress for the same agent" ); agent.m_current_status = agent_t::agent_status_t::state_switch_in_progress; } ~state_switch_guard_t() { m_agent.m_current_status = m_previous_status; } }; } /* namespace impl */ void agent_t::so_change_state( const state_t & new_state ) { ensure_operation_is_on_working_thread( "so_change_state" ); if( new_state.is_target( this ) ) { // Since v.5.5.18 we must check nested state switch operations. // This object will drop pointer to the current state. impl::state_switch_guard_t switch_op_guard( *this ); auto actual_new_state = new_state.actual_state_to_enter(); if( !( *actual_new_state == *m_current_state_ptr ) ) { // New state differs from the current one. // Actual state switch must be performed. do_state_switch( *actual_new_state ); // State listener should be informed. m_state_listener_controller->changed( *this, *m_current_state_ptr ); } } else SO_5_THROW_EXCEPTION( rc_agent_unknown_state, "unable to switch agent to alien state " "(the state that doesn't belong to this agent)" ); } void agent_t::so_initiate_agent_definition() { working_thread_id_sentinel_t sentinel( m_working_thread_id, so_5::query_current_thread_id() ); so_define_agent(); m_current_status = agent_status_t::defined; } void agent_t::so_define_agent() { // Default implementation do nothing. } bool agent_t::so_was_defined() const { return agent_status_t::not_defined_yet != m_current_status; } environment_t & agent_t::so_environment() const { return m_env; } void agent_t::so_bind_to_dispatcher( event_queue_t & queue ) { // We don't expect exceptions here. // And can't restore after them so_5::details::invoke_noexcept_code( [&] { // Since v.5.5.24 we should use event_queue_hook to get an // actual event_queue. auto * actual_queue = impl::internal_env_iface_t{ m_env } .event_queue_on_bind( this, &queue ); std::lock_guard< default_rw_spinlock_t > queue_lock{ m_event_queue_lock }; // Cooperation usage counter should be incremented. // It will be decremented during final agent event execution. coop_t::increment_usage_count( *m_agent_coop ); // A starting demand must be sent first. actual_queue->push( execution_demand_t( this, message_limit::control_block_t::none(), 0, typeid(void), message_ref_t(), &agent_t::demand_handler_on_start ) ); // Only then pointer to the queue could be stored. m_event_queue = actual_queue; } ); } execution_hint_t agent_t::so_create_execution_hint( execution_demand_t & d ) { enum class demand_type_t { message, service_request, enveloped_msg, other }; // We can't use message_kind_t here because there are special // demands like demands for so_evt_start/so_evt_finish. // Because of that a pointer to demand handler will be analyzed. const auto demand_type = (d.m_demand_handler == &agent_t::demand_handler_on_message ? demand_type_t::message : (d.m_demand_handler == &agent_t::demand_handler_on_service_request ? demand_type_t::service_request : (d.m_demand_handler == &agent_t::demand_handler_on_enveloped_msg ? demand_type_t::enveloped_msg : demand_type_t::other))); if( demand_type_t::other != demand_type ) { // Try to find handler for the demand. auto handler = d.m_receiver->m_handler_finder( d, "create_execution_hint" ); if( demand_type_t::message == demand_type ) { if( handler ) return execution_hint_t( d, [handler]( execution_demand_t & demand, current_thread_id_t thread_id ) { process_message( thread_id, demand, handler->m_method ); }, handler->m_thread_safety ); else // Handler not found. return execution_hint_t::create_empty_execution_hint( d ); } else if( demand_type_t::service_request == demand_type ) { // There must be a special hint for service requests // because absence of service handler processed by // different way than absence of event handler. return execution_hint_t( d, [handler]( execution_demand_t & demand, current_thread_id_t thread_id ) { process_service_request( thread_id, demand, std::make_pair( true, handler ) ); }, handler ? handler->m_thread_safety : // If there is no real handler then // there will be only error processing. // That processing is thread safe. thread_safe ); } else { // Execution hint for enveloped message is // very similar to hint for service request. return execution_hint_t( d, [handler]( execution_demand_t & demand, current_thread_id_t thread_id ) { process_enveloped_msg( thread_id, demand, handler ); }, handler ? handler->m_thread_safety : // If there is no real handler then // there will only be actions from // envelope. // These actions should be thread safe. thread_safe ); } } else // This is demand_handler_on_start or demand_handler_on_finish. return execution_hint_t( d, []( execution_demand_t & demand, current_thread_id_t thread_id ) { demand.call_handler( thread_id ); }, not_thread_safe ); } void agent_t::so_deregister_agent_coop( int dereg_reason ) { so_environment().deregister_coop( so_coop_name(), dereg_reason ); } void agent_t::so_deregister_agent_coop_normally() { so_deregister_agent_coop( dereg_reason::normal ); } agent_ref_t agent_t::create_ref() { agent_ref_t agent_ref( this ); return agent_ref; } void agent_t::bind_to_coop( coop_t & coop ) { m_agent_coop = &coop; } void agent_t::shutdown_agent() SO_5_NOEXCEPT { event_queue_t * actual_queue = nullptr; { std::lock_guard< default_rw_spinlock_t > queue_lock{ m_event_queue_lock }; // Since v.5.5.8 shutdown is done by two simple step: // - remove actual value from m_event_queue; // - pushing final demand to actual event queue. // // No new demands will be sent to the agent, but all the subscriptions // remains. They will be destroyed at the very end of agent's lifetime. if( m_event_queue ) { // This pointer will be used later. actual_queue = m_event_queue; // Final event must be pushed to queue. so_5::details::invoke_noexcept_code( [&] { m_event_queue->push( execution_demand_t( this, message_limit::control_block_t::none(), 0, typeid(void), message_ref_t(), &agent_t::demand_handler_on_finish ) ); // No more events will be stored to the queue. m_event_queue = nullptr; } ); } else so_5::details::abort_on_fatal_error( [&] { SO_5_LOG_ERROR( so_environment(), log_stream ) { log_stream << "Unexpected error: m_event_queue contains " "nullptr. Unable to push demand_handler_on_finish for " "the agent (" << this << "). Application will be aborted" << std::endl; } } ); } if( actual_queue ) // Since v.5.5.24 we should utilize event_queue via // event_queue_hook. impl::internal_env_iface_t{ m_env } .event_queue_on_unbind( this, actual_queue ); } void agent_t::so_create_event_subscription( const mbox_t & mbox_ref, std::type_index msg_type, const state_t & target_state, const event_handler_method_t & method, thread_safety_t thread_safety ) { // Since v.5.4.0 there is no need for locking agent's mutex // because this operation can be performed only on agent's // working thread. ensure_operation_is_on_working_thread( "so_create_event_subscription" ); m_subscriptions->create_event_subscription( mbox_ref, msg_type, detect_limit_for_message_type( msg_type ), target_state, method, thread_safety ); } void agent_t::so_create_deadletter_subscription( const mbox_t & mbox, const std::type_index & msg_type, const event_handler_method_t & method, thread_safety_t thread_safety ) { ensure_operation_is_on_working_thread( "so_create_deadletter_subscription" ); m_subscriptions->create_event_subscription( mbox, msg_type, detect_limit_for_message_type( msg_type ), deadletter_state, method, thread_safety ); } void agent_t::so_destroy_deadletter_subscription( const mbox_t & mbox, const std::type_index & msg_type ) { // Since v.5.4.0 there is no need for locking agent's mutex // because this operation can be performed only on agent's // working thread. ensure_operation_is_on_working_thread( "do_drop_deadletter_handler" ); m_subscriptions->drop_subscription( mbox, msg_type, deadletter_state ); } const message_limit::control_block_t * agent_t::detect_limit_for_message_type( const std::type_index & msg_type ) const { const message_limit::control_block_t * result = nullptr; if( m_message_limits ) { result = m_message_limits->find( msg_type ); if( !result ) SO_5_THROW_EXCEPTION( so_5::rc_message_has_no_limit_defined, std::string( "an attempt to subscribe to message type without " "predefined limit for that type, type: " ) + msg_type.name() ); } return result; } void agent_t::do_drop_subscription( const mbox_t & mbox, const std::type_index & msg_type, const state_t & target_state ) { // Since v.5.4.0 there is no need for locking agent's mutex // because this operation can be performed only on agent's // working thread. ensure_operation_is_on_working_thread( "do_drop_subscription" ); m_subscriptions->drop_subscription( mbox, msg_type, target_state ); } void agent_t::do_drop_subscription_for_all_states( const mbox_t & mbox, const std::type_index & msg_type ) { // Since v.5.4.0 there is no need for locking agent's mutex // because this operation can be performed only on agent's // working thread. ensure_operation_is_on_working_thread( "do_drop_subscription_for_all_states" ); m_subscriptions->drop_subscription_for_all_states( mbox, msg_type ); } bool agent_t::do_check_subscription_presence( const mbox_t & mbox, const std::type_index & msg_type, const state_t & target_state ) const SO_5_NOEXCEPT { return nullptr != m_subscriptions->find_handler( mbox->id(), msg_type, target_state ); } bool agent_t::do_check_deadletter_presence( const mbox_t & mbox, const std::type_index & msg_type ) const SO_5_NOEXCEPT { return nullptr != m_subscriptions->find_handler( mbox->id(), msg_type, deadletter_state ); } namespace { /*! * \brief A helper function to select actual demand handler in * dependency of message kind. * * \since * v.5.5.23 */ inline demand_handler_pfn_t select_demand_handler_for_message( const agent_t & agent, const message_ref_t & msg ) { demand_handler_pfn_t result = &agent_t::demand_handler_on_message; if( msg ) { switch( message_kind( *msg ) ) { case message_t::kind_t::classical_message : // Already has value. break; case message_t::kind_t::user_type_message : // Already has value. break; case message_t::kind_t::service_request : result = &agent_t::demand_handler_on_service_request; break; case message_t::kind_t::enveloped_msg : result = &agent_t::demand_handler_on_enveloped_msg; break; case message_t::kind_t::signal : so_5::details::abort_on_fatal_error( [&] { SO_5_LOG_ERROR( agent.so_environment(), log_stream ) { log_stream << "message that has data and message_kind_t::signal!" "Signals can't have data. Application will be aborted!" << std::endl; } } ); break; } } return result; } } /* namespace anonymous */ void agent_t::push_event( const message_limit::control_block_t * limit, mbox_id_t mbox_id, std::type_index msg_type, const message_ref_t & message ) { const auto handler = select_demand_handler_for_message( *this, message ); read_lock_guard_t< default_rw_spinlock_t > queue_lock{ m_event_queue_lock }; if( m_event_queue ) m_event_queue->push( execution_demand_t( this, limit, mbox_id, msg_type, message, handler ) ); } void agent_t::demand_handler_on_start( current_thread_id_t working_thread_id, execution_demand_t & d ) { d.m_receiver->ensure_binding_finished(); working_thread_id_sentinel_t sentinel( d.m_receiver->m_working_thread_id, working_thread_id ); try { d.m_receiver->so_evt_start(); } catch( const std::exception & x ) { impl::process_unhandled_exception( working_thread_id, x, *(d.m_receiver) ); } catch( ... ) // Since v.5.5.24.3 { impl::process_unhandled_unknown_exception( working_thread_id, *(d.m_receiver) ); } } void agent_t::ensure_binding_finished() { // Nothing more to do. // Just lock coop's binding_lock. If cooperation is not finished yet // it would stop the current thread. std::lock_guard< std::mutex > binding_lock{ m_agent_coop->m_binding_lock }; } demand_handler_pfn_t agent_t::get_demand_handler_on_start_ptr() SO_5_NOEXCEPT { return &agent_t::demand_handler_on_start; } void agent_t::demand_handler_on_finish( current_thread_id_t working_thread_id, execution_demand_t & d ) { { // Sentinel must finish its work before decrementing // reference count to cooperation. working_thread_id_sentinel_t sentinel( d.m_receiver->m_working_thread_id, working_thread_id ); try { d.m_receiver->so_evt_finish(); } catch( const std::exception & x ) { impl::process_unhandled_exception( working_thread_id, x, *(d.m_receiver) ); } catch( ... ) // Since v.5.5.24.3 { impl::process_unhandled_unknown_exception( working_thread_id, *(d.m_receiver) ); } // Since v.5.5.15 agent should be returned in default state. d.m_receiver->return_to_default_state_if_possible(); } // Cooperation should receive notification about agent deregistration. coop_t::decrement_usage_count( *(d.m_receiver->m_agent_coop) ); } demand_handler_pfn_t agent_t::get_demand_handler_on_finish_ptr() SO_5_NOEXCEPT { return &agent_t::demand_handler_on_finish; } void agent_t::demand_handler_on_message( current_thread_id_t working_thread_id, execution_demand_t & d ) { message_limit::control_block_t::decrement( d.m_limit ); auto handler = d.m_receiver->m_handler_finder( d, "demand_handler_on_message" ); if( handler ) process_message( working_thread_id, d, handler->m_method ); } demand_handler_pfn_t agent_t::get_demand_handler_on_message_ptr() SO_5_NOEXCEPT { return &agent_t::demand_handler_on_message; } void agent_t::demand_handler_on_service_request( current_thread_id_t working_thread_id, execution_demand_t & d ) { message_limit::control_block_t::decrement( d.m_limit ); static const impl::event_handler_data_t * const null_handler_data = nullptr; process_service_request( working_thread_id, d, std::make_pair( false, null_handler_data ) ); } demand_handler_pfn_t agent_t::get_service_request_handler_on_message_ptr() SO_5_NOEXCEPT { return &agent_t::demand_handler_on_service_request; } void agent_t::demand_handler_on_enveloped_msg( current_thread_id_t working_thread_id, execution_demand_t & d ) { message_limit::control_block_t::decrement( d.m_limit ); auto handler = d.m_receiver->m_handler_finder( d, "demand_handler_on_enveloped_msg" ); process_enveloped_msg( working_thread_id, d, handler ); } demand_handler_pfn_t agent_t::get_demand_handler_on_enveloped_msg_ptr() SO_5_NOEXCEPT { return &agent_t::demand_handler_on_enveloped_msg; } void agent_t::process_message( current_thread_id_t working_thread_id, execution_demand_t & d, event_handler_method_t method ) { working_thread_id_sentinel_t sentinel( d.m_receiver->m_working_thread_id, working_thread_id ); try { method( invocation_type_t::event, d.m_message_ref ); } catch( const std::exception & x ) { impl::process_unhandled_exception( working_thread_id, x, *(d.m_receiver) ); } catch( ... ) // Since v.5.5.24.3 { impl::process_unhandled_unknown_exception( working_thread_id, *(d.m_receiver) ); } } void agent_t::process_service_request( current_thread_id_t working_thread_id, execution_demand_t & d, std::pair< bool, const impl::event_handler_data_t * > handler_data ) { msg_service_request_base_t::dispatch_wrapper( d.m_message_ref, [&] { const impl::event_handler_data_t * handler = handler_data.first ? handler_data.second : d.m_receiver->m_handler_finder( d, "process_service_request" ); if( handler ) { working_thread_id_sentinel_t sentinel( d.m_receiver->m_working_thread_id, working_thread_id ); // This copy is necessary to prevent deallocation of // event-handler if it is implemented as lambda-function. // Deallocation is possible in such case: // // auto mbox = so_environment().create_mbox(); // so_subscribe( mbox ).event< some_signal >( [this, mbox] { // so_drop_subscription< some_signal >( mbox ); // ... // Some other actions. // } ); auto method_to_call = handler->m_method; method_to_call( invocation_type_t::service_request, d.m_message_ref ); } else SO_5_THROW_EXCEPTION( so_5::rc_svc_not_handled, "service request handler is not found for " "the current agent state; state: " + d.m_receiver->so_current_state().query_name() + ", msg_type: " + d.m_msg_type.name() ); } ); } void agent_t::process_enveloped_msg( current_thread_id_t working_thread_id, execution_demand_t & d, const impl::event_handler_data_t * handler_data ) { using namespace enveloped_msg::impl; // We don't expect exceptions here and can't restore after them. so_5::details::invoke_noexcept_code( [&] { auto & envelope = message_to_envelope( d.m_message_ref ); if( handler_data ) { agent_demand_handler_invoker_t invoker{ working_thread_id, d, *handler_data }; envelope.access_hook( so_5::enveloped_msg::access_context_t::handler_found, invoker ); } } ); } void agent_t::ensure_operation_is_on_working_thread( const char * operation_name ) const { if( so_5::query_current_thread_id() != m_working_thread_id ) { std::ostringstream s; s << operation_name << ": operation is enabled only on agent's working thread; " << "working_thread_id: " << m_working_thread_id << ", current_thread_id: " << so_5::query_current_thread_id(); SO_5_THROW_EXCEPTION( so_5::rc_operation_enabled_only_on_agent_working_thread, s.str() ); } } void agent_t::drop_all_delivery_filters() SO_5_NOEXCEPT { if( m_delivery_filters ) { m_delivery_filters->drop_all( *this ); m_delivery_filters.reset(); } } void agent_t::do_set_delivery_filter( const mbox_t & mbox, const std::type_index & msg_type, delivery_filter_unique_ptr_t filter ) { ensure_operation_is_on_working_thread( "set_delivery_filter" ); if( !m_delivery_filters ) m_delivery_filters.reset( new impl::delivery_filter_storage_t() ); m_delivery_filters->set_delivery_filter( mbox, msg_type, std::move(filter), *this ); } void agent_t::do_drop_delivery_filter( const mbox_t & mbox, const std::type_index & msg_type ) SO_5_NOEXCEPT { ensure_operation_is_on_working_thread( "set_delivery_filter" ); if( m_delivery_filters ) m_delivery_filters->drop_delivery_filter( mbox, msg_type, *this ); } const impl::event_handler_data_t * agent_t::handler_finder_msg_tracing_disabled( execution_demand_t & d, const char * /*context_marker*/ ) { auto search_result = find_event_handler_for_current_state( d ); if( !search_result ) // Since v.5.5.21 we should check for deadletter handler for that demand. search_result = find_deadletter_handler( d ); return search_result; } const impl::event_handler_data_t * agent_t::handler_finder_msg_tracing_enabled( execution_demand_t & d, const char * context_marker ) { auto search_result = find_event_handler_for_current_state( d ); if( !search_result ) { // Since v.5.5.21 we should check for deadletter handler for that demand. search_result = find_deadletter_handler( d ); if( search_result ) { // Deadletter handler found. This must be reflected in trace. impl::msg_tracing_helpers::trace_deadletter_handler_search_result( d, context_marker, search_result ); return search_result; } } // This trace will be made if an event_handler is found for the // current state or not found at all (including deadletter handlers). impl::msg_tracing_helpers::trace_event_handler_search_result( d, context_marker, search_result ); return search_result; } const impl::event_handler_data_t * agent_t::find_event_handler_for_current_state( execution_demand_t & d ) { const impl::event_handler_data_t * search_result = nullptr; const state_t * s = &d.m_receiver->so_current_state(); do { search_result = d.m_receiver->m_subscriptions->find_handler( d.m_mbox_id, d.m_msg_type, *s ); if( !search_result ) s = s->parent_state(); } while( search_result == nullptr && s != nullptr ); return search_result; } const impl::event_handler_data_t * agent_t::find_deadletter_handler( execution_demand_t & demand ) { return demand.m_receiver->m_subscriptions->find_handler( demand.m_mbox_id, demand.m_msg_type, deadletter_state ); } void agent_t::do_state_switch( const state_t & state_to_be_set ) SO_5_NOEXCEPT { state_t::path_t old_path; state_t::path_t new_path; // Since v.5.5.22 we will change the value of m_current_state_ptr // during state change procedure. auto current_st = m_current_state_ptr; current_st->fill_path( old_path ); state_to_be_set.fill_path( new_path ); // Find the first item which is different in the paths. std::size_t first_diff = 0; for(; first_diff < std::min( current_st->nested_level(), state_to_be_set.nested_level() ); ++first_diff ) if( old_path[ first_diff ] != new_path[ first_diff ] ) break; // Do call for on_exit and on_enter for states. // on_exit and on_enter should not throw exceptions. so_5::details::invoke_noexcept_code( [&] { impl::msg_tracing_helpers::safe_trace_state_leaving( *this, *current_st ); for( std::size_t i = current_st->nested_level(); i >= first_diff; ) { // Modify current state before calling on_exit handler. m_current_state_ptr = old_path[ i ]; // Perform on_exit actions. old_path[ i ]->call_on_exit(); if( i ) --i; else break; } impl::msg_tracing_helpers::safe_trace_state_entering( *this, state_to_be_set ); for( std::size_t i = first_diff; i <= state_to_be_set.nested_level(); ++i ) { // Modify current state before calling on_exit handler. m_current_state_ptr = new_path[ i ]; // Perform on_enter actions. new_path[ i ]->call_on_enter(); } } ); // Now the current state for the agent can be changed. m_current_state_ptr = &state_to_be_set; m_current_state_ptr->update_history_in_parent_states(); } void agent_t::return_to_default_state_if_possible() SO_5_NOEXCEPT { if( !( st_default == so_current_state() || awaiting_deregistration_state == so_current_state() ) ) { // The agent must be returned to the default state. // All on_exit handlers must be called at this point. so_change_state( st_default ); } } } /* namespace so_5 */
[ "eao197@1d1731ae-3f85-447d-88f8-c72b288064d1" ]
eao197@1d1731ae-3f85-447d-88f8-c72b288064d1
1bd6ca2f007b5f32b354143d816e8e28928aeeca
b4f0a634eff571b6bf4fb233122044042af8932d
/runAsDaemon.cc
233bd0f30e21e183591e0266f5271c45bdcb5707
[]
no_license
tinester/Unix_Daemon
f63a9991adce10f932e345c99411dae3011abcc5
b71a29c19d8971655bed49e828cbd2f861d2f29f
refs/heads/master
2020-04-03T00:10:16.606985
2018-10-26T20:33:39
2018-10-26T20:33:39
154,891,255
0
0
null
null
null
null
UTF-8
C++
false
false
3,466
cc
/* Zach Eagan zse150030@utdallas.edu CS 3376.002 */ #include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/inotify.h> #include <string> #include <map> #include <algorithm> #include <unistd.h> #include <signal.h> #include <string.h> #include "prog5.h" using namespace std; #define EVENT_SIZE ( sizeof (struct inotify_event) ) #define BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) ) int runAsDaemon(map<int, string> confMap) { // create a forkValue for use in event handling pid_t forkValue; // Initialize signal handler struct struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = sigHandler; sigaction(SIGINT, &act, 0); sigaction(SIGTERM, &act, 0); sigaction(SIGHUP, &act, 0); //Initialize inotify stuff int length, i = 0; int fd; int wd; char buffer[BUF_LEN]; // Open log file ofstream myfile; myfile.open(confMap[LOGFILE].c_str()); myfile << "Running in daemon mode" << endl; // Create the pid file ofstream pidfile; pidfile.open("cs3376dirmond.pid"); pidfile << getpid(); pidfile.close(); // buncha inotify stuff fd = inotify_init(); if ( fd < 0 ) { perror( "inotify_init" ); } wd = inotify_add_watch( fd, confMap[WATCHDIR].c_str(), IN_MODIFY); // killed is a global boolean variable while(!killed) { length = read( fd, buffer, BUF_LEN ); if ( length < 0 ) { perror( "read" ); } while(i < length) { myfile << "evaluating an event in " << confMap[WATCHDIR] << endl; struct inotify_event *event = (struct inotify_event *) &buffer[i]; if(event->len) { if(event->mask & IN_MODIFY) { // Spawn a child process to handle a modification event in // the watched directory forkValue = fork(); // Handle event if you're the child then exit if(forkValue == 0) { // Logs modification string nameTmp = event->name; myfile << "modified " << nameTmp << endl; // Prepares a date string (for testing just print to file to see if works) FILE *streamDate; char dateBuff[1000]; string dateCmd = "date --rfc-3339='seconds'"; string modFile = event->name; streamDate = popen(dateCmd.c_str(), "r"); // dateBuff has the date as a cstring fgets(dateBuff, 1000, streamDate); string date = dateBuff; replace(date.begin(), date.end(), ' ', '-'); replace(date.begin(), date.end(), '\n', '\0'); pclose(streamDate); string verFileName = nameTmp + "." + date; myfile << "the modified file name is " << verFileName << endl; string cpFileCmd = "cp " + confMap[WATCHDIR] + '/' + nameTmp + " " + confMap[WATCHDIR] + "/.versions/" + verFileName; // for testing myfile << "cpFileCmd is " << cpFileCmd << endl; system(cpFileCmd.c_str()); return 0; } else if(forkValue == -1) { myfile << "Error in forking and responding to modification event. Exiting..." << endl; return 1; } // Continue this program if you're the parent } } i += EVENT_SIZE + event->len; } // Reset Counter i = 0; } // close inotify and log file (void)inotify_rm_watch(fd, wd); (void)close(fd); myfile.close(); return 0; }
[ "tinester777@gmail.com" ]
tinester777@gmail.com
c36c33e7df759b8d694f3d1fbdbbfa6064350713
8b66e989a5e792d94335915a8b5c85b2daaab541
/tagEditWidget/renamethread.h
6eef14639636e7ccf0c085700c9f584c45d2809b
[]
no_license
piyuanyuan1/VmSplitTool
a2d1471dc5b53da09a4cb9ffa6f774c547c194d2
8df5a628df2ea424521d02954e83aba0f8dc344f
refs/heads/master
2022-06-04T21:35:40.158967
2020-05-01T11:28:59
2020-05-01T11:28:59
259,931,470
0
0
null
null
null
null
UTF-8
C++
false
false
713
h
#ifndef RENAMETHREAD_H #define RENAMETHREAD_H #include <QObject> #include <QThread> #include <QStringList> #include <QDir> #include <QFile> #include <QDebug> #include <QDate> #include <QProcess> #include <QString> #include <QCoreApplication> class renameThread : public QThread { Q_OBJECT public: explicit renameThread(QObject *parent = nullptr); void threadInit(QStringList fileList,QStringList tagList,QString collectionStr,QString saveDir); private: void run(); QProcess *process; QStringList fileNameList; QStringList tagList; QString collectionStr; QString saveDir; signals: void renameFinished(); void renameProgress(int progress); }; #endif // RENAMETHREAD_H
[ "piyuanyuan1@gmail.com" ]
piyuanyuan1@gmail.com
d9aea63e20ca54a97db3720fe3eab8a8c7821b2f
e12ec6b3f8f17fe8906e5f96b2c3f7eb9405988a
/Grid.h
679a0b6d01e1c0f762f43c7976ce107d6d6a5494
[]
no_license
sachin-sanil/Neumann-BC
dec472bcdd3608d992bb57b416149cd065aa7e34
46a4480af10ea68ffa1c333500825c66ea57015d
refs/heads/master
2021-01-01T03:54:38.203496
2016-05-09T18:09:38
2016-05-09T18:09:38
58,397,519
1
0
null
null
null
null
UTF-8
C++
false
false
989
h
// $Id$ /** * @file ./EDIT * @brief Definitions of Grid_int class * @author Mayank, Sachin, Shivang, Vinayak * @author Mat. No. : 22040622 EDIT */ ///@brief Grid_int Class Declarations in header file Grid_int.h. Grid generation and applying boundary conditions. /// Class definitions in Grid_int.cpp #ifndef GRID_H #define GRID_H #include<iostream> #include<vector> #include<cmath> /// @param h= grid spacing /// @param ngp= number of grid points in one row = (2^l+1). /// @param level = level of multigrid = l /// @param frc = force vector /// @param u_app = U approximation vector /// @param res = residual vector class Grid { double h,level,ngp; public: ///@brief Constructor Declarations. ///@param = l_level Local grid level Grid(int l_level); std::vector<double> frc; std::vector<double> u_app; std::vector<double> res; /// To access private data menbers /// double get_hValue(); double get_ngpValue(); std::vector<double> get_u_app(); }; #endif
[ "yx11ufeg@stud.informatik.uni-erlangen.de" ]
yx11ufeg@stud.informatik.uni-erlangen.de
e75581a9fc7b15a5314bdeef874b0616cc7cafc2
09399557a4f051e170c185094075dd1389cf16b0
/InvaderV4.7/export/windows/cpp/obj/src/flixel/tweens/misc/VarTween.cpp
79c4903c92ae91843c115ff84e78015875459b8e
[]
no_license
XweetyK/Space-Invaders
b737ea731a0356fed61cb8d1ce0ab490cfca4415
a7e14890a1799e1cb4db9458b7d1be5dafe20df9
refs/heads/master
2021-01-21T05:10:05.906530
2017-10-04T18:46:17
2017-10-04T18:46:17
101,913,055
0
0
null
null
null
null
UTF-8
C++
false
true
11,773
cpp
// Generated by Haxe 3.4.2 (git build master @ 890f8c7) #include <hxcpp.h> #ifndef INCLUDED_95f339a1d026d52c #define INCLUDED_95f339a1d026d52c #include "hxMath.h" #endif #ifndef INCLUDED_Reflect #include <Reflect.h> #endif #ifndef INCLUDED_flixel_FlxBasic #include <flixel/FlxBasic.h> #endif #ifndef INCLUDED_flixel_tweens_FlxTween #include <flixel/tweens/FlxTween.h> #endif #ifndef INCLUDED_flixel_tweens_FlxTweenManager #include <flixel/tweens/FlxTweenManager.h> #endif #ifndef INCLUDED_flixel_tweens_misc_VarTween #include <flixel/tweens/misc/VarTween.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_a4370a0a6fec63c7_8_new,"flixel.tweens.misc.VarTween","new",0x19cf09e4,"flixel.tweens.misc.VarTween.new","flixel/tweens/misc/VarTween.hx",8,0x836bddcb) HX_LOCAL_STACK_FRAME(_hx_pos_a4370a0a6fec63c7_18_destroy,"flixel.tweens.misc.VarTween","destroy",0xef76787e,"flixel.tweens.misc.VarTween.destroy","flixel/tweens/misc/VarTween.hx",18,0x836bddcb) HX_LOCAL_STACK_FRAME(_hx_pos_a4370a0a6fec63c7_37_tween,"flixel.tweens.misc.VarTween","tween",0xf3504cef,"flixel.tweens.misc.VarTween.tween","flixel/tweens/misc/VarTween.hx",37,0x836bddcb) HX_LOCAL_STACK_FRAME(_hx_pos_a4370a0a6fec63c7_57_update,"flixel.tweens.misc.VarTween","update",0x50d41705,"flixel.tweens.misc.VarTween.update","flixel/tweens/misc/VarTween.hx",57,0x836bddcb) HX_LOCAL_STACK_FRAME(_hx_pos_a4370a0a6fec63c7_84_initializeVars,"flixel.tweens.misc.VarTween","initializeVars",0x0a5a5e18,"flixel.tweens.misc.VarTween.initializeVars","flixel/tweens/misc/VarTween.hx",84,0x836bddcb) namespace flixel{ namespace tweens{ namespace misc{ void VarTween_obj::__construct( ::Dynamic Options, ::flixel::tweens::FlxTweenManager manager){ HX_STACKFRAME(&_hx_pos_a4370a0a6fec63c7_8_new) HXLINE( 12) this->_propertyInfos = ::Array_obj< ::Dynamic>::__new(0); HXLINE( 26) super::__construct(Options,manager); } Dynamic VarTween_obj::__CreateEmpty() { return new VarTween_obj; } void *VarTween_obj::_hx_vtable = 0; Dynamic VarTween_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< VarTween_obj > _hx_result = new VarTween_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool VarTween_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x0734951c) { return inClassId==(int)0x00000001 || inClassId==(int)0x0734951c; } else { return inClassId==(int)0x123505a1; } } void VarTween_obj::destroy(){ HX_STACKFRAME(&_hx_pos_a4370a0a6fec63c7_18_destroy) HXLINE( 19) this->super::destroy(); HXLINE( 20) this->_object = null(); HXLINE( 21) this->_properties = null(); } ::flixel::tweens::misc::VarTween VarTween_obj::tween( ::Dynamic object, ::Dynamic properties,Float duration){ HX_STACKFRAME(&_hx_pos_a4370a0a6fec63c7_37_tween) HXLINE( 49) this->_object = object; HXLINE( 50) this->_properties = properties; HXLINE( 51) this->duration = duration; HXLINE( 52) this->start(); HXLINE( 53) return hx::ObjectPtr<OBJ_>(this); } HX_DEFINE_DYNAMIC_FUNC3(VarTween_obj,tween,return ) void VarTween_obj::update(Float elapsed){ HX_STACKFRAME(&_hx_pos_a4370a0a6fec63c7_57_update) HXLINE( 58) Float delay; HXDLIN( 58) if ((this->executions > (int)0)) { HXLINE( 58) delay = this->loopDelay; } else { HXLINE( 58) delay = this->startDelay; } HXLINE( 60) if ((this->_secondsSinceStart < delay)) { HXLINE( 63) this->super::update(elapsed); } else { HXLINE( 67) if ((this->_propertyInfos->length == (int)0)) { HXLINE( 71) this->initializeVars(); } HXLINE( 74) this->super::update(elapsed); HXLINE( 76) { HXLINE( 76) int _g = (int)0; HXDLIN( 76) ::Array< ::Dynamic> _g1 = this->_propertyInfos; HXDLIN( 76) while((_g < _g1->length)){ HXLINE( 76) ::Dynamic info = _g1->__get(_g); HXDLIN( 76) _g = (_g + (int)1); HXLINE( 78) ::Dynamic _hx_tmp = this->_object; HXDLIN( 78) ::String info1 = ( (::String)(info->__Field(HX_("name",4b,72,ff,48),hx::paccDynamic)) ); HXDLIN( 78) Float info2 = ( (Float)(info->__Field(HX_("startValue",af,57,cf,4d),hx::paccDynamic)) ); HXDLIN( 78) ::Reflect_obj::setProperty(_hx_tmp,info1,(info2 + (( (Float)(info->__Field(HX_("range",bd,a5,1f,e4),hx::paccDynamic)) ) * this->scale))); } } } } void VarTween_obj::initializeVars(){ HX_STACKFRAME(&_hx_pos_a4370a0a6fec63c7_84_initializeVars) HXLINE( 85) ::Array< ::String > fields; HXLINE( 87) if (::Reflect_obj::isObject(this->_properties)) { HXLINE( 89) fields = ::Reflect_obj::fields(this->_properties); } else { HXLINE( 93) HX_STACK_DO_THROW(HX_("Unsupported properties container - use an object containing key/value pairs.",0b,19,89,5b)); } HXLINE( 96) { HXLINE( 96) int _g = (int)0; HXDLIN( 96) while((_g < fields->length)){ HXLINE( 96) ::String p = fields->__get(_g); HXDLIN( 96) _g = (_g + (int)1); HXLINE( 98) if (hx::IsNull( ::Reflect_obj::getProperty(this->_object,p) )) { HXLINE( 100) HX_STACK_DO_THROW(((HX_("The Object does not have the property \"",3c,1e,c1,a6) + p) + HX_("\"",22,00,00,00))); } HXLINE( 103) ::Dynamic a = ::Reflect_obj::getProperty(this->_object,p); HXLINE( 105) if (::Math_obj::isNaN(( (Float)(a) ))) { HXLINE( 107) HX_STACK_DO_THROW(((HX_("The property \"",06,e3,80,a4) + p) + HX_("\" is not numeric.",66,4f,2a,cf))); } HXLINE( 110) ::Array< ::Dynamic> _hx_tmp = this->_propertyInfos; HXDLIN( 110) _hx_tmp->push( ::Dynamic(hx::Anon_obj::Create(3) ->setFixed(0,HX_("range",bd,a5,1f,e4),(::Reflect_obj::getProperty(this->_properties,p) - a)) ->setFixed(1,HX_("name",4b,72,ff,48),p) ->setFixed(2,HX_("startValue",af,57,cf,4d),( (Float)(a) )))); } } } HX_DEFINE_DYNAMIC_FUNC0(VarTween_obj,initializeVars,(void)) hx::ObjectPtr< VarTween_obj > VarTween_obj::__new( ::Dynamic Options, ::flixel::tweens::FlxTweenManager manager) { hx::ObjectPtr< VarTween_obj > __this = new VarTween_obj(); __this->__construct(Options,manager); return __this; } hx::ObjectPtr< VarTween_obj > VarTween_obj::__alloc(hx::Ctx *_hx_ctx, ::Dynamic Options, ::flixel::tweens::FlxTweenManager manager) { VarTween_obj *__this = (VarTween_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(VarTween_obj), true, "flixel.tweens.misc.VarTween")); *(void **)__this = VarTween_obj::_hx_vtable; __this->__construct(Options,manager); return __this; } VarTween_obj::VarTween_obj() { } void VarTween_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(VarTween); HX_MARK_MEMBER_NAME(_object,"_object"); HX_MARK_MEMBER_NAME(_properties,"_properties"); HX_MARK_MEMBER_NAME(_propertyInfos,"_propertyInfos"); ::flixel::tweens::FlxTween_obj::__Mark(HX_MARK_ARG); HX_MARK_END_CLASS(); } void VarTween_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(_object,"_object"); HX_VISIT_MEMBER_NAME(_properties,"_properties"); HX_VISIT_MEMBER_NAME(_propertyInfos,"_propertyInfos"); ::flixel::tweens::FlxTween_obj::__Visit(HX_VISIT_ARG); } hx::Val VarTween_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"tween") ) { return hx::Val( tween_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"update") ) { return hx::Val( update_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"_object") ) { return hx::Val( _object ); } if (HX_FIELD_EQ(inName,"destroy") ) { return hx::Val( destroy_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"_properties") ) { return hx::Val( _properties ); } break; case 14: if (HX_FIELD_EQ(inName,"_propertyInfos") ) { return hx::Val( _propertyInfos ); } if (HX_FIELD_EQ(inName,"initializeVars") ) { return hx::Val( initializeVars_dyn() ); } } return super::__Field(inName,inCallProp); } hx::Val VarTween_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 7: if (HX_FIELD_EQ(inName,"_object") ) { _object=inValue.Cast< ::Dynamic >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"_properties") ) { _properties=inValue.Cast< ::Dynamic >(); return inValue; } break; case 14: if (HX_FIELD_EQ(inName,"_propertyInfos") ) { _propertyInfos=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void VarTween_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("_object","\x5e","\x90","\xb6","\x83")); outFields->push(HX_HCSTRING("_properties","\x12","\xc9","\x98","\x33")); outFields->push(HX_HCSTRING("_propertyInfos","\xf1","\xeb","\xad","\x46")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo VarTween_obj_sMemberStorageInfo[] = { {hx::fsObject /*Dynamic*/ ,(int)offsetof(VarTween_obj,_object),HX_HCSTRING("_object","\x5e","\x90","\xb6","\x83")}, {hx::fsObject /*Dynamic*/ ,(int)offsetof(VarTween_obj,_properties),HX_HCSTRING("_properties","\x12","\xc9","\x98","\x33")}, {hx::fsObject /*cpp::ArrayBase*/ ,(int)offsetof(VarTween_obj,_propertyInfos),HX_HCSTRING("_propertyInfos","\xf1","\xeb","\xad","\x46")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *VarTween_obj_sStaticStorageInfo = 0; #endif static ::String VarTween_obj_sMemberFields[] = { HX_HCSTRING("_object","\x5e","\x90","\xb6","\x83"), HX_HCSTRING("_properties","\x12","\xc9","\x98","\x33"), HX_HCSTRING("_propertyInfos","\xf1","\xeb","\xad","\x46"), HX_HCSTRING("destroy","\xfa","\x2c","\x86","\x24"), HX_HCSTRING("tween","\x6b","\xaa","\x70","\x19"), HX_HCSTRING("update","\x09","\x86","\x05","\x87"), HX_HCSTRING("initializeVars","\x1c","\x71","\xd8","\x51"), ::String(null()) }; static void VarTween_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(VarTween_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void VarTween_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(VarTween_obj::__mClass,"__mClass"); }; #endif hx::Class VarTween_obj::__mClass; void VarTween_obj::__register() { hx::Object *dummy = new VarTween_obj; VarTween_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("flixel.tweens.misc.VarTween","\xf2","\x87","\x4b","\x0a"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = VarTween_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(VarTween_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< VarTween_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = VarTween_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = VarTween_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = VarTween_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace flixel } // end namespace tweens } // end namespace misc
[ "xweetyk@gmail.com" ]
xweetyk@gmail.com
17529aa1876d3495f82527db35ee7cad64666732
0eb84ec824fb34c18a87a4b50292d6cb41d15511
/ComponentWebotsMpsDocking/smartsoft/src-gen/ComponentWebotsMpsDocking.hh
b976fe23dd440ef5fad6e76a7798fce00823869e
[]
no_license
SiChiTong/ComponentRepository
1a75ef4b61e37be63b6c5ec217bfb39587eecb80
19b79ae0112c65dddabcc1209f64c813c68b90d6
refs/heads/master
2023-07-12T13:01:10.615767
2021-08-25T09:59:28
2021-08-25T09:59:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,804
hh
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #ifndef _COMPONENTWEBOTSMPSDOCKING_HH #define _COMPONENTWEBOTSMPSDOCKING_HH #include <map> #include <iostream> #include "aceSmartSoft.hh" #include "smartQueryServerTaskTrigger_T.h" #include "ComponentWebotsMpsDockingCore.hh" #include "ComponentWebotsMpsDockingPortFactoryInterface.hh" #include "ComponentWebotsMpsDockingExtension.hh" // forward declarations class ComponentWebotsMpsDockingPortFactoryInterface; class ComponentWebotsMpsDockingExtension; // includes for PlainOpcUaComponentWebotsMpsDockingExtension // include plain OPC UA device clients // include plain OPC UA status servers // include communication objects #include <CommBasicObjects/CommBaseState.hh> #include <CommBasicObjects/CommBaseStateACE.hh> #include <CommBasicObjects/CommMobileLaserScan.hh> #include <CommBasicObjects/CommMobileLaserScanACE.hh> #include <CommBasicObjects/CommNavigationVelocity.hh> #include <CommBasicObjects/CommNavigationVelocityACE.hh> #include <CommRobotinoObjects/CommRobotinoDockingEventParameter.hh> #include <CommRobotinoObjects/CommRobotinoDockingEventParameterACE.hh> #include <CommRobotinoObjects/CommRobotinoDockingEventResult.hh> #include <CommRobotinoObjects/CommRobotinoDockingEventResultACE.hh> #include <CommBasicObjects/CommTrafficLights.hh> #include <CommBasicObjects/CommTrafficLightsACE.hh> #include <CommRobotinoObjects/RobotinoDockingEventState.hh> #include <CommRobotinoObjects/RobotinoDockingEventStateACE.hh> // include tasks #include "DockingTask.hh" // include UpcallManagers and InputCollectors #include "BaseStateServiceInUpcallManager.hh" #include "BaseStateServiceInInputCollector.hh" #include "LaserServiceInUpcallManager.hh" #include "LaserServiceInInputCollector.hh" // include input-handler(s) // include request-handler(s) // output port wrappers #include "NavigationVelocityServiceOutWrapper.hh" #include "TrafficLightsServiceOutWrapper.hh" #include "RobotDockingEventServiceOutWrapper.hh" // include handler #include "CompHandler.hh" #include "ParameterStateStruct.hh" #include "ParameterUpdateHandler.hh" #include "SmartStateChangeHandler.hh" #include "StateActivityManager.hh" #define COMP ComponentWebotsMpsDocking::instance() class ComponentWebotsMpsDocking : public ComponentWebotsMpsDockingCore { private: static ComponentWebotsMpsDocking *_componentWebotsMpsDocking; // constructor ComponentWebotsMpsDocking(); // copy-constructor ComponentWebotsMpsDocking(const ComponentWebotsMpsDocking& cc); // destructor ~ComponentWebotsMpsDocking() { }; // load parameter from ini file void loadParameter(int argc, char* argv[]); // instantiate comp-handler CompHandler compHandler; // helper method that maps a string-name to an according TaskTriggerSubject Smart::TaskTriggerSubject* getInputTaskTriggerFromString(const std::string &client); // internal map storing the different port-creation factories (that internally map to specific middleware implementations) std::map<std::string, ComponentWebotsMpsDockingPortFactoryInterface*> portFactoryRegistry; // internal map storing various extensions of this component class std::map<std::string, ComponentWebotsMpsDockingExtension*> componentExtensionRegistry; public: ParameterStateStruct getGlobalState() const { return paramHandler.getGlobalState(); } ParameterStateStruct getParameters() const { return paramHandler.getGlobalState(); } // define tasks Smart::TaskTriggerSubject* dockingTaskTrigger; DockingTask *dockingTask; // define input-ports // InputPort BaseStateServiceIn Smart::IPushClientPattern<CommBasicObjects::CommBaseState> *baseStateServiceIn; Smart::InputTaskTrigger<CommBasicObjects::CommBaseState> *baseStateServiceInInputTaskTrigger; BaseStateServiceInUpcallManager *baseStateServiceInUpcallManager; BaseStateServiceInInputCollector *baseStateServiceInInputCollector; // InputPort LaserServiceIn Smart::IPushClientPattern<CommBasicObjects::CommMobileLaserScan> *laserServiceIn; Smart::InputTaskTrigger<CommBasicObjects::CommMobileLaserScan> *laserServiceInInputTaskTrigger; LaserServiceInUpcallManager *laserServiceInUpcallManager; LaserServiceInInputCollector *laserServiceInInputCollector; // define request-ports // define input-handler // define output-ports Smart::ISendClientPattern<CommBasicObjects::CommNavigationVelocity> *navigationVelocityServiceOut; NavigationVelocityServiceOutWrapper *navigationVelocityServiceOutWrapper; Smart::IEventServerPattern<CommRobotinoObjects::CommRobotinoDockingEventParameter, CommRobotinoObjects::CommRobotinoDockingEventResult, CommRobotinoObjects::RobotinoDockingEventState> *robotDockingEventServiceOut; RobotDockingEventServiceOutWrapper *robotDockingEventServiceOutWrapper; std::shared_ptr<Smart::IEventTestHandler<CommRobotinoObjects::CommRobotinoDockingEventParameter, CommRobotinoObjects::CommRobotinoDockingEventResult, CommRobotinoObjects::RobotinoDockingEventState>> robotDockingEventServiceOutEventTestHandler; Smart::IPushServerPattern<CommBasicObjects::CommTrafficLights> *trafficLightsServiceOut; TrafficLightsServiceOutWrapper *trafficLightsServiceOutWrapper; // define answer-ports // define request-handlers // define default slave ports SmartACE::StateSlave *stateSlave; StateActivityManager *stateActivityManager; SmartStateChangeHandler *stateChangeHandler; SmartACE::WiringSlave *wiringSlave; ParamUpdateHandler paramHandler; SmartACE::ParameterSlave *param; /// this method is used to register different PortFactory classes (one for each supported middleware framework) void addPortFactory(const std::string &name, ComponentWebotsMpsDockingPortFactoryInterface *portFactory); SmartACE::SmartComponent* getComponentImpl(); /// this method is used to register different component-extension classes void addExtension(ComponentWebotsMpsDockingExtension *extension); /// this method allows to access the registered component-extensions (automatically converting to the actuall implementation type) template <typename T> T* getExtension(const std::string &name) { auto it = componentExtensionRegistry.find(name); if(it != componentExtensionRegistry.end()) { return dynamic_cast<T*>(it->second); } return 0; } /// initialize component's internal members void init(int argc, char *argv[]); /// execute the component's infrastructure void run(); /// clean-up component's resources void fini(); /// call this method to set the overall component into the Alive state (i.e. component is then ready to operate) void setStartupFinished(); /// connect all component's client ports Smart::StatusCode connectAndStartAllServices(); /// start all assocuated Activities void startAllTasks(); /// start all associated timers void startAllTimers(); Smart::StatusCode connectBaseStateServiceIn(const std::string &serverName, const std::string &serviceName); Smart::StatusCode connectLaserServiceIn(const std::string &serverName, const std::string &serviceName); Smart::StatusCode connectNavigationVelocityServiceOut(const std::string &serverName, const std::string &serviceName); // return singleton instance static ComponentWebotsMpsDocking* instance() { if(_componentWebotsMpsDocking == 0) { _componentWebotsMpsDocking = new ComponentWebotsMpsDocking(); } return _componentWebotsMpsDocking; } static void deleteInstance() { if(_componentWebotsMpsDocking != 0) { delete _componentWebotsMpsDocking; } } // connections parameter struct connections_struct { // component struct struct component_struct { // the name of the component std::string name; std::string initialComponentMode; std::string defaultScheduler; bool useLogger; } component; //--- task parameter --- struct DockingTask_struct { double minActFreq; double maxActFreq; std::string trigger; // only one of the following two params is // actually used at run-time according // to the system config model double periodicActFreq; // or std::string inPortRef; int prescale; // scheduling parameters std::string scheduler; int priority; int cpuAffinity; } dockingTask; //--- upcall parameter --- //--- server port parameter --- struct RobotDockingEventServiceOut_struct { std::string serviceName; std::string roboticMiddleware; } robotDockingEventServiceOut; struct TrafficLightsServiceOut_struct { std::string serviceName; std::string roboticMiddleware; } trafficLightsServiceOut; //--- client port parameter --- struct BaseStateServiceIn_struct { bool initialConnect; std::string serverName; std::string serviceName; std::string wiringName; long interval; std::string roboticMiddleware; } baseStateServiceIn; struct LaserServiceIn_struct { bool initialConnect; std::string serverName; std::string serviceName; std::string wiringName; long interval; std::string roboticMiddleware; } laserServiceIn; struct NavigationVelocityServiceOut_struct { bool initialConnect; std::string serverName; std::string serviceName; std::string wiringName; long interval; std::string roboticMiddleware; } navigationVelocityServiceOut; } connections; }; #endif
[ "matthias@mlutz.de" ]
matthias@mlutz.de
8235bf63456e5f23da49f4e1ed06d2ea40518960
23088e38e0c1376be12f9b7609365a4fb7638286
/ABC/71/A_Meal_delivery.cc
d50e52fc4b6417452484b824a93d0c2659092758
[]
no_license
yukoku/AtCoder
84d508baed54ca5e421f017926061e92eea96bef
4e832122cbc035fb2783fa04126288f56f917b52
refs/heads/master
2020-03-30T07:46:25.167963
2019-07-20T11:14:04
2019-07-20T11:14:04
150,965,837
0
0
null
null
null
null
UTF-8
C++
false
false
332
cc
#include<bits/stdc++.h> constexpr long long INFL = 1LL << 60; constexpr int INF = 1e9; using namespace std; using ll = long long; using P = pair<int, int>; int main() { int x,a,b; cin >> x >> a >> b; if(abs(x-a) > abs(x-b)){ cout << "B" << endl; }else{ cout << "A" << endl; } return 0; }
[ "dasu0dadasu@yahoo.co.jp" ]
dasu0dadasu@yahoo.co.jp
c366b482755154ac0a63c326507a65826d909062
f11b6b83b868d6a06cd2c5510d34bc96519bb1e8
/(시작반2) Level11 - 문제5번.cpp
19ccd7ea43529f76e4834816951a3e1a219254db
[]
no_license
JuicyJerry/mincoding
c2ea35d5ce29ded5c3f4378bdb2267225643cfb6
238882ff59ead0f515613e6fe4879584b98da038
refs/heads/master
2022-12-23T15:18:20.239179
2020-09-22T14:34:05
2020-09-22T14:34:05
260,839,290
0
0
null
null
null
null
UTF-8
C++
false
false
198
cpp
#include <iostream> using namespace std; int main() { int a, b; cin >> a >> b; int* p = &a; int* t = &b; int temp; temp = *p; *p = *t; *t = temp; cout << *p << " " << *t; return 0; }
[ "ju2cyjerry@gmail.com" ]
ju2cyjerry@gmail.com
c1d00377b474ea548897974fd7098bef19a2e27c
effdc2a761c5fda7e4c3fedb0d874e194e2e3c78
/Unclassified/simulated-annealing-2.cc
f07afe846932ac5df798fdac5f144075dd1a3271
[]
no_license
duanqn/AC_lib
286d955462e1a8b5447c27f6b41b1603004e9965
305fbabb9c7bcf3d8a4fbbc17bd9248492332cd9
refs/heads/master
2020-07-12T22:24:19.410464
2015-08-21T09:42:53
2015-08-21T09:42:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
927
cc
//@ Simulated Annealing const int N = 32, T = 1000; //... struct state { double a, b; } cur[N]; double P, Q, R; inline double evaluate (state &s) { } // evalutae the state inline bool legal (state &s) { } // if the state is legal inline double rand1 () { return (double(rand() * 2) / RAND_MAX) - 1; } inline double rand2 () { return double(rand()) / RAND_MAX; } int main () { // Init for (int i = 0; i < N; ++i) { cur[i] = (state){rand2(), rand2()}; res = min(res, evaluate(cur[i])); } for (double e = 1.0; e > 1e-10; e /= 2.0) { for (int i = 0; i < N; ++i) { double cv = evaluate(cur[i]), cr; for (int t = T; t > 0; --t) { state tmp = cur[i]; tmp.a += rand1() * e, tmp.b += rand1() * e; if (legal(tmp)) if ((cr = evaluate(tmp)) < cv) cv = cr, cur[i] = tmp; else if (rand2() < 1e-4) cur[i] = tmp; } res = min(res, cv); } } printf("%.2lf\n", res); return 0; }
[ "wzy196@gmail.com" ]
wzy196@gmail.com
baddef38725b8c74eb7db481360f45e35e77348d
389596cb94cd143b3983dd26182fa3bd28e78665
/Source/TestPRCProj/TestPRCProjGameModeBase.cpp
50ed8dcdee25be3cd571d28d41bf6b1d4d1a92ce
[]
no_license
jyurkiw/UnrealTestPRCProj
1082c41c383d6aa3a8311fa4075e2fa25c925b22
d9723e281436d8b4c5b969cd739e2457ea58fc29
refs/heads/master
2020-09-21T08:21:44.682547
2019-11-28T22:43:57
2019-11-28T22:43:57
224,739,181
0
0
null
null
null
null
UTF-8
C++
false
false
119
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "TestPRCProjGameModeBase.h"
[ "jyurkiw@yahoo.com" ]
jyurkiw@yahoo.com
b120606f0d1b495ba080fe747aaa0eaa0f7484db
6754fedd87afba36ec8f004825bb852b00ac8fb2
/src/boost/accumulators/statistics/weighted_skewness.hpp
99929eae9ea3c3e40a4a0b65c875dcb13f9797dd
[ "BSD-3-Clause", "BSL-1.0" ]
permissive
cpmech/vismatrix
4e7b8a3e0448f4c9565fa649e9c9af0e05707346
a4994864d3592cfa2db24119427fad096303fb4f
refs/heads/main
2021-08-15T21:52:56.975004
2020-09-24T00:55:35
2020-09-24T00:55:35
54,020,206
5
0
null
null
null
null
UTF-8
C++
false
false
3,737
hpp
/////////////////////////////////////////////////////////////////////////////// // weighted_skewness.hpp // // Copyright 2006 Olivier Gygi, Daniel Egloff. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_SKEWNESS_HPP_EAN_28_10_2005 #define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_SKEWNESS_HPP_EAN_28_10_2005 #include <limits> #include <boost/mpl/placeholders.hpp> #include <boost/accumulators/framework/accumulator_base.hpp> #include <boost/accumulators/framework/extractor.hpp> #include <boost/accumulators/framework/parameters/sample.hpp> #include <boost/accumulators/numeric/functional.hpp> #include <boost/accumulators/framework/depends_on.hpp> #include <boost/accumulators/statistics_fwd.hpp> #include <boost/accumulators/statistics/weighted_moment.hpp> #include <boost/accumulators/statistics/weighted_mean.hpp> namespace boost { namespace accumulators { namespace impl { /////////////////////////////////////////////////////////////////////////////// // weighted_skewness_impl /** @brief Skewness estimation for weighted samples The skewness of a sample distribution is defined as the ratio of the 3rd central moment and the \f$ 3/2 \f$-th power $ of the 2nd central moment (the variance) of the samples. The skewness can also be expressed by the simple moments: \f[ \hat{g}_1 = \frac {\widehat{m}_n^{(3)}-3\widehat{m}_n^{(2)}\hat{\mu}_n+2\hat{\mu}_n^3} {\left(\widehat{m}_n^{(2)} - \hat{\mu}_n^{2}\right)^{3/2}} \f] where \f$ \widehat{m}_n^{(i)} \f$ are the \f$ i \f$-th moment and \f$ \hat{\mu}_n \f$ the mean (first moment) of the \f$ n \f$ samples. The skewness estimator for weighted samples is formally identical to the estimator for unweighted samples, except that the weighted counterparts of all measures it depends on are to be taken. */ template<typename Sample, typename Weight> struct weighted_skewness_impl : accumulator_base { typedef typename numeric::functional::multiplies<Sample, Weight>::result_type weighted_sample; // for boost::result_of typedef typename numeric::functional::average<weighted_sample, weighted_sample>::result_type result_type; weighted_skewness_impl(dont_care) {} template<typename Args> result_type result(Args const &args) const { return numeric::average( weighted_moment<3>(args) - 3. * weighted_moment<2>(args) * weighted_mean(args) + 2. * weighted_mean(args) * weighted_mean(args) * weighted_mean(args) , ( weighted_moment<2>(args) - weighted_mean(args) * weighted_mean(args) ) * std::sqrt( weighted_moment<2>(args) - weighted_mean(args) * weighted_mean(args) ) ); } }; } // namespace impl /////////////////////////////////////////////////////////////////////////////// // tag::weighted_skewness // namespace tag { struct weighted_skewness : depends_on<weighted_mean, weighted_moment<2>, weighted_moment<3> > { /// INTERNAL ONLY /// typedef accumulators::impl::weighted_skewness_impl<mpl::_1, mpl::_2> impl; }; } /////////////////////////////////////////////////////////////////////////////// // extract::weighted_skewness // namespace extract { extractor<tag::weighted_skewness> const weighted_skewness = {}; } using extract::weighted_skewness; }} // namespace boost::accumulators #endif
[ "dorival.pedroso@gmail.com" ]
dorival.pedroso@gmail.com
1a067c2762a37e233d4d2866467450b00609b54b
fc1be2eddc48116f9754cef10bc92512a160f720
/C++/ReverseInteger.cc
182fa7de206577237c7d2b12961b96cdc32e2e8c
[]
no_license
eaglesky/leetcode
6d7116a5c5df0c6aaf6441f9d7492f0bf8a0884e
bc9768624e3857c9776ef360b186d754333bbc03
refs/heads/master
2020-05-30T20:19:31.232212
2017-11-01T08:21:26
2017-11-01T08:21:26
22,568,355
2
2
null
null
null
null
UTF-8
C++
false
false
879
cc
#include <climits> #include <cstdlib> #include <iostream> using namespace std; int reverse0(int x) { int ret = 0; while(x != 0) { int dig = x % 10; x = x / 10; ret = ret*10 + dig; if ((ret > INT_MAX/10) || ((ret == INT_MAX/10) && (dig > 7))) break; } return ret; } // Solution to the updated problem int reverse(int x) { int result = 0; for (; x != 0; x /= 10) { int curDig = x % 10; if ((abs(result) > INT_MAX / 10) || ((abs(result) == INT_MAX / 10) && ((curDig > 7) || (curDig < -8)))) return 0; result = result * 10 + curDig; } return result; } int main(int argc, char** argv) { int x = atoi(argv[1]); cout << reverse(x) << endl; cout << INT_MIN << ", " << INT_MAX << endl; cout << -1041 % 10 << endl; return 0; }
[ "allenchin1990@gmail.com" ]
allenchin1990@gmail.com
54ed6ce5c43dab7f4b791056bb6152232f22fe5d
814bbf94e8cc5c56a98fda209203bf1cf5f25086
/Dynamic Programming/BOJ_6378.cpp
b34136bd329a999ad7d216cb3103e9a8b2ad44b2
[]
no_license
JW-1017/Algorithm
9683fa71397a35855fc5ab7dc3dbfd8ea1d04367
9c8a2d7b306f38f5d09c2d799bade8023eb10b5a
refs/heads/master
2020-12-03T08:11:32.887244
2018-10-05T19:11:19
2018-10-05T19:11:19
95,330,636
0
0
null
null
null
null
UTF-8
C++
false
false
1,052
cpp
#include <iostream> #include <string> #include <vector> #include <stack> #include <queue> #include <map> #include <set> #include <cctype> #include <cstring> #include <unordered_map> #include <unordered_set> #include <cmath> #include <functional> #include <algorithm> #include <cstdlib> using namespace std; /* input: 24 39 0 output: 6 3 https://www.acmicpc.net/problem/6378 /* Copyright (C) 2018 by Son */ unordered_map<string, int> dp; int main(){ ios::sync_with_stdio(false); cin.tie(0); int i, len, sum; string num; while (1) { cin >> num; if (num == "0") { break; } sum = 0; len = num.length(); for (i = 0; i < len; i++) { sum += num[i] - '0'; } num = to_string(sum); if (num.length() == 1) { cout << num << "\n"; continue; } while ((len = num.length()) != 1) { if (dp.find(num) != dp.end()) { sum = dp[num]; } else { sum = 0; for (i = 0; i < len; i++) { sum += num[i] - '0'; } dp[num] = sum; } num = to_string(sum); } cout << num << "\n"; } return 0; }
[ "wldndsla8@naver.com" ]
wldndsla8@naver.com
f79f52bc490a782e7b3dae87a4a1d1a6e2533a61
b4c4eeccf6cf31ea368fbe01008a3569408cd381
/Include/Inventaire.h
1f9d87347e07e62875ba3e2e93dfc3a277216c82
[]
no_license
MickaelFP/ProjetAventureTextuelCpp
d685c3ba8fe03b35fa453359a5cb5573e9186202
63b04659c6a19f6cd6e520c5cb05576e1e6dcbd6
refs/heads/main
2023-03-20T09:13:26.333226
2021-03-17T12:00:51
2021-03-17T12:00:51
345,701,381
0
0
null
null
null
null
UTF-8
C++
false
false
318
h
#include"Piles.h" #include"Bouteille.h" #include"BoiteDePillules.h" #include <vector> class Inventaire { public: Inventaire(); ~Inventaire(); void dragDrop(); void addItem(Item* nouvelItem); //(int location,...) void supprItem(Item* itemASuppr); protected: std::vector<Item*> m_inventaire; };
[ "72392674+MickaelFP@users.noreply.github.com" ]
72392674+MickaelFP@users.noreply.github.com
b539275f2f99b873614c75d1fd34d6a9be49170d
ab80df382d367f9ca23e4220c0290a5cafd36a23
/src/qt/walletmodel.cpp
d0177538e2810b642a42a0d15fe9eb1b258efa06
[ "MIT" ]
permissive
EVGHENICOIN/QuantisNet-PIVX-Fork-NEW-BLOCKCHAIN
ce012b1f8205976246c22e555d33136b6e640397
6bd405f4c91df2d3955581c448d6ff71b0b259b1
refs/heads/master
2020-04-27T07:58:22.920514
2019-03-06T20:32:18
2019-03-06T20:32:18
174,154,857
3
0
MIT
2019-03-06T14:31:08
2019-03-06T13:54:51
C++
UTF-8
C++
false
false
27,532
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletmodel.h" #include "addresstablemodel.h" #include "guiconstants.h" #include "recentrequeststablemodel.h" #include "transactiontablemodel.h" #include "base58.h" #include "db.h" #include "keystore.h" #include "main.h" #include "spork.h" #include "sync.h" #include "ui_interface.h" #include "wallet.h" #include "walletdb.h" // for BackupWallet #include <stdint.h> #include <QDebug> #include <QSet> #include <QTimer> using namespace std; WalletModel::WalletModel(CWallet* wallet, OptionsModel* optionsModel, QObject* parent) : QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0), transactionTableModel(0), recentRequestsTableModel(0), cachedBalance(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0), cachedZerocoinBalance(0), cachedUnconfirmedZerocoinBalance(0), cachedImmatureZerocoinBalance(0), cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0) { fHaveWatchOnly = wallet->HaveWatchOnly(); fHaveMultiSig = wallet->HaveMultiSig(); fForceCheckBalanceChanged = false; addressTableModel = new AddressTableModel(wallet, this); transactionTableModel = new TransactionTableModel(wallet, this); recentRequestsTableModel = new RecentRequestsTableModel(wallet, this); // This timer will be fired repeatedly to update the balance pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } CAmount WalletModel::getBalance(const CCoinControl* coinControl) const { if (coinControl) { CAmount nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH (const COutput& out, vCoins) if (out.fSpendable) nBalance += out.tx->vout[out.i].nValue; return nBalance; } return wallet->GetBalance(); } CAmount WalletModel::getUnconfirmedBalance() const { return wallet->GetUnconfirmedBalance(); } CAmount WalletModel::getImmatureBalance() const { return wallet->GetImmatureBalance(); } CAmount WalletModel::getLockedBalance() const { return wallet->GetLockedCoins(); } CAmount WalletModel::getZerocoinBalance() const { return wallet->GetZerocoinBalance(false); } CAmount WalletModel::getUnconfirmedZerocoinBalance() const { return wallet->GetUnconfirmedZerocoinBalance(); } CAmount WalletModel::getImmatureZerocoinBalance() const { return wallet->GetImmatureZerocoinBalance(); } bool WalletModel::haveWatchOnly() const { return fHaveWatchOnly; } CAmount WalletModel::getWatchBalance() const { return wallet->GetWatchOnlyBalance(); } CAmount WalletModel::getWatchUnconfirmedBalance() const { return wallet->GetUnconfirmedWatchOnlyBalance(); } CAmount WalletModel::getWatchImmatureBalance() const { return wallet->GetImmatureWatchOnlyBalance(); } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if (cachedEncryptionStatus != newEncryptionStatus) emit encryptionStatusChanged(newEncryptionStatus); } void WalletModel::pollBalanceChanged() { // Get required locks upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if (!lockMain) return; TRY_LOCK(wallet->cs_wallet, lockWallet); if (!lockWallet) return; if (fForceCheckBalanceChanged || chainActive.Height() != cachedNumBlocks || nZeromintPercentage != cachedZeromintPercentage || cachedTxLocks != nCompleteTXLocks) { fForceCheckBalanceChanged = false; // Balance and number of transactions might have changed cachedNumBlocks = chainActive.Height(); cachedZeromintPercentage = nZeromintPercentage; checkBalanceChanged(); if (transactionTableModel) { transactionTableModel->updateConfirmations(); } } } void WalletModel::emitBalanceChanged() { // Force update of UI elements even when no values have changed emit balanceChanged(cachedBalance, cachedUnconfirmedBalance, cachedImmatureBalance, cachedZerocoinBalance, cachedUnconfirmedZerocoinBalance, cachedImmatureZerocoinBalance, cachedWatchOnlyBalance, cachedWatchUnconfBalance, cachedWatchImmatureBalance); } void WalletModel::checkBalanceChanged() { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; CAmount newBalance = getBalance(); CAmount newUnconfirmedBalance = getUnconfirmedBalance(); CAmount newImmatureBalance = getImmatureBalance(); CAmount newZerocoinBalance = getZerocoinBalance(); CAmount newUnconfirmedZerocoinBalance = getUnconfirmedZerocoinBalance(); CAmount newImmatureZerocoinBalance = getImmatureZerocoinBalance(); CAmount newWatchOnlyBalance = 0; CAmount newWatchUnconfBalance = 0; CAmount newWatchImmatureBalance = 0; if (haveWatchOnly()) { newWatchOnlyBalance = getWatchBalance(); newWatchUnconfBalance = getWatchUnconfirmedBalance(); newWatchImmatureBalance = getWatchImmatureBalance(); } if (cachedBalance != newBalance || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance || cachedZerocoinBalance != newZerocoinBalance || cachedUnconfirmedZerocoinBalance != newUnconfirmedZerocoinBalance || cachedImmatureZerocoinBalance != newImmatureZerocoinBalance || cachedWatchOnlyBalance != newWatchOnlyBalance || cachedWatchUnconfBalance != newWatchUnconfBalance || cachedWatchImmatureBalance != newWatchImmatureBalance || cachedTxLocks != nCompleteTXLocks ) { cachedBalance = newBalance; cachedUnconfirmedBalance = newUnconfirmedBalance; cachedImmatureBalance = newImmatureBalance; cachedZerocoinBalance = newZerocoinBalance; cachedUnconfirmedZerocoinBalance = newUnconfirmedZerocoinBalance; cachedImmatureZerocoinBalance = newImmatureZerocoinBalance; cachedTxLocks = nCompleteTXLocks; cachedWatchOnlyBalance = newWatchOnlyBalance; cachedWatchUnconfBalance = newWatchUnconfBalance; cachedWatchImmatureBalance = newWatchImmatureBalance; emit balanceChanged(newBalance, newUnconfirmedBalance, newImmatureBalance, newZerocoinBalance, newUnconfirmedZerocoinBalance, newImmatureZerocoinBalance, newWatchOnlyBalance, newWatchUnconfBalance, newWatchImmatureBalance); } } void WalletModel::updateTransaction() { // Balance and number of transactions might have changed fForceCheckBalanceChanged = true; } void WalletModel::updateAddressBook(const QString& address, const QString& label, bool isMine, const QString& purpose, int status) { if (addressTableModel) addressTableModel->updateEntry(address, label, isMine, purpose, status); } void WalletModel::updateAddressBook(const QString &pubCoin, const QString &isUsed, int status) { if(addressTableModel) addressTableModel->updateEntry(pubCoin, isUsed, status); } void WalletModel::updateWatchOnlyFlag(bool fHaveWatchonly) { fHaveWatchOnly = fHaveWatchonly; emit notifyWatchonlyChanged(fHaveWatchonly); } void WalletModel::updateMultiSigFlag(bool fHaveMultiSig) { this->fHaveMultiSig = fHaveMultiSig; emit notifyMultiSigChanged(fHaveMultiSig); } bool WalletModel::validateAddress(const QString& address) { CBitcoinAddress addressParsed(address.toStdString()); return addressParsed.IsValid(); } WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction& transaction, const CCoinControl* coinControl) { CAmount total = 0; QList<SendCoinsRecipient> recipients = transaction.getRecipients(); std::vector<std::pair<CScript, CAmount> > vecSend; if (recipients.empty()) { return OK; } if (isAnonymizeOnlyUnlocked()) { return AnonymizeOnlyUnlocked; } QSet<QString> setAddress; // Used to detect duplicates int nAddresses = 0; // Pre-check input data for validity foreach (const SendCoinsRecipient& rcp, recipients) { if (rcp.paymentRequest.IsInitialized()) { // PaymentRequest... CAmount subtotal = 0; const payments::PaymentDetails& details = rcp.paymentRequest.getDetails(); for (int i = 0; i < details.outputs_size(); i++) { const payments::Output& out = details.outputs(i); if (out.amount() <= 0) continue; subtotal += out.amount(); const unsigned char* scriptStr = (const unsigned char*)out.script().data(); CScript scriptPubKey(scriptStr, scriptStr + out.script().size()); vecSend.push_back(std::pair<CScript, CAmount>(scriptPubKey, out.amount())); } if (subtotal <= 0) { return InvalidAmount; } total += subtotal; } else { // User-entered quantisnet address / amount: if (!validateAddress(rcp.address)) { return InvalidAddress; } if (rcp.amount <= 0) { return InvalidAmount; } setAddress.insert(rcp.address); ++nAddresses; CScript scriptPubKey = GetScriptForDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); vecSend.push_back(std::pair<CScript, CAmount>(scriptPubKey, rcp.amount)); total += rcp.amount; } } if (setAddress.size() != nAddresses) { return DuplicateAddress; } CAmount nBalance = getBalance(coinControl); if (total > nBalance) { return AmountExceedsBalance; } { LOCK2(cs_main, wallet->cs_wallet); transaction.newPossibleKeyChange(wallet); CAmount nFeeRequired = 0; std::string strFailReason; CWalletTx* newTx = transaction.getTransaction(); CReserveKey* keyChange = transaction.getPossibleKeyChange(); if (recipients[0].useSwiftTX && total > GetSporkValue(SPORK_5_MAX_VALUE) * COIN) { emit message(tr("Send Coins"), tr("SwiftX doesn't support sending values that high yet. Transactions are currently limited to %1 QUAN.").arg(GetSporkValue(SPORK_5_MAX_VALUE)), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, strFailReason, coinControl, recipients[0].inputType, recipients[0].useSwiftTX); transaction.setTransactionFee(nFeeRequired); if (recipients[0].useSwiftTX && newTx->GetValueOut() > GetSporkValue(SPORK_5_MAX_VALUE) * COIN) { emit message(tr("Send Coins"), tr("SwiftX doesn't support sending values that high yet. Transactions are currently limited to %1 QUAN.").arg(GetSporkValue(SPORK_5_MAX_VALUE)), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } if (!fCreated) { if ((total + nFeeRequired) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance); } emit message(tr("Send Coins"), QString::fromStdString(strFailReason), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } // reject insane fee if (nFeeRequired > ::minRelayTxFee.GetFee(transaction.getTransactionSize()) * 10000) return InsaneFee; } return SendCoinsReturn(OK); } WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction& transaction) { QByteArray transaction_array; /* store serialized transaction */ if (isAnonymizeOnlyUnlocked()) { return AnonymizeOnlyUnlocked; } { LOCK2(cs_main, wallet->cs_wallet); CWalletTx* newTx = transaction.getTransaction(); QList<SendCoinsRecipient> recipients = transaction.getRecipients(); // Store PaymentRequests in wtx.vOrderForm in wallet. foreach (const SendCoinsRecipient& rcp, recipients) { if (rcp.paymentRequest.IsInitialized()) { std::string key("PaymentRequest"); std::string value; rcp.paymentRequest.SerializeToString(&value); newTx->vOrderForm.push_back(make_pair(key, value)); } else if (!rcp.message.isEmpty()) // Message from normal quantisnet:URI (quantisnet:XyZ...?message=example) { newTx->vOrderForm.push_back(make_pair("Message", rcp.message.toStdString())); } } CReserveKey* keyChange = transaction.getPossibleKeyChange(); transaction.getRecipients(); if (!wallet->CommitTransaction(*newTx, *keyChange, (recipients[0].useSwiftTX) ? "ix" : "tx")) return TransactionCommitFailed; CTransaction* t = (CTransaction*)newTx; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << *t; transaction_array.append(&(ssTx[0]), ssTx.size()); } // Add addresses / update labels that we've sent to to the address book, // and emit coinsSent signal for each recipient foreach (const SendCoinsRecipient& rcp, transaction.getRecipients()) { // Don't touch the address book when we have a payment request if (!rcp.paymentRequest.IsInitialized()) { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = CBitcoinAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { LOCK(wallet->cs_wallet); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end()) { wallet->SetAddressBook(dest, strLabel, "send"); } else if (mi->second.name != strLabel) { wallet->SetAddressBook(dest, strLabel, ""); // "" means don't change purpose } } } emit coinsSent(wallet, rcp, transaction_array); } checkBalanceChanged(); // update balance immediately, otherwise there could be a short noticeable delay until pollBalanceChanged hits return SendCoinsReturn(OK); } OptionsModel* WalletModel::getOptionsModel() { return optionsModel; } AddressTableModel* WalletModel::getAddressTableModel() { return addressTableModel; } TransactionTableModel* WalletModel::getTransactionTableModel() { return transactionTableModel; } RecentRequestsTableModel* WalletModel::getRecentRequestsTableModel() { return recentRequestsTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if (!wallet->IsCrypted()) { return Unencrypted; } else if (wallet->fWalletUnlockAnonymizeOnly) { return UnlockedForAnonymizationOnly; } else if (wallet->IsLocked()) { return Locked; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString& passphrase) { if (encrypted) { // Encrypt return wallet->EncryptWallet(passphrase); } else { // Decrypt -- TODO; not supported yet return false; } } bool WalletModel::setWalletLocked(bool locked, const SecureString& passPhrase, bool anonymizeOnly) { if (locked) { // Lock wallet->fWalletUnlockAnonymizeOnly = false; return wallet->Lock(); } else { // Unlock return wallet->Unlock(passPhrase, anonymizeOnly); } } bool WalletModel::isAnonymizeOnlyUnlocked() { return wallet->fWalletUnlockAnonymizeOnly; } bool WalletModel::changePassphrase(const SecureString& oldPass, const SecureString& newPass) { bool retval; { LOCK(wallet->cs_wallet); wallet->Lock(); // Make sure wallet is locked before attempting pass change retval = wallet->ChangeWalletPassphrase(oldPass, newPass); } return retval; } bool WalletModel::backupWallet(const QString& filename) { return BackupWallet(*wallet, filename.toLocal8Bit().data()); } // Handlers for core signals static void NotifyKeyStoreStatusChanged(WalletModel* walletmodel, CCryptoKeyStore* wallet) { qDebug() << "NotifyKeyStoreStatusChanged"; QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); } static void NotifyAddressBookChanged(WalletModel* walletmodel, CWallet* wallet, const CTxDestination& address, const std::string& label, bool isMine, const std::string& purpose, ChangeType status) { QString strAddress = QString::fromStdString(CBitcoinAddress(address).ToString()); QString strLabel = QString::fromStdString(label); QString strPurpose = QString::fromStdString(purpose); qDebug() << "NotifyAddressBookChanged : " + strAddress + " " + strLabel + " isMine=" + QString::number(isMine) + " purpose=" + strPurpose + " status=" + QString::number(status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, strAddress), Q_ARG(QString, strLabel), Q_ARG(bool, isMine), Q_ARG(QString, strPurpose), Q_ARG(int, status)); } // queue notifications to show a non freezing progress dialog e.g. for rescan static bool fQueueNotifications = false; static std::vector<std::pair<uint256, ChangeType> > vQueueNotifications; static void NotifyTransactionChanged(WalletModel* walletmodel, CWallet* wallet, const uint256& hash, ChangeType status) { if (fQueueNotifications) { vQueueNotifications.push_back(make_pair(hash, status)); return; } QString strHash = QString::fromStdString(hash.GetHex()); qDebug() << "NotifyTransactionChanged : " + strHash + " status= " + QString::number(status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection /*, Q_ARG(QString, strHash), Q_ARG(int, status)*/); } static void ShowProgress(WalletModel* walletmodel, const std::string& title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(walletmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyWatchonlyChanged(WalletModel* walletmodel, bool fHaveWatchonly) { QMetaObject::invokeMethod(walletmodel, "updateWatchOnlyFlag", Qt::QueuedConnection, Q_ARG(bool, fHaveWatchonly)); } static void NotifyMultiSigChanged(WalletModel* walletmodel, bool fHaveMultiSig) { QMetaObject::invokeMethod(walletmodel, "updateMultiSigFlag", Qt::QueuedConnection, Q_ARG(bool, fHaveMultiSig)); } static void NotifyZerocoinChanged(WalletModel* walletmodel, CWallet* wallet, const std::string& hexString, const std::string& isUsed, ChangeType status) { QString HexStr = QString::fromStdString(hexString); QString isUsedStr = QString::fromStdString(isUsed); qDebug() << "NotifyZerocoinChanged : " + HexStr + " " + isUsedStr + " status= " + QString::number(status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, HexStr), Q_ARG(QString, isUsedStr), Q_ARG(int, status)); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6)); wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); wallet->NotifyWatchonlyChanged.connect(boost::bind(NotifyWatchonlyChanged, this, _1)); wallet->NotifyMultiSigChanged.connect(boost::bind(NotifyMultiSigChanged, this, _1)); wallet->NotifyZerocoinChanged.connect(boost::bind(NotifyZerocoinChanged, this, _1, _2, _3, _4)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6)); wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); wallet->NotifyWatchonlyChanged.disconnect(boost::bind(NotifyWatchonlyChanged, this, _1)); wallet->NotifyMultiSigChanged.disconnect(boost::bind(NotifyMultiSigChanged, this, _1)); wallet->NotifyZerocoinChanged.disconnect(boost::bind(NotifyZerocoinChanged, this, _1, _2, _3, _4)); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock(bool relock) { bool was_locked = getEncryptionStatus() == Locked; if (!was_locked && isAnonymizeOnlyUnlocked()) { setWalletLocked(true); wallet->fWalletUnlockAnonymizeOnly = false; was_locked = getEncryptionStatus() == Locked; } if (was_locked) { // Request UI to unlock wallet emit requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(valid, relock); // return UnlockContext(this, valid, was_locked && !isAnonymizeOnlyUnlocked()); } WalletModel::UnlockContext::UnlockContext(bool valid, bool relock) : valid(valid), relock(relock) { } WalletModel::UnlockContext::~UnlockContext() { /* if (valid && relock) { wallet->setWalletLocked(true); } */ } void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs) { // Transfer context; old object no longer relocks wallet *this = rhs; rhs.relock = false; } bool WalletModel::getPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const { return wallet->GetPubKey(address, vchPubKeyOut); } // returns a list of COutputs from COutPoints void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs) { LOCK2(cs_main, wallet->cs_wallet); BOOST_FOREACH (const COutPoint& outpoint, vOutpoints) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true); vOutputs.push_back(out); } } bool WalletModel::isSpent(const COutPoint& outpoint) const { LOCK2(cs_main, wallet->cs_wallet); return wallet->IsSpent(outpoint.hash, outpoint.n); } // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const { std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins); LOCK2(cs_main, wallet->cs_wallet); // ListLockedCoins, mapWallet std::vector<COutPoint> vLockedCoins; wallet->ListLockedCoins(vLockedCoins); // add locked coins BOOST_FOREACH (const COutPoint& outpoint, vLockedCoins) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true); if (outpoint.n < out.tx->vout.size() && wallet->IsMine(out.tx->vout[outpoint.n]) == ISMINE_SPENDABLE) vCoins.push_back(out); } BOOST_FOREACH (const COutput& out, vCoins) { COutput cout = out; while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break; cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true); } CTxDestination address; if (!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; mapCoins[QString::fromStdString(CBitcoinAddress(address).ToString())].push_back(out); } } bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const { LOCK2(cs_main, wallet->cs_wallet); return wallet->IsLockedCoin(hash, n); } void WalletModel::lockCoin(COutPoint& output) { LOCK2(cs_main, wallet->cs_wallet); wallet->LockCoin(output); } void WalletModel::unlockCoin(COutPoint& output) { LOCK2(cs_main, wallet->cs_wallet); wallet->UnlockCoin(output); } void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts) { LOCK2(cs_main, wallet->cs_wallet); wallet->ListLockedCoins(vOutpts); } void WalletModel::listZerocoinMints(std::list<CZerocoinMint>& listMints, bool fUnusedOnly, bool fMaturedOnly, bool fUpdateStatus) { listMints.clear(); CWalletDB walletdb(wallet->strWalletFile); listMints = walletdb.ListMintedCoins(fUnusedOnly, fMaturedOnly, fUpdateStatus); } void WalletModel::loadReceiveRequests(std::vector<std::string>& vReceiveRequests) { LOCK(wallet->cs_wallet); BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, wallet->mapAddressBook) BOOST_FOREACH (const PAIRTYPE(std::string, std::string) & item2, item.second.destdata) if (item2.first.size() > 2 && item2.first.substr(0, 2) == "rr") // receive request vReceiveRequests.push_back(item2.second); } bool WalletModel::saveReceiveRequest(const std::string& sAddress, const int64_t nId, const std::string& sRequest) { CTxDestination dest = CBitcoinAddress(sAddress).Get(); std::stringstream ss; ss << nId; std::string key = "rr" + ss.str(); // "rr" prefix = "receive request" in destdata LOCK(wallet->cs_wallet); if (sRequest.empty()) return wallet->EraseDestData(dest, key); else return wallet->AddDestData(dest, key, sRequest); } bool WalletModel::isMine(CBitcoinAddress address) { return IsMine(*wallet, address.Get()); }
[ "aria@euphmail.com" ]
aria@euphmail.com
799d2871191fbb7cd568d1760d10f1144a13b1d6
e13865712d1c9d9db95dd3cc237af90f01665007
/tools/euryopa/WaterLevel.cpp
d3f2959d0e88265ab5292a64af8e38fc6110d2d4
[]
no_license
rwengine/librwgta
b1a4a1e196b3e8c1eaaccad5c80ddd82e44a87bf
79850b4e5ab5e114aaf12761e2ddc203d442954b
refs/heads/master
2020-04-25T05:40:56.710316
2019-01-10T09:16:04
2019-01-10T09:16:04
172,551,687
2
1
null
2019-02-25T17:25:29
2019-02-25T17:25:28
null
UTF-8
C++
false
false
12,619
cpp
#include "euryopa.h" namespace WaterLevel { #define WATERSTARTX params.waterStart.x #define WATERENDX params.waterEnd.x #define WATERSTARTY params.waterStart.y #define WATERENDY params.waterEnd.y #define WATERSMALLSECTORSZX ((WATERENDX - WATERSTARTX)/128) #define WATERSMALLSECTORSZY ((WATERENDY - WATERSTARTY)/128) #define WATERSECTORSZX ((WATERENDX - WATERSTARTX)/64) #define WATERSECTORSZY ((WATERENDY - WATERSTARTY)/64) static int ms_nNoOfWaterLevels; static float ms_aWaterZs[48]; static CRect ms_aWaterRects[48]; // Seems to be unused static uint8 aWaterBlockList[64][64]; static uint8 aWaterFineBlockList[128][128]; rw::Texture *gpWaterTex; rw::Raster *gpWaterRaster; // SA struct WaterVertex { rw::V3d pos; rw::V2d speed; float waveunk, waveheight; }; struct WaterQuad { int indices[4]; int type; }; struct WaterTri { int indices[3]; int type; }; static WaterVertex waterVertices[NUMWATERVERTICES]; static int numWaterVertices; static WaterQuad waterQuads[NUMWATERQUADS]; static int numWaterQuads; static WaterTri waterTris[NUMWATERTRIS]; static int numWaterTris; void InitialiseWaterpro(void) { FILE *file; ms_nNoOfWaterLevels = 0; if(file = fopen_ci("DATA\\waterpro.dat", "rb"), file == nil) return; fread(&ms_nNoOfWaterLevels, 1, sizeof(ms_nNoOfWaterLevels), file); fread(&ms_aWaterZs, 1, sizeof(ms_aWaterZs), file); fread(&ms_aWaterRects, 1, sizeof(ms_aWaterRects), file); fread(&aWaterBlockList, 1, sizeof(aWaterBlockList), file); fread(&aWaterFineBlockList, 1, sizeof(aWaterFineBlockList), file); fclose(file); } void InitialiseWater(void) { WaterVertex v[4]; int type; int nfields; FILE *file; char *line; if(file = fopen_ci("data/water.dat", "rb"), file == nil) return; int h = 0, w = 0; while(line = FileLoader::LoadLine(file)){ if(line[0] == ';' || line[0] == '*' || line[0] == 'p') continue; type = 1; nfields = sscanf(line, "%f %f %f %f %f %f %f " "%f %f %f %f %f %f %f " "%f %f %f %f %f %f %f " "%f %f %f %f %f %f %f " "%d", &v[0].pos.x, &v[0].pos.y, &v[0].pos.z, &v[0].speed.x, &v[0].speed.y, &v[0].waveunk, &v[0].waveheight, &v[1].pos.x, &v[1].pos.y, &v[1].pos.z, &v[1].speed.x, &v[1].speed.y, &v[1].waveunk, &v[1].waveheight, &v[2].pos.x, &v[2].pos.y, &v[2].pos.z, &v[2].speed.x, &v[2].speed.y, &v[2].waveunk, &v[2].waveheight, &v[3].pos.x, &v[3].pos.y, &v[3].pos.z, &v[3].speed.x, &v[3].speed.y, &v[3].waveunk, &v[3].waveheight, &type); if(nfields == 28 || nfields == 29){ // quad if(numWaterVertices+4 > NUMWATERVERTICES || numWaterQuads+1 > NUMWATERQUADS){ log("warning: too much water (%d vertices, %d quads, %d tris)\n", numWaterVertices, numWaterQuads, numWaterTris); continue; } WaterQuad *q = &waterQuads[numWaterQuads++]; q->indices[0] = numWaterVertices++; q->indices[1] = numWaterVertices++; q->indices[2] = numWaterVertices++; q->indices[3] = numWaterVertices++; waterVertices[q->indices[0]] = v[0]; waterVertices[q->indices[1]] = v[1]; waterVertices[q->indices[2]] = v[2]; waterVertices[q->indices[3]] = v[3]; q->type = type; }else{ if(numWaterVertices+3 > NUMWATERVERTICES || numWaterTris+1 > NUMWATERTRIS){ log("warning: too much water (%d vertices, %d quads, %d tris)\n", numWaterVertices, numWaterQuads, numWaterTris); continue; } // triangle WaterTri *t = &waterTris[numWaterTris++]; t->indices[0] = numWaterVertices++; t->indices[1] = numWaterVertices++; t->indices[2] = numWaterVertices++; waterVertices[t->indices[0]] = v[0]; waterVertices[t->indices[1]] = v[1]; waterVertices[t->indices[2]] = v[2]; t->type = type; } } fclose(file); } void Initialise(void) { if(params.water == GAME_SA) InitialiseWater(); else InitialiseWaterpro(); TxdPush(); int ptxd = FindTxdSlot("particle"); TxdMakeCurrent(ptxd); if(gpWaterTex == nil) gpWaterTex = rw::Texture::read(params.waterTex, nil); gpWaterRaster = gpWaterTex->raster; TxdPop(); } #define TEMPBUFFERVERTSIZE 256 #define TEMPBUFFERINDEXSIZE 1024 static int TempBufferIndicesStored; static int TempBufferVerticesStored; static rw::RWDEVICE::Im3DVertex TempVertexBuffer[TEMPBUFFERVERTSIZE]; static uint16 TempIndexBuffer[TEMPBUFFERINDEXSIZE]; float TEXTURE_ADDU, TEXTURE_ADDV; static void RenderAndEmptyRenderBuffer(void) { assert(TempBufferVerticesStored <= TEMPBUFFERVERTSIZE); assert(TempBufferIndicesStored <= TEMPBUFFERINDEXSIZE); if(TempBufferVerticesStored){ rw::im3d::Transform(TempVertexBuffer, TempBufferVerticesStored, nil); rw::im3d::RenderIndexed(rw::PRIMTYPETRILIST, TempIndexBuffer, TempBufferIndicesStored); rw::im3d::End(); } TempBufferVerticesStored = 0; TempBufferIndicesStored = 0; } void RenderOneFlatSmallWaterPoly(float x, float y, float z, rw::RGBA const &color) { if(TempBufferVerticesStored+4 >= TEMPBUFFERVERTSIZE || TempBufferIndicesStored+6 >= TEMPBUFFERINDEXSIZE) RenderAndEmptyRenderBuffer(); int i = TempBufferVerticesStored; TempVertexBuffer[i + 0].setX(x); TempVertexBuffer[i + 0].setY(y); TempVertexBuffer[i + 0].setZ(z); TempVertexBuffer[i + 0].setU(TEXTURE_ADDU); TempVertexBuffer[i + 0].setV(TEXTURE_ADDV); TempVertexBuffer[i + 0].setColor(color.red, color.green, color.blue, color.alpha); TempVertexBuffer[i + 1].setX(x); TempVertexBuffer[i + 1].setY(y + WATERSMALLSECTORSZY); TempVertexBuffer[i + 1].setZ(z); TempVertexBuffer[i + 1].setU(TEXTURE_ADDU); TempVertexBuffer[i + 1].setV(TEXTURE_ADDV + 1.0f); TempVertexBuffer[i + 1].setColor(color.red, color.green, color.blue, color.alpha); TempVertexBuffer[i + 2].setX(x + WATERSMALLSECTORSZX); TempVertexBuffer[i + 2].setY(y + WATERSMALLSECTORSZY); TempVertexBuffer[i + 2].setZ(z); TempVertexBuffer[i + 2].setU(TEXTURE_ADDU + 1.0f); TempVertexBuffer[i + 2].setV(TEXTURE_ADDV + 1.0f); TempVertexBuffer[i + 2].setColor(color.red, color.green, color.blue, color.alpha); TempVertexBuffer[i + 3].setX(x + WATERSMALLSECTORSZX); TempVertexBuffer[i + 3].setY(y); TempVertexBuffer[i + 3].setZ(z); TempVertexBuffer[i + 3].setU(TEXTURE_ADDU + 1.0f); TempVertexBuffer[i + 3].setV(TEXTURE_ADDV); TempVertexBuffer[i + 3].setColor(color.red, color.green, color.blue, color.alpha); TempBufferVerticesStored += 4; TempIndexBuffer[TempBufferIndicesStored++] = i+0; TempIndexBuffer[TempBufferIndicesStored++] = i+1; TempIndexBuffer[TempBufferIndicesStored++] = i+2; TempIndexBuffer[TempBufferIndicesStored++] = i+0; TempIndexBuffer[TempBufferIndicesStored++] = i+2; TempIndexBuffer[TempBufferIndicesStored++] = i+3; } void RenderOneFlatLargeWaterPoly(float x, float y, float z, rw::RGBA const &color) { if(TempBufferVerticesStored+4 >= TEMPBUFFERVERTSIZE || TempBufferIndicesStored+6 >= TEMPBUFFERINDEXSIZE) RenderAndEmptyRenderBuffer(); int i = TempBufferVerticesStored; TempVertexBuffer[i + 0].setX(x); TempVertexBuffer[i + 0].setY(y); TempVertexBuffer[i + 0].setZ(z); TempVertexBuffer[i + 0].setU(TEXTURE_ADDU); TempVertexBuffer[i + 0].setV(TEXTURE_ADDV); TempVertexBuffer[i + 0].setColor(color.red, color.green, color.blue, color.alpha); TempVertexBuffer[i + 1].setX(x); TempVertexBuffer[i + 1].setY(y + WATERSECTORSZY); TempVertexBuffer[i + 1].setZ(z); TempVertexBuffer[i + 1].setU(TEXTURE_ADDU); TempVertexBuffer[i + 1].setV(TEXTURE_ADDV + 2.0f); TempVertexBuffer[i + 1].setColor(color.red, color.green, color.blue, color.alpha); TempVertexBuffer[i + 2].setX(x + WATERSECTORSZX); TempVertexBuffer[i + 2].setY(y + WATERSECTORSZY); TempVertexBuffer[i + 2].setZ(z); TempVertexBuffer[i + 2].setU(TEXTURE_ADDU + 2.0f); TempVertexBuffer[i + 2].setV(TEXTURE_ADDV + 2.0f); TempVertexBuffer[i + 2].setColor(color.red, color.green, color.blue, color.alpha); TempVertexBuffer[i + 3].setX(x + WATERSECTORSZX); TempVertexBuffer[i + 3].setY(y); TempVertexBuffer[i + 3].setZ(z); TempVertexBuffer[i + 3].setU(TEXTURE_ADDU + 2.0f); TempVertexBuffer[i + 3].setV(TEXTURE_ADDV); TempVertexBuffer[i + 3].setColor(color.red, color.green, color.blue, color.alpha); TempBufferVerticesStored += 4; TempIndexBuffer[TempBufferIndicesStored++] = i+0; TempIndexBuffer[TempBufferIndicesStored++] = i+1; TempIndexBuffer[TempBufferIndicesStored++] = i+2; TempIndexBuffer[TempBufferIndicesStored++] = i+0; TempIndexBuffer[TempBufferIndicesStored++] = i+2; TempIndexBuffer[TempBufferIndicesStored++] = i+3; } void RenderWaterpro(void) { int i, j; rw::SetRenderStatePtr(rw::TEXTURERASTER, gpWaterTex->raster); rw::SetRenderState(rw::VERTEXALPHA, 1); rw::SetRenderState(rw::FOGENABLE, gEnableFog); rw::RGBA color = { 255, 255, 255, 255 }; Timecycle::ColourSet *cs = &Timecycle::currentColours; if(params.water == GAME_III){ color.red = clamp(cs->amb.red + cs->dir.red, 0.0f, 1.0f)*255.0f; color.green = clamp(cs->amb.green + cs->dir.green, 0.0f, 1.0f)*255.0f; color.blue = clamp(cs->amb.blue + cs->dir.blue, 0.0f, 1.0f)*255.0f; }else rw::convColor(&color, &cs->water); TEXTURE_ADDU = 0.0f; TEXTURE_ADDV = 0.0f; float x, y, z; rw::Sphere sph; // Small polys sph.radius = sqrt(WATERSMALLSECTORSZX*WATERSMALLSECTORSZX*2.0f)/2.0f; for(i = 0; i < 128; i++) for(j = 0; j < 128; j++){ if(aWaterFineBlockList[i][j] & 0x80) continue; x = WATERSMALLSECTORSZX*i + WATERSTARTX; y = WATERSMALLSECTORSZY*j + WATERSTARTY; z = ms_aWaterZs[aWaterFineBlockList[i][j]]; sph.center.x = x + WATERSMALLSECTORSZX/2; sph.center.y = y + WATERSMALLSECTORSZY/2; sph.center.z = z; if(TheCamera.m_rwcam->frustumTestSphere(&sph) != rw::Camera::SPHEREOUTSIDE) RenderOneFlatSmallWaterPoly(x, y, z, color); } /* // Large polys sph.radius = sqrt(WATERSECTORSZX*WATERSECTORSZX*2.0f)/2.0f; for(i = 0; i < 64; i++) for(j = 0; j < 64; j++){ if(aWaterBlockList[i][j] & 0x80) continue; x = WATERSECTORSZX*i + WATERSTARTX; y = WATERSECTORSZY*j + WATERSTARTY; z = ms_aWaterZs[aWaterBlockList[i][j]]; sph.center.x = x + WATERSECTORSZX/2; sph.center.y = y + WATERSECTORSZY/2; sph.center.z = z; if(Scene.camera->frustumTestSphere(&sph) != rw::Camera::SPHEREOUTSIDE) RenderOneFlatLargeWaterPoly(x, y, z, color); } */ RenderAndEmptyRenderBuffer(); } static const float uvscale = 1/32.0f; static void RenderWaterQuad(WaterQuad *q) { if(TempBufferVerticesStored+4 >= TEMPBUFFERVERTSIZE || TempBufferIndicesStored+6 >= TEMPBUFFERINDEXSIZE) RenderAndEmptyRenderBuffer(); rw::RGBA color; rw::convColor(&color, &Timecycle::currentColours.water); WaterVertex *v; int i = TempBufferVerticesStored; int j; for(j = 0; j < 4; j++){ v = &waterVertices[q->indices[j]]; TempVertexBuffer[i + j].setX(v->pos.x); TempVertexBuffer[i + j].setY(v->pos.y); TempVertexBuffer[i + j].setZ(v->pos.z); TempVertexBuffer[i + j].setU(v->pos.x*uvscale); TempVertexBuffer[i + j].setV(v->pos.y*uvscale); TempVertexBuffer[i + j].setColor(color.red, color.green, color.blue, color.alpha); } TempBufferVerticesStored += 4; TempIndexBuffer[TempBufferIndicesStored++] = i+0; TempIndexBuffer[TempBufferIndicesStored++] = i+1; TempIndexBuffer[TempBufferIndicesStored++] = i+2; TempIndexBuffer[TempBufferIndicesStored++] = i+2; TempIndexBuffer[TempBufferIndicesStored++] = i+1; TempIndexBuffer[TempBufferIndicesStored++] = i+3; } static void RenderWaterTri(WaterTri *t) { if(TempBufferVerticesStored+3 >= TEMPBUFFERVERTSIZE || TempBufferIndicesStored+3 >= TEMPBUFFERINDEXSIZE) RenderAndEmptyRenderBuffer(); rw::RGBA color; rw::convColor(&color, &Timecycle::currentColours.water); WaterVertex *v; int i = TempBufferVerticesStored; int j; for(j = 0; j < 3; j++){ v = &waterVertices[t->indices[j]]; TempVertexBuffer[i + j].setX(v->pos.x); TempVertexBuffer[i + j].setY(v->pos.y); TempVertexBuffer[i + j].setZ(v->pos.z); TempVertexBuffer[i + j].setU(v->pos.x*uvscale); TempVertexBuffer[i + j].setV(v->pos.y*uvscale); TempVertexBuffer[i + j].setColor(color.red, color.green, color.blue, color.alpha); } TempBufferVerticesStored += 3; TempIndexBuffer[TempBufferIndicesStored++] = i+0; TempIndexBuffer[TempBufferIndicesStored++] = i+1; TempIndexBuffer[TempBufferIndicesStored++] = i+2; } void RenderWater(void) { int i; rw::SetRenderStatePtr(rw::TEXTURERASTER, gpWaterTex->raster); rw::SetRenderState(rw::VERTEXALPHA, 1); rw::SetRenderState(rw::FOGENABLE, gEnableFog); for(i = 0; i < numWaterQuads; i++) RenderWaterQuad(&waterQuads[i]); for(i = 0; i < numWaterTris; i++) RenderWaterTri(&waterTris[i]); RenderAndEmptyRenderBuffer(); } void Render(void) { SetRenderState(rw::CULLMODE, rw::CULLNONE); if(params.water == GAME_SA) RenderWater(); else RenderWaterpro(); } }
[ "aap@papnet.eu" ]
aap@papnet.eu
0d0a570a62bbc04f077d809282374e9ad748a141
28560cf98151f64840a235f9fb9b661c2b629118
/StockMaretSimulator/StockMaretSimulator/Failsafe.h
e54121b25b14ecea9bf8fc86866963999442d3bc
[]
no_license
BenskiBoy/StockMarketSimulator
86e3a55a06e585779bbed0c5309246b59ead6f5e
8adf96712969f29e7523cf0daddbe4851f99858e
refs/heads/master
2021-01-01T05:19:56.660653
2016-05-27T02:37:03
2016-05-27T02:37:03
57,019,826
0
0
null
null
null
null
UTF-8
C++
false
false
351
h
#pragma once #ifndef __H_FAILSAFE__ #define __H_FAILSAFE__ #include "Enums.h" #include "Logger.h" #include "News.h" #include <mutex> #include <sstream> using namespace std; class Failsafe { private: News* n; public: Failsafe(News* n); Failsafe::Failsafe(const Failsafe& other) { n = other.n; } void operator()(Logger* l); }; #endif
[ "thwaitsy@gmail.com" ]
thwaitsy@gmail.com
19e98ad5074293519109748816cb9c7beb2e7bf9
51819345c6569587e28393a5df12afa34fd7595f
/qhairprocessing.h
70fff33d74871723b9a2d92f169be9a981bb3c3d
[]
no_license
000ddd00dd0d/Hair-Tracing
0f82aed18595728266b875e266d44a856db7a3ad
9b342780f748083b788725b231a6dde4a0a16a2a
refs/heads/master
2021-01-13T10:15:17.182301
2017-02-08T08:48:49
2017-02-08T08:48:49
69,742,699
5
2
null
null
null
null
UTF-8
C++
false
false
754
h
#ifndef QHAIRPROCESSING_H #define QHAIRPROCESSING_H #include <QtWidgets/QMainWindow> #include <QtWidgets/qaction.h> #include "ui_qhairprocessing.h" #include "LazySnapping.h" #include "Tracing.h" #include <cv.h> #include <highgui.h> class QHairProcessing : public QMainWindow { Q_OBJECT public: QHairProcessing(QWidget *parent = 0); ~QHairProcessing(); private: void createMenus(); void createActions(); void initialize(); private slots: void setForeground(); void setBackground(); void reset(); void newImage(); void matting(); void gaborFilter(); void tracingProcess(); private: QMenu *fileMenu; QAction *newAction; Tracing tracing; public: Ui::QHairProcessingClass ui; LazySnapping ls; }; #endif // QHAIRPROCESSING_H
[ "752936985@qq.com" ]
752936985@qq.com
bd6b35cfda43dc84a72e49a90459792958930bd2
ff104c7eb90b8177648e6bb6443a9538ebc0c48a
/libquic/src/net/log/net_log_event_type.h
aad5e2d16ad88c5b059d1195da495b10405b9a83
[ "BSD-3-Clause" ]
permissive
renwotao/quic
4a76a2e559379ca1a84461f0767e7eadf7bb4d1e
59e5bf1afe0949e9698c3aecb8af378065678b62
refs/heads/master
2020-12-01T02:57:14.688110
2017-03-27T18:09:40
2017-03-27T18:09:40
85,148,484
0
2
null
null
null
null
UTF-8
C++
false
false
634
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_LOG_NET_LOG_EVENT_TYPE_H_ #define NET_LOG_NET_LOG_EVENT_TYPE_H_ namespace net { enum class NetLogEventType { #define EVENT_TYPE(label) label, #include "net/log/net_log_event_type_list.h" #undef EVENT_TYPE COUNT }; // The 'phase' of an event trace (whether it marks the beginning or end // of an event.). enum class NetLogEventPhase { NONE, BEGIN, END, }; } // namespace net #endif // NET_LOG_NET_LOG_EVENT_TYPE_H_
[ "852443964@qq.com" ]
852443964@qq.com
b489b12d017b4946d2de011181c79610d8a86094
4befa37d1e2203ae15c5c2d206aa83fc9c1b2175
/XII/Assignments/3. File Handling/L_4.CPP
99cb2838708010931eb4e26c7a1e313783ad91f2
[]
no_license
aayushvats/CPP_AllKindsOfStuff
87008fae7a29ea04883b78b046d6a2e292fd7fb8
bdf91363f7ac9737ca4b6d1d7fbd8ee8ba99049c
refs/heads/master
2020-07-04T16:50:43.286971
2019-12-04T13:41:09
2019-12-04T13:41:09
202,345,940
3
0
null
null
null
null
UTF-8
C++
false
false
398
cpp
#include<fstream.h> #include<conio.h> #include<string.h> void COPYABC() { ifstream fin("TELEPHON.DAT",ios::in|ios::binary); ofstream fout("TELEBACK.DAT",ios::out|ios::binary); Directory ph; while(!fin.eof()) { fin.read((char*)&ph,sizeof(ph)); if(ph.checkcode("123")==0) fout.write((char*)&ph,sizeof(ph)); } fin.close(); fout.close(); } void main() { clrscr(); COPYABC(); getch(); }
[ "44yu5hv475@gmail.com" ]
44yu5hv475@gmail.com
61e7fb00452be0269e539d93883f8c8d97470368
db92214392a7f20a8a7c9713cd9e8ba4b2d94c7a
/AsyncLog/src/AsyncLog.h
ea13479028b3520cf23b2d0c0e6a58cc0006c869
[]
no_license
SoftwareKiller/ubuntu
fd2af7be1738bdbdccd38a58c7f17b340f618363
6bf390fc8d8c3efc17a7db3331d5f5405abd05bf
refs/heads/master
2022-01-29T23:26:56.528101
2022-01-11T08:38:03
2022-01-11T08:38:03
137,650,835
1
0
null
2020-12-16T15:21:42
2018-06-17T11:42:35
C++
UTF-8
C++
false
false
3,634
h
#pragma once #include <cstdio> #include <string> #include <list> #include <thread> #include <memory> #include <mutex> #include <condition_variable> #include <unistd.h> #include <cstring> #define LOG_API enum LOG_LEVEL { LOG_LEVEL_TRACE, LOG_LEVEL_DEBUG, LOG_LEVEL_INFO, LOG_LEVEL_WARNING, LOG_LEVEL_ERROR, //用于业务错误 LOG_LEVEL_SYSERROR, //用于技术框架本身的错误 LOG_LEVEL_FATAL, //FATAL 级别的日志会让在程序输出日志后退出 LOG_LEVEL_CRITICAL //CRITICAL 日志不受日志级别控制,总是输出 }; #define LOGT(...) CAsyncLog::output(LOG_LEVEL_TRACE, __FILE__, __LINE__, __VA_ARGS__) #define LOGD(...) CAsyncLog::output(LOG_LEVEL_DEBUG, __FILE__, __LINE__, __VA_ARGS__) #define LOGI(...) CAsyncLog::output(LOG_LEVEL_INFO, __FILE__, __LINE__, __VA_ARGS__) #define LOGW(...) CAsyncLog::output(LOG_LEVEL_WARNING, __FILE__, __LINE__, __VA_ARGS__) #define LOGE(...) CAsyncLog::output(LOG_LEVEL_ERROR, __FILE__, __LINE__, __VA_ARGS__) #define LOGSYSE(...) CAsyncLog::output(LOG_LEVEL_SYSERROR, __FILE__, __LINE__, __VA_ARGS__) #define LOGF(...) CAsyncLog::output(LOG_LEVEL_FATAL, __FILE__, __LINE__, __VA_ARGS__) #define LOGC(...) CAsyncLog::output(LOG_LEVEL_CRITICAL, __FILE__, __LINE__, __VA_ARGS__) #define LOG_DEBUG_BIN(buf, buflength) CAsyncLog::outputBinary(buf, buflength) class LOG_API CAsyncLog { public: static bool init(const char* pszLogFileName = nullptr, bool bTruncateLongLine = false, int64_t m_nFileRollSize = 10 * 1024 * 1024); static void uninit(); static void setLevel(LOG_LEVEL nLevel); static bool isRunning(); //不输出线程ID和函数签名、行号 static bool output(long nLevel, const char* pszFmt, ...); //输出线程ID和函数签名、行号 static bool output(long nLevel, const char* pszFileName, int nLineNo, const char* pszFmt, ...); static bool outputBinary(unsigned char* buffer, size_t); private: CAsyncLog() = delete; ~CAsyncLog() = delete; CAsyncLog(const CAsyncLog& rhs) = delete; CAsyncLog& operator=(const CAsyncLog& rhs) = delete; static void makeLinePrefix(long nLevel, std::string& strPrefix); static void getTime(char* pszTime, int nTimeStrLength); static bool createNewFile(const char* pzsLogFileName); static bool writeToFile(const std::string& data); static void crash(); static const char* ullto4Str(int n); static char* formLog(int& index, char* szbuf, size_t size_buf, unsigned char* buffer, size_t size); static void writeThreadProc(); private: static bool m_bToFile; //日志写入控制台还是文件 static FILE* m_hLogFile; static std::string m_strFileName; static std::string m_strFileNamePID; //文件名中的进程ID static bool m_bTruncateLongLog; //长日志是否截断 static LOG_LEVEL m_nCurrentLevel; static int64_t m_nFileRollSize; //单个文件的最大字节数 static int64_t m_nCurrentWrittenSize; //已经写入的字节数目 static std::list<std::string> m_listLinesToWrite; //待写入日志存储区 static std::unique_ptr<std::thread> m_spWriteThread; static std::mutex m_mutexWrite; static std::condition_variable m_cvWrite; static bool m_bExit; static bool m_bRunning; };
[ "378961928@qq.com" ]
378961928@qq.com
b69c88c43269d9ae7409413fb7d83767821d52fc
0b7ed7ae257284c31ba1b43e99d876dfb6999bc8
/SBFspot/ArchData.cpp
2499024c8165c0032fe08490d9f85c8abeb0811d
[]
no_license
hatziliontos/SBFspot-OpenWRT-Cross-Compile-DLINK-DIR-505
0f3ed1ac329caa5f8e0cbc4132c9713056607eb5
76ba5121a376706c344f88744f5e083113cf6145
refs/heads/main
2023-02-11T06:34:26.865453
2021-01-05T04:11:53
2021-01-05T04:11:53
326,744,185
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
16,956
cpp
/************************************************************************************************ SBFspot - Yet another tool to read power production of SMA® solar inverters (c)2012-2020, SBF Latest version found at https://github.com/SBFspot/SBFspot License: Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0) http://creativecommons.org/licenses/by-nc-sa/3.0/ You are free: to Share — to copy, distribute and transmit the work to Remix — to adapt the work Under the following conditions: Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). Noncommercial: You may not use this work for commercial purposes. Share Alike: If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one. DISCLAIMER: A user of SBFspot software acknowledges that he or she is receiving this software on an "as is" basis and the user is not relying on the accuracy or functionality of the software for any purpose. The user further acknowledges that any use of this software will be at his own risk and the copyright owner accepts no responsibility whatsoever arising from the use or application of the software. SMA is a registered trademark of SMA Solar Technology AG ************************************************************************************************/ #include "ArchData.h" using namespace std; using namespace boost; using namespace boost::date_time; using namespace boost::posix_time; using namespace boost::gregorian; E_SBFSPOT ArchiveDayData(InverterData *inverters[], time_t startTime) { if (VERBOSE_NORMAL) { puts("********************"); puts("* ArchiveDayData() *"); puts("********************"); } bool hasMultigate = false; startTime -= 86400; // fix Issue CP23: to overcome problem with DST transition - RB@20140330 E_SBFSPOT rc = E_OK; struct tm start_tm; memcpy(&start_tm, localtime(&startTime), sizeof(start_tm)); start_tm.tm_hour = 0; start_tm.tm_min = 0; start_tm.tm_sec = 0; start_tm.tm_mday++; // fix Issue CP23: to overcome problem with DST transition - RB@20140330 startTime = mktime(&start_tm); if (VERBOSE_NORMAL) printf("startTime = %08lX -> %s\n", startTime, strftime_t("%d/%m/%Y %H:%M:%S", startTime)); for (int inv=0; inverters[inv]!=NULL && inv<MAX_INVERTERS; inv++) { if (inverters[inv]->SUSyID == SID_MULTIGATE) hasMultigate = true; inverters[inv]->hasDayData = false; for(unsigned int i=0; i<sizeof(inverters[inv]->dayData)/sizeof(DayData); i++) { DayData *pdayData = &inverters[inv]->dayData[i]; pdayData->datetime = 0; pdayData->totalWh = 0; pdayData->watt = 0; } } int packetcount = 0; int validPcktID = 0; E_SBFSPOT hasData = E_ARCHNODATA; for (int inv=0; inverters[inv]!=NULL && inv<MAX_INVERTERS; inv++) { if ((inverters[inv]->DevClass != CommunicationProduct) && (inverters[inv]->SUSyID != SID_MULTIGATE)) { do { pcktID++; writePacketHeader(pcktBuf, 0x01, inverters[inv]->BTAddress); writePacket(pcktBuf, 0x09, 0xE0, 0, inverters[inv]->SUSyID, inverters[inv]->Serial); writeLong(pcktBuf, 0x70000200); writeLong(pcktBuf, startTime - 300); writeLong(pcktBuf, startTime + 86100); writePacketTrailer(pcktBuf); writePacketLength(pcktBuf); } while (!isCrcValid(pcktBuf[packetposition-3], pcktBuf[packetposition-2])); if (ConnType == CT_BLUETOOTH) bthSend(pcktBuf); else ethSend(pcktBuf, inverters[inv]->IPAddress); do { unsigned long long totalWh = 0; unsigned long long totalWh_prev = 0; time_t datetime = 0; time_t datetime_prev = 0; time_t datetime_next = 0; bool dblrecord = false; // Flag for double records (twins) const int recordsize = 12; do { if (ConnType == CT_BLUETOOTH) rc = getPacket(inverters[inv]->BTAddress, 1); else rc = ethGetPacket(); if (rc != E_OK) return rc; packetcount = pcktBuf[25]; //TODO: Move checksum validation to getPacket if ((ConnType == CT_BLUETOOTH) && (!validateChecksum())) return E_CHKSUM; else { unsigned short rcvpcktID = get_short(pcktBuf+27) & 0x7FFF; if ((validPcktID == 1) || (pcktID == rcvpcktID)) { validPcktID = 1; for(int x = 41; x < (packetposition - 3); x += recordsize) { datetime_next = (time_t)get_long(pcktBuf + x); if (0 != (datetime_next - datetime)) // Fix Issue 108: sbfspot v307 crashes for daily export (-adnn) { totalWh_prev = totalWh; datetime_prev = datetime; datetime = datetime_next; dblrecord = false; } else dblrecord = true; totalWh = (unsigned long long)get_longlong(pcktBuf + x + 4); if (totalWh != NaN_U64) // Fix Issue 109: Bad request 400: Power value too high for system size { if (totalWh > 0) hasData = E_OK; if (totalWh_prev != 0) { struct tm timeinfo; memcpy(&timeinfo, localtime(&datetime), sizeof(timeinfo)); if (start_tm.tm_mday == timeinfo.tm_mday) { unsigned int idx = (timeinfo.tm_hour * 12) + (timeinfo.tm_min / 5); if (idx < sizeof(inverters[inv]->dayData)/sizeof(DayData)) { if (VERBOSE_HIGHEST && dblrecord) { std::cout << "Overwriting existing record: " << strftime_t("%d/%m/%Y %H:%M:%S", datetime); std::cout << " - " << std::fixed << std::setprecision(3) << (double)inverters[inv]->dayData[idx].totalWh/1000 << "kWh"; std::cout << " - " << std::fixed << std::setprecision(0) << inverters[inv]->dayData[idx].watt << "W" << std::endl; } if (VERBOSE_HIGHEST && ((datetime - datetime_prev) > 300)) { std::cout << "Missing records in datastream " << strftime_t("%d/%m/%Y %H:%M:%S", datetime_prev); std::cout << " -> " << strftime_t("%H:%M:%S", datetime) << std::endl; } inverters[inv]->dayData[idx].datetime = datetime; inverters[inv]->dayData[idx].totalWh = totalWh; //inverters[inv]->dayData[idx].watt = (totalWh - totalWh_prev) * 12; // 60:5 // Fix Issue 105 - Don't assume each interval is 5 mins // This is also a bug in SMA's Sunny Explorer V1.07.17 and before inverters[inv]->dayData[idx].watt = (totalWh - totalWh_prev) * 3600 / (datetime - datetime_prev); inverters[inv]->hasDayData = true; } } } } } //for } else { if (DEBUG_HIGHEST) printf("Packet ID mismatch. Expected %d, received %d\n", pcktID, rcvpcktID); validPcktID = 0; packetcount = 0; } } } while (packetcount > 0); } while (validPcktID == 0); } } if (hasMultigate) { /* * Consolidate micro-inverter daydata into multigate * For each multigate search its connected devices * Add totalWh and power of each device to multigate daydata */ if (VERBOSE_HIGHEST) std::cout << "Consolidating daydata of micro-inverters into multigate..." << std::endl; for (int mg=0; inverters[mg]!=NULL && mg<MAX_INVERTERS; mg++) { InverterData *pmg = inverters[mg]; if (pmg->SUSyID == SID_MULTIGATE) { pmg->hasDayData = true; for (int sb240=0; inverters[sb240]!=NULL && sb240<MAX_INVERTERS; sb240++) { InverterData *psb = inverters[sb240]; if ((psb->SUSyID == SID_SB240) && (psb->multigateID == mg)) { for (unsigned int dd=0; dd < ARRAYSIZE(inverters[0]->dayData); dd++) { pmg->dayData[dd].datetime = psb->dayData[dd].datetime; pmg->dayData[dd].totalWh += psb->dayData[dd].totalWh; pmg->dayData[dd].watt += psb->dayData[dd].watt; } } } } } } return hasData; } E_SBFSPOT ArchiveMonthData(InverterData *inverters[], tm *start_tm) { if (VERBOSE_NORMAL) { puts("**********************"); puts("* ArchiveMonthData() *"); puts("**********************"); } bool hasMultigate = false; E_SBFSPOT rc = E_OK; // Set time to 1st of the month at 12:00:00 start_tm->tm_hour = 12; start_tm->tm_min = 0; start_tm->tm_sec = 0; start_tm->tm_mday = 1; time_t startTime = mktime(start_tm); if (VERBOSE_NORMAL) printf("startTime = %08lX -> %s\n", startTime, strftime_t("%d/%m/%Y %H:%M:%S", startTime)); for (int inv=0; inverters[inv]!=NULL && inv<MAX_INVERTERS; inv++) { if (inverters[inv]->SUSyID == SID_MULTIGATE) hasMultigate = true; inverters[inv]->hasMonthData = false; for(unsigned int i=0; i<sizeof(inverters[inv]->monthData)/sizeof(MonthData); i++) { inverters[inv]->monthData[i].datetime = 0; inverters[inv]->monthData[i].dayWh = 0; inverters[inv]->monthData[i].totalWh = 0; } } int packetcount = 0; int validPcktID = 0; for (int inv=0; inverters[inv]!=NULL && inv<MAX_INVERTERS; inv++) { if ((inverters[inv]->DevClass != CommunicationProduct) && (inverters[inv]->SUSyID != SID_MULTIGATE)) { do { pcktID++; writePacketHeader(pcktBuf, 0x01, inverters[inv]->BTAddress); writePacket(pcktBuf, 0x09, 0xE0, 0, inverters[inv]->SUSyID, inverters[inv]->Serial); writeLong(pcktBuf, 0x70200200); writeLong(pcktBuf, startTime - 86400 - 86400); writeLong(pcktBuf, startTime + 86400 * (sizeof(inverters[inv]->monthData)/sizeof(MonthData) +1)); writePacketTrailer(pcktBuf); writePacketLength(pcktBuf); } while (!isCrcValid(pcktBuf[packetposition-3], pcktBuf[packetposition-2])); if (ConnType == CT_BLUETOOTH) bthSend(pcktBuf); else ethSend(pcktBuf, inverters[inv]->IPAddress); do { unsigned long long totalWh = 0; unsigned long long totalWh_prev = 0; const int recordsize = 12; time_t datetime; unsigned int idx = 0; do { if (ConnType == CT_BLUETOOTH) rc = getPacket(inverters[inv]->BTAddress, 1); else rc = ethGetPacket(); if (rc != E_OK) return rc; //TODO: Move checksum validation to getPacket if ((ConnType == CT_BLUETOOTH) && (!validateChecksum())) return E_CHKSUM; else { packetcount = pcktBuf[25]; unsigned short rcvpcktID = get_short(pcktBuf+27) & 0x7FFF; if ((validPcktID == 1) || (pcktID == rcvpcktID)) { validPcktID = 1; for(int x = 41; x < (packetposition - 3); x += recordsize) { datetime = (time_t)get_long(pcktBuf + x); //datetime -= (datetime % 86400) + 43200; // 3.0 - Round to UTC 12:00 - Removed 3.0.1 see issue C54 datetime += inverters[inv]->monthDataOffset; // Issues 115/130 totalWh = get_longlong(pcktBuf + x + 4); if (totalWh != MAXULONGLONG) { if (totalWh_prev != 0) { struct tm utc_tm; memcpy(&utc_tm, gmtime(&datetime), sizeof(utc_tm)); if (utc_tm.tm_mon == start_tm->tm_mon) { if (idx < sizeof(inverters[inv]->monthData)/sizeof(MonthData)) { inverters[inv]->hasMonthData = true; inverters[inv]->monthData[idx].datetime = datetime; inverters[inv]->monthData[idx].totalWh = totalWh; inverters[inv]->monthData[idx].dayWh = totalWh - totalWh_prev; idx++; } } } totalWh_prev = totalWh; } } //for } else { if (DEBUG_HIGHEST) printf("Packet ID mismatch. Expected %d, received %d\n", pcktID, rcvpcktID); validPcktID = 0; packetcount = 0; } } } while (packetcount > 0); } while (validPcktID == 0); } } if (hasMultigate) { /* * Consolidate micro-inverter monthdata into multigate * For each multigate search its connected devices * Add totalWh and power of each device to multigate daydata */ if (VERBOSE_HIGHEST) std::cout << "Consolidating monthdata of micro-inverters into multigate..." << std::endl; for (int mg=0; inverters[mg]!=NULL && mg<MAX_INVERTERS; mg++) { InverterData *pmg = inverters[mg]; if (pmg->SUSyID == SID_MULTIGATE) { pmg->hasMonthData = true; for (int sb240=0; inverters[sb240]!=NULL && sb240<MAX_INVERTERS; sb240++) { InverterData *psb = inverters[sb240]; if ((psb->SUSyID == SID_SB240) && (psb->multigateID == mg)) { for (unsigned int md=0; md < ARRAYSIZE(inverters[0]->monthData); md++) { pmg->monthData[md].datetime = psb->monthData[md].datetime; pmg->monthData[md].totalWh += psb->monthData[md].totalWh; pmg->monthData[md].dayWh += psb->monthData[md].dayWh; } } } } } } return E_OK; } E_SBFSPOT ArchiveEventData(InverterData *inverters[], boost::gregorian::date startDate, unsigned long UserGroup) { E_SBFSPOT rc = E_OK; unsigned short pcktcount = 0; int validPcktID = 0; time_t startTime = to_time_t(startDate); time_t endTime = startTime + 86400 * startDate.end_of_month().day(); for (int inv=0; inverters[inv]!=NULL && inv<MAX_INVERTERS; inv++) { do { pcktID++; writePacketHeader(pcktBuf, 0x01, inverters[inv]->BTAddress); writePacket(pcktBuf, 0x09, 0xE0, 0, inverters[inv]->SUSyID, inverters[inv]->Serial); writeLong(pcktBuf, UserGroup == UG_USER ? 0x70100200 : 0x70120200); writeLong(pcktBuf, startTime); writeLong(pcktBuf, endTime); writePacketTrailer(pcktBuf); writePacketLength(pcktBuf); } while (!isCrcValid(pcktBuf[packetposition-3], pcktBuf[packetposition-2])); if (ConnType == CT_BLUETOOTH) bthSend(pcktBuf); else ethSend(pcktBuf, inverters[inv]->IPAddress); bool FIRST_EVENT_FOUND = false; do { do { if (ConnType == CT_BLUETOOTH) rc = getPacket(inverters[inv]->BTAddress, 1); else rc = ethGetPacket(); if (rc != E_OK) return rc; //TODO: Move checksum validation to getPacket if ((ConnType == CT_BLUETOOTH) && (!validateChecksum())) return E_CHKSUM; else { pcktcount = get_short(pcktBuf+25); unsigned short rcvpcktID = get_short(pcktBuf+27) & 0x7FFF; if ((validPcktID == 1) || (pcktID == rcvpcktID)) { validPcktID = 1; for (int x = 41; x < (packetposition - 3); x += sizeof(SMA_EVENTDATA)) { SMA_EVENTDATA *pEventData = (SMA_EVENTDATA *)(pcktBuf + x); if (pEventData->DateTime > 0) // Fix Issue 89 { inverters[inv]->eventData.push_back(EventData(UserGroup, pEventData)); if (pEventData->EntryID == 1) { FIRST_EVENT_FOUND = true; rc = E_EOF; } } } } else { if (DEBUG_HIGHEST) printf("Packet ID mismatch. Expected %d, received %d\n", pcktID, rcvpcktID); validPcktID = 0; pcktcount = 0; } } } while (pcktcount > 0); } while ((validPcktID == 0) && (!FIRST_EVENT_FOUND)); } return rc; } //Issues 115/130 E_SBFSPOT getMonthDataOffset(InverterData *inverters[]) { E_SBFSPOT rc = E_OK; time_t now = time(NULL); struct tm now_tm; memcpy(&now_tm, gmtime(&now), sizeof(now_tm)); // Temporarily disable verbose logging int currentVerboseLevel = verbose; verbose = 0; rc = ArchiveMonthData(inverters, &now_tm); verbose = currentVerboseLevel; if (rc == E_OK) { for (int inv=0; inverters[inv]!=NULL && inv<MAX_INVERTERS; inv++) { inverters[inv]->monthDataOffset = 0; if (inverters[inv]->hasMonthData) { // Get last record of monthdata for(int i = 30; i > 0; i--) { if (inverters[inv]->monthData[i].datetime != 0) { now = time(NULL); memcpy(&now_tm, gmtime(&now), sizeof(now_tm)); struct tm inv_tm; memcpy(&inv_tm, gmtime(&inverters[inv]->monthData[i].datetime), sizeof(inv_tm)); if (now_tm.tm_yday == inv_tm.tm_yday) inverters[inv]->monthDataOffset = -86400; break; } } } if ((DEBUG_HIGHEST) && (!quiet)) std::cout << inverters[inv]->SUSyID << ":" << inverters[inv]->Serial << " monthDataOffset=" << inverters[inv]->monthDataOffset << std::endl; } } return rc; }
[ "noreply@github.com" ]
noreply@github.com
9eadb9cd59f90d44e65b7de3fa09b9a7bd20eda9
464aa9d7d6c4906b083e6c3da12341504b626404
/src/lib/romp/sea.cpp
a3bdbcb1d98a3f93a7cfc1e10c324a070a100fad
[]
no_license
v2v3v4/BigWorld-Engine-2.0.1
3a6fdbb7e08a3e09bcf1fd82f06c1d3f29b84f7d
481e69a837a9f6d63f298a4f24d423b6329226c6
refs/heads/master
2023-01-13T03:49:54.244109
2022-12-25T14:21:30
2022-12-25T14:21:30
163,719,991
182
167
null
null
null
null
UTF-8
C++
false
false
3,422
cpp
/****************************************************************************** BigWorld Technology Copyright BigWorld Pty, Ltd. All Rights Reserved. Commercial in confidence. WARNING: This computer program is protected by copyright law and international treaties. Unauthorized use, reproduction or distribution of this program, or any portion of this program, may result in the imposition of civil and criminal penalties as provided by law. ******************************************************************************/ #include "pch.hpp" #include "sea.hpp" #include "moo/render_context.hpp" #include "geometrics.hpp" #include "math/colour.hpp" /** * Constructor */ Sea::Sea() : seaLevel_( 0.f ), wavePeriod_( 1.f ), waveExtent_( 0.f ), tidePeriod_( 1.f ), tideExtent_( 0.f ), surfaceTopColour_( 0x602000ff ), surfaceBotColour_( 0x40ffffff ), underwaterColour_( 0x602000ff ), waveTime_( 0.f ) { } /** * This method loads a sea from a data section */ void Sea::load( DataSectionPtr pSect ) { this->seaLevel( pSect->readFloat( "seaLevel", seaLevel_ ) ); this->wavePeriod( pSect->readFloat( "wavePeriod", wavePeriod_ ) ); this->waveExtent( pSect->readFloat( "waveExtent", waveExtent_ ) ); this->tidePeriod( pSect->readFloat( "tidePeriod", tidePeriod_ ) ); this->tideExtent( pSect->readFloat( "tideExtent", tideExtent_ ) ); this->surfaceTopColour( Colour::getUint32( pSect->readVector4( "surfaceTopColour", Colour::getVector4( surfaceTopColour_ ) ) ) ); this->surfaceBotColour( Colour::getUint32( pSect->readVector4( "surfaceBotColour", Colour::getVector4( surfaceBotColour_ ) ) ) ); this->underwaterColour( Colour::getUint32( pSect->readVector4( "underwaterColour", Colour::getVector4( underwaterColour_ ) ) ) ); waveTime_ = 0.f; } /** * This method saves a sea into a data section */ void Sea::save( DataSectionPtr pSect ) { pSect->writeFloat( "seaLevel", seaLevel_ ); pSect->writeFloat( "wavePeriod", wavePeriod_ ); pSect->writeFloat( "waveExtent", waveExtent_ ); pSect->writeFloat( "tidePeriod", tidePeriod_ ); pSect->writeFloat( "tideExtent", tideExtent_ ); pSect->writeVector4( "surfaceTopColour", Colour::getVector4( surfaceTopColour_ ) ); pSect->writeVector4( "surfaceBotColour", Colour::getVector4( surfaceBotColour_ ) ); pSect->writeVector4( "underwaterColour", Colour::getVector4( underwaterColour_ ) ); } /** * This method draws the sea */ void Sea::draw( float dTime, float timeOfDay ) { float seaNow = seaLevel_ + waveExtent_ * sinf( waveTime_ * 2.f * MATH_PI / wavePeriod_ ) + tideExtent_ * sinf( timeOfDay * 2.f * MATH_PI / tidePeriod_ ); Vector3 pos( Moo::rc().invView().applyToOrigin() ); Moo::rc().push(); Matrix bigFlat; if (pos.y >= seaNow) { bigFlat.setScale( 5000, 0, 5000 ); bigFlat.translation( Vector3( pos.x, seaNow, pos.z ) ); Moo::rc().world( bigFlat ); Geometrics::drawUnitSquareOnXZPlane( Moo::Colour( surfaceTopColour_ ) ); } else { bigFlat.setScale( -5000, 0, 5000 ); bigFlat.translation( Vector3( pos.x, seaNow, pos.z ) ); Moo::rc().world( bigFlat ); Geometrics::drawUnitSquareOnXZPlane( Moo::Colour( surfaceBotColour_ ) ); Geometrics::drawRect( Vector2( 0.f, 0.f ), Vector2( Moo::rc().screenWidth(), Moo::rc().screenHeight() ), Moo::Colour( underwaterColour_ ) ); } Moo::rc().pop(); waveTime_ += dTime; if (waveTime_ > wavePeriod_) waveTime_ -= wavePeriod_; } // sea.cpp
[ "terran.erre@mail.ru" ]
terran.erre@mail.ru
1ff1282c8a786816e6c5b3a9a46192fd0da26990
d4330de4020bcc0167087be22d0bc1e9ad693f01
/ControlSys.cpp
783a6fde3400218a4d2ad9a79a6dccce9023ed21
[]
no_license
MCLiii/TelloFaceTracking
a3a8f69f51fd87bf1487329a47d26c15913c66c9
36362a56929039c684942b454c3fa5544df98126
refs/heads/main
2023-02-19T06:53:44.017672
2021-01-22T03:36:25
2021-01-22T03:36:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
988
cpp
// // Created by Jim Li on 2020/10/20. // #include "ControlSys.h" void ControlSys::state(int fo, int le, int up, int ro, bool safe) { log<<fo<<" "<<" "<<le<<" "<<ro<<" "<<safe<<"\n"; cout<<fo<<" "<<" "<<le<<" "<<ro<<" "<<safe<<"\n"; string msg = "rc " + to_string(fo) + " " + to_string(le) + " " + to_string(up) + " " + to_string(ro); //cout<<msg<<"\n"; packetSend.udpSend(&msg[0]); if (safe) startSecureThread(); } void ControlSys::emergencyStop() { state(0, 0, 0, 0, 0); } void ControlSys::trigger() { sleep(3); emergencyStop(); } void ControlSys::startSecureThread() { t = thread(&ControlSys::trigger, this); t.detach(); } void ControlSys::send(char msg[]) { log<<msg<<"\n"; packetSend.udpSend(msg); } void ControlSys::takeOff() { send("takeoff"); } void ControlSys::land() { send("land"); } void ControlSys::state(int fo, int le, int up) { state(fo * velocity, le * velocity, up * velocity, 0, 0); }
[ "noreply@github.com" ]
noreply@github.com
feda22a8ac44de4c995144dff61cb899fd223483
e68dfb0081d396363c15e9dd486320352af64f4c
/leetcode/InsertInterval.cc
408121e75d4ab724e220440fc2143a2aeae6cd79
[]
no_license
bxyang/helloworld
9abe1176c7973cf8af9451375198a21219d5d7d5
f96ba5e3e1d1fa18056e15faa6336abb994a4242
refs/heads/master
2020-04-09T16:52:09.975377
2018-12-17T03:51:00
2018-12-17T03:51:00
10,117,301
0
0
null
null
null
null
UTF-8
C++
false
false
8,180
cc
/* * ===================================================================================== * * Filename: InsertInterval.cc * * Description: Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. * * * Version: 1.0 * Created: 2013/8/3 18:50:57 * Revision: none * Compiler: gcc * * Author: yang_bao_xing@163.com * Organization: ict * * ===================================================================================== */ /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { // Start typing your C/C++ solution below // DO NOT write int main() function if (intervals.size() == 0) return vector<Interval>(1, newInterval); if (intervals.size() == 1) { Interval i1 = intervals[0]; intervals.clear(); merge_interval(i1, newInterval, intervals); return intervals; } int i = 0; int p1 = -1; int p2 = -1; int start; int end; vector<Interval> ret; vector<Interval>::iterator it = intervals.begin(); for (; it != intervals.end(); it++, i++) { if (newInterval.start <= it -> start) break; } p1 = i; if (p1 == intervals.size()) { Interval i1 = (*(intervals.end() - 1)); intervals.pop_back(); merge_interval(i1, newInterval, intervals); return intervals; } if (p1 == 0) start = newInterval.start; else { if (newInterval.start > intervals[p1-1].end) start = newInterval.start; else start = intervals[--p1].start; } for (int j = 0; j < p1; j++) ret.push_back(intervals[j]); if (i != 0) { it--; i--; } for (; it != intervals.end(); it++, i++) { if (newInterval.end <= it -> end) break; } p2 = i; if (p2 == intervals.size()) { ret.push_back(Interval(start, newInterval.end)); return ret; } if (newInterval.end < intervals[p2].start) { end = newInterval.end; } else { end = intervals[p2].end; p2++; } ret.push_back(Interval(start, end)); for (int j = p2; j < intervals.size(); j++) ret.push_back(intervals[j]); return ret; } void merge_interval(Interval i1, Interval i2, vector<Interval> &intervals) { if (i1.start > i2.end) { intervals.push_back(i2); intervals.push_back(i1); } else if (i1.end < i2.start) { intervals.push_back(i1); intervals.push_back(i2); } else { i1.start = i1.start < i2.start ? i1.start : i2.start; i1.end = i1.end > i2.end ? i1.end : i2.end; intervals.push_back(i1); } } }; /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { // Start typing your C/C++ solution below // DO NOT write int main() function if (intervals.size() == 0) return vector<Interval>(1, newInterval); int i = bi_search(intervals, 0, intervals.size() - 1, newInterval.start); vector<Interval> ret; for (int j = 0; j <= (i-2); j++) ret.push_back(intervals[j]); int start; if (i==0) start = newInterval.start; else { if (newInterval.start <= intervals[i-1].end) start = intervals[i-1].start; else { start = newInterval.start; ret.push_back(intervals[i-1]); } } int k = (i == 0) ? 0:(i-1); int end = newInterval.end; if (intervals[k].start > newInterval.end) ret.push_back(Interval(start, end)); else{ for (; k < intervals.size(); k++) { if (intervals[k].end >= newInterval.end) { if (intervals[k].start > newInterval.end) { end = newInterval.end; k--; break; } end = intervals[k].end; break; } } ret.push_back(Interval(start, end)); k++; } for (; k < intervals.size(); k++) ret.push_back(intervals[k]); return ret; } int bi_search(vector<Interval> &intervals, int left, int right, int target) { while (left < right) { int mid = left + (right - left)/2; int key = intervals[mid].start; if (key >= target) right = mid; else if (key < target) left = mid + 1; } if (intervals[left].start >= target) return left; return intervals.size(); } }; /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { // Start typing your C/C++ solution below // DO NOT write int main() function if (intervals.size() == 0) return vector<Interval>(1, newInterval); vector<Interval> ret; int left = bi_search(intervals, get_start, 0, intervals.size() - 1, newInterval.start); int right = bi_search(intervals, get_end, 0, intervals.size() - 1, newInterval.end); for (int j = 0; j <= (left-2); j++) ret.push_back(intervals[j]); int start; if (left == 0) start = newInterval.start; else { if (newInterval.start <= intervals[left-1].end) start = intervals[left-1].start; else { start = newInterval.start; ret.push_back(intervals[left-1]); } } int end ; if ((right == intervals.size()) || (intervals[right].start > newInterval.end)) { end = newInterval.end; } else { end = intervals[right].end; right++; } ret.push_back(Interval(start, end)); for (; right < intervals.size(); right++) ret.push_back(intervals[right]); return ret; } static int get_start(Interval &interval) { return interval.start; } static int get_end(Interval &interval) { return interval.end; } int bi_search(vector<Interval> &intervals, int (*f) (Interval&), int left, int right, int target) { while (left < right) { int mid = left + (right - left)/2; int key = f(intervals[mid]); if (key >= target) right = mid; else if (key < target) left = mid + 1; } if (f(intervals[right]) >= target) return left; return intervals.size(); } };
[ "yangbaoxing@gmail,com" ]
yangbaoxing@gmail,com
fe34f77c888c1adf4206f2f14b17c182e79a9b67
ca259e07dc944b1a85656f53f7467e59518a715c
/src/planner/binder/statement/bind_show.cpp
60c7d5db817d27f1e655326211d4be62e1ed0680
[ "MIT" ]
permissive
sdmcallister/duckdb
3230a8c925999634479dcb962db113eaa19d3fcb
2d6cf867beb628dac57e8f605a9136738fd7f9a8
refs/heads/master
2023-03-06T08:05:07.475698
2021-01-28T08:15:22
2021-01-28T08:15:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
774
cpp
#include "duckdb/planner/binder.hpp" #include "duckdb/parser/statement/show_statement.hpp" #include "duckdb/planner/operator/logical_show.hpp" using namespace duckdb; using namespace std; BoundStatement Binder::Bind(ShowStatement &stmt) { BoundStatement result; auto plan = Bind(*stmt.info->query); stmt.info->types = plan.types; stmt.info->aliases = plan.names; auto show = make_unique<LogicalShow>(move(plan.plan)); show->types_select = plan.types; show->aliases = plan.names; result.plan = move(show); result.names = {"Field", "Type", "Null", "Key", "Default", "Extra"}; result.types = {LogicalType::VARCHAR, LogicalType::VARCHAR, LogicalType::VARCHAR, LogicalType::VARCHAR, LogicalType::VARCHAR, LogicalType::VARCHAR}; return result; }
[ "nantiamakr@gmail.com" ]
nantiamakr@gmail.com
20449e8c4760534f5d2339f452f1c7af7bc26f02
b4ea48eee50a3637dc1c4b7d0ee013388d32576e
/Bai267/Bai267/main.cpp
cf7dee5a25732bce75b23adfc7af394ec5723dc9
[]
no_license
0793928980/UE4
0c36eaabe34ccb82703bea312681a95398b923c4
190528723786341268e6d07e72ab06e4e27ac307
refs/heads/master
2023-01-01T17:08:13.919799
2020-10-18T16:24:13
2020-10-18T16:24:13
294,868,459
0
0
null
null
null
null
UTF-8
C++
false
false
1,456
cpp
// // main.cpp // Bai267 // // Created by MACBOOK PRO on 10/9/20. // Copyright © 2020 Ganukuyou. All rights reserved. // #include <iostream> using namespace std; void NhapMang(int a[], int &n) { int i,j; int t; for(i=0;i<n;i++) { cout<<"Nhap a["<<i<<"]\n"; cin>>a[i]; for(j=0;j<i;j++) { if(a[i]>a[j]) { t=a[i]; int k; for(k=i;k>j;k--) { a[k]=a[k-1]; } a[j]=t; break; } } } } void nhap (int a[], int &n) { int i, j, k; for(i = 0; i < n; i++) { cout<<"Nhap a["<<i<<"]\n"; cin>>a[i]; for(j = 0; j <i; j++) { if(a[i] > a[j]) { int temp = a[i]; for(k = i; k > j; k--) { a[k] = a[k - 1]; } a[j] = temp; break; } } } } void Xuat(int a[], int n) { int i; for(i=0;i<n;i++) { cout<<a[i]<<" "; } } int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; int n; cout<<"nhap N: \n"; cin>>n; int a[100]; NhapMang(a, n); cout<<"\n------------ Xuat mang ----------\n"; Xuat(a, n); return 0; }
[ "b1807541binhlekg@gmail.com" ]
b1807541binhlekg@gmail.com