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
2cc51186988cc562c30480149d2e4fd2ecf428ff
f65dcb78e78e19a8f4124c57f91cc53fd5c7869a
/2017.7.2/c.cpp
7261ace930e8a620b55bf2565ef4325e6888ac78
[ "Apache-2.0" ]
permissive
1980744819/ACM-code
8a1c46f20a09acc866309176471367d62ca14cef
a697242bc963e682e552e655e3d78527e044e854
refs/heads/master
2020-03-29T01:16:41.766331
2018-09-19T02:39:26
2018-09-19T02:39:26
149,380,865
0
0
null
null
null
null
UTF-8
C++
false
false
1,276
cpp
#include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<cmath> #include<iostream> #include<algorithm> #include<vector> #include<queue> #include<map> #include<set> #include<stack> using namespace std; struct stu{ int pos,step; }; bool book[400005]; int main(){ //freopen("test.txt","r",stdin); int n,k; int num; queue<struct stu>que; struct stu tmp,tm; while(~scanf("%d %d",&n,&k)){ tmp.pos=n; tmp.step=0; que.push(tmp); if(n==k){ printf("0\n"); continue; } while(!que.empty()){ tm=que.front(); //printf("%d %d\n",tm.pos,tm.step); tmp.pos=tm.pos+1; tmp.step=tm.step+1; if(tmp.pos==k){ printf("%d\n",tmp.step); break; } if(book[tmp.pos]==false){ que.push(tmp); book[tmp.pos]=true; } tmp.pos=tm.pos-1; tmp.step=tm.step+1; if(tmp.pos==k){ printf("%d\n",tmp.step); break; } if(book[tmp.pos]==false&&tmp.pos>=0){ que.push(tmp); book[tmp.pos]=true; } tmp.pos=tm.pos*2; tmp.step=tm.step+1; if(tmp.pos==k){ printf("%d\n",tmp.step); break; } if(book[tmp.pos]==false&&tmp.pos<100105){ que.push(tmp); book[tmp.pos]=true; } que.pop(); } while(!que.empty()){ que.pop(); } memset(book,false,sizeof(book)); } return 0; }
[ "1980744819@qq.com" ]
1980744819@qq.com
432e152f8f3d1e39904014ee07ed9d78b890a99d
25ef1af901b18b211530b4945a87e51bd5bc91ed
/AreaCube.cpp
97acb0ee8c1bcec3f5c8b9c60f001935176ad511
[]
no_license
ehacinom/Cpp
45d4d77c400be40ea369a4f91e14516c0d57b65e
09b4b0949c2b6c9341249363fd6a188ffe480525
refs/heads/master
2016-08-11T08:34:51.320084
2016-04-02T05:10:58
2016-04-02T05:10:58
54,847,570
0
0
null
null
null
null
UTF-8
C++
false
false
550
cpp
#include <iostream> int findArea(int length, int width = 20, int height = 12); int main() { int length = 100; int width = 50; int height = 2; int area; area = findArea(length, width, height); std::cout << "First area: " << area << "\n"; area = findArea(length, width); std::cout << "Second area: " << area << "\n"; area = findArea(length); std::cout << "Third area: " << area << "\n\n"; return 0; } int findArea(int length, int width, int height) { return (length * width * height); }
[ "ehacinom@gmail.com" ]
ehacinom@gmail.com
6df72a647623789f28e5d185697de0d80a56d854
afeacb29771604150b1cc14d6e5c105c19bc4bef
/src/behaviours/Flee.h
7a2c5a467b54874bf811d3d71c48116fed2c8afe
[]
no_license
miron178/flock
c94684f59927a4c65fa974d51fec43b9e50208e2
7353a9de120d5c641eebcfcd2587ce652eb6aa6d
refs/heads/master
2023-05-15T02:01:56.019474
2021-06-10T23:57:23
2021-06-10T23:57:23
365,848,149
0
0
null
null
null
null
UTF-8
C++
false
false
248
h
#ifndef FLEE_H #define FLEE_H #include "Behaviour.h" class Flee : public Behaviour { public: Flee(const Entity* a_pAgent, const glm::vec3* a_pTarget); virtual ~Flee() = default; virtual glm::vec3 Force() override; }; #endif //FLEE_H
[ "miron.bury@gmail.com" ]
miron.bury@gmail.com
b7c083ed718e6a2def85707a4c7ded72c6ff03f8
b8d3c2478cb9e26a1ae9f2413e7dac2e78e8f0d3
/Unmanaged/HVisionSystem/include/Matrox/Heighter.h
8a55e4769dd1aa839505b3bcf52c92db2ca305b5
[ "MS-PL", "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
wiseants/Varins
4281ddf31f3cff6b8dc5e62530186d3795e844c7
8b9153bc46c669c572f2e56fe313a92cb546c5ae
refs/heads/master
2022-12-09T20:25:58.574485
2020-11-10T07:38:10
2020-11-10T07:38:10
242,623,978
0
0
NOASSERTION
2022-12-08T02:14:40
2020-02-24T01:50:05
C++
UTF-8
C++
false
false
1,326
h
// Heighter.h: interface for the CHeighter class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_HEIGHTER_H__AFD99754_161B_4ED8_8FB4_844A95ACD938__INCLUDED_) #define AFX_HEIGHTER_H__AFD99754_161B_4ED8_8FB4_844A95ACD938__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <vector> #include <map> #include <list> class CHeighter { public: CHeighter(); virtual ~CHeighter(); void InsertValue(const float& _fZ); float Calculation(const float& _fAveHeight, const float& _fAveBottomHeight); protected: typedef std::vector<float> HeightVec, *LpHeightVec; typedef std::map<int, HeightVec> HeightMap, *LpHeightMap; typedef std::list<HeightVec> HeightVecList, *LpHeightVecList; int FindRange(const float& _fUpper, const float& _fLower, const float& _fGap, const float& _fZ); void AddRangeElement(const int& _iKey, const float& _fZ); void FindMaxCountHeightVec(LpHeightVecList _lpListHeight); void AddHeightList(const LpHeightVec _lpVecHeight, const size_t& _nCount, LpHeightVecList _lpListHeight); float CalcAveHeight(LpHeightVecList _lpListHeight); float CalcAveHeight(LpHeightVec _lpVecHeight); private: HeightVec m_vecHeight; HeightMap m_mapHeight; }; #endif // !defined(AFX_HEIGHTER_H__AFD99754_161B_4ED8_8FB4_844A95ACD938__INCLUDED_)
[ "wiseants@nate.com" ]
wiseants@nate.com
fa315360910c927b0a0a41a0eabbde2c904cfafe
09cbd3eb63b290115682c72d529087ae0a56fc71
/runtime/interpreter/interpreter.cpp
48696f9cf078d52c2ab0ad18bcf4de5d60a4c0d1
[ "Apache-2.0" ]
permissive
openharmony-gitee-mirror/ark_runtime_core
ac3c512a58fd6b52315da0c6f099edf827cd88e6
2e6f195caf482dc9607efda7cfb5cc5f98da5598
refs/heads/master
2022-07-28T07:38:29.271322
2021-11-25T11:45:47
2021-11-25T11:45:47
410,627,949
0
0
null
null
null
null
UTF-8
C++
false
false
1,284
cpp
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "runtime/interpreter/interpreter.h" #include "runtime/include/method.h" #include "runtime/interpreter/arch/macros.h" #include "runtime/interpreter/interpreter_impl.h" #ifdef PANDA_INTERPRETER_ARCH_GLOBAL_REGS_H_ #error "arch/global_reg.h must not be included as it can broke ABI" #endif namespace panda::interpreter { void Execute(ManagedThread *thread, const uint8_t *pc, Frame *frame, bool jump_to_eh) { ExecuteImpl(thread, pc, frame, jump_to_eh); RESTORE_GLOBAL_REGS(); } } // namespace panda::interpreter namespace panda { ALWAYS_INLINE inline const uint8_t *Frame::GetInstrOffset() { return (method_->GetInstructions()); } } // namespace panda
[ "wanyanglan1@huawei.com" ]
wanyanglan1@huawei.com
48d932c9d84eaf9e7af7abfc1ea4be76d314c973
3fe2565e6e13a26ec54e43a767180a787f72a6dc
/drivers/I2Cdev.h
ab2ef3e1a9a23c679672ef495731338ddc222af7
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
bennierex/Python-Navio
2ba1cadbe0e476304deddfb063e417eef8beb6c8
d2a6d53a6e3ffd766c62586bf16985edb87ae0ae
refs/heads/master
2021-01-25T07:08:36.068702
2015-05-20T12:22:31
2015-05-20T12:22:31
25,946,318
1
0
null
null
null
null
UTF-8
C++
false
false
5,231
h
// i2cDev library collection - Main I2C device class header file // Abstracts bit and byte I2C R/W functions into a convenient class // 6/9/2012 by Jeff Rowberg <jeff@rowberg.net> // // Changelog: // 2012-06-09 - fix major issue with reading > 32 bytes at a time with Arduino Wire // - add compiler warnings when using outdated or IDE or limited i2cDev implementation // 2011-11-01 - fix write*Bits mask calculation (thanks sasquatch @ Arduino forums) // 2011-10-03 - added automatic Arduino version detection for ease of use // 2011-10-02 - added Gene Knight's NBWire TwoWire class implementation with small modifications // 2011-08-31 - added support for Arduino 1.0 Wire library (methods are different from 0.x) // 2011-08-03 - added optional timeout parameter to read* methods to easily change from default // 2011-08-02 - added support for 16-bit registers // - fixed incorrect Doxygen comments on some methods // - added timeout value for read operations (thanks mem @ Arduino forums) // 2011-07-30 - changed read/write function structures to return success or byte counts // - made all methods static for multi-device memory savings // 2011-07-28 - initial release /* ============================================ I2Cdev device library code is placed under the MIT license Copyright (c) 2012 Jeff Rowberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================== */ #ifndef I2CDEV_H_ #define I2CDEV_H_ #define RASPBERRY_PI_MODEL_A_I2C "/dev/i2c-0" #define RASPBERRY_PI_MODEL_B_I2C "/dev/i2c-1" #define RASPBERRY_PI_2_MODEL_B_I2C "/dev/i2c-1" #define BANANA_PI_I2C "/dev/i2c-2" #ifndef TRUE #define TRUE (1==1) #define FALSE (0==1) #endif #include <stdint.h> class I2Cdev { public: I2Cdev(); static int8_t readBit(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readBitW(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readBits(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readBitsW(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readByte(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readWord(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint16_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readBytes(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readBytes(const char *i2cDev, uint8_t devAddr, uint8_t length, uint8_t *data, uint16_t timeout=I2Cdev::readTimeout); static int8_t readWords(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data, uint16_t timeout=I2Cdev::readTimeout); static bool writeBit(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data); static bool writeBitW(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t data); static bool writeBits(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data); static bool writeBitsW(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t data); static bool writeByte(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t data); static bool writeWord(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint16_t data); static bool writeBytes(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data); static bool writeWords(const char *i2cDev, uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data); static uint16_t readTimeout; }; #endif // I2CDEV_H_
[ "bennierex@users.noreply.github.com" ]
bennierex@users.noreply.github.com
04356121bf9bb52ffe5cd5574af808e9d06ce847
9c2ba71afca1f1581216e1a20dbbf1d291691560
/MySensorsDimmableLight/MySensorsDimmableLight/MySensorsDimmableLight.ino
acf613e386fb0df8332c1c46634b3228a9b4cc51
[]
no_license
KeesV/mysensors-sketches
e4829899508ce6b548c456e7c05634ec7b625ccb
fcc77876db06914794a5cb38ad2dad5de0c81b13
refs/heads/master
2021-06-21T05:43:02.537371
2017-08-11T15:39:41
2017-08-11T15:39:41
75,478,326
0
0
null
null
null
null
UTF-8
C++
false
false
6,041
ino
/** * The MySensors Arduino library handles the wireless radio link and protocol * between your home built sensors/actuators and HA controller of choice. * The sensors forms a self healing radio network with optional repeaters. Each * repeater and gateway builds a routing tables in EEPROM which keeps track of the * network topology allowing messages to be routed to nodes. * * Created by Henrik Ekblad <henrik.ekblad@mysensors.org> * Copyright (C) 2013-2015 Sensnology AB * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors * * Documentation: http://www.mysensors.org * Support Forum: http://forum.mysensors.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * ******************************* * * REVISION HISTORY * Version 1.0 - January 30, 2015 - Developed by GizMoCuz (Domoticz) * * DESCRIPTION * This sketch provides an example how to implement a Dimmable Light * It is pure virtual and it logs messages to the serial output * It can be used as a base sketch for actual hardware. * Stores the last light state and level in eeprom. * */ // Enable debug prints #define MY_DEBUG // Enable and select radio type attached #define MY_RADIO_NRF24 //#define MY_RADIO_RFM69 #define LED_PIN 6 #define FADE_AMOUNT 10 // how many points to fade the LED by #define MAX_BRIGHTNESS 255 // how bright to make the led #define FADE_DELAY 50 //delay between fade steps, in MS #include <SPI.h> #include <MySensors.h> #define CHILD_ID_LIGHT 1 #define EPROM_LIGHT_STATE 1 #define EPROM_DIMMER_LEVEL 2 #define LIGHT_OFF 0 #define LIGHT_ON 1 #define SN "Dimable Light" #define SV "1.0" int LastLightState=LIGHT_OFF; int ReceivedDimValue=100; int CurrentDimValue = ReceivedDimValue * 2.55; int RequestedDimValue = 255; MyMessage lightMsg(CHILD_ID_LIGHT, V_LIGHT); MyMessage dimmerMsg(CHILD_ID_LIGHT, V_DIMMER); void setup() { //Retreive our last light state from the eprom int LightState=loadState(EPROM_LIGHT_STATE); if (LightState<=1) { LastLightState=LightState; int DimValue=loadState(EPROM_DIMMER_LEVEL); if ((DimValue>0)&&(DimValue<=100)) { //There should be no Dim value of 0, this would mean LIGHT_OFF ReceivedDimValue=DimValue; } } pinMode(LED_PIN, OUTPUT); //Here you actualy switch on/off the light with the last known dim level SetCurrentState2Hardware(); Serial.println( "Node ready to receive messages..." ); } void presentation() { // Send the Sketch Version Information to the Gateway sendSketchInfo(SN, SV); present(CHILD_ID_LIGHT, S_DIMMER ); } void fadeToLevel() { Serial.print("CurrentDimValue = "); Serial.print(CurrentDimValue); Serial.print(", RequestedDimValue = "); Serial.print(RequestedDimValue); Serial.print(", ReceivedDimValue = "); Serial.println(ReceivedDimValue); if ( CurrentDimValue != RequestedDimValue && abs(CurrentDimValue - RequestedDimValue) > FADE_AMOUNT) { int delta = ( RequestedDimValue - CurrentDimValue ) < 0 ? -1 : 1; CurrentDimValue += delta * FADE_AMOUNT; Serial.print("analog write: "); Serial.println(CurrentDimValue); analogWrite(LED_PIN, CurrentDimValue); wait(FADE_DELAY); } else if(RequestedDimValue == 0) { CurrentDimValue = 0; analogWrite(LED_PIN, CurrentDimValue); } } void loop() { fadeToLevel(); } void receive(const MyMessage &message) { if (message.type == V_LIGHT) { Serial.println( "V_LIGHT command received..." ); int lstate= atoi( message.data ); if ((lstate<0)||(lstate>1)) { Serial.println( "V_LIGHT data invalid (should be 0/1)" ); return; } LastLightState=lstate; if(LastLightState == LIGHT_OFF) { ReceivedDimValue = 0; saveState(EPROM_DIMMER_LEVEL, ReceivedDimValue); } saveState(EPROM_LIGHT_STATE, LastLightState); if ((LastLightState==LIGHT_ON)&&(ReceivedDimValue==0)) { //In the case that the Light State = On, but the dimmer value is zero, //then something (probably the controller) did something wrong, //for the Dim value to 100% ReceivedDimValue=100; saveState(EPROM_DIMMER_LEVEL, ReceivedDimValue); } //When receiving a V_LIGHT command we switch the light between OFF and the last received dimmer value //This means if you previously set the lights dimmer value to 50%, and turn the light ON //it will do so at 50% } else if (message.type == V_DIMMER) { Serial.println( "V_DIMMER command received..." ); int dimvalue= atoi( message.data ); if ((dimvalue<0)||(dimvalue>100)) { Serial.println( "V_DIMMER data invalid (should be 0..100)" ); return; } if (dimvalue==0) { LastLightState=LIGHT_OFF; ReceivedDimValue = dimvalue; saveState(EPROM_DIMMER_LEVEL, ReceivedDimValue); } else { LastLightState=LIGHT_ON; ReceivedDimValue=dimvalue; saveState(EPROM_DIMMER_LEVEL, ReceivedDimValue); } } else { Serial.println( "Invalid command received..." ); return; } //Here you set the actual light state/level SetCurrentState2Hardware(); } void SetCurrentState2Hardware() { if (LastLightState==LIGHT_OFF) { Serial.println( "Light state: OFF" ); RequestedDimValue = 0; } else { Serial.print( "Light state: ON, Level: " ); Serial.println( ReceivedDimValue ); //ReceivedDimValue will be between 0..100, while we need 0..255 RequestedDimValue = ReceivedDimValue * 2.55; } //Send current state to the controller SendCurrentState2Controller(); } void SendCurrentState2Controller() { if ((LastLightState==LIGHT_OFF)||(ReceivedDimValue==0)) { Serial.println("Sending dimmer state ZERO"); send(dimmerMsg.set(0)); } else { Serial.print("Sending dimmer state "); Serial.println(ReceivedDimValue); send(dimmerMsg.set(ReceivedDimValue)); } }
[ "kverhaar@hotmail.com" ]
kverhaar@hotmail.com
7072fa66e38cc39d99fef753f4db3fe06ee55bbf
f1ff9e972b69b994433501c9e92dd49421ce70b3
/CPP/buckysTutorial/members/main.cpp
6a351d53b3fd220b494f8aceed1dd5d71823dc21
[]
no_license
jpenna/learning
e36a60c11b9f014cf7ed71f785ad05c14a145aab
4ba99a1a2e048a04be01ccc9f49f48605ac74979
refs/heads/master
2022-12-07T18:10:21.440903
2020-09-08T13:41:11
2020-09-08T13:41:11
201,314,872
0
0
null
null
null
null
UTF-8
C++
false
false
311
cpp
#include <iostream> #include "Sally.h" using namespace std; int main() { Sally sallyObject(3, 87, 10); Sally *sallyPointer = &sallyObject; sallyObject.printVars(); sallyObject.printCrap(); sallyPointer->printCrap(); sallyPointer->printX(); const Sally constObj(9); constObj.printX2(); }
[ "julianopenna@gmail.com" ]
julianopenna@gmail.com
b17e9ec84e33ac6520105a3e347ab99643830577
561a750ba667403eaccc526399df1bc563617e48
/src/blockencodings.cpp
f2caf27dd6f2deb248a90a2240ba2cae0edf5409
[ "MIT" ]
permissive
r3vcoin-project/r3vcoin
ae674638fe201d655dd249ec8273e49e45659882
6f72edb47bae7011a08c9e2621c3955d3bb7ed26
refs/heads/master
2020-03-29T11:26:42.106137
2018-10-29T03:04:50
2018-10-29T03:04:50
149,852,968
0
0
MIT
2018-10-29T03:04:51
2018-09-22T06:48:11
C++
UTF-8
C++
false
false
10,468
cpp
// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "blockencodings.h" #include "consensus/consensus.h" #include "consensus/validation.h" #include "chainparams.h" #include "hash.h" #include "random.h" #include "streams.h" #include "txmempool.h" #include "validation.h" #include "util.h" #include <unordered_map> #define MIN_TRANSACTION_BASE_SIZE (::GetSerializeSize(CTransaction(), SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS)) CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock& block, bool fUseWTXID) : nonce(GetRand(std::numeric_limits<uint64_t>::max())), shorttxids(block.vtx.size() - 1), prefilledtxn(1), header(block) { FillShortTxIDSelector(); //TODO: Use our mempool prior to block acceptance to predictively fill more than just the coinbase prefilledtxn[0] = {0, block.vtx[0]}; for (size_t i = 1; i < block.vtx.size(); i++) { const CTransaction& tx = *block.vtx[i]; shorttxids[i - 1] = GetShortID(fUseWTXID ? tx.GetWitnessHash() : tx.GetHash()); } } void CBlockHeaderAndShortTxIDs::FillShortTxIDSelector() const { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << header << nonce; CSHA256 hasher; hasher.Write((unsigned char*)&(*stream.begin()), stream.end() - stream.begin()); uint256 shorttxidhash; hasher.Finalize(shorttxidhash.begin()); shorttxidk0 = shorttxidhash.GetUint64(0); shorttxidk1 = shorttxidhash.GetUint64(1); } uint64_t CBlockHeaderAndShortTxIDs::GetShortID(const uint256& txhash) const { static_assert(SHORTTXIDS_LENGTH == 6, "shorttxids calculation assumes 6-byte shorttxids"); return SipHashUint256(shorttxidk0, shorttxidk1, txhash) & 0xffffffffffffL; } ReadStatus PartiallyDownloadedBlock::InitData(const CBlockHeaderAndShortTxIDs& cmpctblock, const std::vector<std::pair<uint256, CTransactionRef>>& extra_txn) { if (cmpctblock.header.IsNull() || (cmpctblock.shorttxids.empty() && cmpctblock.prefilledtxn.empty())) return READ_STATUS_INVALID; if (cmpctblock.shorttxids.size() + cmpctblock.prefilledtxn.size() > MAX_BLOCK_BASE_SIZE / MIN_TRANSACTION_BASE_SIZE) return READ_STATUS_INVALID; assert(header.IsNull() && txn_available.empty()); header = cmpctblock.header; txn_available.resize(cmpctblock.BlockTxCount()); int32_t lastprefilledindex = -1; for (size_t i = 0; i < cmpctblock.prefilledtxn.size(); i++) { if (cmpctblock.prefilledtxn[i].tx->IsNull()) return READ_STATUS_INVALID; lastprefilledindex += cmpctblock.prefilledtxn[i].index + 1; //index is a uint16_t, so can't overflow here if (lastprefilledindex > std::numeric_limits<uint16_t>::max()) return READ_STATUS_INVALID; if ((uint32_t)lastprefilledindex > cmpctblock.shorttxids.size() + i) { // If we are inserting a tx at an index greater than our full list of shorttxids // plus the number of prefilled txn we've inserted, then we have txn for which we // have neither a prefilled txn or a shorttxid! return READ_STATUS_INVALID; } txn_available[lastprefilledindex] = cmpctblock.prefilledtxn[i].tx; } prefilled_count = cmpctblock.prefilledtxn.size(); // Calculate map of txids -> positions and check mempool to see what we have (or don't) // Because well-formed cmpctblock messages will have a (relatively) uniform distribution // of short IDs, any highly-uneven distribution of elements can be safely treated as a // READ_STATUS_FAILED. std::unordered_map<uint64_t, uint16_t> shorttxids(cmpctblock.shorttxids.size()); uint16_t index_offset = 0; for (size_t i = 0; i < cmpctblock.shorttxids.size(); i++) { while (txn_available[i + index_offset]) index_offset++; shorttxids[cmpctblock.shorttxids[i]] = i + index_offset; // To determine the chance that the number of entries in a bucket exceeds N, // we use the fact that the number of elements in a single bucket is // binomially distributed (with n = the number of shorttxids S, and p = // 1 / the number of buckets), that in the worst case the number of buckets is // equal to S (due to std::unordered_map having a default load factor of 1.0), // and that the chance for any bucket to exceed N elements is at most // buckets * (the chance that any given bucket is above N elements). // Thus: P(max_elements_per_bucket > N) <= S * (1 - cdf(binomial(n=S,p=1/S), N)). // If we assume blocks of up to 16000, allowing 12 elements per bucket should // only fail once per ~1 million block transfers (per peer and connection). if (shorttxids.bucket_size(shorttxids.bucket(cmpctblock.shorttxids[i])) > 12) return READ_STATUS_FAILED; } // TODO: in the shortid-collision case, we should instead request both transactions // which collided. Falling back to full-block-request here is overkill. if (shorttxids.size() != cmpctblock.shorttxids.size()) return READ_STATUS_FAILED; // Short ID collision std::vector<bool> have_txn(txn_available.size()); { LOCK(pool->cs); const std::vector<std::pair<uint256, CTxMemPool::txiter> >& vTxHashes = pool->vTxHashes; for (size_t i = 0; i < vTxHashes.size(); i++) { uint64_t shortid = cmpctblock.GetShortID(vTxHashes[i].first); std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid); if (idit != shorttxids.end()) { if (!have_txn[idit->second]) { txn_available[idit->second] = vTxHashes[i].second->GetSharedTx(); have_txn[idit->second] = true; mempool_count++; } else { // If we find two mempool txn that match the short id, just request it. // This should be rare enough that the extra bandwidth doesn't matter, // but eating a round-trip due to FillBlock failure would be annoying if (txn_available[idit->second]) { txn_available[idit->second].reset(); mempool_count--; } } } // Though ideally we'd continue scanning for the two-txn-match-shortid case, // the performance win of an early exit here is too good to pass up and worth // the extra risk. if (mempool_count == shorttxids.size()) break; } } for (size_t i = 0; i < extra_txn.size(); i++) { uint64_t shortid = cmpctblock.GetShortID(extra_txn[i].first); std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid); if (idit != shorttxids.end()) { if (!have_txn[idit->second]) { txn_available[idit->second] = extra_txn[i].second; have_txn[idit->second] = true; mempool_count++; extra_count++; } else { // If we find two mempool/extra txn that match the short id, just // request it. // This should be rare enough that the extra bandwidth doesn't matter, // but eating a round-trip due to FillBlock failure would be annoying // Note that we dont want duplication between extra_txn and mempool to // trigger this case, so we compare witness hashes first if (txn_available[idit->second] && txn_available[idit->second]->GetWitnessHash() != extra_txn[i].second->GetWitnessHash()) { txn_available[idit->second].reset(); mempool_count--; extra_count--; } } } // Though ideally we'd continue scanning for the two-txn-match-shortid case, // the performance win of an early exit here is too good to pass up and worth // the extra risk. if (mempool_count == shorttxids.size()) break; } LogPrint("cmpctblock", "Initialized PartiallyDownloadedBlock for block %s using a cmpctblock of size %lu\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock, SER_NETWORK, PROTOCOL_VERSION)); return READ_STATUS_OK; } bool PartiallyDownloadedBlock::IsTxAvailable(size_t index) const { assert(!header.IsNull()); assert(index < txn_available.size()); return txn_available[index] ? true : false; } ReadStatus PartiallyDownloadedBlock::FillBlock(CBlock& block, const std::vector<CTransactionRef>& vtx_missing) { assert(!header.IsNull()); uint256 hash = header.GetHash(); block = header; block.vtx.resize(txn_available.size()); size_t tx_missing_offset = 0; for (size_t i = 0; i < txn_available.size(); i++) { if (!txn_available[i]) { if (vtx_missing.size() <= tx_missing_offset) return READ_STATUS_INVALID; block.vtx[i] = vtx_missing[tx_missing_offset++]; } else block.vtx[i] = std::move(txn_available[i]); } // Make sure we can't call FillBlock again. header.SetNull(); txn_available.clear(); if (vtx_missing.size() != tx_missing_offset) return READ_STATUS_INVALID; CValidationState state; if (!CheckBlock(block, state, Params().GetConsensus(), true, true, true, false)) { // TODO: We really want to just check merkle tree manually here, // but that is expensive, and CheckBlock caches a block's // "checked-status" (in the CBlock?). CBlock should be able to // check its own merkle root and cache that check. if (state.CorruptionPossible()) return READ_STATUS_FAILED; // Possible Short ID collision return READ_STATUS_CHECKBLOCK_FAILED; } LogPrint("cmpctblock", "Successfully reconstructed block %s with %lu txn prefilled, %lu txn from mempool (incl at least %lu from extra pool) and %lu txn requested\n", hash.ToString(), prefilled_count, mempool_count, extra_count, vtx_missing.size()); if (vtx_missing.size() < 5) { for (const auto& tx : vtx_missing) LogPrint("cmpctblock", "Reconstructed block %s required tx %s\n", hash.ToString(), tx->GetHash().ToString()); } return READ_STATUS_OK; }
[ "lun1109@hotmail.com" ]
lun1109@hotmail.com
356ecf974a2c67e85f29977406b73e6d07708769
98d9a385815307f4c4fd5d25d06776c27b37626a
/opdracht1_5/line.cpp
31f4ce3b6b26d9e34269810d03dab3599f1b24e1
[]
no_license
HU-Technische-Informatica/oopc-21-week1-n21twn
b696cbd5bc6c9677e5a886c1a594703f7f1ffd2d
77462fb2027d041d851d591156713bec86ec017c
refs/heads/master
2023-05-18T09:22:00.054938
2021-06-11T10:31:39
2021-06-11T10:31:39
357,811,465
0
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
// example:clTabCtrl // definition of the functions of a line class #include "hwlib.hpp" #include "line.hpp" void line::print(){ hwlib::line line( hwlib::xy( start_x, start_y), hwlib::xy( end_x, end_y ) ); line.draw( w ); w.flush(); }
[ "nickteeuwen21@gmail.com" ]
nickteeuwen21@gmail.com
a7ac1a5ef973fbf9d566c8ec0b4f2b646bfb8e69
370a373bcba48a9beca9f462bf6644b0ffe79f66
/DefaultSFML/src/main.cpp
59a30e1fc464a492bd1c9a702893f131fa8b1636
[]
no_license
Football1995/RTS
b63bd2431595deb2f57af4ed5670b28598a763d1
628056030a6ee6feec611141387431e20e335bf6
refs/heads/master
2020-03-16T20:26:40.584681
2018-05-18T08:18:20
2018-05-18T08:18:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
74,175
cpp
#include <iostream> #include <fstream> #include <sstream> #include <SFML\Graphics.hpp> #include "Profile.h" #include "Button.h" #include "Overlay.h" #include "TextBox.h" #include "Game.h" #include "Sound.h" #include "TextureObject.h" #include "UnitObject.h" using namespace std; using namespace sf; void mainMenu(bool tutorial); void profileMenu(bool tutorial); void settingsMenu(bool tutorial); void playMenu(); void play(string path); void LoadLevel(); void editor(); void resetSelectors(); bool DEBUGMODE = true; Profile *player; SoundObject *sound; TextureObject *m_Gametextures;// \brief handle to all game textures UnitObject *unitObject; //selections bools //_----------------------------------------OLD CODE------------------------------------- bool RoadSelectorBool = false; // true while choosing road bool LightSelectorBool = false; // true while choosing roads bool unitsSelectorBool = false; // true while altering units bool PedSelectorBool = false; // true while altering pedestrians bool StartEndPointsBool = false; // true while altering start and end points bool placingBool = false; // true while placing roads int tutorialState = 0; int main() { player = Profile::getInstance(); sound = SoundObject::getInstance(); unitObject = UnitObject::getInstance(); m_Gametextures = TextureObject::getInstance(); player->loadProfile("default"); sound->loadSounds(); m_Gametextures->loadTextures(); unitObject->loadUnits(); //luanch game if (DEBUGMODE) cout << "Launching Game" << endl; //open profile list fstream file; string lineData; string tempProfile; vector<string> profileNames; file.open("Assets/profiles/profileList.txt"); if (file.is_open()) { while (getline(file, lineData)) { istringstream iss(lineData); iss.str(lineData); iss >> tempProfile; profileNames.push_back(tempProfile); } } else { cout << "Couldnt Open file ... Assets/profiles/profileList.txt" << endl; } file.close(); if (DEBUGMODE) cout << "Profiles present : " << profileNames.size() << endl; //check to see if any profiles were present if (profileNames.size() > 0) { // luanch profileMenu in normal mode player->loadProfile("default"); tutorialState = 11; //profileMenu(false); string mode; cout << endl << endl << "=================================================================" << endl << "Test mode : (ben type Arena) : "; cin >> mode; play(mode); } else { if (DEBUGMODE) cout << "Tutorial mode" << endl; if (DEBUGMODE) cout << "Loading Default profile" << endl; player->loadProfile("default"); if (DEBUGMODE) cout << "Default profile loaded" << endl; // luanch menu in tutorial mode mainMenu(true); } return 0; } void mainMenu(bool tutorial) { Texture mainMenuBackgroundTex; if (!mainMenuBackgroundTex.loadFromFile("Assets/textures/menuScreen.png")) { cout << "Error: menuScreen.png was unable to load."; }; if (tutorial) { //default.txt is now the profile //create main menu assets ...................... //main menu background------------------------- RectangleShape mainMenuBackgroundRect; Sprite mainMenuBackgroundSprite; mainMenuBackgroundRect.setPosition(0, 0); mainMenuBackgroundRect.setSize(Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); mainMenuBackgroundRect.setFillColor(Color::Blue); mainMenuBackgroundSprite.setTexture(mainMenuBackgroundTex); mainMenuBackgroundSprite.setScale(Vector2f(1, 1)); mainMenuBackgroundSprite.setPosition(mainMenuBackgroundRect.getPosition()); //Create buttons------------------------- Vector2f resolutionScale(player->m_sfResolution.x / 1280, player->m_sfResolution.y / 720); Vector2f buttonSize(250 * resolutionScale.x, 100 * resolutionScale.y); Vector2f middleOfScreen((player->m_sfResolution.x / 2) - (buttonSize.x / 2), (player->m_sfResolution.y / 2) - (buttonSize.y / 2)); Text title; Font font; if (!font.loadFromFile("Assets/fonts/ariali.ttf")) { cout << "Error: Font ariali.ttf was unable to load."; }; title.setFont(font); title.setString("Main Menu"); title.setCharacterSize(50*resolutionScale.x); title.setFillColor(Color(0, 0, 0)); title.setPosition(Vector2f(middleOfScreen.x, 25 * resolutionScale.y)); Button play("Play", Vector2f(middleOfScreen.x, 100 * resolutionScale.y), buttonSize, resolutionScale, "Button_Grey"); Button profile("Profile", Vector2f(middleOfScreen.x, 250 * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Button settings("Settings", Vector2f(middleOfScreen.x, 400 * resolutionScale.y), buttonSize, resolutionScale, "Button_Grey"); Button quit("Quit", Vector2f(middleOfScreen.x, 550 * resolutionScale.y), buttonSize, resolutionScale, "Button_Grey"); Button profileGrey("Profile", Vector2f(middleOfScreen.x, 250 * resolutionScale.y), buttonSize, resolutionScale, "Button_Grey"); Button settingsGreen ("Settings", Vector2f(middleOfScreen.x, 400 * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Vector2f middleOfScreenOverlay(player->m_sfResolution.x / 2 - (250 * resolutionScale.x), player->m_sfResolution.y / 2 - (250 * resolutionScale.y)); Overlay firstOverlayMessage(middleOfScreenOverlay, Vector2f(500 * resolutionScale.x, 500 * resolutionScale.y), "\tWelcome to Traffic Management !\n\t Please click on Profiles\n\n\n(Click on messages like this to close them)"); Overlay secondOverlayMessage(middleOfScreenOverlay, Vector2f(500 * resolutionScale.x, 500 * resolutionScale.y), "\tYou have now created your profile!\n\t Please click on settings\n\n\n"); if (tutorialState >= 6) firstOverlayMessage.m_bDraw = false; secondOverlayMessage.m_bDraw = false; if (tutorialState == 6)secondOverlayMessage.m_bDraw = true; RenderWindow window(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Main Menu"); window.setFramerateLimit(60); while (window.isOpen()) { //handle input Event event; Vector2f sfMousePos; while (window.pollEvent(event)) { sfMousePos = window.mapPixelToCoords(Mouse::getPosition(window)); if (event.type == Event::Closed) { window.close(); // Allows window to close when 'X' is pressed return; } if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { if (settingsGreen.m_bClicked(sfMousePos) && tutorialState == 7) { //close and open profile menu tutorialState = 8; window.close(); settingsMenu(true); } if (secondOverlayMessage.m_bClicked(sfMousePos) && tutorialState == 6) { tutorialState = 7; secondOverlayMessage.m_bDraw = false; } if (profile.m_bClicked(sfMousePos) && tutorialState == 1) { //close and open profile menu tutorialState = 2; window.close(); profileMenu(true); } if (firstOverlayMessage.m_bClicked(sfMousePos) && tutorialState == 0) { firstOverlayMessage.m_bDraw = false; tutorialState = 1; } } } } window.clear(Color::Green); window.draw(mainMenuBackgroundSprite); window.draw(title); // buttons window.draw(play); window.draw(profile); if (tutorialState == 7) { window.draw(profileGrey); } else { window.draw(profile); } if (tutorialState == 7) { window.draw(settingsGreen); } else { window.draw(settings); } window.draw(quit); // first overlay window.draw(firstOverlayMessage); window.draw(secondOverlayMessage); window.display(); } } else if (!tutorial) { //we now have a profile //create main menu assets ...................... player->m_sProfileName; //main menu background------------------------- RectangleShape mainMenuBackgroundRect; Sprite mainMenuBackgroundSprite; mainMenuBackgroundRect.setPosition(0, 0); mainMenuBackgroundRect.setSize(Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); mainMenuBackgroundRect.setFillColor(Color::Blue); mainMenuBackgroundSprite.setTexture(mainMenuBackgroundTex); mainMenuBackgroundSprite.setScale(Vector2f(1, 1)); mainMenuBackgroundSprite.setPosition(mainMenuBackgroundRect.getPosition()); //Create buttons------------------------- Vector2f resolutionScale(player->m_sfResolution.x / 1280, player->m_sfResolution.y / 720); Vector2f buttonSize(250 * resolutionScale.x, 100 * resolutionScale.y); Vector2f middleOfScreen((player->m_sfResolution.x / 2) - (buttonSize.x / 2), (player->m_sfResolution.y / 2) - (buttonSize.y / 2)); Text title; Font font; if (!font.loadFromFile("Assets/fonts/ariali.ttf")) { cout << "Error: Font ariali.ttf was unable to load."; }; title.setFont(font); title.setString("Main Menu"); title.setCharacterSize(50 * resolutionScale.x); title.setFillColor(Color(0, 0, 0)); title.setPosition(Vector2f(middleOfScreen.x, 25 * resolutionScale.y)); Button play("Play", Vector2f(middleOfScreen.x, 100 * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Button profile("Profile", Vector2f(middleOfScreen.x, 250 * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Button settings("Settings", Vector2f(middleOfScreen.x, 400 * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Button quit("Quit", Vector2f(middleOfScreen.x, 550 * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Vector2f middleOfScreenOverlay(player->m_sfResolution.x / 2 - (250 * resolutionScale.x), player->m_sfResolution.y / 2 - (250 * resolutionScale.y)); Overlay firstOverlayMessage(middleOfScreenOverlay, Vector2f(500 * resolutionScale.x, 500 * resolutionScale.y), "\tYou have now finished the tutorial! \n\nClick play to start playing"); if (tutorialState == 11)firstOverlayMessage.m_bDraw = false; RenderWindow window; if (player->m_bFullscreen == true) window.create(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Main Menu", Style::Fullscreen); else window.create(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Main Menu"); window.setFramerateLimit(60); while (window.isOpen()) { //handle input Event event; Vector2f sfMousePos; while (window.pollEvent(event)) { sfMousePos = window.mapPixelToCoords(Mouse::getPosition(window)); if (event.type == Event::Closed) { window.close(); // Allows window to close when 'X' is pressed return; } if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { if (firstOverlayMessage.m_bClicked(sfMousePos) && tutorialState == 10) { firstOverlayMessage.m_bDraw = false; tutorialState = 11; // finished } if (play.m_bClicked(sfMousePos) && tutorialState == 11) { window.close(); playMenu(); } if (settings.m_bClicked(sfMousePos) && tutorialState == 11) { window.close(); settingsMenu(false); } if (profile.m_bClicked(sfMousePos) && tutorialState == 11) { window.close(); profileMenu(false); } if (quit.m_bClicked(sfMousePos) && tutorialState == 11) { window.close(); // Allows window to close when 'X' is pressed player->saveProfile(); return; } } } } window.clear(Color::Green); window.draw(mainMenuBackgroundSprite); window.draw(title); // buttons window.draw(play); window.draw(profile); window.draw(settings); window.draw(quit); // first overlay window.draw(firstOverlayMessage); window.display(); } } } void profileMenu(bool tutorial) { Texture profileBackgroundTex; if (!profileBackgroundTex.loadFromFile("Assets/textures/menuScreen.png")) { cout << "Error: menuScreen.png was unable to load."; }; if (tutorial) { //for profile screen // enter at tutorial state 2 // after close message tutorial state 3 // after click new tutorial sate 4 //create profile assets ...................... //profile background------------------------- RectangleShape profileBackgroundRect; Sprite profileBackgroundSprite; profileBackgroundRect.setPosition(0, 0); profileBackgroundRect.setSize(Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); profileBackgroundRect.setFillColor(Color::Blue); profileBackgroundSprite.setTexture(profileBackgroundTex); profileBackgroundSprite.setScale(Vector2f(1, 1)); profileBackgroundSprite.setPosition(profileBackgroundRect.getPosition()); //Create buttons------------------------- Vector2f resolutionScale(player->m_sfResolution.x / 1280, player->m_sfResolution.y / 720); Vector2f buttonSize(250 * resolutionScale.x, 100 * resolutionScale.y); Vector2f middleOfScreen((player->m_sfResolution.x / 2) - (buttonSize.x / 2), (player->m_sfResolution.y / 2) - (buttonSize.y / 2)); Button New("New", Vector2f(middleOfScreen.x - buttonSize.x, 100 + middleOfScreen.y * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Button Select("Select", Vector2f(middleOfScreen.x , 100 + middleOfScreen.y *resolutionScale.y), buttonSize, resolutionScale, "Button_Grey"); Button Delete("Delete", Vector2f(middleOfScreen.x + buttonSize.x, 100 + middleOfScreen.y * resolutionScale.y), buttonSize, resolutionScale, "Button_Grey"); Text title; Font font; if (!font.loadFromFile("Assets/fonts/ariali.ttf")) { cout << "Error: Font ariali.ttf was unable to load."; }; title.setFont(font); title.setString("Profiles"); title.setCharacterSize(55 * resolutionScale.x); title.setFillColor(Color(0, 0, 0)); title.setPosition(Vector2f(middleOfScreen.x, 25 * resolutionScale.y)); //Enter you name Sprite RectangleShape listOfProfilesRect; Sprite listOfProfilesSprite; Texture listOfProfilesTex; if (!listOfProfilesTex.loadFromFile("Assets/textures/profileMenuEmpty.png")) { cout << "Error: ProfileEnterBackground.png was unable to load."; }; listOfProfilesRect.setPosition(Vector2f(middleOfScreen.x - buttonSize.x , -120 + middleOfScreen.y * resolutionScale.y)); listOfProfilesRect.setSize(Vector2f(buttonSize.x * 3, 240 * resolutionScale.y)); listOfProfilesRect.setFillColor(Color::Blue); listOfProfilesSprite.setTexture(listOfProfilesTex); listOfProfilesSprite.setScale(Vector2f( 1 * resolutionScale.x , 1 * resolutionScale.y )); listOfProfilesSprite.setPosition(listOfProfilesRect.getPosition()); //Enter you name Sprite RectangleShape nameEntryRect; Sprite nameEntrySprite; Texture nameEntryTex; if (!nameEntryTex.loadFromFile("Assets/textures/ProfileEnterBackground.png")) { cout << "Error: ProfileEnterBackground.png was unable to load."; }; nameEntryRect.setPosition((player->m_sfResolution.x /2) - (579 /2 * resolutionScale.x), (player->m_sfResolution.y / 2) - (144 / 2 * resolutionScale.y)); nameEntryRect.setSize(Vector2f(579 * resolutionScale.x, 144*resolutionScale.y)); nameEntryRect.setFillColor(Color::Blue); nameEntrySprite.setTexture(nameEntryTex); nameEntrySprite.setScale(Vector2f(1 * resolutionScale.x, 1 * resolutionScale.y)); nameEntrySprite.setPosition(nameEntryRect.getPosition()); //create text box Vector2f edgeOfTextBox(nameEntryRect.getPosition().x + (579 * resolutionScale.x) / 8, nameEntryRect.getPosition().y + (144 * resolutionScale.y) / 2); TextBox playerEnterNameBox("", edgeOfTextBox , Vector2f(343*resolutionScale.x, 37*resolutionScale.y), "Textbox"); Button Submit("Submit", Vector2f(edgeOfTextBox.x + 343 * resolutionScale.x, edgeOfTextBox.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); //create overlays Vector2f middleOfScreenOverlay(player->m_sfResolution.x / 2 - (300 * resolutionScale.x), player->m_sfResolution.y / 2 - (300 * resolutionScale.y)); Overlay firstOverlayMessage(middleOfScreenOverlay, Vector2f(500 * resolutionScale.x, 500 * resolutionScale.y), "\tWelcome to the Profile Menu !\n\t There are currently no profiles available.\n\n\n Please click New to create a profile."); Overlay secondOverlayMessage(middleOfScreenOverlay, Vector2f(500 * resolutionScale.x, 500 * resolutionScale.y), "\tPlease enter your name into the box !\n\t And click submit when your finished."); firstOverlayMessage.m_bDraw = true; secondOverlayMessage.m_bDraw = false; RenderWindow window(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Main Menu"); window.setFramerateLimit(60); while (window.isOpen()) { //handle input Event event; Vector2f sfMousePos; while (window.pollEvent(event)) { sfMousePos = window.mapPixelToCoords(Mouse::getPosition(window)); if (event.type == Event::Closed) { window.close(); // Allows window to close when 'X' is pressed return; } if (event.type == sf::Event::KeyPressed && playerEnterNameBox.m_bIsEntering == true) { playerEnterNameBox.takeInput(event.key.code); } if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { if (tutorialState == 5 && Submit.m_bClicked(sfMousePos)) { tutorialState = 6; //create a new profile with there name player->newProfile(playerEnterNameBox.m_sText); window.close(); mainMenu(true); } if (playerEnterNameBox.m_bClicked(sfMousePos) && tutorialState == 5) { playerEnterNameBox.m_bIsEntering = true; } if (secondOverlayMessage.m_bClicked(sfMousePos) && tutorialState == 4) { tutorialState = 5; } if (New.m_bClicked(sfMousePos) && tutorialState == 3) { //change profile menu state tutorialState = 4; } if (firstOverlayMessage.m_bClicked(sfMousePos) && tutorialState == 2) { tutorialState = 3; } } } } window.clear(Color::Green); window.draw(profileBackgroundSprite); window.draw(title); // buttons if (tutorialState != 4 && tutorialState != 5) { window.draw(listOfProfilesSprite); window.draw(New); window.draw(Select); window.draw(Delete); } else // enter player name { window.draw(nameEntrySprite); window.draw(playerEnterNameBox); window.draw(Submit); } if(tutorialState == 3)firstOverlayMessage.m_bDraw = false; if (tutorialState == 4)secondOverlayMessage.m_bDraw = true; if (tutorialState == 5)secondOverlayMessage.m_bDraw = false; // overlays window.draw(firstOverlayMessage); window.draw(secondOverlayMessage); window.display(); } } else if (!tutorial) { //create profile assets ...................... //profile background------------------------- RectangleShape profileBackgroundRect; Sprite profileBackgroundSprite; profileBackgroundRect.setPosition(0, 0); profileBackgroundRect.setSize(Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); profileBackgroundRect.setFillColor(Color::Blue); profileBackgroundSprite.setTexture(profileBackgroundTex); profileBackgroundSprite.setScale(Vector2f(1, 1)); profileBackgroundSprite.setPosition(profileBackgroundRect.getPosition()); //Create buttons------------------------- Vector2f resolutionScale(player->m_sfResolution.x / 1280, player->m_sfResolution.y / 720); Vector2f buttonSize(250 * resolutionScale.x, 100 * resolutionScale.y); Vector2f middleOfScreen((player->m_sfResolution.x / 2) - (buttonSize.x / 2), (player->m_sfResolution.y / 2) - (buttonSize.y / 2)); Button New("New", Vector2f(middleOfScreen.x - buttonSize.x, 100 + middleOfScreen.y * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Button Select("Select", Vector2f(middleOfScreen.x, 100 + middleOfScreen.y *resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Button Delete("Delete", Vector2f(middleOfScreen.x + buttonSize.x, 100 + middleOfScreen.y * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Text title; Font font; if (!font.loadFromFile("Assets/fonts/ariali.ttf")) { cout << "Error: Font ariali.ttf was unable to load."; }; title.setFont(font); title.setString("Profiles"); title.setCharacterSize(55 * resolutionScale.x); title.setFillColor(Color(0, 0, 0)); title.setPosition(Vector2f(middleOfScreen.x, 25 * resolutionScale.y)); //Enter you name Sprite RectangleShape listOfProfilesRect; Sprite listOfProfilesSprite; Texture listOfProfilesTex; if (!listOfProfilesTex.loadFromFile("Assets/textures/profileMenu.png")) { cout << "Error: ProfileEnterBackground.png was unable to load."; }; listOfProfilesRect.setPosition(Vector2f(middleOfScreen.x - buttonSize.x, -120 + middleOfScreen.y * resolutionScale.y)); listOfProfilesRect.setSize(Vector2f(buttonSize.x * 3, 240 * resolutionScale.y)); listOfProfilesRect.setFillColor(Color::Blue); listOfProfilesSprite.setTexture(listOfProfilesTex); listOfProfilesSprite.setScale(Vector2f(1 * resolutionScale.x, 1 * resolutionScale.y)); listOfProfilesSprite.setPosition(listOfProfilesRect.getPosition()); //create text box Vector2f edgeOfTextBox(listOfProfilesRect.getPosition().x , listOfProfilesRect.getPosition().y + (144 * resolutionScale.y) / 2); TextBox playerEnterNameBox("Enter profile name", edgeOfTextBox, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); RenderWindow window(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Profiles Menu"); window.setFramerateLimit(60); Vector2f middleOfScreenOverlay(player->m_sfResolution.x / 2 - (250 * resolutionScale.x), player->m_sfResolution.y / 2 - (250 * resolutionScale.y)); Overlay failedOverlayMessage(middleOfScreenOverlay, Vector2f(500 * resolutionScale.x, 500 * resolutionScale.y), "\tThe Profile you entered does not exist \n\nPlease try again"); failedOverlayMessage.m_bDraw = false; while (window.isOpen()) { //handle input Event event; Vector2f sfMousePos; while (window.pollEvent(event)) { sfMousePos = window.mapPixelToCoords(Mouse::getPosition(window)); if (event.type == Event::Closed) { window.close(); // Allows window to close when 'X' is pressed return; } if (event.type == sf::Event::KeyPressed && playerEnterNameBox.m_bIsEntering == true) { playerEnterNameBox.takeInput(event.key.code); } if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { if (failedOverlayMessage.m_bClicked(sfMousePos) && failedOverlayMessage.m_bDraw == true) { failedOverlayMessage.m_bDraw = false; } if (Select.m_bClicked(sfMousePos)) { if (player->loadProfile(playerEnterNameBox.m_sText)) { window.close(); mainMenu(false); } else { playerEnterNameBox.m_sText.clear(); failedOverlayMessage.m_bDraw = true; } } if (Delete.m_bClicked(sfMousePos)) { // open profile list fstream file; string lineData; string tempProfile; vector<string> profileNames; file.open("Assets/profiles/profileList.txt"); if (DEBUGMODE) cout << "opening Profile list" << endl; if (file.is_open()) { while (getline(file, lineData)) { istringstream iss(lineData); iss.str(lineData); iss >> tempProfile; profileNames.push_back(tempProfile); } } else { cout << "Couldnt Open file ... Assets/profiles/profileList.txt" << endl; } file.close(); //search vector of names for what was entered for (int i = 0; i < profileNames.size(); i++) { if (profileNames[i] == playerEnterNameBox.m_sText+".txt") { //remove the name profileNames.erase(profileNames.begin() + i); } } //ammend profile list ofstream ofile; ofile.open("Assets/profiles/profileList.txt"); for (int i = 0; i < profileNames.size(); i++) { ofile << profileNames[i] << endl; } window.close(); profileMenu(false); } if (playerEnterNameBox.m_bClicked(sfMousePos) ) { playerEnterNameBox.m_bIsEntering = true; } if (New.m_bClicked(sfMousePos)) { //create a new profile with there name player->newProfile(playerEnterNameBox.m_sText); window.close(); mainMenu(false); } } } } window.clear(Color::Green); window.draw(profileBackgroundSprite); window.draw(title); window.draw(listOfProfilesSprite); window.draw(playerEnterNameBox); window.draw(New); window.draw(Select); window.draw(Delete); window.draw(failedOverlayMessage); window.display(); } } } void settingsMenu(bool tutorial) { if (tutorial) { //main menu background------------------------- RectangleShape settingsBackgroundRect; Sprite settingsBackgroundSprite; Texture settingsBackgroundTex; if (!settingsBackgroundTex.loadFromFile("Assets/textures/settingsWindow.png")) { cout << "Error: settingsWindow.png was unable to load."; }; settingsBackgroundRect.setPosition(0, 0); settingsBackgroundRect.setSize(Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); settingsBackgroundRect.setFillColor(Color::Blue); //settingsBackgroundSprite.setTextureRect({ 0,0,(int)player->m_sfResolution.x,(int)player->m_sfResolution.y }); settingsBackgroundSprite.setScale(Vector2f(player->m_sfResolution.x / 3840, player->m_sfResolution.y / 2160)); settingsBackgroundSprite.setTexture(settingsBackgroundTex); settingsBackgroundSprite.setPosition(settingsBackgroundRect.getPosition()); RectangleShape settingsRect; settingsRect.setPosition(player->m_sfResolution.x / 8, player->m_sfResolution.y / 8); //Create buttons------------------------- Vector2f resolutionScale(player->m_sfResolution.x / 1280, player->m_sfResolution.y / 720); Vector2f buttonSize(250 * resolutionScale.x, 100 * resolutionScale.y); Vector2f middleOfScreen((player->m_sfResolution.x / 2) - (buttonSize.x / 2), (player->m_sfResolution.y / 2) - (buttonSize.y / 2)); Text title; Font font; if (!font.loadFromFile("Assets/fonts/ariali.ttf")) { cout << "Error: Font ariali.ttf was unable to load."; }; title.setFont(font); title.setString("Settings"); title.setCharacterSize(55 * resolutionScale.x); title.setFillColor(Color(0, 0, 0)); title.setPosition(Vector2f(middleOfScreen.x, 25 * resolutionScale.y)); Vector2f middleOfScreenOverlay(player->m_sfResolution.x / 2 - (250 * resolutionScale.x), player->m_sfResolution.y / 2 - (250 * resolutionScale.y)); //create text box Vector2f TextBoxStart(180 * resolutionScale.x, 300 * resolutionScale.y); string s; s = to_string(player->m_iGameAudioVolume); TextBox gameVolume("Game Volume " + s, TextBoxStart, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button gameVolumeSubmit("Submit", Vector2f(TextBoxStart.x + (343 * resolutionScale.x), TextBoxStart.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); TextBoxStart.y += 100 * resolutionScale.y; s = to_string(player->m_iMusicAudioVolume); TextBox musicVolume("Music Volume " + s, TextBoxStart, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button musicVolumeSubmit("Submit", Vector2f(TextBoxStart.x + (343 * resolutionScale.x), TextBoxStart.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); TextBoxStart.y += 100 * resolutionScale.y; s = to_string(player->m_iInterfaceAudioVolume); TextBox interfaceVolume("Interface Volume " + s, TextBoxStart, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button interfaceVolumeSubmit("Submit", Vector2f(TextBoxStart.x + (343 * resolutionScale.x), TextBoxStart.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); s = to_string(player->m_sfResolution.x); TextBoxStart = Vector2f(700 * resolutionScale.x, 300 * resolutionScale.y); TextBox resolutionX("Resolution : x " + s, TextBoxStart, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button resolutionXSubmit("Submit", Vector2f(TextBoxStart.x + (343 * resolutionScale.x), TextBoxStart.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); TextBoxStart.y += 100 * resolutionScale.y;; s = to_string(player->m_sfResolution.y); TextBox resolutionY("Resolution : y " + s, TextBoxStart, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button resolutionYSubmit("Submit", Vector2f(TextBoxStart.x + (343 * resolutionScale.x), TextBoxStart.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); TextBoxStart.y += 100 * resolutionScale.y; if (player->m_bFullscreen == true) s = "Yes"; if (player->m_bFullscreen == false) s = "No"; TextBox fullScreen("Fullscreen Mode " + s, TextBoxStart, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button fullScreenSubmit("Submit", Vector2f(TextBoxStart.x + (343 * resolutionScale.x), TextBoxStart.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); Button Save("Save", Vector2f(settingsRect.getPosition().x, player->m_sfResolution.y - buttonSize.y), buttonSize, resolutionScale, "Button_Green"); Button Cancel("Cancel", Vector2f(settingsRect.getPosition().x + 3 * buttonSize.x, player->m_sfResolution.y - buttonSize.y), buttonSize, resolutionScale, "Button_Grey"); Overlay firstOverlayMessage(middleOfScreenOverlay, Vector2f(500 * resolutionScale.x, 500 * resolutionScale.y), "\tWelcome to the settings screen !\n\t Here you can alter any settings you wish\n\n\n Click save when your done."); RenderWindow window(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Main Menu"); window.setFramerateLimit(60); while (window.isOpen()) { //handle input Event event; Vector2f sfMousePos; while (window.pollEvent(event)) { sfMousePos = window.mapPixelToCoords(Mouse::getPosition(window)); if (event.type == Event::Closed) { window.close(); // Allows window to close when 'X' is pressed return; } if (event.type == sf::Event::KeyPressed && tutorialState == 9) { gameVolume.takeInput(event.key.code); musicVolume.takeInput(event.key.code); interfaceVolume.takeInput(event.key.code); resolutionX.takeInput(event.key.code); resolutionY.takeInput(event.key.code); fullScreen.takeInput(event.key.code); } if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { if (tutorialState == 9 && Save.m_bClicked(sfMousePos)) { player->saveProfile(); window.close(); tutorialState = 10; mainMenu(false); } if (tutorialState == 9 ) { if (gameVolume.m_bClicked(sfMousePos)) { gameVolume.m_bIsEntering = true; musicVolume.m_bIsEntering = false; interfaceVolume.m_bIsEntering = false; resolutionX.m_bIsEntering = false; resolutionY.m_bIsEntering = false; fullScreen.m_bIsEntering = false; } if (musicVolume.m_bClicked(sfMousePos)) { gameVolume.m_bIsEntering = false; musicVolume.m_bIsEntering = true; interfaceVolume.m_bIsEntering = false; resolutionX.m_bIsEntering = false; resolutionY.m_bIsEntering = false; fullScreen.m_bIsEntering = false; } if (interfaceVolume.m_bClicked(sfMousePos)) { gameVolume.m_bIsEntering = false; musicVolume.m_bIsEntering = false; interfaceVolume.m_bIsEntering = true; resolutionX.m_bIsEntering = false; resolutionY.m_bIsEntering = false; fullScreen.m_bIsEntering = false; } if (resolutionX.m_bClicked(sfMousePos)) { gameVolume.m_bIsEntering = false; musicVolume.m_bIsEntering = false; interfaceVolume.m_bIsEntering = false; resolutionX.m_bIsEntering = true; resolutionY.m_bIsEntering = false; fullScreen.m_bIsEntering = false; } if (resolutionY.m_bClicked(sfMousePos)) { gameVolume.m_bIsEntering = false; musicVolume.m_bIsEntering = false; interfaceVolume.m_bIsEntering = false; resolutionX.m_bIsEntering = false; resolutionY.m_bIsEntering = true; fullScreen.m_bIsEntering = false; } if (fullScreen.m_bClicked(sfMousePos)) { gameVolume.m_bIsEntering = false; musicVolume.m_bIsEntering = false; interfaceVolume.m_bIsEntering = false; resolutionX.m_bIsEntering = false; resolutionY.m_bIsEntering = false; fullScreen.m_bIsEntering = true; } } if (tutorialState == 9 && fullScreenSubmit.m_bClicked(sfMousePos)) { if (fullScreen.m_sText == "yes") player->m_bFullscreen = true; else if (fullScreen.m_sText == "no") player->m_bFullscreen = false; else player->m_bFullscreen = false; } if (tutorialState == 9 && gameVolumeSubmit.m_bClicked(sfMousePos)) { string input = gameVolume.m_sText; int value = atoi(input.c_str()); if (value >= 0 && value <= 100) { player->m_iGameAudioVolume = value; } } if (tutorialState == 9 && musicVolumeSubmit.m_bClicked(sfMousePos)) { string input = musicVolume.m_sText; int value = atoi(input.c_str()); if (value >= 0 && value <= 100) { player->m_iMusicAudioVolume = value; } } if (tutorialState == 9 && interfaceVolumeSubmit.m_bClicked(sfMousePos)) { string input = interfaceVolume.m_sText; int value = atoi(input.c_str()); if (value >= 0 && value <= 100) { player->m_iInterfaceAudioVolume = value; } } if (tutorialState == 9 && resolutionXSubmit.m_bClicked(sfMousePos)) { string input = resolutionX.m_sText; int value = atoi(input.c_str()); if (value >= 800 && value <= 3840) { player->m_sfResolution.x = value; } } if (tutorialState == 9 && resolutionYSubmit.m_bClicked(sfMousePos)) { string input = resolutionY.m_sText; int value = atoi(input.c_str()); if (value >= 600 && value <= 2160) { player->m_sfResolution.y = value; } } if (firstOverlayMessage.m_bClicked(sfMousePos) && tutorialState == 8) { firstOverlayMessage.m_bDraw = false; tutorialState = 9; } } } } window.clear(Color::Green); window.draw(settingsBackgroundSprite); window.draw(title); // buttons window.draw(gameVolume); window.draw(gameVolumeSubmit); window.draw(interfaceVolume); window.draw(interfaceVolumeSubmit); window.draw(musicVolume); window.draw(musicVolumeSubmit); window.draw(resolutionX); window.draw(resolutionXSubmit); window.draw(resolutionY); window.draw(resolutionYSubmit); window.draw(fullScreen); window.draw(fullScreenSubmit); window.draw(Save); window.draw(Cancel); // first overlay window.draw(firstOverlayMessage); window.display(); } } else { player = Profile::getInstance(); //main menu background------------------------- RectangleShape settingsBackgroundRect; Sprite settingsBackgroundSprite; Texture settingsBackgroundTex; if (!settingsBackgroundTex.loadFromFile("Assets/textures/settingsWindow.png")) { cout << "Error: settingsWindow.png was unable to load."; }; settingsBackgroundRect.setPosition(0, 0); settingsBackgroundRect.setSize(Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); settingsBackgroundRect.setFillColor(Color::Blue); //settingsBackgroundSprite.setTextureRect({ 0,0,(int)player->m_sfResolution.x,(int)player->m_sfResolution.y }); settingsBackgroundSprite.setScale(Vector2f(player->m_sfResolution.x / 3840, player->m_sfResolution.y / 2160)); settingsBackgroundSprite.setTexture(settingsBackgroundTex); settingsBackgroundSprite.setPosition(settingsBackgroundRect.getPosition()); RectangleShape settingsRect; settingsRect.setPosition(player->m_sfResolution.x / 8, player->m_sfResolution.y / 8); //Create buttons------------------------- Vector2f resolutionScale(player->m_sfResolution.x / 1280, player->m_sfResolution.y / 720); Vector2f buttonSize(250 * resolutionScale.x, 100 * resolutionScale.y); Vector2f middleOfScreen((player->m_sfResolution.x / 2) - (buttonSize.x / 2), (player->m_sfResolution.y / 2) - (buttonSize.y / 2)); Text title; Font font; if (!font.loadFromFile("Assets/fonts/ariali.ttf")) { cout << "Error: Font ariali.ttf was unable to load."; }; title.setFont(font); title.setString("Settings"); title.setCharacterSize(55 * resolutionScale.x); title.setFillColor(Color(0, 0, 0)); title.setPosition(Vector2f(middleOfScreen.x, 25 * resolutionScale.y)); Vector2f middleOfScreenOverlay(player->m_sfResolution.x / 2 - (250 * resolutionScale.x), player->m_sfResolution.y / 2 - (250 * resolutionScale.y)); //create text box Vector2f TextBoxStart(180 * resolutionScale.x, 300 * resolutionScale.y); string s; s = to_string(player->m_iGameAudioVolume); TextBox gameVolume("Game Volume : " , s , TextBoxStart, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button gameVolumeSubmit("Submit", Vector2f(TextBoxStart.x + (343 * resolutionScale.x), TextBoxStart.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); TextBoxStart.y += 100 * resolutionScale.y; s = to_string(player->m_iMusicAudioVolume); TextBox musicVolume("Music Volume : " , s, TextBoxStart, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button musicVolumeSubmit("Submit", Vector2f(TextBoxStart.x + (343 * resolutionScale.x), TextBoxStart.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); TextBoxStart.y += 100 * resolutionScale.y; s = to_string(player->m_iInterfaceAudioVolume); TextBox interfaceVolume("Interface Volume : " , s, TextBoxStart, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button interfaceVolumeSubmit("Submit", Vector2f(TextBoxStart.x + (343 * resolutionScale.x), TextBoxStart.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); s = to_string(player->m_sfResolution.x); TextBoxStart = Vector2f(700 * resolutionScale.x, 300 * resolutionScale.y); TextBox resolutionX("Resolution (x) : " , s , TextBoxStart, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button resolutionXSubmit("Submit", Vector2f(TextBoxStart.x + (343 * resolutionScale.x), TextBoxStart.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); TextBoxStart.y += 100 * resolutionScale.y;; s = to_string(player->m_sfResolution.y); TextBox resolutionY("Resolution (y) : " , s, TextBoxStart, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button resolutionYSubmit("Submit", Vector2f(TextBoxStart.x + (343 * resolutionScale.x), TextBoxStart.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); TextBoxStart.y += 100 * resolutionScale.y; if (player->m_bFullscreen == true) s = "Yes"; if (player->m_bFullscreen == false) s = "No"; TextBox fullScreen("Fullscreen Mode : " , s, TextBoxStart, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button fullScreenSubmit("Submit", Vector2f(TextBoxStart.x + (343 * resolutionScale.x), TextBoxStart.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); Button Save("Save", Vector2f(settingsRect.getPosition().x, player->m_sfResolution.y - buttonSize.y), buttonSize, resolutionScale, "Button_Green"); Button Cancel("Cancel", Vector2f(settingsRect.getPosition().x + 3 * buttonSize.x, player->m_sfResolution.y - buttonSize.y), buttonSize, resolutionScale, "Button_Green"); RenderWindow window; if (player->m_bFullscreen == true) window.create(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Main Menu", Style::Fullscreen); else window.create(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Settings"); window.setFramerateLimit(60); while (window.isOpen()) { //handle input Event event; Vector2f sfMousePos; while (window.pollEvent(event)) { sfMousePos = window.mapPixelToCoords(Mouse::getPosition(window)); if (event.type == Event::Closed) { window.close(); // Allows window to close when 'X' is pressed return; } if (event.type == sf::Event::KeyPressed ) { gameVolume.takeInput(event.key.code); musicVolume.takeInput(event.key.code); interfaceVolume.takeInput(event.key.code); resolutionX.takeInput(event.key.code); resolutionY.takeInput(event.key.code); fullScreen.takeInput(event.key.code); } if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { if (Save.m_bClicked(sfMousePos)) { player->saveProfile(); window.close(); mainMenu(false); } if (Cancel.m_bClicked(sfMousePos)) { window.close(); mainMenu(false); } if (gameVolume.m_bClicked(sfMousePos)) { gameVolume.m_bIsEntering = true; musicVolume.m_bIsEntering = false; interfaceVolume.m_bIsEntering = false; resolutionX.m_bIsEntering = false; resolutionY.m_bIsEntering = false; fullScreen.m_bIsEntering = false; } if (musicVolume.m_bClicked(sfMousePos)) { gameVolume.m_bIsEntering = false; musicVolume.m_bIsEntering = true; interfaceVolume.m_bIsEntering = false; resolutionX.m_bIsEntering = false; resolutionY.m_bIsEntering = false; fullScreen.m_bIsEntering = false; } if (interfaceVolume.m_bClicked(sfMousePos)) { gameVolume.m_bIsEntering = false; musicVolume.m_bIsEntering = false; interfaceVolume.m_bIsEntering = true; resolutionX.m_bIsEntering = false; resolutionY.m_bIsEntering = false; fullScreen.m_bIsEntering = false; } if (resolutionX.m_bClicked(sfMousePos)) { gameVolume.m_bIsEntering = false; musicVolume.m_bIsEntering = false; interfaceVolume.m_bIsEntering = false; resolutionX.m_bIsEntering = true; resolutionY.m_bIsEntering = false; fullScreen.m_bIsEntering = false; } if (resolutionY.m_bClicked(sfMousePos)) { gameVolume.m_bIsEntering = false; musicVolume.m_bIsEntering = false; interfaceVolume.m_bIsEntering = false; resolutionX.m_bIsEntering = false; resolutionY.m_bIsEntering = true; fullScreen.m_bIsEntering = false; } if (fullScreen.m_bClicked(sfMousePos)) { gameVolume.m_bIsEntering = false; musicVolume.m_bIsEntering = false; interfaceVolume.m_bIsEntering = false; resolutionX.m_bIsEntering = false; resolutionY.m_bIsEntering = false; fullScreen.m_bIsEntering = true; } if ( fullScreenSubmit.m_bClicked(sfMousePos)) { if (fullScreen.m_sText == "yes") { player->m_bFullscreen = true; window.close(); settingsMenu(false); } else if (fullScreen.m_sText == "no") { player->m_bFullscreen = false; window.close(); settingsMenu(false); } else { player->m_bFullscreen = false; fullScreen.m_sText = "No"; } } if ( gameVolumeSubmit.m_bClicked(sfMousePos)) { string input = gameVolume.m_sText; int value = atoi(input.c_str()); if (value >= 0 && value <= 100) { player->m_iGameAudioVolume = value; window.close(); settingsMenu(false); } else { gameVolume.m_sText = to_string(player->m_iGameAudioVolume); } } if ( musicVolumeSubmit.m_bClicked(sfMousePos)) { string input = musicVolume.m_sText; int value = atoi(input.c_str()); if (value >= 0 && value <= 100) { player->m_iMusicAudioVolume = value; window.close(); settingsMenu(false); } else { musicVolume.m_sText = to_string(player->m_iMusicAudioVolume); } } if ( interfaceVolumeSubmit.m_bClicked(sfMousePos)) { string input = interfaceVolume.m_sText; int value = atoi(input.c_str()); if (value >= 0 && value <= 100) { player->m_iInterfaceAudioVolume = value; window.close(); settingsMenu(false); } else { interfaceVolume.m_sText = to_string(player->m_iInterfaceAudioVolume); } } if ( resolutionXSubmit.m_bClicked(sfMousePos)) { string input = resolutionX.m_sText; int value = atoi(input.c_str()); if (value >= 800 && value <= 3840) { player->m_sfResolution.x = value; window.close(); settingsMenu(false); } else { resolutionX.m_sText = to_string(player->m_sfResolution.x); } } if ( resolutionYSubmit.m_bClicked(sfMousePos)) { string input = resolutionY.m_sText; int value = atoi(input.c_str()); if (value >= 600 && value <= 2160) { player->m_sfResolution.y = value; window.close(); settingsMenu(false); } else { resolutionY.m_sText = to_string(player->m_sfResolution.y); } } } } } window.clear(Color::Green); window.draw(settingsBackgroundSprite); window.draw(title); // buttons window.draw(gameVolume); window.draw(gameVolumeSubmit); window.draw(interfaceVolume); window.draw(interfaceVolumeSubmit); window.draw(musicVolume); window.draw(musicVolumeSubmit); window.draw(resolutionX); window.draw(resolutionXSubmit); window.draw(resolutionY); window.draw(resolutionYSubmit); window.draw(fullScreen); window.draw(fullScreenSubmit); window.draw(Save); window.draw(Cancel); window.display(); } } } void playMenu() { Texture mainMenuBackgroundTex; if (!mainMenuBackgroundTex.loadFromFile("Assets/textures/menuScreen.png")) { cout << "Error: menuScreen.png was unable to load."; }; //we now have a profile //create main menu assets ...................... //main menu background------------------------- RectangleShape mainMenuBackgroundRect; Sprite mainMenuBackgroundSprite; mainMenuBackgroundRect.setPosition(0, 0); mainMenuBackgroundRect.setSize(Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); mainMenuBackgroundRect.setFillColor(Color::Blue); mainMenuBackgroundSprite.setTexture(mainMenuBackgroundTex); mainMenuBackgroundSprite.setScale(Vector2f(1, 1)); mainMenuBackgroundSprite.setPosition(mainMenuBackgroundRect.getPosition()); //Create Positioning variables------------------------- Vector2f resolutionScale(player->m_sfResolution.x / 1280, player->m_sfResolution.y / 720); Vector2f buttonSize(250 * resolutionScale.x, 100 * resolutionScale.y); Vector2f middleOfScreen((player->m_sfResolution.x / 2) - (buttonSize.x / 2), (player->m_sfResolution.y / 2) - (buttonSize.y / 2)); Text title; Font font; if (!font.loadFromFile("Assets/fonts/ariali.ttf")) { cout << "Error: Font ariali.ttf was unable to load."; }; title.setFont(font); title.setString("Play Menu"); title.setCharacterSize(50 * resolutionScale.x); title.setFillColor(Color(0, 0, 0)); title.setPosition(Vector2f(middleOfScreen.x, 25 * resolutionScale.y)); Button LevelsButton("Play", Vector2f(50 * resolutionScale.x, 400 * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Button LoadButton("Load", Vector2f(350 * resolutionScale.x, 400 * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Button EditorButton("Editor", Vector2f( 650 * resolutionScale.x, 400 * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); Button BackButton("Main Menu", Vector2f( 950 * resolutionScale.x, 400 * resolutionScale.y), buttonSize, resolutionScale, "Button_Green"); RenderWindow window; if (player->m_bFullscreen == true) window.create(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Main Menu", Style::Fullscreen); else window.create(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Play Menu"); window.setFramerateLimit(60); while (window.isOpen()) { //handle input Event event; Vector2f sfMousePos; while (window.pollEvent(event)) { sfMousePos = window.mapPixelToCoords(Mouse::getPosition(window)); if (event.type == Event::Closed) { window.close(); // Allows window to close when 'X' is pressed return; } if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { if (EditorButton.m_bClicked(sfMousePos) ) { window.close(); editor(); } if (LevelsButton.m_bClicked(sfMousePos) ) { window.close(); string level = "CampaignLevels/level0" +to_string(player->m_uilevel); play(level); } if (LoadButton.m_bClicked(sfMousePos) ) { window.close(); LoadLevel(); } if (BackButton.m_bClicked(sfMousePos) ) { window.close(); // Allows window to close when 'X' is pressed mainMenu(false); } } } } window.clear(Color::Green); window.draw(mainMenuBackgroundSprite); window.draw(title); // buttons window.draw(EditorButton); window.draw(LevelsButton); window.draw(LoadButton); window.draw(BackButton); window.display(); } } void play(string path) { Game Level; Level = Game(path); //Create a window with the specifications of the profile RenderWindow window; if (player->m_bFullscreen == true) window.create(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), path, Style::Fullscreen); else window.create(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), path); window.setFramerateLimit(60); window.setVerticalSyncEnabled(true); //create a view to fill the windowfor game render View gameView; gameView.setViewport(sf::FloatRect(0, 0, 1.0f, 1.0f)); gameView.setCenter(sf::Vector2f(-500, -500)); gameView.setSize(sf::Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); //create a view to fill the windowfor game render View hudView; hudView.setViewport(sf::FloatRect(0, 0, 1.0f, 1.0f)); hudView.setCenter(sf::Vector2f(player->m_sfResolution.x / 2, player->m_sfResolution.y / 2)); hudView.setSize(sf::Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); Event event; int iMouseWheel; //helps scale hud elements Vector2f resolutionScale(player->m_sfResolution.x / 1280, player->m_sfResolution.y / 720); Vector2f buttonSize(250 * resolutionScale.x, 100 * resolutionScale.y); Vector2f middleOfScreen((player->m_sfResolution.x / 2) - (buttonSize.x / 2), (player->m_sfResolution.y / 2) - (buttonSize.y / 2)); Overlay winOverlay(Vector2f(200 * resolutionScale.x, 150 * resolutionScale.y), Vector2f(888 * resolutionScale.x, 500 * resolutionScale.y), "Congratulations , you completed the level!\n\n Click anywhere to go back to the menu"); Overlay loseOverlay(Vector2f(200 * resolutionScale.x, 150 * resolutionScale.y), Vector2f(888 * resolutionScale.x, 500 * resolutionScale.y), "Bad Luck , you failed to complete the level\n\n Click anywhere to go back to the menu"); winOverlay.m_bDraw = false; loseOverlay.m_bDraw = false; bool bPaused = false; gameView.zoom(2.5); //input delay Clock inputDelay; while (window.isOpen()) { Vector2f sfMousePos; sfMousePos = window.mapPixelToCoords(Mouse::getPosition(window), gameView); //cout << "mouse :" << sfMousePos.x << " " << sfMousePos << endl; //move camera float fMoveSpeed = 10; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::LShift)) { fMoveSpeed *= 3; } //key presses if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W)) { gameView.move(Vector2f(0.0f, -fMoveSpeed)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S)) { gameView.move(Vector2f(0.0f, fMoveSpeed)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) { gameView.move(Vector2f(-fMoveSpeed, 0.0f)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) { gameView.move(Vector2f(fMoveSpeed, 0.0f)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::R)) { Level = Game(path); } Time elapsedTime = inputDelay.getElapsedTime(); if (elapsedTime.asMilliseconds() >= 100.0f) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::P)) { if (bPaused == false) bPaused = true; else if (bPaused == true) bPaused = false; inputDelay.restart(); } if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { cout << "CLICKED AT " << sfMousePos.x << " " << sfMousePos.y << endl; Level.loopClickables(sfMousePos); inputDelay.restart(); } } } while (window.pollEvent(event)) { sfMousePos = window.mapPixelToCoords(Mouse::getPosition(window), hudView); if (event.type == Event::Closed) { window.close(); // Allows window to close when 'X' is pressed return; } if (event.type == Event::MouseWheelMoved) { iMouseWheel = event.mouseWheel.delta; if (iMouseWheel > 0) { //zoom in gameView.zoom(0.9); } if (iMouseWheel < 0) { //zoom out gameView.zoom(1.1); } } } window.clear(Color::Black); //draw the game if (bPaused == false) { Level.updateScene(0.016f); } window.setView(gameView); Level.drawScene(window); //draw the hud window.setView(hudView); window.draw(Level.m_sfHudTopBarSprite); //show the window window.display(); } } void LoadLevel() { //Create a window with the specifications of the profile RenderWindow window; if (player->m_bFullscreen == true) window.create(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Editor", Style::Fullscreen); else window.create(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Load Level"); window.setFramerateLimit(60); window.setVerticalSyncEnabled(true); //create a view to fill the windowfor game render View gameView; gameView.setViewport(sf::FloatRect(0, 0, 1.0f, 1.0f)); gameView.setCenter(sf::Vector2f(player->m_sfResolution.x / 2, player->m_sfResolution.y / 2)); gameView.setSize(sf::Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); //create a view to fill the windowfor game render View hudView; hudView.setViewport(sf::FloatRect(0, 0, 1.0f, 1.0f)); hudView.setCenter(sf::Vector2f(player->m_sfResolution.x / 2, player->m_sfResolution.y / 2)); hudView.setSize(sf::Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); Event event; int iMouseWheel; //helps scale hud elements Vector2f resolutionScale(player->m_sfResolution.x / 1280, player->m_sfResolution.y / 720); Vector2f buttonSize(250 * resolutionScale.x, 100 * resolutionScale.y); Vector2f middleOfScreen((player->m_sfResolution.x / 2) - (buttonSize.x / 2), (player->m_sfResolution.y / 2) - (buttonSize.y / 2)); //Enter your level Sprite RectangleShape listOfProfilesRect; Sprite listOfProfilesSprite; Texture listOfProfilesTex; if (!listOfProfilesTex.loadFromFile("Assets/textures/profileMenu.png")) { cout << "Error: ProfileEnterBackground.png was unable to load."; }; listOfProfilesRect.setPosition(Vector2f(middleOfScreen.x - buttonSize.x, -120 + middleOfScreen.y * resolutionScale.y)); listOfProfilesRect.setSize(Vector2f(buttonSize.x * 3, 240 * resolutionScale.y)); listOfProfilesRect.setFillColor(Color::Blue); listOfProfilesSprite.setTexture(listOfProfilesTex); listOfProfilesSprite.setScale(Vector2f(1 * resolutionScale.x, 1 * resolutionScale.y)); listOfProfilesSprite.setPosition(listOfProfilesRect.getPosition()); Button QuitButton ("Exit", Vector2f(player->m_sfResolution.x - 300 * resolutionScale.x, player->m_sfResolution.y - 90 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); //create text box Vector2f edgeOfTextBox(listOfProfilesRect.getPosition().x, listOfProfilesRect.getPosition().y + (144 * resolutionScale.y) / 2); TextBox saveLevelEntryName("Enter level name", edgeOfTextBox, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); TextBox loadLevelEntryName("Enter level name", edgeOfTextBox, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button loadSubmitButton("Submit", Vector2f(edgeOfTextBox.x + 343, edgeOfTextBox.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); loadLevelEntryName.m_bIsEntering = true; while (window.isOpen()) { Vector2f sfMousePos; sfMousePos = window.mapPixelToCoords(Mouse::getPosition(window), gameView); //move camera float fMoveSpeed = 10; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::LShift)) { fMoveSpeed *= 3; } //key presses if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W)) { gameView.move(Vector2f(0.0f, -fMoveSpeed)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S)) { gameView.move(Vector2f(0.0f, fMoveSpeed)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) { gameView.move(Vector2f(-fMoveSpeed, 0.0f)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) { gameView.move(Vector2f(fMoveSpeed, 0.0f)); } while (window.pollEvent(event)) { sfMousePos = window.mapPixelToCoords(Mouse::getPosition(window), hudView); if (event.type == Event::Closed) { window.close(); // Allows window to close when 'X' is pressed return; } if (event.type == sf::Event::KeyPressed && loadLevelEntryName.m_bIsEntering == true) { loadLevelEntryName.takeInput(event.key.code); } if (event.type == Event::MouseWheelMoved) { iMouseWheel = event.mouseWheel.delta; if (iMouseWheel > 0) { //zoom in gameView.zoom(0.9); } if (iMouseWheel < 0) { //zoom out gameView.zoom(1.1); } } if (Mouse::isButtonPressed(sf::Mouse::Left)) { if (loadSubmitButton.m_bClicked(sfMousePos) && loadLevelEntryName.m_bIsEntering == true) { loadLevelEntryName.m_bIsEntering = false; play(loadLevelEntryName.m_sText); window.close(); gameView.setCenter(sf::Vector2f(player->m_sfResolution.x / 2, player->m_sfResolution.y / 2)); } else if (QuitButton.m_bClicked(sfMousePos)) { window.close(); playMenu(); } } } window.clear(Color::Black); //draw the hud window.setView(hudView); window.draw(QuitButton); if (loadLevelEntryName.m_bIsEntering) { window.draw(listOfProfilesSprite); window.draw(loadLevelEntryName); window.draw(loadSubmitButton); } //show the window window.display(); } } void editor() { //Game Object Game Editor; Editor = Game("editor"); //Create a window with the specifications of the profile RenderWindow window; if (player->m_bFullscreen == true) window.create(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Editor", Style::Fullscreen); else window.create(VideoMode(player->m_sfResolution.x, player->m_sfResolution.y), "Editor"); window.setFramerateLimit(60); window.setVerticalSyncEnabled(true); //create a view to fill the windowfor game render View gameView; gameView.setViewport(sf::FloatRect(0, 0, 1.0f, 1.0f)); gameView.setCenter(sf::Vector2f(player->m_sfResolution.x / 2, player->m_sfResolution.y / 2)); gameView.setSize(sf::Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); //create a view to fill the windowfor game render View hudView; hudView.setViewport(sf::FloatRect(0, 0, 1.0f, 1.0f)); hudView.setCenter(sf::Vector2f(player->m_sfResolution.x / 2, player->m_sfResolution.y / 2)); hudView.setSize(sf::Vector2f(player->m_sfResolution.x, player->m_sfResolution.y)); //helps scale hud elements Vector2f resolutionScale(player->m_sfResolution.x / 1280, player->m_sfResolution.y / 720); Vector2f buttonSize(250 * resolutionScale.x, 100 * resolutionScale.y); Vector2f middleOfScreen((player->m_sfResolution.x / 2) - (buttonSize.x / 2), (player->m_sfResolution.y / 2) - (buttonSize.y / 2)); //create Buttons for the editor--------------------------------- Button BackgroundButton ("Background", Vector2f(0, 0), Vector2f(300 * resolutionScale.x , 88.5 * resolutionScale.y) , resolutionScale, "Button_Green" ); Button SizeButton ("Level Size", Vector2f(0, 90 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); Button TimeButton ("Time of Day", Vector2f(0, 180 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); Button RoadSelectorButton ("Roads", Vector2f(0, 270 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button twoWayButton ("Two Way Road", Vector2f(300 * resolutionScale.x, 120 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button TJunctionButton ("T - Junction", Vector2f(300 * resolutionScale.x, 210 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button CrossRoadsButton ("Cross Roads", Vector2f(300 * resolutionScale.x, 300 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button CornerButton ("Corner", Vector2f(300 * resolutionScale.x, 390 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button trafficLightButton ("Lights", Vector2f(0, 360 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button normalLightButton ("Traffic Lights", Vector2f(300 * resolutionScale.x, 315 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button pedLightButton ("Pedestrian Lights", Vector2f(300 * resolutionScale.x, 405 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button unitsButton ("units", Vector2f(0, 450 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button lessunitsButton ("-", Vector2f(300 * resolutionScale.x, 450 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); Button numberunitsButton (" ", Vector2f(550 * resolutionScale.x, 450 * resolutionScale.y), Vector2f(250 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button moreunitsButton ("+", Vector2f(800 * resolutionScale.x, 450 * resolutionScale.y), Vector2f(250 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); Button pedsButton ("Pedestrians", Vector2f(0, 540 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button lessPedsButton ("-", Vector2f(300 * resolutionScale.x, 540 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); Button numberPedsButton (" ", Vector2f(550 * resolutionScale.x, 540 * resolutionScale.y), Vector2f(250 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button morePedsButton ("+", Vector2f(800 * resolutionScale.x, 540 * resolutionScale.y), Vector2f(250 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); Button StartEndPointsButton ("Start/End Points", Vector2f(0, 630 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button startPointButton ("Start Point", Vector2f(300 * resolutionScale.x, 630 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 44.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); Button endPointButton ("End Point", Vector2f(300 * resolutionScale.x, 675 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 44.5 * resolutionScale.y), resolutionScale, "Button_Yellow" ); //Menu Buttons------------------------------------------------- Button newButton ("New", Vector2f(player->m_sfResolution.x - 300 * resolutionScale.x, 0), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); Button saveButton ("Save", Vector2f( player->m_sfResolution.x - 300 * resolutionScale.x, 90 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); Button loudButton ("Load", Vector2f(player->m_sfResolution.x - 300 * resolutionScale.x, 180 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); Button helpButton ("Help", Vector2f(player->m_sfResolution.x - 300 * resolutionScale.x, 270 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); Button pathfinding ("Grid", Vector2f(player->m_sfResolution.x - 300 * resolutionScale.x, 360 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); Button QuitButton ("Exit", Vector2f(player->m_sfResolution.x - 300 * resolutionScale.x, player->m_sfResolution.y - 90 * resolutionScale.y), Vector2f(300 * resolutionScale.x, 88.5 * resolutionScale.y), resolutionScale, "Button_Green" ); //Enter you level Sprite RectangleShape listOfProfilesRect; Sprite listOfProfilesSprite; Texture listOfProfilesTex; if (!listOfProfilesTex.loadFromFile("Assets/textures/profileMenu.png")) { cout << "Error: ProfileEnterBackground.png was unable to load."; }; listOfProfilesRect.setPosition(Vector2f(middleOfScreen.x - buttonSize.x, -120 + middleOfScreen.y * resolutionScale.y)); listOfProfilesRect.setSize(Vector2f(buttonSize.x * 3, 240 * resolutionScale.y)); listOfProfilesRect.setFillColor(Color::Blue); listOfProfilesSprite.setTexture(listOfProfilesTex); listOfProfilesSprite.setScale(Vector2f(1 * resolutionScale.x, 1 * resolutionScale.y)); listOfProfilesSprite.setPosition(listOfProfilesRect.getPosition()); //create text box Vector2f edgeOfTextBox(listOfProfilesRect.getPosition().x, listOfProfilesRect.getPosition().y + (144 * resolutionScale.y) / 2); TextBox saveLevelEntryName("Enter level name", edgeOfTextBox, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); TextBox loadLevelEntryName("Enter level name", edgeOfTextBox, Vector2f(343 * resolutionScale.x, 37 * resolutionScale.y), "Textbox"); Button saveSubmitButton("Submit", Vector2f(edgeOfTextBox.x + 343, edgeOfTextBox.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); Button loadSubmitButton("Submit", Vector2f(edgeOfTextBox.x + 343, edgeOfTextBox.y), Vector2f(buttonSize.x / 2.5, buttonSize.y / 2.5), resolutionScale, "Button_Green"); //help screen Overlay helpOverlayMessage(Vector2f(200 * resolutionScale.x,150 * resolutionScale.y), Vector2f(888 * resolutionScale.x, 500 * resolutionScale.y), "This is the level editor\n\n-You can move around with W,A,S,D\n-Zoom in and out with the mouse wheel\n-Interact with the buttons with left mouse\n\nOnce an you have selected an object for placement : \n - Place it with enter\n - Cancel with Right mouse\n\nPress Help to veiw this message again"); helpOverlayMessage.m_bDraw = true; float fRotation = 0; //selection string string sType; // type of object been placed by the editor //input delay Clock inputDelay; //bool for when the player is using the menu button bool usingMenu = true; // true when using buttons (stops un wanted interaction) while (window.isOpen()) { //handle input Event event; Vector2f sfMousePos; Vector2f sfPlacingPos; int iMouseWheel; Time elapsedTime = inputDelay.getElapsedTime(); if (elapsedTime.asMilliseconds() >= 100.0f) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Q) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) { fRotation -= 90; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::E) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) { fRotation += 90; } if (fRotation >= 360)fRotation = 0; if (fRotation < 0)fRotation = 270; inputDelay.restart(); } if (!usingMenu) { //move camera float fMoveSpeed = 10; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::LShift)) { fMoveSpeed *= 3; } //key presses if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W)) { gameView.move(Vector2f(0.0f, -fMoveSpeed)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S)) { gameView.move(Vector2f(0.0f, fMoveSpeed)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) { gameView.move(Vector2f(-fMoveSpeed, 0.0f)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right) || sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) { gameView.move(Vector2f(fMoveSpeed, 0.0f)); } //move the editor objects sfPlacingPos = window.mapPixelToCoords(Mouse::getPosition(window), gameView); } while (window.pollEvent(event)) { sfMousePos = window.mapPixelToCoords(Mouse::getPosition(window), hudView); if (event.type == Event::MouseWheelMoved) { iMouseWheel= event.mouseWheel.delta; if (iMouseWheel > 0) { //zoom in gameView.zoom(0.9); } if (iMouseWheel < 0) { //zoom out gameView.zoom(1.1); } } if (event.type == Event::Closed) { window.close(); // Allows window to close when 'X' is pressed return; } if (event.type == sf::Event::KeyPressed && saveLevelEntryName.m_bIsEntering == true) { saveLevelEntryName.takeInput(event.key.code); } if (event.type == sf::Event::KeyPressed && loadLevelEntryName.m_bIsEntering == true) { loadLevelEntryName.takeInput(event.key.code); } } window.clear(Color::Black); //draw the game window.setView(gameView); Editor.updateScene(0.01f); Editor.drawScene(window); //draw the hud window.setView(hudView); if (!placingBool && !usingMenu) { window.draw(BackgroundButton); window.draw(SizeButton); window.draw(TimeButton); window.draw(RoadSelectorButton); window.draw(trafficLightButton); window.draw(unitsButton); window.draw(pedsButton); window.draw(StartEndPointsButton); if (RoadSelectorBool) { window.draw(twoWayButton); window.draw(TJunctionButton); window.draw(CrossRoadsButton); window.draw(CornerButton); } if (LightSelectorBool) { window.draw(normalLightButton); window.draw(pedLightButton); } if (unitsSelectorBool) { window.draw(lessunitsButton); window.draw(numberunitsButton); window.draw(moreunitsButton); } if (PedSelectorBool) { window.draw(lessPedsButton); window.draw(numberPedsButton); window.draw(morePedsButton); } if (StartEndPointsBool) { window.draw(startPointButton); window.draw(endPointButton); } window.draw(newButton); window.draw(saveButton); window.draw(loudButton); window.draw(helpButton); window.draw(pathfinding); window.draw(QuitButton); window.draw(helpOverlayMessage); } if (usingMenu) { window.draw(helpOverlayMessage); if (saveLevelEntryName.m_bIsEntering) { window.draw(listOfProfilesSprite); window.draw(saveLevelEntryName); window.draw(saveSubmitButton); } if (loadLevelEntryName.m_bIsEntering) { window.draw(listOfProfilesSprite); window.draw(loadLevelEntryName); window.draw(loadSubmitButton); } } //show the window window.display(); } } void resetSelectors() { RoadSelectorBool = false; LightSelectorBool = false; unitsSelectorBool = false; PedSelectorBool = false; StartEndPointsBool = false; placingBool = false; }
[ "thechristoph10@googlemail.com" ]
thechristoph10@googlemail.com
1778af7ce72ad16c2e40aedfeac388321607665b
dbe71f422219752454925871cf27df8c84da312d
/cpp/divinhr.cpp
d7e5d55b66ab666691786c5a0066dd8c4c5cded9
[]
no_license
tsp1998/CPP
8e1ee8f2ea746416123db23bcdfca3827960ffbf
44d110574a84032bcdfe3c2ee9f09bb7b060d21d
refs/heads/master
2023-03-27T22:07:15.887860
2021-03-28T07:00:21
2021-03-28T07:00:21
326,348,172
0
0
null
null
null
null
UTF-8
C++
false
false
468
cpp
#include <iostream> using namespace std; class base { public: int a, b; void getval(int x, int y); }; void base::getval(int x, int y) { a = x; b = y; } class derived : public base { public: int div; void display(); }; void derived::display() { div = a / b; cout << " Result of division=" << div; } int main() { derived obj; obj.getval(35, 5); obj.display(); return 0; } output : Result of division = 7cse @cse - OptiPlex - 380 : ~ / 50 $ ^ C
[ "shubham.tandale@qualitiasoft.com" ]
shubham.tandale@qualitiasoft.com
9bee778374950544eb66df9d6c9a66c6706a6906
b809105a869fccce86101a5e016f092f8e870b1c
/src/LineDeformer.cpp
8dbcaff80c5f0346c56baeed7ad23d07c559a975
[]
no_license
ReemiiX/Multi-view-Wire-Art
261413bee6926dd77222460fc43593cbba6e01ee
5fdbcc609caedd3c92651b173f205fa480003c05
refs/heads/master
2022-11-13T05:13:21.664561
2020-06-27T02:41:48
2020-06-27T02:41:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,657
cpp
#include "LineDeformer.h" LineDeformer::LineDeformer(Source *s) { m_source = s; } LineDeformer::~LineDeformer() { } void LineDeformer::getParametricCurves(const vector<float*> &segments, const vector<int> &ptNum, vector<Spline3D*> &curves, std::vector<float> &firstLastLock, float fr){ // Prepare Spline HSSSpline::PathPoints<3> points; HSSSpline::Samples samples; // For preserving First & Last float *first, *last; int numSegment = segments.size(); for (int i = 0; i < numSegment; i++){ points.val.clear(); // Create Spline Spline3D *spline = new Spline3D(); for (int j = 0; j < ptNum[i]; j++){ float *v = segments[i] + j * 3; HSSSpline::PathPoint<3> p; p[0] = v[0]; p[1] = v[1]; p[2] = v[2]; points.val.push_back(p); } first = segments[i]; last = segments[i] + (ptNum[i] - 1) * 3; spline->assignPoints(points); float fitRatio = 0; float length = points.val.size(); // Auto Fit Ratio definition if (fr <= 0){ if (length >= 300){ fitRatio = 0.005; } else if (length >= 200){ fitRatio = 0.01; } else if (length >= 100){ fitRatio = 0.05; } else{ fitRatio = 0.1; } } else{ fitRatio = fr; } // Fit Curve spline->fittingCurve(2.0); //spline->UniformSampling(samples, 10); // Record First and Last firstLastLock.push_back(first[0]); firstLastLock.push_back(first[1]); firstLastLock.push_back(first[2]); firstLastLock.push_back(last[0]); firstLastLock.push_back(last[1]); firstLastLock.push_back(last[2]); curves.push_back(spline); m_curves.push_back(spline); // Fix first & last HSSSpline::PathPoints<3> &ctrls = spline->getCtrlPoints(); int numCtrl = ctrls.val.size(); ctrls[0][0] = first[0]; ctrls[0][1] = first[1]; ctrls[0][2] = first[2]; ctrls[numCtrl - 1][0] = last[0]; ctrls[numCtrl - 1][1] = last[1]; ctrls[numCtrl - 1][2] = last[2]; spline->reFitCurve(); } } void LineDeformer::initCurve(const std::vector<float*> &segs, const std::vector<int> &ptNums, std::vector<Spline3D*> &curves, std::vector<float> &firstLastLock){ // First setup need parametric curves this->getParametricCurves(segs, ptNums, curves, firstLastLock, -1); // Set up adjacency matrix int numSeg = segs.size(); m_adjacencyMat = new unsigned char*[numSeg]; for (int i = 0; i < numSeg; i++){ m_adjacencyMat[i] = new unsigned char[numSeg]; } LineWidget::setupAdjacencyMatrix(segs, ptNums, m_adjacencyMat); m_adjacencyMatSize = numSeg; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// glm::vec3 LineDeformer::getDeformVector_180124(float *src){ glm::vec3 resDV = { 0, 0, 0 }; int numImage = m_source->m_ioList.size(); for (int i = 0; i < numImage; i++){ int nearestPixel[2]; m_source->m_ioList[i]->getNearestThinContourPixel(src, nearestPixel); // Get projected pixel int srcPixel[2]; m_source->m_ioList[i]->getToleranceProj(src, srcPixel, 3); // Get vertex in world space glm::vec3 worldNP = m_source->m_ioList[i]->getWorldSpaceVertex(nearestPixel); glm::vec3 worldSRC = m_source->m_ioList[i]->getWorldSpaceVertex(srcPixel); glm::vec3 dv = worldNP - worldSRC; float f = glm::length(glm::vec3(src[0], src[1], src[2]) - m_source->m_ioList[i]->m_viewPos); float n = glm::length(worldSRC - m_source->m_ioList[i]->m_viewPos); dv = dv * f / n; float srcDT = m_source->m_ioList[i]->getDistanceTransformVerThin(src); resDV = resDV + dv * this->getDeformVectorWeight(srcDT) * 1.0f ; } return resDV; } float LineDeformer::getDeformVectorWeight(float x){ x = x * m_dtWeight; const float MU = 0.0; float tmp = glm::exp(-1 * x * x / (2 * m_sigma * m_sigma)); float f = tmp / sqrt(2 * glm::pi<float>() * m_sigma * m_sigma); return f; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void LineDeformer::initDeformProcess(const std::vector<Spline3D*> &curves, const std::vector<float> &firstLastLock){ int numCurve = curves.size(); //////////////////////////////////////////////////////////////////// // Create Two Buffers m_buffer0 = new CurveStructure; m_buffer0->curveCtrls = std::vector<float*>(numCurve); m_buffer0->numCurveCtrl = std::vector<int>(numCurve); m_buffer1 = new CurveStructure; m_buffer1->curveCtrls = std::vector<float*>(numCurve); m_buffer1->numCurveCtrl = std::vector<int>(numCurve); // Create initial case and set to buffer0, then prepare buffer1 for (int i = 0; i < numCurve; i++){ HSSSpline::PathPoints<3> &ctrls = curves[i]->getCtrlPoints(); int numCtrl = ctrls.val.size(); float *ctrlBuffer0 = new float[numCtrl * 3]; m_buffer0->curveCtrls[i] = ctrlBuffer0; m_buffer0->numCurveCtrl[i] = numCtrl; float *ctrlBuffer1 = new float[numCtrl * 3]; m_buffer1->curveCtrls[i] = ctrlBuffer1; m_buffer1->numCurveCtrl[i] = numCtrl; } int numNum = firstLastLock.size(); m_buffer0->firstLastLock = std::vector<float>(numNum); m_buffer1->firstLastLock = std::vector<float>(numNum); this->setUpInitialCurveStructure(curves, firstLastLock); m_sampleBuffer = new float[10000 * 3]; } void LineDeformer::setUpInitialCurveStructure(const std::vector<Spline3D*> &curves, const std::vector<float> &firstLastLock){ int numCurve = curves.size(); // Create initial case and set to buffer0, then prepare buffer1 for (int i = 0; i < numCurve; i++){ HSSSpline::PathPoints<3> &ctrls = curves[i]->getCtrlPoints(); int numCtrl = ctrls.val.size(); float *ctrlBuffer0 = m_buffer0->curveCtrls[i]; for (int j = 0; j < numCtrl; j++){ ctrlBuffer0[j * 3 + 0] = ctrls[j][0]; ctrlBuffer0[j * 3 + 1] = ctrls[j][1]; ctrlBuffer0[j * 3 + 2] = ctrls[j][2]; } } int numNum = firstLastLock.size(); for (int i = 0; i < numNum; i++){ m_buffer0->firstLastLock[i] = firstLastLock[i]; } } void LineDeformer::deform_180125(std::vector<Spline3D*> &curves, std::vector<float> &firstLastLock, const std::string &processedFileName, bool outputProcessedSS){ this->setUpInitialCurveStructure(curves, firstLastLock); int numCurve = curves.size(); ProgressTestSender::Instance()->addLog("Start Deform"); int numDeformStep = 0; while (true){ if (numDeformStep < 300 && outputProcessedSS){ this->outputCurveSamples(processedFileName + "_" + std::to_string(numDeformStep) + ".ss", curves); } if (!this->getDeformedStructure_180125(curves, m_buffer0->firstLastLock, m_buffer1, 0.1, outputProcessedSS)){ break; } numDeformStep++; if (numDeformStep >= 1000){ break; } // Exchange CurveStructure *hold = m_buffer0; m_buffer0 = m_buffer1; m_buffer1 = hold; } ProgressTestSender::Instance()->addLog("Num Deform Step: " + std::to_string(numDeformStep)); /////////////////////////////////////////////////////////////////// // Set to best for (int i = 0; i < numCurve; i++){ HSSSpline::PathPoints<3> &ctrls = curves[i]->getCtrlPoints(); int numCtrl = ctrls.val.size(); float *ctrlBuffer = m_buffer0->curveCtrls[i]; for (int j = 0; j < numCtrl; j++){ ctrls[j][0] = ctrlBuffer[j * 3 + 0]; ctrls[j][1] = ctrlBuffer[j * 3 + 1]; ctrls[j][2] = ctrlBuffer[j * 3 + 2]; } ctrls[0][0] = m_buffer0->firstLastLock[i * 6 + 0]; ctrls[0][1] = m_buffer0->firstLastLock[i * 6 + 1]; ctrls[0][2] = m_buffer0->firstLastLock[i * 6 + 2]; ctrls[numCtrl - 1][0] = m_buffer0->firstLastLock[i * 6 + 3]; ctrls[numCtrl - 1][1] = m_buffer0->firstLastLock[i * 6 + 4]; ctrls[numCtrl - 1][2] = m_buffer0->firstLastLock[i * 6 + 5]; curves[i]->reFitCurve(); } int numNum = firstLastLock.size(); for (int i = 0; i < numNum; i++){ firstLastLock[i] = m_buffer0->firstLastLock[i]; } } bool LineDeformer::getDeformedStructure_180125(const std::vector<Spline3D*> &curves, const std::vector<float> &firstLastLock, CurveStructure *res, float translateRatio, bool requireReFit){ std::vector<glm::vec3> deformVector; //std::vector<glm::vec3> gaussianDeformVector; std::vector<glm::vec3> firstLastLockDeformVector; // Deform target is Ctrl Points int numCurve = curves.size(); // Get minimum deform vector & maximum deform vector float minDeformVectorMagnitude = 100; float maxDeformVectorMagnitude = -1; for (int i = 0; i < numCurve; i++){ // Get Ctrl Points HSSSpline::PathPoints<3> &ctrls = curves[i]->getCtrlPoints(); int numCtrl = ctrls.val.size(); for (int j = 0; j < numCtrl; j++){ HSSSpline::PathPoint<3> &p = ctrls.val.at(j); float src[3] = { p[0], p[1], p[2] }; float res[3] = { 0 }; glm::vec3 dv = this->getDeformVector_180124(src); float mag = glm::length(dv); deformVector.push_back(dv); if (mag < minDeformVectorMagnitude){ minDeformVectorMagnitude = mag; } else if (mag > maxDeformVectorMagnitude){ maxDeformVectorMagnitude = mag; } } // Deform first float firstLock[] = { firstLastLock[i * 6 + 0], firstLastLock[i * 6 + 1], firstLastLock[i * 6 + 2] }; float firstLockRes[3]; glm::vec3 firstLockDeformVector = this->getDeformVector_180124(firstLock); float mag = glm::length(firstLockDeformVector); firstLastLockDeformVector.push_back(firstLockDeformVector); if (mag < minDeformVectorMagnitude){ minDeformVectorMagnitude = mag; } else if (mag > maxDeformVectorMagnitude){ maxDeformVectorMagnitude = mag; } // Deform Last float lastLock[] = { firstLastLock[i * 6 + 3], firstLastLock[i * 6 + 4], firstLastLock[i * 6 + 5] }; float lastLockRes[3]; glm::vec3 lastLockDeformVector = this->getDeformVector_180124(lastLock); firstLastLockDeformVector.push_back(lastLockDeformVector); mag = glm::length(lastLockDeformVector); if (mag < minDeformVectorMagnitude){ minDeformVectorMagnitude = mag; } else if (mag > maxDeformVectorMagnitude){ maxDeformVectorMagnitude = mag; } } // Record minimumDeformMagnitudes.push_back(minDeformVectorMagnitude); maximumDeformMagnitudes.push_back(maxDeformVectorMagnitude); ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // If magnitude < minimum deform vector, the deform process is end if (maxDeformVectorMagnitude < 0.1){ return false; } // Calculate the deformed structure int dvOffset = 0; for (int i = 0; i < numCurve; i++){ // Get Ctrl Points HSSSpline::PathPoints<3> &ctrls = curves[i]->getCtrlPoints(); int numCtrl = ctrls.val.size(); // Apply & Saving the result if (numCtrl != res->numCurveCtrl[i]){ // Rebuild a buffer if (numCtrl > res->numCurveCtrl[i]){ delete[] res->curveCtrls[i]; res->curveCtrls[i] = new float[numCtrl * 3]; } res->numCurveCtrl[i] = numCtrl; } else{ // Use existed } float *buffer = res->curveCtrls[i]; for (int j = 0; j < numCtrl; j++){ HSSSpline::PathPoint<3> &p = ctrls.val.at(j); const glm::vec3 &r = deformVector[dvOffset]; p[0] = p[0] + translateRatio * r[0]; p[1] = p[1] + translateRatio * r[1]; p[2] = p[2] + translateRatio * r[2]; buffer[j * 3 + 0] = p[0]; buffer[j * 3 + 1] = p[1]; buffer[j * 3 + 2] = p[2]; dvOffset++; } float firstLock[] = { firstLastLock[i * 6 + 0], firstLastLock[i * 6 + 1], firstLastLock[i * 6 + 2] }; glm::vec3 dv = firstLastLockDeformVector[i * 2 + 0]; ctrls[0][0] = firstLock[0] + translateRatio * dv.x; ctrls[0][1] = firstLock[1] + translateRatio * dv.y; ctrls[0][2] = firstLock[2] + translateRatio * dv.z; float lastLock[] = { firstLastLock[i * 6 + 3], firstLastLock[i * 6 + 4], firstLastLock[i * 6 + 5] }; dv = firstLastLockDeformVector[i * 2 + 1]; ctrls[numCtrl - 1][0] = lastLock[0] + translateRatio * dv.x; ctrls[numCtrl - 1][1] = lastLock[1] + translateRatio * dv.y; ctrls[numCtrl - 1][2] = lastLock[2] + translateRatio * dv.z; res->firstLastLock[i * 6 + 0] = ctrls[0][0]; res->firstLastLock[i * 6 + 1] = ctrls[0][1]; res->firstLastLock[i * 6 + 2] = ctrls[0][2]; res->firstLastLock[i * 6 + 3] = ctrls[numCtrl - 1][0]; res->firstLastLock[i * 6 + 4] = ctrls[numCtrl - 1][1]; res->firstLastLock[i * 6 + 5] = ctrls[numCtrl - 1][2]; ////////////////////////////////////////////////////////////////////////////////////////////////////// // Apply & Saving the result if (requireReFit){ curves[i]->reFitCurve(); } } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////// void LineDeformer::outputCurveSamples(const std::string &fileName, const std::vector<Spline3D*> &curves){ // Open file std::ofstream output(fileName, ios::binary); if (!output.is_open()){ return; } int numCurve = curves.size(); output.write((char*)(&numCurve), 4); for (int i = 0; i < numCurve; i++){ int numNum = 0; curves[i]->getLineVertex(m_sampleBuffer, &numNum, 0.1); int numVertex = numNum / 3; output.write((char*)(&numVertex), 4); output.write((char*)m_sampleBuffer, numNum * 4); } output.close(); } void LineDeformer::getCurveSamples(vector<float*> &segments, vector<int> &ptNum, const std::vector<Spline3D*> &curves, const std::vector<float> &firstLastLock){ float *buffer = new float[10000]; for (int i = 0; i < curves.size(); i++){ Spline3D *spline = curves[i]; ///////////////////////////////////////////////////////////////// int count = 0; spline->getLineVertex(buffer, &count, 0.1); // Save the data float *v = new float[count]; int ptCount = count / 3; for (int i = 0; i < count; i++){ v[i] = buffer[i]; } segments.push_back(v); ptNum.push_back(ptCount); } }
[ "kevin30112@gmail.com" ]
kevin30112@gmail.com
65c94f8ff191270c1b1dea4935c597771ee50b09
1d37f83cee096eaaaa8bf649784c134dc971a1a1
/Medium/UniquePaths.cpp
5596f71f0843953aad5315ec88e5b71ae63a115c
[ "MIT" ]
permissive
wxdai/LeetCode-Solutions
408f838acb63d5f29d2f3949cee609de3a3c781b
1d90e8ab818cfb1188bfb2997cda31c3192eb8f7
refs/heads/master
2021-01-15T13:49:10.882049
2016-02-23T23:45:36
2016-02-23T23:45:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
455
cpp
class Solution { public: int uniquePaths(int m, int n) { int paths[m][n]; for (int row = 0; row < m; row++) { for (int col = 0; col < n; col++) { if (row == 0 || col == 0) { paths[row][col] = 1; } else { paths[row][col] = paths[row - 1][col] + paths[row][col - 1]; } } } return paths[m - 1][n - 1]; } };
[ "machuiwen@gmail.com" ]
machuiwen@gmail.com
7f9393cdfda3ee10114b11d0bd93e5d65e4ca2b9
4e9aa6d8635d6bfcbaeecbb9420ebdc4c4489fba
/ARXTest/cadtest/DefGEPlugin/PolyLineWorkSurfaceDraw.cpp
d2bfd2ee28978046daf21546e1ff1fddec265c81
[]
no_license
softwarekid/myexercise
4daf73591917c8ba96f81e620fd2c353323a1ae5
7bea007029c4c656c49490a69062648797084117
refs/heads/master
2021-01-22T11:47:01.421922
2014-03-15T09:47:41
2014-03-15T09:47:41
18,024,710
0
3
null
null
null
null
GB18030
C++
false
false
5,680
cpp
#include "StdAfx.h" #include "PolyLineWorkSurfaceDraw.h" #include "DrawTool.h" #include "DrawSpecial.h" ACRX_CONS_DEFINE_MEMBERS ( PolyLineWorkSurfaceDraw, PolyLineTunnelDraw, 1 ) PolyLineWorkSurfaceDraw::PolyLineWorkSurfaceDraw( void ) { } void PolyLineWorkSurfaceDraw::setAllExtraParamsToDefault() { PolyLineTunnelDraw::setAllExtraParamsToDefault(); //m_oneSideLineWeight = AcDb::kLnWt100; m_trunkWidth = 30; m_trunkLength = 100; m_arrowWidth = 20; m_arrowLength = 30; m_clockWise = false; } void PolyLineWorkSurfaceDraw::configExtraParams() { } void PolyLineWorkSurfaceDraw::readExtraParam( DrawParamReader& reader ) { PolyLineTunnelDraw::readExtraParam( reader ); //int lw; //reader.readInt(lw); //m_oneSideLineWeight = (AcDb::LineWeight)lw; reader.readDouble( m_trunkWidth ); reader.readDouble( m_trunkLength ); reader.readDouble( m_arrowWidth ); reader.readDouble( m_arrowLength ); reader.readBoolean( m_clockWise ); } void PolyLineWorkSurfaceDraw::writeExtraParam( DrawParamWriter& writer ) { PolyLineTunnelDraw::writeExtraParam( writer ); //writer.writeInt(m_oneSideLineWeight); writer.writeDouble( m_trunkWidth ); writer.writeDouble( m_trunkLength ); writer.writeDouble( m_arrowWidth ); writer.writeDouble( m_arrowLength ); writer.writeBoolean( m_clockWise ); } // 计算箭头的起始中点 static AcGePoint3d CaclArrowPoint( const AcGePoint3d& m_startPt, const AcGePoint3d& m_endPt, double m_width, double angle ) { AcGeVector3d v = m_endPt - m_startPt; AcGePoint3d pt = m_startPt + v * 0.5; v.normalize(); v.rotateBy( angle, AcGeVector3d::kZAxis ); return ( pt + v * m_width ); } void PolyLineWorkSurfaceDraw::drawArrow( AcGiWorldDraw* mode, bool clockWise ) { double angle = ( clockWise ? ( -PI / 2 ) : ( PI / 2 ) ); // 主干中心始点坐标 AcGePoint3d pt = CaclArrowPoint( m_startPt, m_endPt, m_width / 2, angle ); // 中点 AcGeVector3d v = m_endPt - m_startPt; v.normalize(); // 向量标准化(|v|=1) // 主干两侧的始点坐标 AcGePoint3d sp1 = pt + v * m_trunkWidth; AcGePoint3d sp2 = pt - v * m_trunkWidth; v.rotateBy( angle, AcGeVector3d::kZAxis ); // 主干两侧的末点坐标 AcGePoint3d tp1 = sp1 + v * m_trunkLength; AcGePoint3d tp2 = sp2 + v * m_trunkLength; // 箭头尖端坐标 AcGePoint3d ap = pt + v * ( m_trunkLength + m_arrowLength ); v.rotateBy( -1 * angle, AcGeVector3d::kZAxis ); // 箭头两侧的坐标 AcGePoint3d ap1 = tp1 + v * m_arrowWidth; AcGePoint3d ap2 = tp2 - v * m_arrowWidth; // 绘制箭头 DrawLine( mode, sp1, tp1 ); DrawLine( mode, tp1, ap1 ); DrawLine( mode, ap1, ap ); DrawLine( mode, ap, ap2 ); DrawLine( mode, ap2, tp2 ); DrawLine( mode, tp2, sp2 ); } void PolyLineWorkSurfaceDraw::drawText( AcGiWorldDraw* mode ) { // 绘制文字 AcGeVector3d v = m_endPt - m_startPt; AcGePoint3d pt = m_startPt + v * 0.5; // 中心点 if( v.x < 0 ) v.negate(); double angle = v.angleTo( AcGeVector3d::kXAxis, -AcGeVector3d::kZAxis ); v.normalize(); v.rotateBy( PI / 2, AcGeVector3d::kZAxis ); // 始终与文字反向 pt += v * m_width * 0.5; DrawMText( mode, pt, angle, _T( "回采工作面" ), m_width * 0.618, AcDbMText::kBottomCenter ); } Adesk::Boolean PolyLineWorkSurfaceDraw::subWorldDraw( AcGiWorldDraw* mode ) { assertReadEnabled(); //PolyLineTunnelDraw::subWorldDraw(mode); DrawPolyLine( mode, m_startPt, m_endPt, m_width ); DrawJoint( mode, m_startPt, m_width * 0.5, jdt ); // 绘制始节点 DrawJoint( mode, m_endPt, m_width * 0.5, jdt ); // 绘制末节点 // 绘制一个文字 drawText( mode ); // 绘制回采箭头 drawArrow( mode, m_clockWise ); return Adesk::kTrue; } Acad::ErrorStatus PolyLineWorkSurfaceDraw::subGetGripPoints( AcGePoint3dArray& gripPoints, AcDbIntArray& osnapModes, AcDbIntArray& geomIds ) const { assertReadEnabled () ; gripPoints.append( m_startPt ); if( m_startPt == m_endPt ) { AcGePoint3d pt( m_startPt ); pt.x = pt.x + m_width * 0.3; gripPoints.append( pt ); } else { gripPoints.append( m_endPt ); double angle = ( m_clockWise ? ( -PI / 2 ) : ( PI / 2 ) ); // 主干中心始点坐标 AcGePoint3d pt = CaclArrowPoint( m_startPt, m_endPt, m_width / 2, angle ); // 中点 AcGeVector3d v = m_endPt - m_startPt; v.normalize(); // 向量标准化(|v|=1) v.rotateBy( angle, AcGeVector3d::kZAxis ); // 箭头尖端坐标 AcGePoint3d ap = pt + v * ( m_trunkLength + m_arrowLength ); gripPoints.append( ap ); } return Acad::eOk; } Acad::ErrorStatus PolyLineWorkSurfaceDraw::subMoveGripPointsAt ( const AcDbIntArray& indices, const AcGeVector3d& offset ) { assertWriteEnabled () ; for( int i = 0; i < indices.length(); i++ ) { int idx = indices.at( i ); if ( idx == 0 ) { m_startPt += offset; } if ( idx == 1 ) { m_endPt += offset; } if( idx == 2 ) { double angle = ( m_clockWise ? ( -PI / 2 ) : ( PI / 2 ) ); AcGeVector3d v = m_endPt - m_startPt; v.normalize(); v.rotateBy( angle, AcGeVector3d::kZAxis ); // 计算offset在a1方向上的投影长度 double L = offset.dotProduct( v ); if( L < 0 && abs( L ) > ( m_trunkLength + m_arrowLength ) ) m_clockWise = !m_clockWise; } } return Acad::eOk; }
[ "anheihb03dlj@163.com" ]
anheihb03dlj@163.com
2338f5dce8dfa4a5f233d60e3516582e32a670ab
4ac71ef9f0193770844f04b914b496ba0675d6d8
/Test/test3.cpp
af1a03dd25299ee00e8ab08020bf67542ca8654d
[]
no_license
taronegeorage/AlgorithmTraining
9002d8f7cd6112d63087a60e7b72be4d3e82a2ae
8f179d6e304a9a0be1530cefab2728152ca92a22
refs/heads/master
2021-07-09T17:55:01.408919
2020-07-19T17:04:04
2020-07-19T17:04:04
168,528,260
0
0
null
null
null
null
UTF-8
C++
false
false
791
cpp
// #include <iostream> // int result[100]; // using namespace std; // int main() { // int n, m; // scanf("%d%d", &n, &m); // for(int i = 0; i < m; i++) { // int tmp; // scanf("%d", &tmp); // result[tmp]++; // } // for(int i = 1; i <= n; i++){ // cout << result[n] << " "; // } // int ans = 1000; // printf("%d\n", ans); // return 0; // } #include<iostream> using namespace std; int a[1005]; int main() { int n,m; scanf("%d%d",&n,&m); int ans=m; while(m--){ int x; scanf("%d",&x); a[x]++; } for(int i = 1; i <= n; i++){ cout << a[n] << " "; } for(int i=1; i<=n; i++) if(ans>a[i]) ans=a[i]; printf("%d\n",ans); return 0; }
[ "1155118584@link.cuhk.edu.hk" ]
1155118584@link.cuhk.edu.hk
8c97864a82cf508894934b8487d0e73af0569123
c0ddcb1e288878cbc81ba002cb9fc0d37be1e7c5
/dataBaseWindow/ImprovedLineEdit.cpp
c520af61fcc95e3af58d3cd15ed7eb45766578ad
[]
no_license
aovelacq/DeliveryChecker
94eef786a8e08e38f6bd3c56f6a601146e927b37
03cb6e0aaf2146ef47772a8eb6af322f41d327b0
refs/heads/master
2022-09-16T09:57:38.721419
2020-05-31T14:45:23
2020-05-31T14:45:23
257,295,042
0
0
null
null
null
null
UTF-8
C++
false
false
344
cpp
#include "ImprovedLineEdit.h" ImprovedLineEdit::ImprovedLineEdit(QWidget *parent) : QLineEdit(parent) { } void ImprovedLineEdit::focusInEvent(QFocusEvent *e) { QLineEdit::focusInEvent(e); emit(focussed(true)); } void ImprovedLineEdit::focusOutEvent(QFocusEvent *e) { QLineEdit::focusOutEvent(e); emit(focussed(false)); }
[ "jobled@velecsystems.com" ]
jobled@velecsystems.com
e34e1ae452950afe7d42f098153ee1fb0ce2df99
d4bfae1b7aba456a355487e98c50dfd415ccb9ba
/chrome/test/base/mash_browser_tests_main.cc
47d736f6cd126e3dde93a005041b3c920e2d6067
[ "BSD-3-Clause" ]
permissive
mindaptiv/chromium
d123e4e215ef4c82518a6d08a9c4211433ae3715
a93319b2237f37862989129eeecf87304ab4ff0c
refs/heads/master
2023-05-19T22:48:12.614549
2016-08-23T02:56:57
2016-08-23T02:56:57
66,865,429
1
1
null
2016-08-29T17:35:46
2016-08-29T17:35:45
null
UTF-8
C++
false
false
6,007
cc
// 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. #include <algorithm> #include "base/at_exit.h" #include "base/command_line.h" #include "base/debug/debugger.h" #include "base/memory/ptr_util.h" #include "base/process/launch.h" #include "base/sys_info.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/test/base/chrome_test_launcher.h" #include "chrome/test/base/chrome_test_suite.h" #include "chrome/test/base/mojo_test_connector.h" #include "content/public/common/mojo_shell_connection.h" #include "content/public/test/test_launcher.h" #include "services/shell/public/cpp/connector.h" #include "services/shell/public/cpp/service.h" #include "services/shell/public/cpp/service_context.h" #include "services/shell/runner/common/switches.h" #include "services/shell/runner/host/child_process.h" #include "services/shell/runner/init.h" namespace { void ConnectToDefaultApps(shell::Connector* connector) { connector->Connect("mojo:mash_session"); } class MashTestSuite : public ChromeTestSuite { public: MashTestSuite(int argc, char** argv) : ChromeTestSuite(argc, argv) {} void SetMojoTestConnector(std::unique_ptr<MojoTestConnector> connector) { mojo_test_connector_ = std::move(connector); } MojoTestConnector* mojo_test_connector() { return mojo_test_connector_.get(); } private: // ChromeTestSuite: void Shutdown() override { mojo_test_connector_.reset(); ChromeTestSuite::Shutdown(); } std::unique_ptr<MojoTestConnector> mojo_test_connector_; DISALLOW_COPY_AND_ASSIGN(MashTestSuite); }; // Used to setup the command line for passing a mojo channel to tests. class MashTestLauncherDelegate : public ChromeTestLauncherDelegate { public: MashTestLauncherDelegate() : ChromeTestLauncherDelegate(nullptr) {} ~MashTestLauncherDelegate() override {} MojoTestConnector* GetMojoTestConnectorForSingleProcess() { // This is only called for single process tests, in which case we need // the TestSuite to own the MojoTestConnector. DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch( content::kSingleProcessTestsFlag)); DCHECK(test_suite_); test_suite_->SetMojoTestConnector(base::WrapUnique(new MojoTestConnector)); return test_suite_->mojo_test_connector(); } private: // ChromeTestLauncherDelegate: int RunTestSuite(int argc, char** argv) override { test_suite_.reset(new MashTestSuite(argc, argv)); const int result = test_suite_->Run(); test_suite_.reset(); return result; } std::unique_ptr<content::TestState> PreRunTest( base::CommandLine* command_line, base::TestLauncher::LaunchOptions* test_launch_options) override { if (!mojo_test_connector_) { mojo_test_connector_.reset(new MojoTestConnector); service_.reset(new shell::Service); shell_connection_.reset(new shell::ServiceContext( service_.get(), mojo_test_connector_->Init())); ConnectToDefaultApps(shell_connection_->connector()); } return mojo_test_connector_->PrepareForTest(command_line, test_launch_options); } void OnDoneRunningTests() override { // We have to shutdown this state here, while an AtExitManager is still // valid. shell_connection_.reset(); service_.reset(); mojo_test_connector_.reset(); } std::unique_ptr<MashTestSuite> test_suite_; std::unique_ptr<MojoTestConnector> mojo_test_connector_; std::unique_ptr<shell::Service> service_; std::unique_ptr<shell::ServiceContext> shell_connection_; DISALLOW_COPY_AND_ASSIGN(MashTestLauncherDelegate); }; std::unique_ptr<content::MojoShellConnection> CreateMojoShellConnection( MashTestLauncherDelegate* delegate) { std::unique_ptr<content::MojoShellConnection> connection( content::MojoShellConnection::Create( delegate->GetMojoTestConnectorForSingleProcess()->Init(), base::ThreadTaskRunnerHandle::Get())); connection->Start(); ConnectToDefaultApps(connection->GetConnector()); return connection; } } // namespace bool RunMashBrowserTests(int argc, char** argv, int* exit_code) { base::CommandLine::Init(argc, argv); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); if (!command_line.HasSwitch("run-in-mash")) return false; if (command_line.HasSwitch(switches::kChildProcess) && !command_line.HasSwitch(MojoTestConnector::kTestSwitch)) { base::AtExitManager at_exit; shell::InitializeLogging(); // TODO(sky): nuke once resolve why test isn't shutting down: 594600. LOG(ERROR) << "starting app " << command_line.GetCommandLineString(); shell::WaitForDebuggerIfNecessary(); #if !defined(OFFICIAL_BUILD) && defined(OS_WIN) base::RouteStdioToConsole(false); #endif *exit_code = shell::ChildProcessMain(); // TODO(sky): nuke once resolve why test isn't shutting down: 594600. LOG(ERROR) << "child exit_code=" << *exit_code; return true; } int default_jobs = std::max(1, base::SysInfo::NumberOfProcessors() / 2); MashTestLauncherDelegate delegate; // --single_process and no primoridal pipe token indicate we were run directly // from the command line. In this case we have to start up MojoShellConnection // as though we were embedded. content::MojoShellConnection::Factory shell_connection_factory; if (command_line.HasSwitch(content::kSingleProcessTestsFlag) && !command_line.HasSwitch(switches::kPrimordialPipeToken)) { shell_connection_factory = base::Bind(&CreateMojoShellConnection, &delegate); content::MojoShellConnection::SetFactoryForTest(&shell_connection_factory); } *exit_code = LaunchChromeTests(default_jobs, &delegate, argc, argv); // TODO(sky): nuke once resolve why test isn't shutting down: 594600. LOG(ERROR) << "RunMashBrowserTests exit_code=" << *exit_code; return true; }
[ "serg.zhukovsky@gmail.com" ]
serg.zhukovsky@gmail.com
a1951601705944346b9ef8caba06843579481471
3d051b4e7532811456198a58a39c403252d10595
/virtual-1/E.cpp
bf52970ffb64d21888ae3f3a3a27190a60eb8623
[]
no_license
ItsLucas/acm
3c1aeee36a96ec33965e7c321bdc76d2c4d0e09f
3659bc82862124146f760923167a15ae1507ed80
refs/heads/master
2021-07-22T11:20:52.094674
2020-07-21T02:56:40
2020-07-21T02:56:40
198,808,058
0
0
null
null
null
null
UTF-8
C++
false
false
1,083
cpp
#include <bits/stdc++.h> using namespace std; const int N = 200005, M = 200005; struct dat { int l, r, ans, id; } q[M]; struct node { int t, dur; }; node a[N], b[N]; int n, m, siz, tot, blk[N], res, L, R, cnt[N]; inline bool cmp1(dat a, dat b) { return blk[a.l] < blk[b.l] || (blk[a.l] == blk[b.l] && (blk[a.l] & 1 ? a.r < b.r : a.r > b.r)); } inline bool cmp2(dat a, dat b) { return a.id < b.id; } inline int find(int x) { int l = 1, r = tot, mid; while (l <= r) { mid = l + r >> 1; if (b[mid].dur == x) return mid; if (b[mid].dur < x) l = mid + 1; else r = mid - 1; } } inline void add(int col) { if (++cnt[col] == 1) ++res; } inline void del(int col) { if (--cnt[col] == 0) --res; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n, t; cin >> n >> t; siz = sqrt(n); for (int i = 1; i <= n; i++) { cin >> a[i].t >> a[i].dur; b[i] = a[i]; blk[i] = (i - 1) / siz + 1; } }
[ "itslucas@itslucas.me" ]
itslucas@itslucas.me
74ab9ee33dc1f2a226580bec6d7ff1f374507858
615bd336a8026dc73c7b48f885dbae32f3799ec9
/codeforces/1316/B.cpp
eef0826e8d99dd203e38e69ee5ca19523fb6ff26
[]
no_license
yash-gupta2000/CP_Codeforces
82c842a8775229a1ab6da027f8b2471bbfc849f9
c22b8ebe57f705c239a075def7a479192213c266
refs/heads/master
2023-02-09T02:04:42.817749
2018-12-14T05:50:00
2020-12-21T07:49:38
323,261,076
0
0
null
null
null
null
UTF-8
C++
false
false
705
cpp
#include <bits/stdc++.h> using namespace std; string modified(string& s, int n, int k) { string result_prefix = s.substr(k - 1, n - k + 1); string result_suffix = s.substr(0, k - 1); if (n % 2 == k % 2) reverse(result_suffix.begin(), result_suffix.end()); return result_prefix + result_suffix; } int main () { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); string s, best_s, temp; int t, n, best_k; cin >> t; while (t--) { cin >> n >> s; best_s = modified(s, n, 1); best_k = 1; for (int k = 2; k <= n; ++k) { temp = modified(s, n, k); if (temp < best_s) { best_s = temp; best_k = k; } } cout << best_s << '\n' << best_k << '\n'; } return 0; }
[ "y25.gupta@gmail.com" ]
y25.gupta@gmail.com
96992b92fc7c5b583d5146074f770845617c1fa6
46b922e408654398fc69b6f5399c0d71579cb468
/Src/FM79979Engine/MagicTower/MagicTower/StageData.cpp
0a1f0e0bf8604b2bc996832e140ec900bd3d070d
[]
no_license
radtek/FM79979
514355d91e0f3d2a73371f6b264b2e77335ed841
96f32530070d27e96b8a5d7159e5a216a33e91a2
refs/heads/master
2023-03-27T19:02:49.263164
2021-03-29T09:38:46
2021-03-29T09:38:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,257
cpp
#include "stdafx.h" #include "StageData.h" cGameData::cGameData() { m_ViewableSize.x = m_MainRoleFocusGridIndex.x = 5; m_ViewableSize.y = m_MainRoleFocusGridIndex.y = 5; } cGameData::~cGameData() { } //all image we need to load void cGameData::ProcessLevelData() { const WCHAR*l_strFileName = this->m_pCurrentTiXmlElement->Attribute(L"FileName"); if(!m_LevelData.ParseWithMyParse( UT::WcharToChar(l_strFileName).c_str() )) { UT::ErrorMsg(l_strFileName,L"parse failed"); } } void cGameData::ProcessViewableSizeData() { PARSE_CURRENT_ELEMENT_START COMPARE_NAME("Row") { m_ViewableSize.x = VALUE_TO_INT; } else COMPARE_NAME("Column") { m_ViewableSize.y = VALUE_TO_INT; } else COMPARE_NAME("MainRoleFocusGridIndex") { m_MainRoleFocusGridIndex = VALUE_TO_POINT; } PARSE_NAME_VALUE_END } // //<Data> // <ImageSetupFile FileName=""/> // <MapDataFile FileName="" TMPFile="" /> // <UserData FileName="" /> //</Data> void cGameData::HandleElementData(TiXmlElement*e_pTiXmlElement) { const WCHAR*l_strValue = e_pTiXmlElement->Value(); if(e_pTiXmlElement->m_bDone) return; if(!wcscmp(l_strValue,L"LevelData")) { ProcessLevelData(); } if(!wcscmp(l_strValue,L"ViewableUnits")) { ProcessViewableSizeData(); } }
[ "osimejp@yahoo.co.jp" ]
osimejp@yahoo.co.jp
12c186819de88ef03bc2c2c2cef075eec875bc5c
e4ed8a7508815b79425d9bbbd822c7c096490fe6
/Song.h
9f7020fcc6c35d80541a5a356c83f45ade5695e1
[]
no_license
mehahalabe/UTPod
f9b943ba9c6854c79b08dedd473c6ffba3c9ef1c
829bb7e6fa3b8df6c624151e8f4829f7d72fa9d1
refs/heads/master
2020-09-01T20:43:57.335552
2019-11-01T19:45:36
2019-11-01T19:45:36
219,052,011
0
0
null
null
null
null
UTF-8
C++
false
false
593
h
// // Created by mehah on 10/27/2019. // #ifndef UTPOD_SONG_H #define UTPOD_SONG_H #include <string> using namespace std; class Song { private: string title, artist; int size; public: Song(); Song(string art,string titl, int siz); string getTitle(){ return title; } string getArtist(){ return artist; } int getSize() { return size; } bool operator >(Song const &rhs); bool operator <(Song const &rhs); bool operator ==(Song const &rhs); }; #endif //UTPOD_SONG_H
[ "noreply@github.com" ]
noreply@github.com
b4485e6511e97cb20b8ce2de957b2afcaa549d9e
bae99a8af02919cd53e890255373e9e0e913bb09
/Print.cpp
0975df157f6466cfb9d57b009984e223f6e7cce7
[]
no_license
kevinmehall/Printer
07b87cd1f53a188147b2bada5fbcba55998a08d1
d6c33af394c87100027e247de684413c3e3dc1b7
refs/heads/master
2021-01-23T12:25:47.317148
2012-11-25T23:01:09
2012-11-25T23:01:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,023
cpp
/* Print.cpp - Base class that provides print() and println() Copyright (c) 2008 David A. Mellis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis */ #include <stdio.h> #include <string.h> #include <math.h> #include "wiring_minimal.h" #include "Print.h" // Public Methods ////////////////////////////////////////////////////////////// /* default implementation: may be overridden */ void Print::write(const char *str) { while (*str) write(*str++); } /* default implementation: may be overridden */ void Print::write(const uint8_t *buffer, size_t size) { while (size--) write(*buffer++); } void Print::print(const char str[]) { write(str); } void Print::print(char c, int base) { print((long) c, base); } void Print::print(unsigned char b, int base) { print((unsigned long) b, base); } void Print::print(int n, int base) { print((long) n, base); } void Print::print(unsigned int n, int base) { print((unsigned long) n, base); } void Print::print(long n, int base) { if (base == 0) { write(n); } else if (base == 10) { if (n < 0) { print('-'); n = -n; } printNumber(n, 10); } else { printNumber(n, base); } } void Print::print(unsigned long n, int base) { if (base == 0) write(n); else printNumber(n, base); } void Print::print(double n, int digits) { printFloat(n, digits); } void Print::println(void) { print('\r'); print('\n'); } void Print::println(const char c[]) { print(c); println(); } void Print::println(char c, int base) { print(c, base); println(); } void Print::println(unsigned char b, int base) { print(b, base); println(); } void Print::println(int n, int base) { print(n, base); println(); } void Print::println(unsigned int n, int base) { print(n, base); println(); } void Print::println(long n, int base) { print(n, base); println(); } void Print::println(unsigned long n, int base) { print(n, base); println(); } void Print::println(double n, int digits) { print(n, digits); println(); } // Private Methods ///////////////////////////////////////////////////////////// void Print::printNumber(unsigned long n, uint8_t base) { unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars. unsigned long i = 0; if (n == 0) { print('0'); return; } while (n > 0) { buf[i++] = n % base; n /= base; } for (; i > 0; i--) print((char) (buf[i - 1] < 10 ? '0' + buf[i - 1] : 'A' + buf[i - 1] - 10)); } void Print::printFloat(double number, uint8_t digits) { // Handle negative numbers if (number < 0.0) { print('-'); number = -number; } // Round correctly so that print(1.999, 2) prints as "2.00" double rounding = 0.5; for (uint8_t i=0; i<digits; ++i) rounding /= 10.0; number += rounding; // Extract the integer part of the number and print it unsigned long int_part = (unsigned long)number; double remainder = number - (double)int_part; print(int_part); // Print the decimal point, but only if there are digits beyond if (digits > 0) print("."); // Extract digits from the remainder one at a time while (digits-- > 0) { remainder *= 10.0; int toPrint = int(remainder); print(toPrint); remainder -= toPrint; } }
[ "km@kevinmehall.net" ]
km@kevinmehall.net
fb96f7c3c626150bbab5d901a01c845da7406ad9
438adbdb52b3f65f9adca6d14a87d9a4a85d3e84
/TransportationMode/QueryTM.cpp
c20b766ae99029810445c428375b93d7e416ea30
[]
no_license
hhrny/CDistRange
ad593107c23cce72247e549b1edc84ad001d06ff
578724eb0a7e6c938b1aa589e21ff27ad8a0fef6
refs/heads/master
2020-12-24T09:22:44.688081
2017-04-29T06:41:12
2017-04-29T06:41:12
73,297,395
1
1
null
null
null
null
UTF-8
C++
false
false
127,839
cpp
/* ---- This file is part of SECONDO. Copyright (C) 2004, University in Hagen, Department of Computer Science, Database Systems for New Applications. SECONDO 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. SECONDO 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 SECONDO; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ---- //paragraph [1] Title: [{\Large \bf \begin {center}] [\end {center}}] //[TOC] [\tableofcontents] [1] Header File of the Transportation Mode Algebra March, 2011 Jianqiu xu [TOC] 1 Overview 2 Defines and includes */ #include "BusNetwork.h" #include "QueryTM.h" #include <bitset> /* convert a genrange object to a 2D line in space or 3D line in a building */ void QueryTM::GetLineOrLine3D(GenRange* gr, Space* sp) { BusNetwork* bn = sp->LoadBusNetwork(IF_BUSNETWORK); for(int i = 0;i < gr->Size();i++){ Line l(0); GenRangeElem grelem; gr->Get( i, grelem, l); int infra_type = sp->GetInfraType(grelem.oid); switch(infra_type){ case IF_LINE: // cout<<"road network "<<endl; GetLineInRoad(grelem.oid, &l, sp); break; case IF_REGION: // cout<<"region based outdoor"<<endl; GetLineInRegion(grelem.oid, &l, sp); break; case IF_FREESPACE: // cout<<"free space"<<endl; GetLineInFreeSpace(&l); break; case IF_BUSNETWORK: // cout<<"bus network"<<endl; GetLineInBusNetwork(grelem.oid, &l, bn); break; case IF_GROOM: // cout<<"indoor "<<endl; GetLineInGRoom(grelem.oid, &l, sp); break; default: assert(false); break; } } sp->CloseBusNetwork(bn); } /* get the overall line in road network */ void QueryTM::GetLineInRoad(int oid, Line* l, Space* sp) { Network* rn = sp->LoadRoadNetwork(IF_LINE); Tuple* route_tuple = rn->GetRoute(oid); SimpleLine* sl = (SimpleLine*)route_tuple->GetAttribute(ROUTE_CURVE); Rectangle<2> bbox = sl->BoundingBox(); route_tuple->DeleteIfAllowed(); sp->CloseRoadNetwork(rn); Line* newl = new Line(0); newl->StartBulkLoad(); int edgeno = 0; for(int i = 0;i < l->Size();i++){ HalfSegment hs1; l->Get(i, hs1); if(!hs1.IsLeftDomPoint())continue; Point lp = hs1.GetLeftPoint(); Point rp = hs1.GetRightPoint(); Point newlp(true, lp.GetX() + bbox.MinD(0), lp.GetY() + bbox.MinD(1)); Point newrp(true, rp.GetX() + bbox.MinD(0), rp.GetY() + bbox.MinD(1)); HalfSegment hs2(true, newlp, newrp); hs2.attr.edgeno = edgeno++; *newl += hs2; hs2.SetLeftDomPoint(!hs2.IsLeftDomPoint()); *newl += hs2; } newl->EndBulkLoad(); line_list1.push_back(*newl); delete newl; /* Line3D* l3d = new Line3D(0); line3d_list.push_back(*l3d); delete l3d;*/ } /* get the overall line in region based outdoor */ void QueryTM::GetLineInRegion(int oid, Line* l, Space* sp) { Pavement* pm = sp->LoadPavement(IF_REGION); DualGraph* dg = pm->GetDualGraph(); Rectangle<2> bbox = dg->rtree_node->BoundingBox(); pm->CloseDualGraph(dg); sp->ClosePavement(pm); Line* newl = new Line(0); newl->StartBulkLoad(); int edgeno = 0; for(int i = 0;i < l->Size();i++){ HalfSegment hs1; l->Get(i, hs1); if(!hs1.IsLeftDomPoint())continue; Point lp = hs1.GetLeftPoint(); Point rp = hs1.GetRightPoint(); Point newlp(true, lp.GetX() + bbox.MinD(0), lp.GetY() + bbox.MinD(1)); Point newrp(true, rp.GetX() + bbox.MinD(0), rp.GetY() + bbox.MinD(1)); HalfSegment hs2(true, newlp, newrp); hs2.attr.edgeno = edgeno++; *newl += hs2; hs2.SetLeftDomPoint(!hs2.IsLeftDomPoint()); *newl += hs2; } newl->EndBulkLoad(); line_list1.push_back(*newl); delete newl; // Line3D* l3d = new Line3D(0); // line3d_list.push_back(*l3d); // delete l3d; } /* get the overall line in free space */ void QueryTM::GetLineInFreeSpace(Line* l) { line_list1.push_back(*l); // Line3D* l3d = new Line3D(0); // line3d_list.push_back(*l3d); // delete l3d; } /* get the overall line in bus network. oid corresponds to a bus route */ void QueryTM::GetLineInBusNetwork(int oid, Line* l, BusNetwork* bn) { SimpleLine br_sl(0); bn->GetBusRouteGeoData(oid, br_sl); Rectangle<2> bbox = br_sl.BoundingBox(); Line* newl = new Line(0); newl->StartBulkLoad(); int edgeno = 0; for(int i = 0;i < l->Size();i++){ HalfSegment hs1; l->Get(i, hs1); if(!hs1.IsLeftDomPoint())continue; Point lp = hs1.GetLeftPoint(); Point rp = hs1.GetRightPoint(); Point newlp(true, lp.GetX() + bbox.MinD(0), lp.GetY() + bbox.MinD(1)); Point newrp(true, rp.GetX() + bbox.MinD(0), rp.GetY() + bbox.MinD(1)); HalfSegment hs2(true, newlp, newrp); hs2.attr.edgeno = edgeno++; *newl += hs2; hs2.SetLeftDomPoint(!hs2.IsLeftDomPoint()); *newl += hs2; } newl->EndBulkLoad(); line_list1.push_back(*newl); delete newl; /* Line3D* l3d = new Line3D(0); line3d_list.push_back(*l3d); delete l3d;*/ } /* get the overall line for indoor environment (line3D) */ void QueryTM::GetLineInGRoom(int oid, Line* l, Space* sp) { // cout<<"indoor not implemented"<<endl; } ///////////////////////////////////////////////////////////////////////// //////////////////// range query for generic moving objects///////////// //////////////////////////////////////////////////////////////////////// string QueryTM::GenmoRelInfo = "(rel (tuple ((Oid int) (Trip1 genmo) \ (Trip2 mpoint))))"; string QueryTM::GenmoUnitsInfo = "(rel (tuple ((Traj_id int) (MT_box rect3)\ (Mode int) (SubTrip mpoint) (DivPos int) (Id int))))"; string QueryTM::GenmoRangeQuery = "(rel (tuple ((T periods) (BOX rect)\ (Mode string))))"; /* decompose the units of genmo 0: single mode in a movement tuple 1: combine walk + m in a movement tuple plus single mode in a movement tuple */ void QueryTM::DecomposeGenmo(Relation* genmo_rel, double len) { ///indoor: group all units inside one building // // walk: a walking segment // // car, taxi, bicycle: a road segment /// // bus: a bus route segment //// // metro: // free space: a unit // cout<<"oid maxsize "<<oid_list.max_size()<<endl // <<"Periods maxsize "<<time_list.max_size()<<endl // <<"Bos maxsize "<<box_list.max_size()<<endl; /// oid maxsize 1,07374,1823 //// Periods maxsize 8947,8485 /// Bos maxsize 1,0737,4182 for(int i = 1;i <= genmo_rel->GetNoTuples();i++){ Tuple* tuple = genmo_rel->GetTuple(i, false); int oid = ((CcInt*)tuple->GetAttribute(GENMO_OID))->GetIntval(); GenMO* mo1 = (GenMO*)tuple->GetAttribute(GENMO_TRIP1); MPoint* mo2 = (MPoint*)tuple->GetAttribute(GENMO_TRIP2); // CreateMTuple_0(oid, mo1, mo2, len); // cout<<"oid "<<oid<<endl; // if(oid != 1234) { // tuple->DeleteIfAllowed(); // continue; // } if(mt_type) CreateMTuple_1(oid, mo1, mo2, len);//single mode + a pair of modes else CreateMTuple_0(oid, mo1, mo2, len);//only single mode tuple->DeleteIfAllowed(); // break; } // cout<<oid_list.size()<<" "<<box_list.size() // <<" "<<tm_list.size()<<" "<<mp_list.size()<<endl; } /* create movement tuples: single mode original method us atperiods to find mpoint, 5500 genmo need 60sec new method use unit index (record last access position), 5500 genmo need 20 sec */ void QueryTM::CreateMTuple_0(int oid, GenMO* mo1, MPoint* mo2, double len) { // cout<<"oid "<<oid<<endl; int up_pos = 0; for(int i = 0;i < mo1->GetNoComponents();i++){ UGenLoc unit; mo1->Get(i, unit); int tm = unit.GetTM(); switch(tm){ case TM_BUS: CollectBusMetro(i, oid, TM_BUS, mo1, mo2, up_pos); break; case TM_WALK: CollectWalk_0(i, oid, mo1, mo2, len, up_pos); break; case TM_INDOOR: CollectIndoor(i, oid, TM_INDOOR, mo1, mo2, up_pos); break; case TM_CAR: CollectCBT(i, oid, TM_CAR, mo1, mo2, up_pos, len); break; case TM_BIKE: CollectCBT(i, oid, TM_BIKE, mo1, mo2, up_pos, len); break; case TM_TAXI: CollectCBT(i, oid, TM_TAXI, mo1, mo2, up_pos, len); break; case TM_METRO: CollectBusMetro(i, oid, TM_METRO, mo1, mo2, up_pos); break; case TM_FREE: CollectFree_0(i, oid, TM_FREE, mo1, mo2, up_pos); break; default: assert(false); break; } } } /* extend the method above to be able to process a pair of modes combine walk and another */ void QueryTM::CreateMTuple_1(int oid, GenMO* mo1, MPoint* mo2, double len) { // cout<<"oid "<<oid<<endl; int up_pos = 0; for(int j = 0;j < mo1->GetNoComponents();j++){ UGenLoc unit; mo1->Get(j, unit); int tm = unit.GetTM(); switch(tm){ case TM_BUS: CollectBusMetro(j, oid, TM_BUS, mo1, mo2, up_pos); break; case TM_WALK: CollectWalk_1(j, oid, mo1, mo2, len, up_pos);//two mtuples break; case TM_INDOOR: CollectIndoor(j, oid, TM_INDOOR, mo1, mo2, up_pos); break; case TM_CAR: CollectCBT(j, oid, TM_CAR, mo1, mo2, up_pos, len); break; case TM_BIKE: CollectCBT(j, oid, TM_BIKE, mo1, mo2, up_pos, len); break; case TM_TAXI: CollectCBT(j, oid, TM_TAXI, mo1, mo2, up_pos, len); break; case TM_METRO: CollectBusMetro(j, oid, TM_METRO, mo1, mo2, up_pos); break; case TM_FREE: CollectFree_1(j, oid, TM_FREE, mo1, mo2, up_pos);//two mtuples break; default: assert(false); break; } } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// ///////store not only a single mode but also a pair of modes////////////// // cout<<"oid size "<<oid_list.size()<<endl; // cout<<Oid_list.size()<<" "<<Box_list.size() // <<" "<<Tm_list.size()<<" "<<Mp_list.size()<<endl; ///////////////// output information /////////////////// // for(unsigned int i = 0;i < oid_list.size();i++){ // Periods* peri = new Periods(0); // mp_list[i].DefTime(*peri); // cout<<GetTMStrExt(tm_list[i])<<" "<<*peri<<endl; // delete peri; // } if(oid_list.size() == 1){//////indoor trips, as one movement tuple Oid_list.push_back(oid_list[0]); Tm_list.push_back(tm_list[0]); Box_list.push_back(box_list[0]); Mp_list.push_back(mp_list[0]); div_list.push_back(-1);//one mode }else{ for(unsigned int i = 0;i < oid_list.size() - 1;i++){ int j = i + 1; if(tm_list[i] == tm_list[j]){ Oid_list.push_back(oid_list[i]); Tm_list.push_back(tm_list[i]); Box_list.push_back(box_list[i]); Mp_list.push_back(mp_list[i]); div_list.push_back(-1);//one mode if(i == oid_list.size() - 2){ Oid_list.push_back(oid_list[j]); Tm_list.push_back(tm_list[j]); Box_list.push_back(box_list[j]); Mp_list.push_back(mp_list[j]); div_list.push_back(-1);//one mode } }else{ Rectangle<3> box1 = box_list[i]; Rectangle<3> box2 = box_list[j]; Rectangle<3> box = box1.Union(box2); int m1 = tm_list[i]; int m2 = tm_list[j]; if(m1 == TM_WALK || m2 == TM_WALK){ int m = -1; if(m1 == TM_WALK){ m = m2 + 2*ARR_SIZE(str_tm); }else{ m = m1 + ARR_SIZE(str_tm); } MPoint* mp1 = &mp_list[i]; MPoint* mp2 = &mp_list[j]; MPoint* mp = new MPoint(0); mp->StartBulkLoad(); for(int k = 0;k < mp1->GetNoComponents();k++){ UPoint u; mp1->Get(k, u); mp->Add(u); } for(int k = 0;k < mp2->GetNoComponents();k++){ UPoint u; mp2->Get(k, u); mp->Add(u); } mp->EndBulkLoad(); Oid_list.push_back(oid_list[i]); Tm_list.push_back(m); //bit index Box_list.push_back(box); Mp_list.push_back(*mp); div_list.push_back(mp1->GetNoComponents());//two modes, record pos delete mp; if(i < oid_list.size() - 2){ int next_elem = j + 1; if(tm_list[j] == tm_list[next_elem]){ i++; } } }else{ cout<<"should not be here"<<endl; assert(false); } } } } oid_list.clear(); box_list.clear(); tm_list.clear(); mp_list.clear(); } /* get movement tuples for bus and metro collect a piece of continuous movement (bus or metro), get the units in mp use start and end time instants */ void QueryTM::CollectBusMetro(int& i, int oid, int m, GenMO* mo1, MPoint* mo2, int& up_pos) { // cout<<"CollectBusMetro"<<endl; int j = i; int index1 = i; int64_t start_time = -1; int64_t end_time = -1; while(j < mo1->GetNoComponents()){ UGenLoc unit; mo1->Get(j, unit); if(unit.GetTM() == m){ if(start_time < 0){ start_time = unit.timeInterval.start.ToDouble()*ONEDAY_MSEC; end_time = unit.timeInterval.end.ToDouble()*ONEDAY_MSEC; } j++; }else{ break; } } i = j -1; int index2 = j - 1; ///////////////////get pieces of movement from mpoint/////////////////// int pos1 = -1; int pos2 = -1; vector<MPoint*> mp_pointer_list; int counter = 0; mp_pointer_list.push_back(new MPoint(0)); mp_pointer_list[counter]->StartBulkLoad(); for(int index = up_pos; index < mo2->GetNoComponents();index++){ UPoint u; mo2->Get(index, u); mp_pointer_list[counter]->Add(u); if(start_time < 0) start_time = u.timeInterval.start.ToDouble()*ONEDAY_MSEC; if(pos1 < 0) pos1 = index; if(index == up_pos && u.p0.Distance(u.p1) < EPSDIST){ //waiting at the stop continue; } int64_t cur_t = u.timeInterval.end.ToDouble()*ONEDAY_MSEC; /////////////// at a bus stop or end ///////////////////////// if(u.p0.Distance(u.p1) < EPSDIST || cur_t == end_time){ mp_pointer_list[counter]->EndBulkLoad(); mp_list.push_back(*mp_pointer_list[counter]);//store a subtrip // cout<<oid<<" "<<subtrip_list[subtrip_list.size() - 1]<<endl; // cout<<mp<<endl; // Periods* peri = new Periods(0); // mp.DefTime(*peri); // cout<<*peri<<endl; // delete peri; ///////////////////////////////////////////////// /* Instant st(instanttype); Instant et(instanttype); Periods* peri_t = new Periods(0); peri_t->StartBulkLoad(); Interval<Instant> time_span; st.ReadFrom(start_time/ONEDAY_MSEC); et.ReadFrom(cur_t/ONEDAY_MSEC); time_span.start = st; time_span.lc = true; time_span.end = et; time_span.rc = false; peri_t->MergeAdd(time_span); peri_t->EndBulkLoad();*/ // cout<<*peri<<" "<<*peri_t<<endl; ///////////////////////////////////////////////////// Rectangle<2> box_spatial = mp_pointer_list[counter]->BoundingBoxSpatial(); // cout<<box_spatial.MinD(0)<<" "<<box_spatial.MaxD(0)<<" " // <<box_spatial.MinD(1)<<" "<<box_spatial.MaxD(1)<<endl; double min[2], max[2]; min[0] = box_spatial.MinD(0); min[1] = box_spatial.MinD(1); max[0] = box_spatial.MaxD(0); max[1] = box_spatial.MaxD(1); if(fabs(box_spatial.MinD(0) - box_spatial.MaxD(0)) < EPSDIST){ min[0] -= TEN_METER; max[0] += TEN_METER; } if(fabs(box_spatial.MinD(1) - box_spatial.MaxD(1)) < EPSDIST){ min[1] -= TEN_METER; max[1] += TEN_METER; } box_spatial.Set(true, min, max); oid_list.push_back(oid); // time_list.push_back(*peri); // time_list.push_back(*peri_t); // box_list.push_back(box_spatial); Rectangle<3> tm_box(true, start_time/ONEDAY_MSEC, end_time/ONEDAY_MSEC, min[0], max[0], min[1], max[1] ); box_list.push_back(tm_box); tm_list.push_back(m); Point p1(true, index1, index2); pos2 = index; assert(pos1 >= 0 && pos2 >= pos1); Point p2(true, pos1, pos2);//index in mpoint // index_list1.push_back(p1); //genmo index // index_list2.push_back(p2); //mpoint index // index_list.push_back(p2); // delete peri; // delete peri_t; //////////////////////////////////////////// counter++; mp_pointer_list.push_back(new MPoint(0)); mp_pointer_list[counter]->StartBulkLoad(); ////////////////////////////////////////////// start_time = -1; pos1 = -1; } if(cur_t == end_time) { up_pos = index + 1; break; } } /////////reallocate memory///////////////////// for(int i = 0;i <= counter;i++) delete mp_pointer_list[i]; } /* collect all walking units collect a complete part of walking movement and use the time period to find the units in mp use start and end time instants */ void QueryTM::CollectWalk_0(int& i, int oid, GenMO* mo1, MPoint* mo2, double len, int& up_pos) { // cout<<"CollectWalk"<<endl; int index1 = i; int j = i; double l = 0.0; int64_t start_time = -1; int64_t end_time = -1; while(j < mo1->GetNoComponents()){ UGenLoc unit; mo1->Get(j, unit); if(unit.GetTM() == TM_WALK){ if(start_time < 0) start_time = unit.timeInterval.start.ToDouble()*ONEDAY_MSEC; end_time = unit.timeInterval.end.ToDouble()*ONEDAY_MSEC; Point p1(true, unit.gloc1.GetLoc().loc1, unit.gloc1.GetLoc().loc2); Point p2(true, unit.gloc2.GetLoc().loc1, unit.gloc2.GetLoc().loc2); l += p1.Distance(p2); if(l > len){ MPoint* mp = new MPoint(0); mp->StartBulkLoad(); int pos1 = up_pos; int pos2 = -1; for(int index = up_pos; index < mo2->GetNoComponents();index++){ UPoint u; mo2->Get(index, u); mp->Add(u); int64_t cur_t = u.timeInterval.end.ToDouble()*ONEDAY_MSEC; if(cur_t == end_time){ up_pos = index + 1; pos2 = index; break; } } mp->EndBulkLoad(); mp_list.push_back(*mp); // Periods* peri = new Periods(0); // mp->DefTime(*peri); // delete peri; /////////////////////////////////////////////////////// // Instant st(instanttype); // Instant et(instanttype); // // Periods* peri_t = new Periods(0); // peri_t->StartBulkLoad(); // Interval<Instant> time_span; // st.ReadFrom(start_time/ONEDAY_MSEC); // et.ReadFrom(end_time/ONEDAY_MSEC); // // time_span.start = st; // time_span.lc = true; // time_span.end = et; // time_span.rc = false; // // peri_t->MergeAdd(time_span); // peri_t->EndBulkLoad(); // cout<<*peri<<" "<<*peri_t<<endl; ///////////////////////////////////////////////////////// oid_list.push_back(oid); // time_list.push_back(*peri); /* time_list.push_back(*peri_t); box_list.push_back(mp->BoundingBoxSpatial());*/ Rectangle<3> tm_box(true, start_time/ONEDAY_MSEC, end_time/ONEDAY_MSEC, mp->BoundingBoxSpatial().MinD(0), mp->BoundingBoxSpatial().MaxD(0), mp->BoundingBoxSpatial().MinD(1), mp->BoundingBoxSpatial().MaxD(1) ); box_list.push_back(tm_box); tm_list.push_back(TM_WALK); Point p1(true, index1, j); assert(pos1 >= 0 && pos2 >= pos1); Point p2(true, pos1, pos2);//index in mpoint // index_list1.push_back(p1); //genmo index // index_list2.push_back(p2); //mpoint index index1 = j; // delete peri; delete mp; // delete peri_t; start_time = -1; end_time = -1; l = 0.0; } j++; }else{ break; } } int index2 = j - 1; if(start_time > 0 && start_time < end_time){ MPoint* mp = new MPoint(0); mp->StartBulkLoad(); int pos1 = up_pos; int pos2 = -1; for(int index = up_pos;index < mo2->GetNoComponents();index++){ UPoint u; mo2->Get(index, u); mp->Add(u); if(index == up_pos) start_time = u.timeInterval.start.ToDouble()*ONEDAY_MSEC; int64_t cur_t = u.timeInterval.end.ToDouble()*ONEDAY_MSEC; if(cur_t == end_time){ up_pos = index + 1; pos2 = index; break; } } mp->EndBulkLoad(); mp_list.push_back(*mp);//store a sub trip // Periods* peri = new Periods(0); // mp->DefTime(*peri); // delete peri; ///////////////////////////////////////////////////// // Instant st(instanttype); // Instant et(instanttype); // // Periods* peri_t = new Periods(0); // peri_t->StartBulkLoad(); // Interval<Instant> time_span; // st.ReadFrom(start_time/ONEDAY_MSEC); // et.ReadFrom(end_time/ONEDAY_MSEC); // // time_span.start = st; // time_span.lc = true; // time_span.end = et; // time_span.rc = false; // // peri_t->MergeAdd(time_span); // peri_t->EndBulkLoad(); // cout<<*peri<<" "<<*peri_t<<endl; ///////////////////////////////////////////////////// oid_list.push_back(oid); // time_list.push_back(*peri); /* time_list.push_back(*peri_t); box_list.push_back(mp->BoundingBoxSpatial());*/ Rectangle<3> tm_box(true, start_time/ONEDAY_MSEC, end_time/ONEDAY_MSEC, mp->BoundingBoxSpatial().MinD(0), mp->BoundingBoxSpatial().MaxD(0), mp->BoundingBoxSpatial().MinD(1), mp->BoundingBoxSpatial().MaxD(1) ); box_list.push_back(tm_box); tm_list.push_back(TM_WALK); Point p1(true, index1, index2); assert(pos1 >=0 && pos2 >= pos1); Point p2(true, pos1, pos2);//index in mpoint // index_list1.push_back(p1); //genmo index // index_list2.push_back(p2); //mpoint index // delete peri; delete mp; // delete peri_t; } /////////////////////////////////////////////////////////////////// i = j - 1; } /* almost the same as collectwalk 0, but be sure that there are at least two mtules */ void QueryTM::CollectWalk_1(int& i, int oid, GenMO* mo1, MPoint* mo2, double len, int& up_pos) { // cout<<"CollectWalk"<<endl; int mtuple = 0; int index1 = i; int j = i; double l = 0.0; int64_t start_time = -1; int64_t end_time = -1; while(j < mo1->GetNoComponents()){ UGenLoc unit; mo1->Get(j, unit); if(unit.GetTM() == TM_WALK){ if(start_time < 0) start_time = unit.timeInterval.start.ToDouble()*ONEDAY_MSEC; end_time = unit.timeInterval.end.ToDouble()*ONEDAY_MSEC; Point p1(true, unit.gloc1.GetLoc().loc1, unit.gloc1.GetLoc().loc2); Point p2(true, unit.gloc2.GetLoc().loc1, unit.gloc2.GetLoc().loc2); l += p1.Distance(p2); if(l > len){ MPoint* mp = new MPoint(0); mp->StartBulkLoad(); int pos1 = up_pos; int pos2 = -1; for(int index = up_pos; index < mo2->GetNoComponents();index++){ UPoint u; mo2->Get(index, u); mp->Add(u); int64_t cur_t = u.timeInterval.end.ToDouble()*ONEDAY_MSEC; if(cur_t == end_time){ up_pos = index + 1; pos2 = index; break; } } mp->EndBulkLoad(); mp_list.push_back(*mp); ///////////////////////////////////////////////////////// oid_list.push_back(oid); // time_list.push_back(*peri); /* time_list.push_back(*peri_t); box_list.push_back(mp->BoundingBoxSpatial());*/ Rectangle<3> tm_box(true, start_time/ONEDAY_MSEC, end_time/ONEDAY_MSEC, mp->BoundingBoxSpatial().MinD(0), mp->BoundingBoxSpatial().MaxD(0), mp->BoundingBoxSpatial().MinD(1), mp->BoundingBoxSpatial().MaxD(1) ); box_list.push_back(tm_box); tm_list.push_back(TM_WALK); mtuple++; Point p1(true, index1, j); assert(pos1 >= 0 && pos2 >= pos1); Point p2(true, pos1, pos2);//index in mpoint // index_list1.push_back(p1); //genmo index // index_list2.push_back(p2); //mpoint index index1 = j; // delete peri; delete mp; // delete peri_t; start_time = -1; end_time = -1; l = 0.0; } j++; }else{ break; } } int index2 = j - 1; if(start_time > 0 && start_time < end_time){ MPoint* mp = new MPoint(0); mp->StartBulkLoad(); int pos1 = up_pos; int pos2 = -1; for(int index = up_pos;index < mo2->GetNoComponents();index++){ UPoint u; mo2->Get(index, u); mp->Add(u); if(index == up_pos) start_time = u.timeInterval.start.ToDouble()*ONEDAY_MSEC; int64_t cur_t = u.timeInterval.end.ToDouble()*ONEDAY_MSEC; if(cur_t == end_time){ up_pos = index + 1; pos2 = index; break; } } mp->EndBulkLoad(); mp_list.push_back(*mp);//store a sub trip ///////////////////////////////////////////////////// oid_list.push_back(oid); mtuple++; // time_list.push_back(*peri); /* time_list.push_back(*peri_t); box_list.push_back(mp->BoundingBoxSpatial());*/ Rectangle<3> tm_box(true, start_time/ONEDAY_MSEC, end_time/ONEDAY_MSEC, mp->BoundingBoxSpatial().MinD(0), mp->BoundingBoxSpatial().MaxD(0), mp->BoundingBoxSpatial().MinD(1), mp->BoundingBoxSpatial().MaxD(1) ); box_list.push_back(tm_box); tm_list.push_back(TM_WALK); Point p1(true, index1, index2); assert(pos1 >=0 && pos2 >= pos1); Point p2(true, pos1, pos2);//index in mpoint // index_list1.push_back(p1); //genmo index // index_list2.push_back(p2); //mpoint index // delete peri; delete mp; // delete peri_t; } /////////////////////////////////////////////////////////////////// i = j - 1; if(mtuple == 1){//decompose into two movements MPoint* mp = &(mp_list[mp_list.size() - 1]); if(mp->GetNoComponents() == 1){///////////only one unit, one mtuples /////doing nothing }else if(tm_list.size() > 1 && tm_list[tm_list.size() - 2] == TM_WALK){ //two already //if the last movement is also walking, do not split }else{///////////two mtuples // cout<<"mp "<<*mp<<" "<<mp->GetNoComponents()<<endl; int div_pos = (int)(mp->GetNoComponents()/2.0); // cout<<"div_pos "<<div_pos<<endl; MPoint* mp1 = new MPoint(0); mp1->StartBulkLoad(); double st1, et1; for(int k = 0;k < div_pos;k++){ UPoint u; mp->Get(k, u); mp1->Add(u); if(k == 0) st1 = u.timeInterval.start.ToDouble(); if(k == div_pos - 1)et1 = u.timeInterval.end.ToDouble(); } mp1->EndBulkLoad(); // mp_list[mp_list.size() - 1] = *mp1;//update the one in the list Rectangle<3> tm_box1(true, st1, et1, mp1->BoundingBoxSpatial().MinD(0), mp1->BoundingBoxSpatial().MaxD(0), mp1->BoundingBoxSpatial().MinD(1), mp1->BoundingBoxSpatial().MaxD(1) ); // box_list[box_list.size() - 1] = tm_box1;//update the one in the list // delete mp1; MPoint* mp2 = new MPoint(0); mp2->StartBulkLoad(); double st2, et2; // cout<<" div_pos "<<div_pos<<" "<<mp->GetNoComponents()<<endl; for(int k = div_pos; k < mp->GetNoComponents();k++){ UPoint u; mp->Get(k, u); mp2->Add(u); if(k == div_pos) st2 = u.timeInterval.start.ToDouble(); if(k == mp->GetNoComponents() - 1) et2 = u.timeInterval.end.ToDouble(); } mp2->EndBulkLoad(); box_list[box_list.size() - 1] = tm_box1;//update the one in the list mp_list[mp_list.size() - 1] = *mp1;//update the one in the list mp_list.push_back(*mp2); oid_list.push_back(oid); Rectangle<3> tm_box2(true, st2, et2, mp2->BoundingBoxSpatial().MinD(0), mp2->BoundingBoxSpatial().MaxD(0), mp2->BoundingBoxSpatial().MinD(1), mp2->BoundingBoxSpatial().MaxD(1) ); box_list.push_back(tm_box2); tm_list.push_back(TM_WALK);//use walk insead of free delete mp1; delete mp2; } } } /* collect movement tuples for car, taxi and bike for each movement on one road, get the units in mp use start and end time instants */ void QueryTM::CollectCBT(int&i, int oid, int m, GenMO* mo1, MPoint* mo2, int& up_pos, double len) { // cout<<"CollectCBT"<<endl; int index1 = i; int j = i; int64_t start_time = -1; int64_t end_time = -1; double l = 0; int last_rid = -1; while(j < mo1->GetNoComponents()){ UGenLoc unit; mo1->Get(j, unit); if(unit.GetTM() == m){ if(start_time < 0) start_time = unit.timeInterval.start.ToDouble()*ONEDAY_MSEC; end_time = unit.timeInterval.end.ToDouble()*ONEDAY_MSEC; l += fabs(unit.gloc1.GetLoc().loc1 - unit.gloc2.GetLoc().loc1); // cout<<unit.gloc1<<" "<<unit.gloc2<<endl; // cout<<"l "<<l<<endl; int cur_rid = unit.GetOid(); if(last_rid == -1){ last_rid = cur_rid; // }else if(last_rid != cur_rid){ }else if(last_rid != cur_rid && l > len){//driving length is long MPoint* mp = new MPoint(0); mp->StartBulkLoad(); int pos1 = up_pos; int pos2 = -1; for(int index = up_pos;index < mo2->GetNoComponents();index++){ UPoint u; mo2->Get(index, u); mp->Add(u); int64_t cur_t = u.timeInterval.end.ToDouble()*ONEDAY_MSEC; if(cur_t == end_time){ up_pos = index + 1; pos2 = index; break; } } mp->EndBulkLoad(); mp_list.push_back(*mp);//store a subtrip // Periods* peri = new Periods(0); // mp->DefTime(*peri); // delete peri; ////////////////////////////////////////////// // Instant st(instanttype); // Instant et(instanttype); // // Periods* peri_t = new Periods(0); // peri_t->StartBulkLoad(); // Interval<Instant> time_span; // st.ReadFrom(start_time/ONEDAY_MSEC); // et.ReadFrom(end_time/ONEDAY_MSEC); // // time_span.start = st; // time_span.lc = true; // time_span.end = et; // time_span.rc = false; // // peri_t->MergeAdd(time_span); // peri_t->EndBulkLoad(); // cout<<*peri<<" "<<*peri_t<<endl; //////////////////////////////////// oid_list.push_back(oid); // time_list.push_back(*peri); // time_list.push_back(*peri_t); // box_list.push_back(mp->BoundingBoxSpatial()); Rectangle<3> tm_box(true, start_time/ONEDAY_MSEC, end_time/ONEDAY_MSEC, mp->BoundingBoxSpatial().MinD(0), mp->BoundingBoxSpatial().MaxD(0), mp->BoundingBoxSpatial().MinD(1), mp->BoundingBoxSpatial().MaxD(1) ); box_list.push_back(tm_box); tm_list.push_back(m); Point p1(true, index1, j); assert(pos1 >= 0 && pos2 >= pos1); Point p2(true, pos1, pos2);//index in mpoint // index_list1.push_back(p1); //genmo index // index_list2.push_back(p2); //mpoint index index1 = j; last_rid = cur_rid; start_time = -1; end_time = -1; // delete peri; delete mp; // delete peri_t; l = 0.0; } j++; }else{ break; } } int index2 = j - 1; if(start_time > 0 && start_time < end_time){ MPoint* mp = new MPoint(0); mp->StartBulkLoad(); int pos1 = up_pos; int pos2 = -1; for(int index = up_pos;index < mo2->GetNoComponents();index++){ UPoint u; mo2->Get(index, u); mp->Add(u); if(index == up_pos) start_time = u.timeInterval.start.ToDouble()*ONEDAY_MSEC; int64_t cur_t = u.timeInterval.end.ToDouble()*ONEDAY_MSEC; if(cur_t == end_time){ up_pos = index + 1; pos2 = index; break; } } mp->EndBulkLoad(); mp_list.push_back(*mp); // Periods* peri = new Periods(0); // mp->DefTime(*peri); // delete peri; ////////////////////////////////////////////////// // Instant st(instanttype); // Instant et(instanttype); // // Periods* peri_t = new Periods(0); // peri_t->StartBulkLoad(); // Interval<Instant> time_span; // st.ReadFrom(start_time/ONEDAY_MSEC); // et.ReadFrom(end_time/ONEDAY_MSEC); // // time_span.start = st; // time_span.lc = true; // time_span.end = et; // time_span.rc = false; // // peri_t->MergeAdd(time_span); // peri_t->EndBulkLoad(); // cout<<*peri<<" "<<*peri_t<<endl; //////////////////////////////////////////////////// oid_list.push_back(oid); /* time_list.push_back(*peri_t); box_list.push_back(mp->BoundingBoxSpatial());*/ Rectangle<3> tm_box(true, start_time/ONEDAY_MSEC, end_time/ONEDAY_MSEC, mp->BoundingBoxSpatial().MinD(0), mp->BoundingBoxSpatial().MaxD(0), mp->BoundingBoxSpatial().MinD(1), mp->BoundingBoxSpatial().MaxD(1) ); box_list.push_back(tm_box); tm_list.push_back(m); Point p1(true, index1, index2); assert(pos1 >= 0 && pos2 >= pos1); Point p2(true, pos1, pos2);//index in mpoint // index_list1.push_back(p1); // index_list2.push_back(p2); // delete peri; delete mp; // delete peri_t; } /////////////////////////////////////////////////////////////////// i = j - 1; } /* collect all indoor units inside one building as one movement tuple use start and end time instants */ void QueryTM::CollectIndoor(int& i, int oid, int m, GenMO* mo1, MPoint* mo2, int& up_pos) { // cout<<"CollectIndoorFree"<<endl; int index1 = i; int j = i; int64_t start_time = -1; int64_t end_time = -1; while(j < mo1->GetNoComponents()){ UGenLoc unit; mo1->Get(j, unit); if(unit.GetTM() == m){ if(start_time < 0) start_time = unit.timeInterval.start.ToDouble()*ONEDAY_MSEC; end_time = unit.timeInterval.end.ToDouble()*ONEDAY_MSEC; j++; }else{ break; } } int index2 = j - 1; // cout<<start_time<<" "<<end_time<<endl; MPoint* mp = new MPoint(0); mp->StartBulkLoad(); int pos1 = up_pos; int pos2 = -1; for(int index = up_pos; index < mo2->GetNoComponents(); index++){ UPoint u; mo2->Get(index, u); mp->Add(u); int64_t cur_t = u.timeInterval.end.ToDouble()*ONEDAY_MSEC; if(cur_t == end_time){ // cout<<"find end time "<<endl; up_pos = index + 1; pos2 = index; break; } } mp->EndBulkLoad(); mp_list.push_back(*mp);//store a sub trip //////////////////////////////////////////////////////////////////// oid_list.push_back(oid); Rectangle<3> tm_box(true, start_time/ONEDAY_MSEC, end_time/ONEDAY_MSEC, mp->BoundingBoxSpatial().MinD(0), mp->BoundingBoxSpatial().MaxD(0), mp->BoundingBoxSpatial().MinD(1), mp->BoundingBoxSpatial().MaxD(1) ); box_list.push_back(tm_box); tm_list.push_back(m); Point p1(true, index1, index2); assert(pos1 >= 0 && pos2 >= pos1); Point p2(true, pos1, pos2);//index in mpoint /////////////////////////////////////////////////////////////////// // delete peri_t; // delete peri; delete mp; i = j - 1; } /* ignore such a small piece of movement to compute movement tuples */ void QueryTM::CollectFree_0(int& i, int oid, int m, GenMO* mo1, MPoint* mo2, int& up_pos) { // cout<<"CollectIndoorFree"<<endl; int index1 = i; int j = i; int64_t start_time = -1; int64_t end_time = -1; while(j < mo1->GetNoComponents()){ UGenLoc unit; mo1->Get(j, unit); if(unit.GetTM() == m){ if(start_time < 0) start_time = unit.timeInterval.start.ToDouble()*ONEDAY_MSEC; end_time = unit.timeInterval.end.ToDouble()*ONEDAY_MSEC; j++; }else{ break; } } int index2 = j - 1; // cout<<start_time<<" "<<end_time<<endl; MPoint* mp = new MPoint(0); mp->StartBulkLoad(); int pos1 = up_pos; int pos2 = -1; for(int index = up_pos; index < mo2->GetNoComponents(); index++){ UPoint u; mo2->Get(index, u); mp->Add(u); int64_t cur_t = u.timeInterval.end.ToDouble()*ONEDAY_MSEC; if(cur_t == end_time){ // cout<<"find end time "<<endl; up_pos = index + 1; pos2 = index; break; } } mp->EndBulkLoad(); //////////////////////////////////////////////////////////////////// Rectangle<3> tm_box(true, start_time/ONEDAY_MSEC, end_time/ONEDAY_MSEC, mp->BoundingBoxSpatial().MinD(0), mp->BoundingBoxSpatial().MaxD(0), mp->BoundingBoxSpatial().MinD(1), mp->BoundingBoxSpatial().MaxD(1) ); mp_list.push_back(*mp);//store a sub trip oid_list.push_back(oid); box_list.push_back(tm_box); // tm_list.push_back(m); tm_list.push_back(TM_WALK);//here, we use walk instead of free Point p1(true, index1, index2); assert(pos1 >= 0 && pos2 >= pos1); Point p2(true, pos1, pos2);//index in mpoint /////////////////////////////////////////////////////////////////// // delete peri_t; // delete peri; delete mp; i = j - 1; } /* almost the same as collectfree 0 but here we get two movement tuples if the trip contains more than one units, this is to combine walk and m in the future */ void QueryTM::CollectFree_1(int& i, int oid, int m, GenMO* mo1, MPoint* mo2, int& up_pos) { // cout<<"CollectIndoorFree"<<endl; int index1 = i; int j = i; int64_t start_time = -1; int64_t end_time = -1; while(j < mo1->GetNoComponents()){ UGenLoc unit; mo1->Get(j, unit); if(unit.GetTM() == m){ if(start_time < 0) start_time = unit.timeInterval.start.ToDouble()*ONEDAY_MSEC; end_time = unit.timeInterval.end.ToDouble()*ONEDAY_MSEC; j++; }else{ break; } } int index2 = j - 1; // cout<<start_time<<" "<<end_time<<endl; MPoint* mp = new MPoint(0); mp->StartBulkLoad(); int pos1 = up_pos; int pos2 = -1; for(int index = up_pos; index < mo2->GetNoComponents(); index++){ UPoint u; mo2->Get(index, u); mp->Add(u); int64_t cur_t = u.timeInterval.end.ToDouble()*ONEDAY_MSEC; if(cur_t == end_time){ // cout<<"find end time "<<endl; up_pos = index + 1; pos2 = index; break; } } mp->EndBulkLoad(); //////////////////////////////////////////////////////////////////// Rectangle<3> tm_box(true, start_time/ONEDAY_MSEC, end_time/ONEDAY_MSEC, mp->BoundingBoxSpatial().MinD(0), mp->BoundingBoxSpatial().MaxD(0), mp->BoundingBoxSpatial().MinD(1), mp->BoundingBoxSpatial().MaxD(1) ); // mp_list.push_back(*mp);//store a sub trip // oid_list.push_back(oid); // box_list.push_back(tm_box); // tm_list.push_back(TM_WALK);//be careful, use walk instead of free // cout<<tm_box<<endl; if(mp->GetNoComponents() == 1){///////////only one unit, one mtuples mp_list.push_back(*mp);//store a sub trip oid_list.push_back(oid); box_list.push_back(tm_box); tm_list.push_back(TM_WALK);//be careful, use walk instead of free }else if(tm_list.size() > 0 && tm_list[tm_list.size() - 1] == TM_WALK){//do not split mp_list.push_back(*mp);//store a sub trip oid_list.push_back(oid); box_list.push_back(tm_box); tm_list.push_back(TM_WALK);//be careful, use walk instead of free }else{////////two mtuples int div_pos = (int)(mp->GetNoComponents()/2.0); MPoint* mp1 = new MPoint(0); mp1->StartBulkLoad(); double st1, et1; for(int i = 0;i < div_pos;i++){ UPoint u; mp->Get(i, u); mp1->Add(u); if(i == 0) st1 = u.timeInterval.start.ToDouble(); if(i == div_pos - 1)et1 = u.timeInterval.end.ToDouble(); } mp1->EndBulkLoad(); mp_list.push_back(*mp1); oid_list.push_back(oid); Rectangle<3> tm_box1(true, st1, et1, mp1->BoundingBoxSpatial().MinD(0), mp1->BoundingBoxSpatial().MaxD(0), mp1->BoundingBoxSpatial().MinD(1), mp1->BoundingBoxSpatial().MaxD(1) ); box_list.push_back(tm_box1); // cout<<"sub box1 "<<tm_box1<<endl; tm_list.push_back(TM_WALK);//use walk instead of free delete mp1; MPoint* mp2 = new MPoint(0); mp2->StartBulkLoad(); double st2, et2; for(int i = div_pos; i < mp->GetNoComponents();i++){ UPoint u; mp->Get(i, u); mp2->Add(u); if(i == div_pos) st2 = u.timeInterval.start.ToDouble(); if(i == mp->GetNoComponents() - 1) et2 = u.timeInterval.end.ToDouble(); } mp2->EndBulkLoad(); mp_list.push_back(*mp2); oid_list.push_back(oid); Rectangle<3> tm_box2(true, st2, et2, mp2->BoundingBoxSpatial().MinD(0), mp2->BoundingBoxSpatial().MaxD(0), mp2->BoundingBoxSpatial().MinD(1), mp2->BoundingBoxSpatial().MaxD(1) ); box_list.push_back(tm_box2); // cout<<"sub box2 "<<tm_box2<<endl; tm_list.push_back(TM_WALK);//use walk insead of free delete mp2; }////////end for if else Point p1(true, index1, index2); assert(pos1 >= 0 && pos2 >= pos1); Point p2(true, pos1, pos2);//index in mpoint delete mp; i = j - 1; } /* for each node calculate tm values using an integer, stops when there are several values because this can not be used to prune tm-rtree nodes */ unsigned long QueryTM::Node_TM(R_Tree<3, TupleId>* tmrtree, Relation* rel, SmiRecordId nodeid, int attr_pos) { R_TreeNode<3, TupleId>* node = tmrtree->GetMyNode(nodeid,false, tmrtree->MinEntries(0), tmrtree->MaxEntries(0)); if(node->IsLeaf()){ cout<<"leaf node "<<nodeid<<endl; int pos = -1; //////////////for testing//////////////// for(int j = 0;j < node->EntryCount();j++){ R_TreeLeafEntry<3, TupleId> e = (R_TreeLeafEntry<3, TupleId>&)(*node)[j]; Tuple* tuple = rel->GetTuple(e.info, false); int m = ((CcInt*)tuple->GetAttribute(attr_pos))->GetIntval(); tuple->DeleteIfAllowed(); // cout<<"j "<<j<<" tm "<<GetTMStr(m)<<endl; // pos = (int)ARR_SIZE(str_tm) - 1 - m; if(pos < 0) pos = (int)(ARR_SIZE(str_tm) - 1 - m); else assert(pos == (int)(ARR_SIZE(str_tm) - 1 - m)); } delete node; bitset<ARR_SIZE(str_tm)> modebits; modebits.reset(); modebits.set(pos, 1); cout<<modebits.to_ulong()<<" "<<modebits.to_string()<<endl; ////////////////////output the result/////////////////// oid_list.push_back(nodeid); mode_list.push_back(modebits.to_ulong()); return modebits.to_ulong(); }else{ cout<<"non leaf node "<<nodeid<<endl; bitset<ARR_SIZE(str_tm)> modebits; modebits.reset(); for(int j = 0;j < node->EntryCount();j++){ R_TreeInternalEntry<3> e = (R_TreeInternalEntry<3>&)(*node)[j]; int son_tm = Node_TM(tmrtree, rel, e.pointer, attr_pos); if(son_tm < 0){//if sontm < 0, stops delete node; return -1; } bitset<ARR_SIZE(str_tm)> m_bit(son_tm); ///////////// union value of each son tm to tm////////////// /* cout<<"new one "<<m_bit.to_string() <<" before "<<modebits.to_string()<<endl;*/ modebits = modebits | m_bit; // cout<<"after"<<modebits.to_string()<<endl; } delete node; ///////////////////output the result /////////////////// cout<<modebits.to_ulong()<<" "<<modebits.to_string()<<endl; oid_list.push_back(nodeid); mode_list.push_back(modebits.to_ulong()); ////////////////////////////////////////////////////// if(modebits.count() > 1) return -1; return modebits.to_ulong(); } } /* get nodes of TM-RTree */ void QueryTM::TM_RTreeNodes(TM_RTree<3,TupleId>* tmrtree) { SmiRecordId node_id = tmrtree->RootRecordId(); int level = 0; GetNodes(tmrtree, node_id, level); } /* get nodes information */ void QueryTM::GetNodes(TM_RTree<3, TupleId>* tmrtree, SmiRecordId nodeid, int level) { TM_RTreeNode<3, TupleId>* node = tmrtree->GetMyNode(nodeid,false, tmrtree->MinEntries(0), tmrtree->MaxEntries(0)); if(node->IsLeaf()){ long m = node->GetTMValue(); // cout<<"leaf node "<<nodeid<<" m "<<m<<" "<<GetModeString(m)<<endl; // bitset<ARR_SIZE(str_tm)> mode_bit(m); bitset<TM_SUM_NO> mode_bit(m); // assert(mode_bit.count() == 1);//one mode in a leaf node (before) assert(mode_bit.count() >= 1);//3D rtree and TMRtree ///////////////output result/////////////////////////////// oid_list.push_back(nodeid); level_list.push_back(level); b_list.push_back(true); mode_list.push_back(m);// bit value to integer value box_list.push_back(node->BoundingBox()); entry_list.push_back(node->EntryCount()); delete node; }else{ for(int j = 0;j < node->EntryCount();j++){ R_TreeInternalEntry<3> e = (R_TreeInternalEntry<3>&)(*node)[j]; GetNodes(tmrtree, e.pointer, level + 1); } long m = node->GetTMValue(); // cout<<"non leaf node "<<nodeid<<" m "<<m<<endl; oid_list.push_back(nodeid); level_list.push_back(level); b_list.push_back(false); mode_list.push_back(m); box_list.push_back(node->BoundingBox()); entry_list.push_back(node->EntryCount()); delete node; ////////////////////////////////////////////////////// } } /* range query on generic moving objects using TM-RTree using a queue to store nodes 1) check mode; 2) check query window */ void QueryTM::RangeTMRTree(TM_RTree<3,TupleId>* tmrtree, Relation* units_rel, Relation* query_rel, int treetype) { // cout<<units_rel->GetNoTuples()<<" "<<query_rel->GetNoTuples()<<endl; // cout<<"genmo no "<<genmo_rel->GetNoTuples()<<endl; if(query_rel->GetNoTuples() != 1){ cout<<"one query tuple "<<endl; return; } for(int i = 1;i <= query_rel->GetNoTuples();i++){ Tuple* tuple = query_rel->GetTuple(i, false); Periods* peri = (Periods*)tuple->GetAttribute(GM_TIME); Rectangle<2>* box = (Rectangle<2>*)tuple->GetAttribute(GM_SPATIAL); string mode = ((CcString*)tuple->GetAttribute(GM_Q_MODE))->GetValue(); // cout<<*peri<<" "<<*box<<" "<<mode<<endl; ////////////////////////////////////////////////////////////////// double min[3], max[3]; Interval<Instant> time_span; peri->Get(0, time_span); min[0] = time_span.start.ToDouble(); max[0] = time_span.end.ToDouble(); min[1] = box->MinD(0); max[1] = box->MaxD(0); min[2] = box->MinD(1); max[2] = box->MaxD(1); Rectangle<3> query_box(true, min, max); ////////////////////////////////////////////////////////////////// vector<long> seq_tm; int type = ModeType(mode, seq_tm); //seqtm bit value to integer if(type < 0){ cout<<"mode error "<<mode<<endl; tuple->DeleteIfAllowed(); break; } ///////////////////////////////////////////////////////////////////// ////////////////////////single mode////////////////////////////////// ///////////////////////////////////////////////////////////////////// if(type == SINMODE){ //////////////filter step //////////////////////////// // bitset<ARR_SIZE(str_tm)> modebits(seq_tm[0]); bitset<TM_SUM_NO> modebits(seq_tm[0]);//bit index to an anteger cout<<"single mode "<<GetModeStringExt(seq_tm[0]) <<" "<<modebits.to_string()<<endl; assert(modebits.count() == 1); int bit_pos = -1; for(int i = 0;i < (int)modebits.size();i++){ if(modebits.test(i)){ bit_pos = i; break; } } int sin_mode_no = (int)ARR_SIZE(str_tm); assert(0 <= bit_pos && bit_pos <= sin_mode_no); if(treetype == TMRTREE)// TMRTree SinMode_Filter1(tmrtree, query_box, bit_pos, units_rel); else if(treetype == ADRTREE)//ADRTree SinMode_Filter2(tmrtree, query_box, bit_pos, units_rel); else if(treetype == RTREE3D){//3DRTRee SinMode_Filter3(tmrtree, query_box, bit_pos, units_rel); }else if(treetype == TMRTREETEST){ //only single mode in mtuples SinMode_Filter1(tmrtree, query_box, bit_pos, units_rel); } else{ cout<<"wrong type "<<treetype<<endl; assert(false); } //////////////refinement //////////////////////////////// SinMode_Refinement(query_box, bit_pos, units_rel); } /////////////////////////////////////////////////////////////// ///////////////////// multiple modes ////////////////////////// //////////////////////////////////////////////////////////////// if(type == MULMODE){ //not necessary use the total length, because the value belongs to // the first nine bitset<ARR_SIZE(str_tm)> modebits(seq_tm[0]);//integer from bit index cout<<"multiple mode "<<GetModeStringExt(seq_tm[0]) <<" "<<modebits.to_string()<<endl; assert(modebits.count() >= 2); vector<bool> bit_pos(ARR_SIZE(str_tm), false);// first part enough int mode_count = 0; for(unsigned int i = 0;i < modebits.size();i++){ if(modebits.test(i)){ bit_pos[i] = true; mode_count++; } } if(treetype == TMRTREE){//TMRTree filter multiple modes MulMode_Filter1(tmrtree, query_box, bit_pos, units_rel); }else if(treetype == ADRTREE) {//ADRTREE, simply stores the value MulMode_Filter2(tmrtree, query_box, bit_pos, units_rel); }else if(treetype == RTREE3D){//3DRTree MulMode_Filter3(tmrtree, query_box, bit_pos, units_rel); }else if(treetype == TMRTREETEST){//TMRTree only single mode MulMode_Filter1(tmrtree, query_box, bit_pos, units_rel); }else{ cout<<"wrong tree type "<<endl; assert(false); } MulMode_Refinement(query_box, bit_pos, units_rel, mode_count); } /////////////////////////////////////////////////////////////////// /////////////////// a sequence of modes//////////////////////////// ////////////////////////////////////////////////////////////////// if(type == SEQMODE){//a sequence of modes cout<<"a sequence of modes "<<endl; vector<bool> bit_pos(ARR_SIZE(str_tm), false);//mark the index bitset<ARR_SIZE(str_tm)> modebits; modebits.reset(); for(unsigned int i = 0;i < seq_tm.size();i++){ // cout<<GetTMStrExt(seq_tm[i])<<" "; bit_pos[seq_tm[i]] = true; modebits.set(seq_tm[i]); } // cout<<endl; // cout<<modebits.to_string()<<" " // <<GetModeStringExt(modebits.to_ulong())<<endl;; ///////////split the mode value by walk + m/////////////// assert(seq_tm.size() > 1); int sin_mode_no = ARR_SIZE(str_tm); vector<bool> m_bit_list(3*sin_mode_no, false); for(unsigned int i = 0;i < seq_tm.size();i++){ // cout<<GetTMStrExt(seq_tm[i])<<" "; if(i < seq_tm.size() - 1){ unsigned int j = i + 1; int m1 = seq_tm[i]; int m2 = seq_tm[j]; assert(m1 != m2); if(m1 == TM_WALK){ m_bit_list[m2 + 2*sin_mode_no] = true; }else if(m2 == TM_WALK){ m_bit_list[m1 + sin_mode_no] = true; }else{ assert(false); } } } ///////////1 include these modes; 2 with a certain order///////////// if(treetype == TMRTREE){ SeqMode_Filter1(tmrtree, query_box, m_bit_list); }else if(treetype == ADRTREE){ SeqMode_Filter2(tmrtree, query_box, units_rel, m_bit_list); }else if(treetype == RTREE3D){ SeqMode_Filter3(tmrtree, query_box, units_rel, m_bit_list); }else if(treetype == TMRTREETEST){//get all mtuples contain these modes SeqMode_Filter4(tmrtree, query_box, bit_pos, units_rel); }else{ cout<<"wrong tree type "<<endl; assert(false); } SeqMode_Refinement(query_box, bit_pos, units_rel, seq_tm, m_bit_list); } tuple->DeleteIfAllowed(); } } /* get the type of range query: single mode or a sequence of modes 1: single mode or multiple modes but no order; 2: a sequence of modes seq tm stores mode value(s) */ int QueryTM::ModeType(string mode, vector<long>& seq_tm) { vector<int> pos_list1;//single or multiple modes vector<int> pos_list2;// a sequence of modes char buffer[16]; int index = 0; for(unsigned int i = 0;i < mode.length();i++){ // cout<<i<<" "<<mode[i]<<endl; if(isalpha(mode[i])){ buffer[index] = mode[i]; index++; } if(mode[i] == ','){ buffer[index] = '\0'; // cout<<i<<" "<<buffer<<endl; index = 0; string m(buffer); // cout<<m<<endl; pos_list1.push_back(GetTM(m)); } if(mode[i] == ';'){ buffer[index] = '\0'; // cout<<i<<" "<<buffer<<endl; index = 0; string m(buffer); // cout<<m<<endl; pos_list2.push_back(GetTM(m)); } if(i == mode.length() - 1){ buffer[index] = '\0'; // cout<<i<<" "<<buffer<<endl; index = 0; string m(buffer); // cout<<m<<endl; if(pos_list2.size() > 0){ pos_list2.push_back(GetTM(m)); }else{ pos_list1.push_back(GetTM(m)); } } } // cout<<pos_list1.size()<<" "<<pos_list2.size()<<endl; if(pos_list1.size() > 0 && pos_list2.size() > 0){//do not mix mul and seq return -1; } if(pos_list1.size() > 0){ // bitset<ARR_SIZE(str_tm)> modebits; bitset<TM_SUM_NO> modebits; modebits.reset(); for(unsigned int i = 0;i < pos_list1.size();i++){ // cout<<"i "<<ARR_SIZE(str_tm)<<" " // <<pos_list1[i]<<" " // <<ARR_SIZE(str_tm) - 1 - pos_list1[i]<<endl; // cout<<pos_list1[i]<<endl; if(pos_list1[i] < 0) return -1; assert(pos_list1[i] >= 0); modebits.set((int)(pos_list1[i]), 1); } // cout<<modebits.to_ulong()<<endl; seq_tm.push_back(modebits.to_ulong()); if(pos_list1.size() == 1) return SINMODE; else return MULMODE; } if(pos_list2.size() > 0){/////modes with a certain order // set the value in seqtm list// for(unsigned int i = 0;i < pos_list2.size();i++){ // cout<<GetTMStrExt(pos_list2[i])<<" "; seq_tm.push_back(pos_list2[i]);//store the mode bit index } return SEQMODE;//a sequence of values } return -1; } inline bool ModeCheck1(bitset<TM_SUM_NO> node_bit, int bit_pos) { if(node_bit.test(bit_pos)) return true; if(bit_pos == TM_WALK){//mode walk if(node_bit.to_ulong() >= (unsigned int)pow(2, ARR_SIZE(str_tm))) return true; }else{ if(node_bit.test(bit_pos + ARR_SIZE(str_tm)) || node_bit.test(bit_pos + 2*ARR_SIZE(str_tm)))return true; } return false; } /* traverse TMRTree to find units that intersect the query box query mode is a single mode */ void QueryTM::SinMode_Filter1(TM_RTree<3,TupleId>* tmrtree, Rectangle<3> query_box, int bit_pos, Relation* units_rel) { //////////////////////////////////////////////////////////////// Interval<Instant> time_span; Instant st(instanttype); Instant et(instanttype); st.ReadFrom(query_box.MinD(0)); time_span.start = st; time_span.lc = true; et.ReadFrom(query_box.MaxD(0)); time_span.end = et; time_span.rc = false; double min[2], max[2]; min[0] = query_box.MinD(1); min[1] = query_box.MinD(2); max[0] = query_box.MaxD(1); max[1] = query_box.MaxD(2); Rectangle<2> spatial_box(true, min, max); Region query_reg(spatial_box); //////////////////////////////////////////////////////////////// // cout<<"SinModefilter query box "<<query_box<<endl; queue<SmiRecordId> query_list; query_list.push(tmrtree->RootRecordId()); // cout<<"bit pos "<<bit_pos<<endl; int node_count = 0; while(query_list.empty() == false){ SmiRecordId nodeid = query_list.front(); query_list.pop(); TM_RTreeNode<3, TupleId>* node = tmrtree->GetMyNode(nodeid,false, tmrtree->MinEntries(0), tmrtree->MaxEntries(0)); bitset<TM_SUM_NO> node_bit(node->GetTMValue()); // cout<<nodeid<<" "<<GetModeStringExt(node->GetTMValue()); bool res = ModeCheck1(node_bit, bit_pos); // if(node_bit.test(bit_pos)){///////transportation mode check if(res){///////transportation mode check /* cout<<"node id "<<nodeid <<" mode "<<GetModeString(node->GetTMValue())<<endl;*/ if(node->IsLeaf()){ for(int j = 0;j < node->EntryCount();j++){ R_TreeLeafEntry<3, TupleId> e = (R_TreeLeafEntry<3, TupleId>&)(*node)[j]; if(e.box.Intersects(query_box)){ //query window unit_tid_list.push_back(e.info); } } }else{ for(int j = 0;j < node->EntryCount();j++){//finish R_TreeInternalEntry<3> e = (R_TreeInternalEntry<3>&)(*node)[j]; if(e.box.Intersects(query_box)){ //query window query_list.push(e.pointer); } } } node_count++; } delete node; } cout<<node_count<<" nodes accessed " <<unit_tid_list.size()<<" candidates "<<endl; } /* traverse ADRTree to find units that intersect the query box query mode is a single mode in a leaf node it needs to acces units relation to get precise mode value */ void QueryTM::SinMode_Filter2(TM_RTree<3,TupleId>* tmrtree, Rectangle<3> query_box, int bit_pos, Relation* units_rel) { // cout<<"SinModefilter 3DRtree query box "<<query_box<<endl; queue<SmiRecordId> query_list; query_list.push(tmrtree->RootRecordId()); // cout<<"bit pos "<<bit_pos<<endl; int sin_mode_no = (int)ARR_SIZE(str_tm); int node_count = 0; while(query_list.empty() == false){ SmiRecordId nodeid = query_list.front(); query_list.pop(); TM_RTreeNode<3, TupleId>* node = tmrtree->GetMyNode(nodeid,false, tmrtree->MinEntries(0), tmrtree->MaxEntries(0)); bitset<TM_SUM_NO> node_bit(node->GetTMValue()); bool res = ModeCheck1(node_bit, bit_pos); if(res){ /* cout<<"node id "<<nodeid <<" mode "<<GetModeString(node->GetTMValue())<<endl;*/ if(node->IsLeaf()){ for(int j = 0;j < node->EntryCount();j++){ R_TreeLeafEntry<3, TupleId> e = (R_TreeLeafEntry<3, TupleId>&)(*node)[j]; Tuple* mtuple = units_rel->GetTuple(e.info, false); int mode = ((CcInt*)mtuple->GetAttribute(GM_MODE))->GetIntval(); // cout<<"bit_pos "<<bit_pos<<" "<< mode<<endl; // cout<<GetTMStr(bit_pos)<<" "<<GetTMStr(mode)<<endl; // if(bit_pos == (total_size - mode) && // e.box.Intersects(query_box)){ //query window // unit_tid_list.push_back(e.info); // } if(bit_pos == TM_WALK){ if(bit_pos == mode || mode >= sin_mode_no){ if(e.box.Intersects(query_box)){ unit_tid_list.push_back(e.info); } } }else{ if(bit_pos == mode || (mode == bit_pos + sin_mode_no) || (mode == bit_pos + 2*sin_mode_no)){ if(e.box.Intersects(query_box)){ unit_tid_list.push_back(e.info); } } } mtuple->DeleteIfAllowed(); } }else{ for(int j = 0;j < node->EntryCount();j++){//finish R_TreeInternalEntry<3> e = (R_TreeInternalEntry<3>&)(*node)[j]; if(e.box.Intersects(query_box)){ //query window query_list.push(e.pointer); } } } node_count++; } delete node; } cout<<node_count<<" nodes accessed " <<unit_tid_list.size()<<" candidates "<<endl; } /* traverse 3DRTree to find units that intersect the query box no mode check for a node query mode is a single mode in a leaf node it needs to acces units relation to get precise mode value */ void QueryTM::SinMode_Filter3(TM_RTree<3,TupleId>* tmrtree, Rectangle<3> query_box, int bit_pos, Relation* units_rel) { // cout<<"SinModefilter 3DRtree query box "<<query_box<<endl; queue<SmiRecordId> query_list; query_list.push(tmrtree->RootRecordId()); // cout<<"bit pos "<<bit_pos<<endl; int sin_mode_no = (int)ARR_SIZE(str_tm); int node_count = 0; while(query_list.empty() == false){ SmiRecordId nodeid = query_list.front(); query_list.pop(); TM_RTreeNode<3, TupleId>* node = tmrtree->GetMyNode(nodeid,false, tmrtree->MinEntries(0), tmrtree->MaxEntries(0)); /* cout<<"node id "<<nodeid <<" mode "<<GetModeString(node->GetTMValue())<<endl;*/ if(node->IsLeaf()){ for(int j = 0;j < node->EntryCount();j++){ R_TreeLeafEntry<3, TupleId> e = (R_TreeLeafEntry<3, TupleId>&)(*node)[j]; Tuple* mtuple = units_rel->GetTuple(e.info, false); int mode = ((CcInt*)mtuple->GetAttribute(GM_MODE))->GetIntval(); // cout<<"bit_pos "<<bit_pos<<" "<< total_size - mode<<endl; // cout<<GetTMStr(bit_pos)<<" "<<GetTMStr(mode)<<endl; // if(bit_pos == (total_size - mode) && // e.box.Intersects(query_box)){ //query window // unit_tid_list.push_back(e.info); // } if(bit_pos == TM_WALK){ if(bit_pos == mode || mode >= sin_mode_no){ if(e.box.Intersects(query_box)){ unit_tid_list.push_back(e.info); } } }else{ if(bit_pos == mode || (mode == bit_pos + sin_mode_no) || (mode == bit_pos + 2*sin_mode_no)){ if(e.box.Intersects(query_box)){ unit_tid_list.push_back(e.info); } } } mtuple->DeleteIfAllowed(); } }else{ for(int j = 0;j < node->EntryCount();j++){//finish R_TreeInternalEntry<3> e = (R_TreeInternalEntry<3>&)(*node)[j]; if(e.box.Intersects(query_box)){ //query window query_list.push(e.pointer); } } } node_count++; delete node; } cout<<node_count<<" nodes accessed " <<unit_tid_list.size()<<" candidates "<<endl; } /* from the result by traversing TMRtree, check the precise value just return the complete trajectory if its sub trip satisfies the condition. it needs much work to decompose the trajectory into pieces and it might not be necessary */ void QueryTM::SinMode_Refinement(Rectangle<3> query_box, int bit_pos, Relation* units_rel) { // cout<<"refinement candidate number "<<unit_tid_list.size()<<endl; Interval<Instant> time_span; Instant st(instanttype); Instant et(instanttype); st.ReadFrom(query_box.MinD(0)); time_span.start = st; time_span.lc = true; et.ReadFrom(query_box.MaxD(0)); time_span.end = et; time_span.rc = false; double min[2], max[2]; min[0] = query_box.MinD(1); min[1] = query_box.MinD(2); max[0] = query_box.MaxD(1); max[1] = query_box.MaxD(2); Rectangle<2> spatial_box(true, min, max); Region query_reg(spatial_box); set<int> res_id;//store trajectory id; int sin_mode_no = (int)ARR_SIZE(str_tm); for(unsigned int i = 0;i < unit_tid_list.size();i++){ Tuple* mtuple = units_rel->GetTuple(unit_tid_list[i], false); int traj_id = ((CcInt*)mtuple->GetAttribute(GM_TRAJ_ID))->GetIntval(); // if(traj_id != 1247){ // mtuple->DeleteIfAllowed(); // continue; // } if(res_id.find(traj_id) != res_id.end()){ mtuple->DeleteIfAllowed(); continue; } int m = ((CcInt*)mtuple->GetAttribute(GM_MODE))->GetIntval();//bit index // Rectangle<3>* mt_box = (Rectangle<3>*)mtuple->GetAttribute(GM_BOX); // printf("%.6f %.6f\n", mt_box->MinD(0), mt_box->MaxD(0)); // assert((int)(ARR_SIZE(str_tm) - 1 - m) == bit_pos); // cout<<GetTMStrExt(m)<<" bit_pos "<<bit_pos<<"m "<<m<<endl; if(bit_pos == TM_WALK){ assert(m == bit_pos || m >= sin_mode_no); }else{ assert(m == bit_pos || m == (bit_pos + sin_mode_no) || m == (bit_pos + 2*sin_mode_no)); } // cout<<"traj id "<<traj_id<<endl; ///////////////////////////////////////////////////////////// //////////////////// get trajectory////////////////////////// ///////////////////////////////////////////////////////////// MPoint* mo2 = (MPoint*)mtuple->GetAttribute(GM_SUBTRIP); int div_pos = ((CcInt*)mtuple->GetAttribute(GM_DIV))->GetIntval(); int start = -1; int end = -1; if(div_pos < 0){//single mode case start = 0; end = mo2->GetNoComponents(); }else{// a pair of modes if(bit_pos == TM_WALK){ if(sin_mode_no <= m && m < 2*sin_mode_no){//second part start = div_pos; end = mo2->GetNoComponents(); }else if(m >= 2*sin_mode_no && m < 3*sin_mode_no){//first part start = 0; end = div_pos; }else{ assert(false); } }else{ ///////other modes if(sin_mode_no <= m && m < 2*sin_mode_no){ start = 0; end = div_pos; }else if(m >= 2*sin_mode_no && m < 3*sin_mode_no){ start = div_pos; end = mo2->GetNoComponents(); }else{ assert(false); } } } assert(0 <= start && start < end); bool query_res = CheckMPoint(mo2, start, end, time_span, &query_reg); if(query_res){//////return sub trips oid_list.push_back(traj_id); res_id.insert(traj_id); } /////////////////////////////////////////////////////////// mtuple->DeleteIfAllowed(); } } /* traverse TMRTree to find units that intersect the query box query mode is multiple modes */ void QueryTM::MulMode_Filter1(TM_RTree<3,TupleId>* tmrtree, Rectangle<3> query_box, vector<bool> bit_pos, Relation* units_rel) { //////////////////////////////////////////////////////////////// Interval<Instant> time_span; Instant st(instanttype); Instant et(instanttype); st.ReadFrom(query_box.MinD(0)); time_span.start = st; time_span.lc = true; et.ReadFrom(query_box.MaxD(0)); time_span.end = et; time_span.rc = false; double min[2], max[2]; min[0] = query_box.MinD(1); min[1] = query_box.MinD(2); max[0] = query_box.MaxD(1); max[1] = query_box.MaxD(2); Rectangle<2> spatial_box(true, min, max); Region query_reg(spatial_box); //////////////////////////////////////////////////////////////// // cout<<"SinModefilter query box "<<query_box<<endl; queue<SmiRecordId> query_list; query_list.push(tmrtree->RootRecordId()); int sin_mode_no = ARR_SIZE(str_tm); // cout<<"bit pos "<<bit_pos<<endl; int node_count = 0; while(query_list.empty() == false){ SmiRecordId nodeid = query_list.front(); query_list.pop(); TM_RTreeNode<3, TupleId>* node = tmrtree->GetMyNode(nodeid,false, tmrtree->MinEntries(0), tmrtree->MaxEntries(0)); bitset<TM_SUM_NO> node_bit(node->GetTMValue()); // cout<<nodeid<<" "<<node_bit.to_string()<<endl; bool node_mode = false; for(unsigned int i = 0;i < bit_pos.size();i++){//check existence if(bit_pos[i] == false || i == TM_WALK) continue; ////for other modes, connected to m + walk/////////// if(node_bit.test(i) || node_bit.test(i + sin_mode_no) || node_bit.test(i + 2*sin_mode_no)){ node_mode = true; break; } } ////////////////////////////////////////////////////////////// if(bit_pos[TM_WALK]){//////////including walking if(node_bit.test(TM_WALK) || node_bit.test(sin_mode_no + TM_INDOORWALK) || node_bit.test(sin_mode_no + TM_WALKINDOOR)){ node_mode = true; } } // cout<<endl<<GetModeStringExt(node->GetTMValue())<<" "<<node_mode<<endl; if(node_mode){ /* cout<<"node id "<<nodeid <<" mode "<<GetModeStringExt(node->GetTMValue())<<endl;*/ if(node->IsLeaf()){ for(int j = 0;j < node->EntryCount();j++){ R_TreeLeafEntry<3, TupleId> e = (R_TreeLeafEntry<3, TupleId>&)(*node)[j]; if(e.box.Intersects(query_box)){ //query window unit_tid_list.push_back(e.info); } } }else{ for(int j = 0;j < node->EntryCount();j++){//finish R_TreeInternalEntry<3> e = (R_TreeInternalEntry<3>&)(*node)[j]; if(e.box.Intersects(query_box)){ //query window query_list.push(e.pointer); } } } node_count++; } delete node; } cout<<node_count<<" nodes accessed " <<unit_tid_list.size()<<" candidates "<<endl; } /* traverse ADRTree to find units that intersect the query box query mode is multiple modes */ void QueryTM::MulMode_Filter2(TM_RTree<3,TupleId>* tmrtree, Rectangle<3> query_box, vector<bool> bit_pos, Relation* units_rel) { // cout<<"SinModefilter 3DRtree query box "<<query_box<<endl; queue<SmiRecordId> query_list; query_list.push(tmrtree->RootRecordId()); int sin_mode_no = (int)ARR_SIZE(str_tm); int node_count = 0; while(query_list.empty() == false){ SmiRecordId nodeid = query_list.front(); query_list.pop(); TM_RTreeNode<3, TupleId>* node = tmrtree->GetMyNode(nodeid,false, tmrtree->MinEntries(0), tmrtree->MaxEntries(0)); bitset<TM_SUM_NO> node_bit(node->GetTMValue()); bool node_mode = false; for(unsigned int i = 0;i < bit_pos.size();i++){//check existence if(bit_pos[i] == false || i == TM_WALK) continue; ////for other modes, connected to m + walk/////////// if(node_bit.test(i) || node_bit.test(i + sin_mode_no) || node_bit.test(i + 2*sin_mode_no)){ node_mode = true; break; } } /////////////////more than two modes//////////////////////// //////////////can not be only walk///////////////////////// if(bit_pos[TM_WALK]){//////////including walking if(node_bit.test(TM_WALK) || node_bit.test(sin_mode_no + TM_INDOORWALK) || node_bit.test(sin_mode_no + TM_WALKINDOOR)){ node_mode = true; } } if(node_mode){ if(node->IsLeaf()){ for(int j = 0;j < node->EntryCount();j++){ R_TreeLeafEntry<3, TupleId> e = (R_TreeLeafEntry<3, TupleId>&)(*node)[j]; Tuple* mtuple = units_rel->GetTuple(e.info, false); // int mode = // ((CcInt*)mtuple->GetAttribute(GM_MODE))->GetIntval(); if(e.box.Intersects(query_box)){ // cout<<GetTMStrExt(mode)<<endl; int mode = ((CcInt*)mtuple->GetAttribute(GM_MODE))->GetIntval(); bool res = false; if(mode < sin_mode_no){ if(bit_pos[mode]) res = true; }else if(sin_mode_no <= mode && mode < 2*sin_mode_no){ int m1 = mode - sin_mode_no; int m2= TM_WALK; if(bit_pos[m1] || bit_pos[m2]) res = true; }else if(2*sin_mode_no <= mode && mode < 3*sin_mode_no){ int m1 = TM_WALK; int m2 = mode - 2*sin_mode_no; if(bit_pos[m1] || bit_pos[m2]) res = true; }else{ assert(false); } if(res){ unit_tid_list.push_back(e.info); } } // for(int i = 0;i < (int)bit_pos.size();i++){ // if(bit_pos[i] == false) continue; // if(bit_pos[i] == TM_WALK){ // if(mode >= sin_mode_no && e.box.Intersects(query_box)){ // unit_tid_list.push_back(e.info); // } // }else{ // if( ((i == sin_mode_no) || (i + sin_mode_no) == mode || // (i + 2*sin_mode_no) == mode) && // e.box.Intersects(query_box)){//query window, mode check // unit_tid_list.push_back(e.info); // } // } // // } mtuple->DeleteIfAllowed(); } }else{ for(int j = 0;j < node->EntryCount();j++){//finish R_TreeInternalEntry<3> e = (R_TreeInternalEntry<3>&)(*node)[j]; if(e.box.Intersects(query_box)){ //query window query_list.push(e.pointer); } } } node_count++; } delete node; } cout<<node_count<<" nodes accessed " <<unit_tid_list.size()<<" candidates "<<endl; } /* 3DRtree for multiple modes, there are no modes information in the node */ void QueryTM::MulMode_Filter3(TM_RTree<3,TupleId>* tmrtree, Rectangle<3> query_box, vector<bool> bit_pos, Relation* units_rel) { // cout<<"SinModefilter 3DRtree query box "<<query_box<<endl; queue<SmiRecordId> query_list; query_list.push(tmrtree->RootRecordId()); int sin_mode_no = (int)ARR_SIZE(str_tm); int node_count = 0; while(query_list.empty() == false){ SmiRecordId nodeid = query_list.front(); query_list.pop(); TM_RTreeNode<3, TupleId>* node = tmrtree->GetMyNode(nodeid,false, tmrtree->MinEntries(0), tmrtree->MaxEntries(0)); if(node->IsLeaf()){ for(int j = 0;j < node->EntryCount();j++){ R_TreeLeafEntry<3, TupleId> e = (R_TreeLeafEntry<3, TupleId>&)(*node)[j]; Tuple* mtuple = units_rel->GetTuple(e.info, false); int mode = ((CcInt*)mtuple->GetAttribute(GM_MODE))->GetIntval(); if(e.box.Intersects(query_box)){ // cout<<GetTMStrExt(mode)<<endl; bool res = false; if(mode < sin_mode_no){ if(bit_pos[mode]) res = true; }else if(sin_mode_no <= mode && mode < 2*sin_mode_no){ int m1 = mode - sin_mode_no; int m2= TM_WALK; if(bit_pos[m1] || bit_pos[m2]) res = true; }else if(2*sin_mode_no <= mode && mode < 3*sin_mode_no){ int m1 = TM_WALK; int m2 = mode - 2*sin_mode_no; if(bit_pos[m1] || bit_pos[m2]) res = true; }else{ assert(false); } if(res){ unit_tid_list.push_back(e.info); } } mtuple->DeleteIfAllowed(); } }else{ for(int j = 0;j < node->EntryCount();j++){//finish R_TreeInternalEntry<3> e = (R_TreeInternalEntry<3>&)(*node)[j]; if(e.box.Intersects(query_box)){ //query window query_list.push(e.pointer); } } } node_count++; delete node; } cout<<node_count<<" nodes accessed " <<unit_tid_list.size()<<" candidates "<<endl; } /* from the result by traversing TMRtree, check the precise value just return the complete trajectory if its sub trip satisfies the condition. it needs much work to decompose the trajectory into pieces and it might not be necessary. multiple modes */ void QueryTM::MulMode_Refinement(Rectangle<3> query_box, vector<bool> bit_pos, Relation* units_rel, int mode_count) { // cout<<"refinement candidate number "<<unit_tid_list.size()<<endl; Interval<Instant> time_span; Instant st(instanttype); Instant et(instanttype); st.ReadFrom(query_box.MinD(0)); time_span.start = st; time_span.lc = true; et.ReadFrom(query_box.MaxD(0)); time_span.end = et; time_span.rc = false; double min[2], max[2]; min[0] = query_box.MinD(1); min[1] = query_box.MinD(2); max[0] = query_box.MaxD(1); max[1] = query_box.MaxD(2); Rectangle<2> spatial_box(true, min, max); Region query_reg(spatial_box); map<int, Traj_Mode> res_traj;//binary search tree int sin_mode_no = ARR_SIZE(str_tm); for(unsigned int i = 0;i < unit_tid_list.size();i++){ Tuple* mtuple = units_rel->GetTuple(unit_tid_list[i], false); int traj_id = ((CcInt*)mtuple->GetAttribute(GM_TRAJ_ID))->GetIntval(); int m = ((CcInt*)mtuple->GetAttribute(GM_MODE))->GetIntval(); MPoint* mp = (MPoint*)mtuple->GetAttribute(GM_SUBTRIP); int div_pos = ((CcInt*)mtuple->GetAttribute(GM_DIV))->GetIntval(); map<int, Traj_Mode>::iterator iter = res_traj.find(traj_id); // cout<<"traj_id "<<traj_id<<" "<<GetTMStrExt(m)<<endl; // cout<<*mp<<endl; if(iter == res_traj.end()){//not exist, insert into the tree // cout<<"new tuple "<<endl; int start = -1; int end = -1; bitset<ARR_SIZE(str_tm)> m_bit; m_bit.reset(); if(m < sin_mode_no){//////////0-8 if(bit_pos[m]){ //such a mode exists in the query start = 0; end = mp->GetNoComponents(); }else{//ignore if does not exist cout<<"should not occur"<<endl; mtuple->DeleteIfAllowed(); assert(false); continue; } m_bit.set(m); if(CheckMPoint(mp, start, end, time_span, &query_reg)){ Traj_Mode traj_mode(m_bit); res_traj.insert(pair<int, Traj_Mode>(traj_id, traj_mode)); } }else if(sin_mode_no <= m && m < 2*sin_mode_no){ ///9-17 int m1 = m - sin_mode_no; int m2 = TM_WALK; if(bit_pos[m1] && bit_pos[m2]){///both exist /* start = 0; end = mp->GetNoComponents(); m_bit.set(m1); m_bit.set(m2);*/ start = 0; end = div_pos; bool res1 = CheckMPoint(mp, start, end, time_span, &query_reg); if(res1) m_bit.set(m1); start = div_pos; end = mp->GetNoComponents(); bool res2 = CheckMPoint(mp, start, end, time_span, &query_reg); if(res2) m_bit.set(m2); if(res1 || res2){ Traj_Mode traj_mode(m_bit); res_traj.insert(pair<int, Traj_Mode>(traj_id, traj_mode)); } }else if(bit_pos[m1] && bit_pos[m2] == false){ start = 0; end = div_pos; m_bit.set(m1); if(CheckMPoint(mp, start, end, time_span, &query_reg)){ Traj_Mode traj_mode(m_bit); res_traj.insert(pair<int, Traj_Mode>(traj_id, traj_mode)); } }else if(bit_pos[m1] == false && bit_pos[m2]){ start = div_pos; end = mp->GetNoComponents(); m_bit.set(m2); if(CheckMPoint(mp, start, end, time_span, &query_reg)){ Traj_Mode traj_mode(m_bit); res_traj.insert(pair<int, Traj_Mode>(traj_id, traj_mode)); } }else{ assert(false); } }else if(2*sin_mode_no <= m && m < 3*sin_mode_no){//18-26 int m1 = TM_WALK; int m2 = m - 2*sin_mode_no; if(bit_pos[m1] && bit_pos[m2]){ // start = 0; // end = mp->GetNoComponents(); // m_bit.set(m1); // m_bit.set(m2); start = 0; end = div_pos; bool res1 = CheckMPoint(mp, start, end, time_span, &query_reg); if(res1) m_bit.set(m1); start = div_pos; end = mp->GetNoComponents(); bool res2 = CheckMPoint(mp, start, end, time_span, &query_reg); if(res2) m_bit.set(m2); if(res1 || res2){ Traj_Mode traj_mode(m_bit); res_traj.insert(pair<int, Traj_Mode>(traj_id, traj_mode)); } }else if(bit_pos[m1] && bit_pos[m2] == false){ start = 0; end = div_pos; m_bit.set(m1); if(CheckMPoint(mp, start, end, time_span, &query_reg)){ Traj_Mode traj_mode(m_bit); res_traj.insert(pair<int, Traj_Mode>(traj_id, traj_mode)); } }else if(bit_pos[m1] == false && bit_pos[m2]){ start = div_pos; end = mp->GetNoComponents(); m_bit.set(m2); if(CheckMPoint(mp, start, end, time_span, &query_reg)){ Traj_Mode traj_mode(m_bit); res_traj.insert(pair<int, Traj_Mode>(traj_id, traj_mode)); } }else{ assert(false); } }else{ assert(false); } //////temporal and spatial condition//////////////// // if(CheckMPoint(mp, start, end, time_span, &query_reg)){ // Traj_Mode traj_mode(m_bit); // res_traj.insert(pair<int, Traj_Mode>(traj_id, traj_mode)); // } }else{ // iter->second.Print(); if(iter->second.Mode_Count() == mode_count){//find the trajectory //do nothing //cout<<"exist already "<<endl; }else{ assert(iter->second.Mode_Count() < mode_count); //check whether a new bit has to be marked/// //satisfy temporal and spatial coniditon//// /// need such a mode and does not exist or find already/// int start = -1; int end = -1; bitset<ARR_SIZE(str_tm)> m_bit; m_bit.reset(); if(m < sin_mode_no){//////////////0-8 //already results if(bit_pos[m] == false || iter->second.modebits.test(m)){ mtuple->DeleteIfAllowed(); continue; } if(bit_pos[m]){ start = 0; end = mp->GetNoComponents(); m_bit.set(m); } ///////////temporal and spatial checking////////////////// ////////mark the new bit//////////////////////// if(CheckMPoint(mp, start, end, time_span, &query_reg)){ iter->second.modebits = iter->second.modebits | m_bit; } }else if(sin_mode_no <= m && m < 2*sin_mode_no){//9-17 int m1 = m - sin_mode_no; int m2 = TM_WALK; if(bit_pos[m1] && iter->second.modebits.test(m1) == false){ start = 0; end = div_pos; if(CheckMPoint(mp, start, end, time_span, &query_reg)){ m_bit.set(m1); iter->second.modebits = iter->second.modebits | m_bit; } } if(bit_pos[m2] && iter->second.modebits.test(m2) == false){ start = div_pos; end = mp->GetNoComponents(); if(CheckMPoint(mp, start, end, time_span, &query_reg)){ m_bit.set(m2); iter->second.modebits = iter->second.modebits | m_bit; } } }else if(2*sin_mode_no <= m && m < 3*sin_mode_no){//18-26 int m1 = TM_WALK; int m2 = m - 2*sin_mode_no; if(bit_pos[m1] && iter->second.modebits.test(m1) == false){ start = 0; end = div_pos; if(CheckMPoint(mp, start, end, time_span, &query_reg)){ m_bit.set(m1); iter->second.modebits = iter->second.modebits | m_bit; } } if(bit_pos[m2] && iter->second.modebits.test(m2) == false){ start = div_pos; end = mp->GetNoComponents(); if(CheckMPoint(mp, start, end, time_span, &query_reg)){ m_bit.set(m2); iter->second.modebits = iter->second.modebits | m_bit; } } }else{ assert(false); } } } /////////////////////////////////////////////////////////// mtuple->DeleteIfAllowed(); } map<int, Traj_Mode>::iterator iter; for(iter = res_traj.begin(); iter != res_traj.end();iter++){ if(iter->second.Mode_Count() == mode_count){ // iter->second.Print(); oid_list.push_back(iter->first); } } } /* check the spatial and temporal condition of a sub trip */ bool QueryTM::CheckMPoint(MPoint* mp, int start, int end, Interval<Instant>& time_span, Region* query_reg) { // cout<<"CheckMPoint "<<endl; for(;start < end; start++){ UPoint up; mp->Get(start, up); // ///////////////precise value checking///////////////// if(time_span.Intersects(up.timeInterval)){ UPoint up2; up.AtInterval(time_span, up2);///////////time interval if(!AlmostEqual(up2.p0, up2.p1)){ HalfSegment hs(true, up2.p0, up2.p1); if(query_reg->Intersects(hs)){//find the result, terminate return true; } }else{ if(up2.p0.Inside(*query_reg)){//find the result, terminate return true; } } } } return false; } /* simple (baseline) method to test the correctness */ void QueryTM::RangeQuery(Relation* rel1, Relation* rel2) { // cout<<rel1->GetNoTuples()<<" "<<rel2->GetNoTuples()<<endl; assert(rel2->GetNoTuples() == 1); Tuple* q_tuple = rel2->GetTuple(1, false); Periods* peri = (Periods*)q_tuple->GetAttribute(GM_TIME); Rectangle<2>* q_box = (Rectangle<2>*)q_tuple->GetAttribute(GM_SPATIAL); string mode = ((CcString*)q_tuple->GetAttribute(GM_Q_MODE))->GetValue(); vector<long> seq_tm; int type = ModeType(mode, seq_tm); //seqtm bit value to integer if(type < 0){ cout<<"mode error "<<mode<<endl; q_tuple->DeleteIfAllowed(); return; } if(type == SINMODE){ // cout<<"single mode "<<endl; int m = GetTM(mode); Sin_RangeQuery(rel1, peri, q_box, m); } if(type == MULMODE){ Mul_RangeQuery(rel1, peri, q_box, seq_tm[0]); } if(type == SEQMODE){ Seq_RangeQuery(rel1, peri, q_box, seq_tm); } q_tuple->DeleteIfAllowed(); } /* a single mode: baseline method */ void QueryTM::Sin_RangeQuery(Relation* rel1, Periods* peri, Rectangle<2>* q_box, int m) { Interval<Instant> time_span; peri->Get(0, time_span); Region query_reg(*q_box); // cout<<*peri<<" "<<*q_box<<" "<<GetTMStrExt(m)<<endl; for(int i = 1;i <= rel1->GetNoTuples();i++){ Tuple* tuple = rel1->GetTuple(i, false); int traj_id = ((CcInt*)tuple->GetAttribute(GENMO_OID))->GetIntval(); GenMO* mo1 = (GenMO*)tuple->GetAttribute(GENMO_TRIP1); // if(traj_id != 1247){ // tuple->DeleteIfAllowed(); // continue; // } Periods* mo_t = new Periods(0); mo1->DefTime(*mo_t); if(mo_t->Intersects(*peri) == false){ delete mo_t; tuple->DeleteIfAllowed(); continue; } delete mo_t; MPoint* mo2 = (MPoint*)tuple->GetAttribute(GENMO_TRIP2); MPoint* sub_mo = new MPoint(0); mo2->AtPeriods(*peri, *sub_mo); if(sub_mo->BoundingBoxSpatial().Intersects(*q_box) == false){ delete sub_mo; tuple->DeleteIfAllowed(); continue; } MReal* mode_index_tmp = new MReal(0); // mo1->IndexOnUnits(mode_index_tmp); mo1->IndexOnUnits2(mode_index_tmp); MReal* mode_index = new MReal(0); mode_index_tmp->AtPeriods(*peri, *mode_index); // cout<<*mode_index<<endl; delete mode_index_tmp; if(ContainMode1_Sin(mode_index, m) == false){ delete sub_mo; delete mode_index; tuple->DeleteIfAllowed(); continue; } ///////////////////////////////////////////////////// bool query_res = false; for(int j = 0;j < sub_mo->GetNoComponents();j++){ UPoint up; sub_mo->Get(j, up); if(time_span.Intersects(up.timeInterval)){ UPoint up2; up.AtInterval(time_span, up2);///////////time interval if(!AlmostEqual(up2.p0, up2.p1)){ HalfSegment hs(true, up2.p0, up2.p1); if(query_reg.Intersects(hs)){//find the result, terminate if(ContainMode2_Sin(mode_index, up2.timeInterval, m)){ query_res = true; break; } } }else{ if(up2.p0.Inside(query_reg)){//find the result, terminate if(ContainMode2_Sin(mode_index, up2.timeInterval, m)){ query_res = true; break; } } } } } delete sub_mo; delete mode_index; if(query_res){ oid_list.push_back(traj_id); } tuple->DeleteIfAllowed(); } } /* baseline method: multiple modes */ void QueryTM::Mul_RangeQuery(Relation* rel1, Periods* peri, Rectangle<2>* q_box, int m) { Interval<Instant> time_span; peri->Get(0, time_span); Region query_reg(*q_box); // the first nine bitset<ARR_SIZE(str_tm)> modebits(m);//integer from bit index cout<<"baseline method multiple mode "<<GetModeStringExt(m) <<" "<<modebits.to_string()<<endl; assert(modebits.count() >= 2); vector<bool> bit_pos(ARR_SIZE(str_tm), false);// first part enough int mode_count = 0; for(unsigned int i = 0;i < modebits.size();i++){ if(modebits.test(i)){ bit_pos[i] = true; mode_count++; } } map<int, Traj_Mode> res_traj;//binary search tree for(int i = 1;i <= rel1->GetNoTuples();i++){ Tuple* tuple = rel1->GetTuple(i, false); int traj_id = ((CcInt*)tuple->GetAttribute(GENMO_OID))->GetIntval(); GenMO* mo1 = (GenMO*)tuple->GetAttribute(GENMO_TRIP1); Periods* mo_t = new Periods(0); mo1->DefTime(*mo_t); if(mo_t->Intersects(*peri) == false){ delete mo_t; tuple->DeleteIfAllowed(); continue; } delete mo_t; MPoint* mo2 = (MPoint*)tuple->GetAttribute(GENMO_TRIP2); MPoint* sub_mo = new MPoint(0); mo2->AtPeriods(*peri, *sub_mo); if(sub_mo->BoundingBoxSpatial().Intersects(*q_box) == false){ delete sub_mo; tuple->DeleteIfAllowed(); continue; } /////////////////////////////////////////////////////////////// MReal* mode_index_tmp = new MReal(0); mo1->IndexOnUnits(mode_index_tmp); MReal* mode_index = new MReal(0); mode_index_tmp->AtPeriods(*peri, *mode_index); // cout<<*mode_index<<endl; delete mode_index_tmp; if(ContainMode1_Mul(mode_index, bit_pos, mode_count) == false){ delete sub_mo; delete mode_index; tuple->DeleteIfAllowed(); continue; } ///////////////spatial and temporal checking////////////////////////// for(int j = 0;j < sub_mo->GetNoComponents();j++){ UPoint up; sub_mo->Get(j, up); if(time_span.Intersects(up.timeInterval)){ UPoint up2; up.AtInterval(time_span, up2);///////////time interval if(!AlmostEqual(up2.p0, up2.p1)){ HalfSegment hs(true, up2.p0, up2.p1); if(query_reg.Intersects(hs)){//find the result, terminate ContainMode2_Mul(res_traj, mode_index, up2.timeInterval, bit_pos, traj_id, mode_count); } }else{ if(up2.p0.Inside(query_reg)){//find the result, terminate ContainMode2_Mul(res_traj, mode_index, up2.timeInterval, bit_pos, traj_id, mode_count); } } } } delete sub_mo; delete mode_index; tuple->DeleteIfAllowed(); } /////////////////////collect the result/////////////////////////// map<int, Traj_Mode>::iterator iter; for(iter = res_traj.begin(); iter != res_traj.end();iter++){ if(iter->second.Mode_Count() == mode_count){ oid_list.push_back(iter->first); } } } /* check whether a mode is included */ bool QueryTM::ContainMode1_Sin(MReal* mode_index, int m) { for(int i = 0;i < mode_index->GetNoComponents();i++){ UReal ur; mode_index->Get(i, ur); if((int)(ur.a) == m){ return true; } } return false; } /* check several modes are included all of modes have to be considered */ bool QueryTM::ContainMode1_Mul(MReal* mode_index, vector<bool> bit_pos, int m_count) { int m_no = 0; vector<bool> input_mode(ARR_SIZE(str_tm), false); for(int i = 0;i < mode_index->GetNoComponents();i++){ UReal ur; mode_index->Get(i, ur); int m = (int)ur.a; input_mode[m] = true; } for(unsigned int i = 0;i < bit_pos.size();i++){ if(input_mode[i] && bit_pos[i]) m_no++; } if(m_no == m_count) return true; return false; } /* from mreal, get a sub unit, check the transportation mode */ bool QueryTM::ContainMode2_Sin(MReal* mode_index, Interval<Instant>& t, int m) { for(int j = 0;j < mode_index->GetNoComponents();j++){ UReal ur; mode_index->Get(j, ur); if(t.Intersects(ur.timeInterval)){ UReal ur2; ur.AtInterval(t, ur2);///////////time interval if((int)(ur2.a) == m)return true; } } return false; } /* from mreal, get a sub unit, check the transportation mode only mark bit (modes) that are asked by the query */ void QueryTM::ContainMode2_Mul(map<int, Traj_Mode>& res_traj, MReal* mode_index, Interval<Instant>& t, vector<bool> bit_pos, int traj_id, int mode_count) { bool res = false; int m = -1; for(int j = 0;j < mode_index->GetNoComponents();j++){ UReal ur; mode_index->Get(j, ur); if(t.Intersects(ur.timeInterval)){ UReal ur2; ur.AtInterval(t, ur2);///////////time interval m = (int)(ur2.a); if(bit_pos[m]){ res = true; break; } } } if(res == false) return; map<int, Traj_Mode>::iterator iter = res_traj.find(traj_id); if(iter == res_traj.end()){/////////a new one, insert bitset<ARR_SIZE(str_tm)> m_bit; m_bit.reset(); m_bit.set(m); Traj_Mode traj_mode(m_bit); res_traj.insert(pair<int, Traj_Mode>(traj_id, traj_mode)); }else{ if(iter->second.Mode_Count() == mode_count)return; bitset<ARR_SIZE(str_tm)> m_bit;/////mark the new bit mode m_bit.reset(); m_bit.set(m); iter->second.modebits = iter->second.modebits | m_bit; } } /* baseline method to check a sequence of modes */ void QueryTM::Seq_RangeQuery(Relation* rel1, Periods* peri, Rectangle<2>* q_box, vector<long> seq_tm) { // for(unsigned int i = 0;i < seq_tm.size();i++){ // cout<<GetTMStrExt(seq_tm[i])<<" "; // } Interval<Instant> time_span; peri->Get(0, time_span); Region query_reg(*q_box); vector<bool> bit_pos(ARR_SIZE(str_tm), false);// first part enough bitset<ARR_SIZE(str_tm)> modebits;//different multiple modes modebits.reset();//indoor;walk;bus;walk, the result is 3 instead of 4 for(unsigned int i = 0;i < seq_tm.size();i++){ bit_pos[seq_tm[i]] = true; modebits.set(seq_tm[i], 1); } int mode_count = modebits.count(); //some modes appear more then once map<int, Seq_Mode> res_traj;//binary search tree for(int i = 1;i <= rel1->GetNoTuples();i++){ Tuple* tuple = rel1->GetTuple(i, false); int traj_id = ((CcInt*)tuple->GetAttribute(GENMO_OID))->GetIntval(); GenMO* mo1 = (GenMO*)tuple->GetAttribute(GENMO_TRIP1); Periods* mo_t = new Periods(0); mo1->DefTime(*mo_t); if(mo_t->Intersects(*peri) == false){ delete mo_t; tuple->DeleteIfAllowed(); continue; } delete mo_t; MPoint* mo2 = (MPoint*)tuple->GetAttribute(GENMO_TRIP2); MPoint* sub_mo = new MPoint(0); mo2->AtPeriods(*peri, *sub_mo); if(sub_mo->BoundingBoxSpatial().Intersects(*q_box) == false){ delete sub_mo; tuple->DeleteIfAllowed(); continue; } /////////////////////////////////////////////////////////////// MReal* mode_index_tmp = new MReal(0); mo1->IndexOnUnits(mode_index_tmp); MReal* mode_index = new MReal(0); mode_index_tmp->AtPeriods(*peri, *mode_index); // cout<<*mode_index<<endl; delete mode_index_tmp; //such a sub trip, all modes are included//////////// if(ContainMode1_Mul(mode_index, bit_pos, mode_count) == false){ delete sub_mo; delete mode_index; tuple->DeleteIfAllowed(); continue; } ///////////////spatial and temporal checking////////////////////////// for(int j = 0;j < sub_mo->GetNoComponents();j++){ UPoint up; sub_mo->Get(j, up); if(time_span.Intersects(up.timeInterval)){ UPoint up2; up.AtInterval(time_span, up2);///////////time interval if(!AlmostEqual(up2.p0, up2.p1)){ HalfSegment hs(true, up2.p0, up2.p1); if(query_reg.Intersects(hs)){// ContainMode3_Seq(res_traj, mode_index, bit_pos, up2.timeInterval, traj_id, seq_tm); } }else{ if(up2.p0.Inside(query_reg)){// ContainMode3_Seq(res_traj, mode_index, bit_pos, up2.timeInterval, traj_id, seq_tm); } } } } delete sub_mo; delete mode_index; tuple->DeleteIfAllowed(); } /////////////////////collect the result/////////////////////////// map<int, Seq_Mode>::iterator iter; for(iter = res_traj.begin(); iter != res_traj.end();iter++){ if(iter->second.Status()){ oid_list.push_back(iter->first); } } } /* simple method: check a sequence of modes */ void QueryTM::ContainMode3_Seq(map<int, Seq_Mode>& res_traj, MReal* mode_index, vector<bool> bit_pos, Interval<Instant>& t, int traj_id, vector<long> seq_tm) { bool res = false; int m = -1; for(int j = 0;j < mode_index->GetNoComponents();j++){//check mode UReal ur; mode_index->Get(j, ur); if(t.Intersects(ur.timeInterval)){ UReal ur2; ur.AtInterval(t, ur2);///////////time interval m = (int)(ur2.a); if(bit_pos[m]){ res = true; break; } } } if(res == false) return; assert(0 <= m && m < (int)(ARR_SIZE(str_tm))); map<int, Seq_Mode>::iterator iter = res_traj.find(traj_id); if(iter == res_traj.end()){//a new one, insert double st = t.start.ToDouble(); double et = t.end.ToDouble(); MInt mp_tm(0); MakeTMUnit(mp_tm, st, et, m); Seq_Mode seq_m(mp_tm); res_traj.insert(pair<int, Seq_Mode>(traj_id, seq_m)); }else{ if(iter->second.Status()){//doing nothing, find the result already }else{ double st = t.start.ToDouble(); double et = t.end.ToDouble(); iter->second.Update(st, et, m); iter->second.CheckStatus(seq_tm); } } } /* TMRTree, filter step: a sequence of modes */ void QueryTM::SeqMode_Filter1(TM_RTree<3,TupleId>* tmrtree, Rectangle<3> query_box, vector<bool> m_bit_list) { // for(unsigned int i = 0;i < m_bit_list.size();i++){ // cout<<" i "<<i<<" "<<m_bit_list[i]<<endl; // if(m_bit_list[i])cout<<GetTMStrExt(i)<<endl; // } ///////////////////////////////////////////////////////// Interval<Instant> time_span; Instant st(instanttype); Instant et(instanttype); st.ReadFrom(query_box.MinD(0)); time_span.start = st; time_span.lc = true; et.ReadFrom(query_box.MaxD(0)); time_span.end = et; time_span.rc = false; double min[2], max[2]; min[0] = query_box.MinD(1); min[1] = query_box.MinD(2); max[0] = query_box.MaxD(1); max[1] = query_box.MaxD(2); Rectangle<2> spatial_box(true, min, max); Region query_reg(spatial_box); ///////////////////////////////////////////////////////// queue<SmiRecordId> query_list; query_list.push(tmrtree->RootRecordId()); int node_count = 0; while(query_list.empty() == false){ SmiRecordId nodeid = query_list.front(); query_list.pop(); TM_RTreeNode<3, TupleId>* node = tmrtree->GetMyNode(nodeid,false, tmrtree->MinEntries(0), tmrtree->MaxEntries(0)); bitset<TM_SUM_NO> node_bit(node->GetTMValue()); // cout<<nodeid<<" "<<node_bit.to_string()<<endl; bool node_mode = false; for(unsigned int i = 0;i < node_bit.size();i++){ // if(node_bit.test(i))cout<<"i "<<i<<endl; if(node_bit.test(i) && m_bit_list[i]){ node_mode = true; break; } } // cout<<GetModeStringExt(node->GetTMValue())<<" "<<node_mode<<endl; if(node_mode){ if(node->IsLeaf()){ for(int j = 0;j < node->EntryCount();j++){ R_TreeLeafEntry<3, TupleId> e = (R_TreeLeafEntry<3, TupleId>&)(*node)[j]; if(e.box.Intersects(query_box)){ //query window unit_tid_list.push_back(e.info); } } }else{ for(int j = 0;j < node->EntryCount();j++){ R_TreeInternalEntry<3> e = (R_TreeInternalEntry<3>&)(*node)[j]; if(e.box.Intersects(query_box)){ //query window query_list.push(e.pointer); } } } node_count++; } delete node; } cout<<node_count<<" nodes accessed " <<unit_tid_list.size()<<" candidates "<<endl; } /* filter step for a sequence of modes, ADRTree */ void QueryTM::SeqMode_Filter2(TM_RTree<3,TupleId>* tmrtree, Rectangle<3> query_box, Relation* units_rel, vector<bool> m_bit_list) { // for(unsigned int i = 0;i < m_bit_list.size();i++){ // cout<<" i "<<i<<" "<<m_bit_list[i]<<endl; // if(m_bit_list[i])cout<<GetTMStrExt(i)<<endl; // } ///////////////////////////////////////////////////////// Interval<Instant> time_span; Instant st(instanttype); Instant et(instanttype); st.ReadFrom(query_box.MinD(0)); time_span.start = st; time_span.lc = true; et.ReadFrom(query_box.MaxD(0)); time_span.end = et; time_span.rc = false; double min[2], max[2]; min[0] = query_box.MinD(1); min[1] = query_box.MinD(2); max[0] = query_box.MaxD(1); max[1] = query_box.MaxD(2); Rectangle<2> spatial_box(true, min, max); Region query_reg(spatial_box); ///////////////////////////////////////////////////////// queue<SmiRecordId> query_list; query_list.push(tmrtree->RootRecordId()); int node_count = 0; while(query_list.empty() == false){ SmiRecordId nodeid = query_list.front(); query_list.pop(); TM_RTreeNode<3, TupleId>* node = tmrtree->GetMyNode(nodeid,false, tmrtree->MinEntries(0), tmrtree->MaxEntries(0)); bitset<TM_SUM_NO> node_bit(node->GetTMValue()); // cout<<nodeid<<" "<<node_bit.to_string()<<endl; bool node_mode = false; for(unsigned int i = 0;i < node_bit.size();i++){ // if(node_bit.test(i))cout<<"i "<<i<<endl; if(node_bit.test(i) && m_bit_list[i]){ node_mode = true; break; } } // cout<<GetModeStringExt(node->GetTMValue())<<" "<<node_mode<<endl; if(node_mode){ if(node->IsLeaf()){ for(int j = 0;j < node->EntryCount();j++){ R_TreeLeafEntry<3, TupleId> e = (R_TreeLeafEntry<3, TupleId>&)(*node)[j]; Tuple* mtuple = units_rel->GetTuple(e.info, false); if(e.box.Intersects(query_box)){ //query window int mode = ((CcInt*)mtuple->GetAttribute(GM_MODE))->GetIntval(); if(m_bit_list[mode]) unit_tid_list.push_back(e.info); } mtuple->DeleteIfAllowed(); } }else{ for(int j = 0;j < node->EntryCount();j++){ R_TreeInternalEntry<3> e = (R_TreeInternalEntry<3>&)(*node)[j]; if(e.box.Intersects(query_box)){ //query window query_list.push(e.pointer); } } } node_count++; } delete node; } cout<<node_count<<" nodes accessed " <<unit_tid_list.size()<<" candidates "<<endl; } /* filter step: a sequence of modes 3DRtree */ void QueryTM::SeqMode_Filter3(TM_RTree<3,TupleId>* tmrtree, Rectangle<3> query_box, Relation* units_rel, vector<bool> m_bit_list) { // for(unsigned int i = 0;i < m_bit_list.size();i++){ // cout<<" i "<<i<<" "<<m_bit_list[i]<<endl; // if(m_bit_list[i])cout<<GetTMStrExt(i)<<endl; // } ///////////////////////////////////////////////////////// Interval<Instant> time_span; Instant st(instanttype); Instant et(instanttype); st.ReadFrom(query_box.MinD(0)); time_span.start = st; time_span.lc = true; et.ReadFrom(query_box.MaxD(0)); time_span.end = et; time_span.rc = false; double min[2], max[2]; min[0] = query_box.MinD(1); min[1] = query_box.MinD(2); max[0] = query_box.MaxD(1); max[1] = query_box.MaxD(2); Rectangle<2> spatial_box(true, min, max); Region query_reg(spatial_box); ///////////////////////////////////////////////////////// queue<SmiRecordId> query_list; query_list.push(tmrtree->RootRecordId()); int node_count = 0; while(query_list.empty() == false){ SmiRecordId nodeid = query_list.front(); query_list.pop(); TM_RTreeNode<3, TupleId>* node = tmrtree->GetMyNode(nodeid,false, tmrtree->MinEntries(0), tmrtree->MaxEntries(0)); // cout<<GetModeStringExt(node->GetTMValue())<<" "<<node_mode<<endl; if(node->IsLeaf()){ for(int j = 0;j < node->EntryCount();j++){ R_TreeLeafEntry<3, TupleId> e = (R_TreeLeafEntry<3, TupleId>&)(*node)[j]; Tuple* mtuple = units_rel->GetTuple(e.info, false); if(e.box.Intersects(query_box)){ //query window int mode = ((CcInt*)mtuple->GetAttribute(GM_MODE))->GetIntval(); if(m_bit_list[mode]) unit_tid_list.push_back(e.info); } mtuple->DeleteIfAllowed(); } }else{ for(int j = 0;j < node->EntryCount();j++){ R_TreeInternalEntry<3> e = (R_TreeInternalEntry<3>&)(*node)[j]; if(e.box.Intersects(query_box)){ //query window query_list.push(e.pointer); } } } node_count++; delete node; } cout<<node_count<<" nodes accessed " <<unit_tid_list.size()<<" candidates "<<endl; } /* a sequence of transportation modes */ void QueryTM::SeqMode_Filter4(TM_RTree<3,TupleId>* tmrtree, Rectangle<3> query_box, vector<bool> bit_pos, Relation* units_rel) { MulMode_Filter1(tmrtree, query_box, bit_pos, units_rel); } inline double GetStartTimeValue(MPoint* mp, int pos) { assert(0 <= pos && pos < mp->GetNoComponents()); UPoint u; mp->Get(pos, u); return u.timeInterval.start.ToDouble(); } inline double GetEndTimeValue(MPoint* mp, int pos) { assert(0 <= pos && pos < mp->GetNoComponents()); UPoint u; mp->Get(pos, u); return u.timeInterval.end.ToDouble(); } /* refinement step for a sequence of modes */ void QueryTM::SeqMode_Refinement(Rectangle<3> query_box, vector<bool> bit_pos, Relation* units_rel, vector<long> seq_tm, vector<bool> m_bit_list) { Interval<Instant> time_span; Instant st(instanttype); Instant et(instanttype); st.ReadFrom(query_box.MinD(0)); time_span.start = st; time_span.lc = true; et.ReadFrom(query_box.MaxD(0)); time_span.end = et; time_span.rc = false; double min[2], max[2]; min[0] = query_box.MinD(1); min[1] = query_box.MinD(2); max[0] = query_box.MaxD(1); max[1] = query_box.MaxD(2); Rectangle<2> spatial_box(true, min, max); Region query_reg(spatial_box); map<int, Seq_Mode> res_traj;//binary search tree int sin_mode_no = ARR_SIZE(str_tm); for(unsigned int i = 0;i < unit_tid_list.size();i++){ Tuple* mtuple = units_rel->GetTuple(unit_tid_list[i], false); int traj_id = ((CcInt*)mtuple->GetAttribute(GM_TRAJ_ID))->GetIntval(); int m = ((CcInt*)mtuple->GetAttribute(GM_MODE))->GetIntval(); int div_pos = ((CcInt*)mtuple->GetAttribute(GM_DIV))->GetIntval(); // if(traj_id != 3594){ // mtuple->DeleteIfAllowed(); // continue; // } MPoint* mp = (MPoint*)mtuple->GetAttribute(GM_SUBTRIP); // cout<<"mtuple mode "<<GetTMStrExt(m)<<" "<<*mp<<endl; // cout<<"traj_id "<<traj_id<<" div_pos "<<div_pos<<endl; /////////////////////////////////////////////////////////// map<int, Seq_Mode>::iterator iter = res_traj.find(traj_id); if(iter == res_traj.end()){//a new mtuple or trajectory if(m < sin_mode_no){/////mode value 0-8 assert(div_pos == -1); if(bit_pos[m] == false){//this should be done by filter step mtuple->DeleteIfAllowed(); assert(false); continue; } int start = 0; int end = mp->GetNoComponents(); ////temporal and spatial checking///// bool res = CheckMPoint(mp, start, end, time_span, &query_reg); if(res == false){ mtuple->DeleteIfAllowed(); continue; } double st = GetStartTimeValue(mp, start); double et = GetEndTimeValue(mp, end - 1); // cout<<st<<" "<<et<<endl; MInt mp_tm(0); MakeTMUnit(mp_tm, st, et, m); // cout<<mp_tm<<endl; Seq_Mode seq_m(mp_tm); res_traj.insert(pair<int, Seq_Mode>(traj_id, seq_m)); }else if(sin_mode_no <= m && m < 2*sin_mode_no){ if(m_bit_list[m] == false){//this should be done by filter step mtuple->DeleteIfAllowed(); assert(false); continue; } int start = 0; int end = div_pos; bool res1 = CheckMPoint(mp, start, end, time_span, &query_reg); if(res1 == false){ mtuple->DeleteIfAllowed(); continue; } /////////////////////////////////////////////////////////////////// //////we split the two modes, store them separately in the tree//// /////////////////////////////////////////////////////////////////// double st1 = GetStartTimeValue(mp, start); double et1 = GetEndTimeValue(mp, div_pos - 1); MInt mp_tm(0); MakeTMUnit(mp_tm, st1, et1, m - sin_mode_no); Seq_Mode seq_m(mp_tm); res_traj.insert(pair<int, Seq_Mode>(traj_id, seq_m)); /////////////////////second part////////////////////////// start = div_pos; end = mp->GetNoComponents(); bool res2 = CheckMPoint(mp, start, end, time_span, &query_reg); if(res2 == false){ mtuple->DeleteIfAllowed(); continue; } iter = res_traj.find(traj_id); double st2 = GetStartTimeValue(mp, div_pos); double et2 = GetEndTimeValue(mp, mp->GetNoComponents() - 1); iter->second.Update(st2, et2, TM_WALK); }else if(2*sin_mode_no <= m && m < 3*sin_mode_no){ if(m_bit_list[m] == false){//this should be done by filter step mtuple->DeleteIfAllowed(); assert(false); continue; } int start = 0; int end = div_pos; bool res1 = CheckMPoint(mp, start, end, time_span, &query_reg); if(res1 == false){ mtuple->DeleteIfAllowed(); continue; } /////////////////////////////////////////////////////////////////// //////we split the two modes, store them separately in the tree//// /////////////////////////////////////////////////////////////////// double st1 = GetStartTimeValue(mp, start); double et1 = GetEndTimeValue(mp, div_pos - 1); MInt mp_tm(0); MakeTMUnit(mp_tm, st1, et1, TM_WALK); Seq_Mode seq_m(mp_tm); res_traj.insert(pair<int, Seq_Mode>(traj_id, seq_m)); //////////////////second part////////////////////////////////// start = div_pos; end = mp->GetNoComponents(); bool res2 = CheckMPoint(mp, start, end, time_span, &query_reg); if(res2 == false){ mtuple->DeleteIfAllowed(); continue; } iter = res_traj.find(traj_id); double st2 = GetStartTimeValue(mp, div_pos); double et2 = GetEndTimeValue(mp, mp->GetNoComponents() - 1); iter->second.Update(st2, et2, m - 2*sin_mode_no); }else{ assert(false); } }else{ if(iter->second.Status()){//as a result already ///doing nothing }else{/////need to update the value if(m < sin_mode_no){ // cout<<"update the mode"<<endl; if(bit_pos[m] == false){//this should be done by filter step mtuple->DeleteIfAllowed(); assert(false); continue; } int start = 0; int end = mp->GetNoComponents(); ////temporal and spatial checking///// bool res = CheckMPoint(mp, start, end, time_span, &query_reg); if(res == false){ mtuple->DeleteIfAllowed(); continue; } double st = GetStartTimeValue(mp, start); double et = GetEndTimeValue(mp, end - 1); iter->second.Update(st, et, m); iter->second.CheckStatus(seq_tm); }else if(sin_mode_no <= m && m < 2*sin_mode_no){ if(m_bit_list[m] == false){//this should be done by filter step mtuple->DeleteIfAllowed(); assert(false); continue; } int start = 0; int end = div_pos; ////temporal and spatial checking///// bool res1 = CheckMPoint(mp, start, end, time_span, &query_reg); if(res1 == false){ mtuple->DeleteIfAllowed(); continue; } /////////////////////////////////////////////////////////////////// //////we split the two modes, store them separately in the tree//// /////////////////////////////////////////////////////////////////// double st1 = GetStartTimeValue(mp, start); double et1 = GetEndTimeValue(mp, div_pos - 1); iter->second.Update(st1, et1, m - sin_mode_no); /////////////////////second part/////////////////// start = div_pos; end = mp->GetNoComponents(); ////temporal and spatial checking///// bool res2 = CheckMPoint(mp, start, end, time_span, &query_reg); if(res2 == false){ mtuple->DeleteIfAllowed(); iter->second.CheckStatus(seq_tm); continue; } double st2 = GetStartTimeValue(mp, div_pos); double et2 = GetEndTimeValue(mp, end - 1); iter->second.Update(st2, et2, TM_WALK); iter->second.CheckStatus(seq_tm); }else if(2*sin_mode_no <= m && m < 3*sin_mode_no){ if(m_bit_list[m] == false){//this should be done by filter step mtuple->DeleteIfAllowed(); assert(false); continue; } /////////////////////////////////////////////////////////////////// //////we split the two modes, store them separately in the tree//// /////////////////////////////////////////////////////////////////// int start = 0; int end = div_pos; ////temporal and spatial checking///// bool res1 = CheckMPoint(mp, start, end, time_span, &query_reg); if(res1 == false){ mtuple->DeleteIfAllowed(); continue; } double st1 = GetStartTimeValue(mp, start); double et1 = GetEndTimeValue(mp, div_pos - 1); iter->second.Update(st1, et1, TM_WALK); //////////////////second part/////////////////////////// start = div_pos; end = mp->GetNoComponents(); bool res2 = CheckMPoint(mp, start, end, time_span, &query_reg); if(res2 == false){ mtuple->DeleteIfAllowed(); iter->second.CheckStatus(seq_tm); continue; } double st2 = GetStartTimeValue(mp, div_pos); double et2 = GetEndTimeValue(mp, end - 1); iter->second.Update(st2, et2, m - 2*sin_mode_no); iter->second.CheckStatus(seq_tm); }else{ assert(false); } } } mtuple->DeleteIfAllowed(); } /////////////////////output the result//////////////////// map<int, Seq_Mode>::iterator iter; // cout<<"res count "<<res_traj.size()<<endl; for(iter = res_traj.begin(); iter != res_traj.end();iter++){ // iter->second.Print(); if(iter->second.Status()){ oid_list.push_back(iter->first); } } } /* update the moving integer: simply insert 1: simply insert and check the status later 2: insert, merge and the procedure of checking might be easy */ void Seq_Mode::Update(double st, double et, int m) { //////////simply insert, there might be gaps//////////////// UInt u; Instant start(instanttype); Instant end(instanttype); start.ReadFrom(st); end.ReadFrom(et); u.timeInterval.start = start; u.timeInterval.end = end; u.timeInterval.lc = true; u.timeInterval.rc = false; u.constValue.Set(m); u.SetDefined(true); seq_tm.Add(u); // seq_tm.SortbyUnitTime(); } /* check whether the sequence of mode is satisfied the current mode is set found only when its previous has been found */ void Seq_Mode::CheckStatus(vector<long> m_list) { // cout<<"check status "<<endl; if(seq_tm.GetNoComponents() < (int)m_list.size()) return;//impossible be true // vector<bool> flag(m_list.size(), false); // for(int i = 0;i < seq_tm.GetNoComponents();i++){ // UInt u; // seq_tm.Get(i, u); // int index = tm_index[u.constValue.GetValue()]; // assert(index >= 0 && index < (int)m_list.size()); // if(index == 0)flag[index] = true; // else{ // int prev = index - 1; // if(flag[prev]){//only when its previous has been found // flag[index] = true; // if(index == (int)m_list.size() - 1){//find the result // status = true; // break; // } // } // } // } seq_tm.SortbyUnitTime(); ///////////this checking is or will be consistent with the mtuples//// ////where the filter step only considers mtules with a pair of modes///// vector<int> tmp_res; for(int i = 0;i < seq_tm.GetNoComponents();i++){ UInt u; seq_tm.Get(i, u); int m = u.constValue.GetValue(); if(tmp_res.size() == 0){ if(m == m_list[0]){//put the start value tmp_res.push_back(m); } }else{ if(m == m_list[tmp_res.size()]){ tmp_res.push_back(m); if(tmp_res.size() == m_list.size()){ status = true; break; } } } } } /* create a new moving integer, only one unit */ void QueryTM::MakeTMUnit(MInt& mp_tm, double st, double et, int m) { UInt u; Instant start(instanttype); Instant end(instanttype); start.ReadFrom(st); end.ReadFrom(et); u.timeInterval.start = start; u.timeInterval.end = end; u.timeInterval.lc = true; u.timeInterval.rc = false; u.constValue.Set(m); u.SetDefined(true); mp_tm.Add(u); //simply insert }
[ "1016755439@qq.com" ]
1016755439@qq.com
67b7053a0bd5710c8cce7cbf7b7acce37b207bd7
b0212a94e7afc906889455f33e753f114b9f5d7e
/praduck/BaseTile.cpp
0e4b1da943c2d5b6e37200e11001894008a83278
[]
no_license
kumavis/plusplus-warrior
0796f8286c1a3df2832a30d56cf5f37c52e4f658
ab7e426930a0cd14df1d59857ac9a0bbbb9c5bbf
refs/heads/master
2023-08-18T14:50:24.794390
2014-02-14T19:58:19
2014-02-14T19:58:19
16,425,387
1
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
// // BaseTile.cpp // praduck // // Created by aaron davis on 1/31/14. // Copyright (c) 2014 aaron davis. All rights reserved. // #include "BaseTile.h" using namespace std; ostream& operator<<(ostream& os, BaseTile& tile) { os << tile.representation; return os; }
[ "aaron.d@apple.com" ]
aaron.d@apple.com
1b9b2973df1dd857efc63116ccecba7b5e490b13
11ce39581c9f1ddc4dce24590bb9143eb4f6aa2e
/style/SideBySideItem.cxx
eb8b415c88f1f4e7e07170cab15bc8920adee821
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
OS2World/DEV-UTIL-OpenJade
17cd31f0fb3944ca141715a291936b97a49fb6f1
c8090374fa863bab9824f63be27e2c9b2d3fa2bd
refs/heads/master
2016-08-04T23:57:47.412638
2015-01-06T16:43:20
2015-01-06T16:43:21
28,872,480
1
0
null
null
null
null
UTF-8
C++
false
false
451
cxx
#include "SideBySideItem.h" #ifdef DSSSL_NAMESPACE namespace DSSSL_NAMESPACE { #endif void SideBySideItemFlowObj::processInner(ProcessContext &context) { FOTBuilder &fotb = context.currentFOTBuilder(); fotb.startSideBySideItem(); CompoundFlowObj::processInner(context); fotb.endSideBySideItem(); } FlowObj *SideBySideItemFlowObj::copy(Collector &c) const { return new (c) SideBySideItemFlowObj(*this); } #ifdef DSSSL_NAMESPACE } #endif
[ "miturbide@nextstep.com.ec" ]
miturbide@nextstep.com.ec
6bbb71bb470f4cdea1a97691930479d2624e765b
fe122756f4f2bc04ede8d4239d40e6dcd0b31048
/GameClient/db/ModInfoDbm.cpp
b4fcbc7483f483b53411e0406a5ef87b08c49550
[]
no_license
jamesxia4/BattleMarine
7c060a6a26159b6423039de45ade39a03aa5bdc7
7986108da77c0e95f30ef3b5a982ca183d733905
refs/heads/master
2021-06-15T09:03:10.559913
2017-04-03T06:52:33
2017-04-03T06:52:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,068
cpp
/* * Education Frameworks * Copyright © 2015-2017 Origin Studio Inc. * */ #include "ModInfoDbm.h" #include "../CommonHeader.h" bool CModInfoDbm::Load() { std::string szPath = "..\\Data\\modinfo.csv"; if (false == CDBM::Load(szPath.c_str())) { CONSOLE("file not found: " << szPath.c_str()); return false; } g_kModInfoList.Clear(); INT iModOffset = GetField("mi_mod")->GetOffset(); INT iMapOffset = GetField("mi_map")->GetOffset(); INT iRuleOffset = GetField("mi_rule")->GetOffset(); INT iTimeOffset = GetField("mi_time")->GetOffset(); INT iItemDropOffset = GetField("mi_itemdrop")->GetOffset(); INT iModSize = GetField("mi_mod")->GetSize(); INT iMapSize = GetField("mi_map")->GetSize(); INT iRuleSize = GetField("mi_rule")->GetSize(); INT iTimeSize = GetField("mi_time")->GetSize(); INT iItemDropSize = GetField("mi_itemdrop")->GetSize(); for (INT i = 0; i < GetDataCount(); ++i) { std::string szMod(GetData(i, iModOffset), iModSize); std::string szMap(GetData(i, iMapOffset), iMapSize); std::string szRule(GetData(i, iRuleOffset), iRuleSize); std::string szTime(GetData(i, iTimeOffset), iTimeSize); std::string szItemDrop(GetData(i, iItemDropOffset), iItemDropSize); MOD_TYPE eType = MOD_NONE; if(0 == strcmp(szMod.c_str(), "FFA")) { eType = MOD_FFA; } else if(0 == strcmp(szMod.c_str(), "TDM")) { eType = MOD_TDM; } else if(0 == strcmp(szMod.c_str(), "ZOMBIE")) { eType = MOD_ZOMBIE; } UINT uiMap = atoll(szMap.c_str()); UINT uiRule = atoll(szRule.c_str()); UINT uiTime = atoll(szTime.c_str()); bool bItemDrop = false; if(0 == strcmp(szItemDrop.c_str(), "TRUE")) { bItemDrop = true; } SModInfo tInfo; tInfo.type = eType; tInfo.map_id = uiMap; tInfo.rule = uiRule; tInfo.time = uiTime; tInfo.item_drop = bItemDrop; //CONSOLE("modinfo: type: " << tInfo.GetType() << ", map id: " << tInfo.GetMapId() << ", rule: " << tInfo.GetRule() << ", time: " << tInfo.GetTime() << ", item drop: " << tInfo.IsItemDrop()); g_kModInfoList.Insert(tInfo); } Clear(); return true; }
[ "yourbrodie@naver.com" ]
yourbrodie@naver.com
61ca638237987bbd067146bb28880da19a1c1ae5
a1ca7ef26c0f2f4645b8a96e60cb5608c7c57a9a
/CD/Sources/viewTask/tooltipnote.cpp
00454cc9edd5b09e984dbac3dd43e319ca55f24c
[]
no_license
paulnta/ProAgenda
cf96cd36f2bdfbcf20e1acd45b8cd0b4951759ab
eac0c0fbf9a2fc07ad6b101bb476da6fb63ed575
refs/heads/master
2021-01-10T05:25:48.865146
2015-06-02T13:18:40
2015-06-02T13:18:40
49,986,703
0
0
null
null
null
null
UTF-8
C++
false
false
93
cpp
#include "tooltipnote.h" tooltipNote::tooltipNote() { } tooltipNote::~tooltipNote() { }
[ "jerome.moret@heig-vd.ch" ]
jerome.moret@heig-vd.ch
7f977a85a1312b686bbeedbc864d9944f3660618
024204219a714dcaf33d1ea5564a7c22d7aa6ce2
/bifit_preproc.cpp
c8ef5489f9797106799d4d5dd80e58d19a9b958a
[]
no_license
lidonggit/obtain_gs_info
7c2b8e1b20d5f38fae80dec0e0c029b0a4e5597f
dd8740cdba3737de27a33f2f41766428a537fe95
refs/heads/master
2021-01-10T19:50:34.394219
2014-01-21T21:46:59
2014-01-21T21:46:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,199
cpp
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <string> #include <iostream> #include <fstream> #define MY_DEBUG #define MAX(a,b) \ ({ __typeof__ (a) _a = (a); __typeof__ (b) _b = (b); _a > _b ? _a : _b;}) #define MIN(a,b) \ ({ __typeof__ (a) _a = (a); __typeof__ (b) _b = (b); _a < _b ? _a : _b;}) using namespace std; typedef struct memreginfo { int size; unsigned int addr; string other_info; bool valid_flag; //flag for adjusting memory record }MEMREF; void adjust_mem_record(MEMREF *item, MEMREF *mem_record, int mem_record_counter) { bool adjust_flag; int round_counter = 0; while(1) { round_counter++; adjust_flag = false; for(int i=0; i < mem_record_counter; i++) { if(mem_record[i].valid_flag == false) continue; if(item->addr <= mem_record[i].addr && item->addr+item->size >= mem_record[i].addr + mem_record[i].size) { mem_record[i].valid_flag = false; //invalidate the record if((item->other_info.find(mem_record[i].other_info) == string::npos) && (mem_record[i].other_info.find(item->other_info) == string::npos)) item->other_info = item->other_info + mem_record[i].other_info; else if((item->other_info.find(mem_record[i].other_info) == string::npos) && (mem_record[i].other_info.find(item->other_info) != string::npos)) item->other_info = mem_record[i].other_info; adjust_flag = true; continue; } if((item->addr >= mem_record[i].addr && item->addr < mem_record[i].addr + mem_record[i].size -1) || (item->addr < mem_record[i].addr && item->addr+item->size-1 >= mem_record[i].addr)) { item->size = MAX(item->addr+item->size-1, mem_record[i].addr+mem_record[i].size-1) - MIN(item->addr, mem_record[i].addr) + 1; item->addr = MIN(item->addr, mem_record[i].addr); if((item->other_info.find(mem_record[i].other_info) == string::npos) && (mem_record[i].other_info.find(item->other_info) == string::npos)) item->other_info = item->other_info + mem_record[i].other_info; else if((item->other_info.find(mem_record[i].other_info) == string::npos) && (mem_record[i].other_info.find(item->other_info) != string::npos)) item->other_info = mem_record[i].other_info; adjust_flag = true; mem_record[i].valid_flag = false; break; } } //for loop if(adjust_flag) continue; else break; } //while return; } int main(int argc, char *argv[]) { char *filepath; int mem_size_cut = 0; if(argc != 3) { printf("Usage: bifit_preproc file_path mem_size_cut\n"); exit(1); } else { filepath = argv[1]; mem_size_cut = (int)atol(argv[2]); } //read data object info into the memory ifstream sg_input; sg_input.open(filepath); if(!sg_input) { cerr << "Error: could not open the input file " << filepath << endl; } int item_counter = 0; string obj_info; while(getline(sg_input, obj_info)) ++item_counter; cout << "***** There are " << item_counter << " data objects *****" << endl; MEMREF *mr_temp, *mr_record; mr_temp = new MEMREF[item_counter]; mr_record = new MEMREF[item_counter]; sg_input.clear(); sg_input.seekg(0, ios::beg); for(int i=0; i<item_counter; i++) { std::getline(sg_input, obj_info); //get addr and size size_t addr_pos = obj_info.find("addr"); size_t size_pos = obj_info.find("size"); string obj_size = obj_info.substr(size_pos+4); string obj_addr = obj_info.substr(addr_pos+4, size_pos-1-(addr_pos+4)+1); mr_temp[i].size = strtol(obj_size.c_str(), NULL, 0); mr_temp[i].addr = (unsigned int)strtol(obj_addr.c_str(), NULL, 0); mr_temp[i].other_info = obj_info.substr(0, addr_pos-1); } sg_input.close(); //consolidating the overlapped memory regions bool adjust_flag = false; int mem_record_counter=0; for(int i=0; i<item_counter; i++) { adjust_flag = false; adjust_mem_record(mr_temp+i, mr_record, mem_record_counter); /*add into mem_record*/ mr_record[mem_record_counter].addr = mr_temp[i].addr; mr_record[mem_record_counter].size = mr_temp[i].size; mr_record[mem_record_counter].other_info = mr_temp[i].other_info; mr_record[mem_record_counter].valid_flag = true; mem_record_counter++; } //for loop int valid_record_counter = 0; for(int i=0; i< mem_record_counter; i++) { if(mr_record[i].valid_flag) { valid_record_counter++; /*cout << mr_record[i].other_info << " addr " << hex << mr_record[i].addr << dec << " size " << mr_record[i].size << endl; */ } } cout << "***** Collected " << valid_record_counter << " valid mem records in total (mem_size_cut=1048976)*****" << endl; //gather consolidated memory region information MEMREF valid_record[valid_record_counter]; int temp_counter=0; for(int i=0; i < mem_record_counter; i++) { if(mr_record[i].valid_flag) { valid_record[temp_counter].size = mr_record[i].size; valid_record[temp_counter].addr = mr_record[i].addr; valid_record[temp_counter].other_info = mr_record[i].other_info; temp_counter++; } } //bubble sorting MEMREF temp_record; for (int i=0 ; i <(valid_record_counter - 1); i++) { for (int j=0 ; j < valid_record_counter - i - 1; j++) { if (valid_record[j].size < valid_record[j+1].size) /* For decreasing order use < */ { temp_record.size = valid_record[j].size; temp_record.addr = valid_record[j].addr; temp_record.other_info = valid_record[j].other_info; valid_record[j].size = valid_record[j+1].size; valid_record[j].addr = valid_record[j+1].addr; valid_record[j].other_info = valid_record[j+1].other_info; valid_record[j+1].size = temp_record.size; valid_record[j+1].addr = temp_record.addr; valid_record[j+1].other_info = temp_record.other_info; } } } //output for(int i=0; i<valid_record_counter; i++) { if(valid_record[i].size > mem_size_cut) cout << valid_record[i].other_info << " addr " << hex << valid_record[i].addr << dec << " size " << valid_record[i].size << endl; } }
[ "dol@dmz02.ftpn.ornl.gov" ]
dol@dmz02.ftpn.ornl.gov
64d623dc5496acd9f74d87ad13bdc620ae2a343c
adc40f93a5621374426240b64dfe781d223241d8
/Source/MyProject/MyActorf.h
dddc117fdcee3e513634e5f3665d55b3a9657770
[]
no_license
alexsantosfilho/Prova1
740e4238034eb9e2ac8067dce2acf6cf06d01064
325d636a4f7f8fda5fdaaff91105ad6797734d31
refs/heads/master
2020-09-14T02:23:41.545740
2016-09-05T19:48:35
2016-09-05T19:48:35
67,268,783
0
0
null
null
null
null
UTF-8
C++
false
false
875
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GameFramework/Actor.h" #include "MyActorf.generated.h" UCLASS() class MYPROJECT_API AMyActorf :public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AMyActorf(); // Called when the game starts or when spawned virtual void BeginPlay() override; // Called every frame virtual void Tick(float DeltaSeconds) override; private: UPROPERTY(EditAnywhere) UShapeComponent* Root; UPROPERTY(EditAnywhere) UStaticMeshComponent* MeshComp; UPROPERTY(VisibleAnywhere, Category = Tick) float RunningTime = 1; UPROPERTY(VisibleAnywhere, Category = Tick) float RunningTime2 = 2; UFUNCTION() void OnHit(class AActor* OtherActor, class UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit); };
[ "tudomaistv@gmail.com" ]
tudomaistv@gmail.com
fb2715a66b13cce9a49fb42f59aa211638f33446
1c37ce592bf818cca25555468df07ace296206cb
/random_b/appending_mex.cpp
4841ba35a05e2cbccc5c1cb9975f14248c04479d
[]
no_license
Eglis05/CodeForces
7f55ec40e978f8310b186ce90d7d5e2cbcfea760
78371d56c4d486b948dce21880b99252d27442c7
refs/heads/main
2023-01-21T23:24:25.734234
2020-11-30T19:46:13
2020-11-30T19:46:13
307,812,555
0
0
null
null
null
null
UTF-8
C++
false
false
447
cpp
//https://codeforces.com/contest/1054/problem/B #include <iostream> #include <math.h> using namespace std; int main() { int n,bigg=0; cin >> n; int *a; a = new int[n]; char ok = 'T'; cin >> a[0]; if (a[0] != 0) {cout <<'1'; ok='F';} for (int i=1; i<n;i++) { cin >> a[i]; if ((a[i]>bigg+1) && ok=='T') {cout <<i+1; ok='F';} bigg = max(bigg,a[i]); } if (ok == 'T') {cout << "-1";} }
[ "eglisbalani5@gmail.com" ]
eglisbalani5@gmail.com
96ca13408c042f704b52142d6d485f7f726403e8
e0d68d2828a9965ac78130f36792092eb5550095
/metarurururururu/Game/Game/physics/PhysicsStaticObject.cpp
1417cea3fd1cd95207e38ef26677ed165b398cc9
[]
no_license
kyarameru1102/metaru
b627b40070d8bc8825282fe3bf89b814001dbf87
0140aa4525a1985598b3d757535fac726d3e1afa
refs/heads/master
2021-07-25T04:20:07.313408
2020-08-28T03:03:55
2020-08-28T03:03:55
213,589,382
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
790
cpp
/*! * @brief 静的オブジェクト。 */ #include "stdafx.h" #include "physics/PhysicsStaticObject.h" PhysicsStaticObject::PhysicsStaticObject() { } PhysicsStaticObject::~PhysicsStaticObject() { g_physics.RemoveRigidBody(m_rigidBody); } void PhysicsStaticObject::CreateMeshObject(SkinModel& skinModel, CVector3 pos, CQuaternion rot, CVector3 scl) { //メッシュコライダーを作成。 m_meshCollider.CreateFromSkinModel(skinModel, nullptr); //剛体を作成、 RigidBodyInfo rbInfo; rbInfo.collider = &m_meshCollider; //剛体に形状(コライダー)を設定する。 rbInfo.mass = 0.0f; rbInfo.pos = pos; rbInfo.rot = rot; rbInfo.scl = scl; m_rigidBody.Create(rbInfo); //剛体を物理ワールドに追加する。 g_physics.AddRigidBody(m_rigidBody); }
[ "kbc18b19@stu.kawahara.ac.jp" ]
kbc18b19@stu.kawahara.ac.jp
f7e9ddfe70319669433bbe1e94f66a6861c1fe2e
de556018150aacefb5821e31597e2b673a561c3f
/Animations/AnimatedTransformation.cpp
a50b5e8347c2c1cc477e92ba2694bf2047109c05
[]
no_license
OpenEngineDK/extensions-AnimationFramework
095401ca3d12cb25034a5158a04faf2858e159e2
ddad4cec018beba523c31ebc6146a3fed556120b
refs/heads/master
2021-01-01T04:44:57.062446
2016-05-05T00:21:18
2016-05-05T00:21:18
58,073,085
0
0
null
null
null
null
UTF-8
C++
false
false
3,661
cpp
// // ------------------------------------------------------------------- // Copyright (C) 2007 OpenEngine.dk (See AUTHORS) // // This program is free software; It is covered by the GNU General // Public License version 2 or any later version. // See the GNU General Public License for more details (see LICENSE). //-------------------------------------------------------------------- #include "AnimatedTransformation.h" #include <utility> #include <Logging/Logger.h> namespace OpenEngine { namespace Animations { AnimatedTransformation::AnimatedTransformation(TransformationNode* target) { this->target = target; } AnimatedTransformation::~AnimatedTransformation() { } void AnimatedTransformation::SetName(std::string name) { this->name = name; } std::string AnimatedTransformation::GetName() { return name; } void AnimatedTransformation::SetAnimatedNode(TransformationNode* target) { this->target = target; } TransformationNode* AnimatedTransformation::GetAnimatedNode() { return target; } void AnimatedTransformation::AddRotationKey(unsigned int time, Math::Quaternion<float> key) { rotationKeys.push_back(std::make_pair(time, key)); } void AnimatedTransformation::AddPositionKey(unsigned int time, Math::Vector<3,float> key) { positionKeys.push_back(std::make_pair(time, key)); } void AnimatedTransformation::AddScalingKey( unsigned int time, Math::Vector<3,float> key) { scalingKeys.push_back(std::make_pair(time, key)); } void AnimatedTransformation::UpdateAndApply(unsigned int time) { // Find rotation key frame interval and interpolate in between. std::pair<double, Math::Quaternion<float> > rotElm, rotStart, rotEnd; rotStart.first = -1; rotEnd.first = -1; std::vector< std::pair<double, Math::Quaternion<float> > >::iterator itr; for(itr=rotationKeys.begin(); itr!=rotationKeys.end(); itr++){ rotElm = *itr; if( time >= rotElm.first ) { rotStart = rotElm; }else{ rotEnd = rotElm; break; } } rotElm = rotStart; // Interpolation between rotStart.second and rotEnd.second. if( rotStart.first != -1 && rotEnd.first != -1 ){ double delta = rotEnd.first - rotStart.first; double iTime = time - rotStart.first; double progr = 0; if( delta > 0 ) progr = iTime / delta; rotElm.second = Quaternion<float>(rotStart.second, rotEnd.second, progr); } // Apply rotation to affected transformation node. target->SetRotation(rotElm.second); // Find position key frame interval and interpolate in between. std::pair<double, Math::Vector<3,float> > posElm, posStart, posEnd; posStart.first = -1; posEnd.first = -1; std::vector< std::pair<double, Math::Vector<3,float> > >::iterator posItr; for(posItr=positionKeys.begin(); posItr!=positionKeys.end(); posItr++) { posElm = *posItr; if( time >= posElm.first ) { posStart = posElm; } else { posEnd = posElm; break; } } posElm = posStart; if( posStart.first != -1 && posEnd.first != -1 ){ double delta = posEnd.first - posStart.first; double iTime = time - posStart.first; double progr = 0; if( delta > 0 ) progr = iTime / delta; // Interpolate vector: deltaVec * scale + startVec posElm.second = ((posEnd.second - posStart.second) * progr) + posStart.second; } // Apply position to affected transformation node. target->SetPosition(posElm.second); } } // NS Animations } // NS OpenEngine
[ "norby@genx.dk" ]
norby@genx.dk
19e2b69cc8910efdbd9a2c52b80062f7f2c1d9f6
abc49a11150dc74113a070efcd7cff54c11957d5
/Games/ManipulatingActors/Source/ManipulatingActors/ManipulatingActorsGameModeBase.cpp
a87781e940f6a6793e8114c3fb7309132af60cd4
[]
no_license
lgpinguim/UnrealStudies
47dbba17b176bb0c28645597c308cd3c9d6f214e
f60c56b77bf69405150de6157a1cbf0e86e67c6b
refs/heads/master
2022-06-05T02:04:45.833585
2020-05-05T12:16:16
2020-05-05T12:16:16
239,595,316
1
0
null
null
null
null
UTF-8
C++
false
false
126
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "ManipulatingActorsGameModeBase.h"
[ "lg_pinguim@hotmail.com" ]
lg_pinguim@hotmail.com
5ebd3fb22a88c004467c7ecca6e16db0b6c6e9c3
0e56ee6fdfe0dd3dad736e608c2e823e8bbed521
/egen/TestHarness/Reference/inc/EGenGenerateAndLoadBaseOutput.h
7852d31d9bb52314edef596ba299a83b16b82521
[ "Artistic-1.0" ]
permissive
dotweiba/dbt5
d510ab80e979704db71b6d25a9cd7a1a754640b4
39e23b0a0bfd4dfcb80cb2231270324f6bbf4b42
refs/heads/master
2021-03-09T23:10:31.789560
2020-04-27T00:07:33
2020-04-27T00:38:06
246,391,034
0
0
NOASSERTION
2020-03-10T19:36:36
2020-03-10T19:36:36
null
UTF-8
C++
false
false
3,409
h
/* * Legal Notice * * This document and associated source code (the "Work") is a preliminary * version of a benchmark specification being developed by the TPC. The * Work is being made available to the public for review and comment only. * The TPC reserves all right, title, and interest to the Work as provided * under U.S. and international laws, including without limitation all patent * and trademark rights therein. * * No Warranty * * 1.1 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE INFORMATION * CONTAINED HEREIN IS PROVIDED "AS IS" AND WITH ALL FAULTS, AND THE * AUTHORS AND DEVELOPERS OF THE WORK HEREBY DISCLAIM ALL OTHER * WARRANTIES AND CONDITIONS, EITHER EXPRESS, IMPLIED OR STATUTORY, * INCLUDING, BUT NOT LIMITED TO, ANY (IF ANY) IMPLIED WARRANTIES, * DUTIES OR CONDITIONS OF MERCHANTABILITY, OF FITNESS FOR A PARTICULAR * PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OF * WORKMANLIKE EFFORT, OF LACK OF VIRUSES, AND OF LACK OF NEGLIGENCE. * ALSO, THERE IS NO WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT, * QUIET POSSESSION, CORRESPONDENCE TO DESCRIPTION OR NON-INFRINGEMENT * WITH REGARD TO THE WORK. * 1.2 IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THE WORK BE LIABLE TO * ANY OTHER PARTY FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO THE * COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS * OF USE, LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT, * INDIRECT, OR SPECIAL DAMAGES WHETHER UNDER CONTRACT, TORT, WARRANTY, * OR OTHERWISE, ARISING IN ANY WAY OUT OF THIS OR ANY OTHER AGREEMENT * RELATING TO THE WORK, WHETHER OR NOT SUCH AUTHOR OR DEVELOPER HAD * ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. * * Contributors * - Sergey Vasilevskiy */ /* * Base interface used to output generation and load progress * and any other supporting information. */ #ifndef EGEN_GENERATE_AND_LOAD_BASE_OUTPUT_H #define EGEN_GENERATE_AND_LOAD_BASE_OUTPUT_H namespace TPCE { class CGenerateAndLoadBaseOutput { public: /* * Virtual destructor. Provided so that a sponsor-specific * destructor can be called on destruction from the base-class pointer. * * PARAMETERS: * none. * * RETURNS: * not applicable. */ virtual ~CGenerateAndLoadBaseOutput() {}; /* * Output beginning of table generation. * * PARAMETERS: * IN szMsg - string to output to the user * * RETURNS: * none. */ virtual void OutputStart(string szMsg) = 0; /* * Output progress of table generation. * * PARAMETERS: * IN szMsg - string to output to the user * * RETURNS: * none. */ virtual void OutputProgress(string szMsg) = 0; /* * Output completion of table generation. * * PARAMETERS: * IN szMsg - string to output to the user * * RETURNS: * none. */ virtual void OutputComplete(string szMsg) = 0; /* * Output end-of-line. * * PARAMETERS: * IN szMsg - string to output to the user * * RETURNS: * none. */ virtual void OutputNewline() = 0; }; } // namespace TPCE #endif //EGEN_GENERATE_AND_LOAD_BASE_OUTPUT_H
[ "devnull@localhost" ]
devnull@localhost
1bae235cdb06cca4e890cf0570162ce2b911cd5b
b7f7756ee79768bcdff05ac96575f25ca975cd79
/Gray Code/Gray Code.cpp
074115a5a179c30282dc026a6ec174bfea0de8c5
[]
no_license
suwei111333/BaseInterviewCode
e8a3c3b4e283676d0b438a5d3276c73ac9877343
205089eda593add518be518176e15d8f5aae37f8
refs/heads/master
2021-01-10T19:04:41.076863
2013-11-05T08:41:04
2013-11-05T08:41:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
861
cpp
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> grayCode(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function bool* lpbFlat = new bool[1<< n]; memset(lpbFlat, 0, sizeof(bool)* (1<< n)); vector<int> lvGrayCode; int lcurrentWord = 0; int lnNumGrayCode = 1 << n; while(lnNumGrayCode >0) { lnNumGrayCode--; lpbFlat[lcurrentWord] = true; lvGrayCode.push_back(lcurrentWord); for(int i = 0; i< n; i++) { int ltmpWord = lcurrentWord & (1 << i) ? lcurrentWord & (~(1<<i)): lcurrentWord | (1 << i); if(lpbFlat[ltmpWord] == false) { lcurrentWord = ltmpWord; break; } } } return lvGrayCode; } }; int main() { Solution mSolution; int n; while(cin >> n) { mSolution.grayCode(n); } return 0; }
[ "wsu@CHN-WSU.corp.microstrategy.com" ]
wsu@CHN-WSU.corp.microstrategy.com
f59a97c4ad0fe9b71b2c8918fee41499470197cf
e4cfbc596c302495a8f73a3d3eaec2456c068585
/include/Swiften/Session/BasicSessionStream.h
e1f32f479159b59dfe806c218290c6185ce035b7
[]
no_license
dannyzhan/IM
a38e50943f2a52bcce494cce07b9c20a8a0b6498
913d72fd97c1436ba5c21e111c1df4614c72bead
refs/heads/master
2016-09-06T02:17:27.726347
2013-03-12T09:44:57
2013-03-12T09:44:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,793
h
/* * Copyright (c) 2010 Remko Tronçon * Licensed under the GNU General Public License v3. * See Documentation/Licenses/GPLv3.txt for more information. */ #pragma once #include <boost/shared_ptr.hpp> #include <Swiften/Base/SafeByteArray.h> #include <Swiften/Network/Connection.h> #include <Swiften/Session/SessionStream.h> #include <Swiften/Elements/StreamType.h> #include <Swiften/TLS/TLSError.h> namespace Swift { class TLSContextFactory; class TLSLayer; class TimerFactory; class WhitespacePingLayer; class PayloadParserFactoryCollection; class PayloadSerializerCollection; class StreamStack; class XMPPLayer; class ConnectionLayer; class CompressionLayer; class XMLParserFactory; class BasicSessionStream : public SessionStream { public: BasicSessionStream( StreamType streamType, boost::shared_ptr<Connection> connection, PayloadParserFactoryCollection* payloadParserFactories, PayloadSerializerCollection* payloadSerializers, TLSContextFactory* tlsContextFactory, TimerFactory* whitespacePingLayerFactory, XMLParserFactory* xmlParserFactory ); ~BasicSessionStream(); virtual void close(); virtual bool isOpen(); virtual void writeHeader(const ProtocolHeader& header); virtual void writeElement(boost::shared_ptr<Element>); virtual void writeFooter(); virtual void writeData(const std::string& data); virtual bool supportsZLibCompression(); virtual void addZLibCompression(); virtual bool supportsTLSEncryption(); virtual void addTLSEncryption(); virtual bool isTLSEncrypted(); virtual Certificate::ref getPeerCertificate() const; virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const; virtual ByteArray getTLSFinishMessage() const; virtual void setWhitespacePingEnabled(bool); virtual void resetXMPPParser(); private: void handleConnectionFinished(const boost::optional<Connection::Error>& error); void handleXMPPError(); void handleTLSConnected(); void handleTLSError(boost::shared_ptr<TLSError>); void handleStreamStartReceived(const ProtocolHeader&); void handleElementReceived(boost::shared_ptr<Element>); void handleDataRead(const SafeByteArray& data); void handleDataWritten(const SafeByteArray& data); private: bool available; boost::shared_ptr<Connection> connection; PayloadParserFactoryCollection* payloadParserFactories; PayloadSerializerCollection* payloadSerializers; TLSContextFactory* tlsContextFactory; TimerFactory* timerFactory; StreamType streamType; XMPPLayer* xmppLayer; ConnectionLayer* connectionLayer; CompressionLayer* compressionLayer; TLSLayer* tlsLayer; WhitespacePingLayer* whitespacePingLayer; StreamStack* streamStack; }; }
[ "deshan.you@gmail.com" ]
deshan.you@gmail.com
f64f9271ca553ded4b0d4c1e0774f8cd9a4cd8a1
0503bd4387d8c21fe41fd8ad0964a5d4a83635c1
/GardenGame/src/Static.cpp
b374b52ac99a9484141e7f9ddba1581a069604ce
[]
no_license
Saafan/GardenGame
3792226f1c66c4c2b2118bb73cf463559a86473b
5dbdb082809f847cb2d9902c69b445996c326d0d
refs/heads/master
2023-01-30T22:48:33.866627
2020-12-09T15:27:41
2020-12-09T15:27:41
313,931,357
0
0
null
null
null
null
UTF-8
C++
false
false
151
cpp
#include <iostream> #include <vector> #include <map> int main() { std::map<int, int> m; m[1]++; m[1]++; m[1]++; std::cout << m[1] << std::endl; }
[ "abdullah.safaan@gmail.com" ]
abdullah.safaan@gmail.com
2ef9b7b30f557630d340afec8545e4c55961eb29
9408b76b4fddcd4bf8e66588ec3c4036048d6804
/SharedInfoHandleTable/SharedInfoHandleTable/stdafx.cpp
8faa46fb40cd65c7e65c192c21b6565657a5c9e7
[ "Unlicense", "GFDL-1.2-only", "CC-BY-3.0", "LicenseRef-scancode-public-domain" ]
permissive
y11en/windows_kernel_address_leaks
13a41e98cdf079ff8a63e6d072da6b073109c8a4
3810bec445c0afaa4e23338241ba0359aea398d1
refs/heads/master
2020-12-02T15:30:40.517805
2017-07-07T10:05:33
2017-07-07T10:05:33
231,050,364
0
0
Unlicense
2019-12-31T07:52:39
2019-12-31T07:52:05
null
UTF-8
C++
false
false
300
cpp
// stdafx.cpp : source file that includes just the standard includes // SharedInfoHandleTable.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "samdanielbrown@gmail.com" ]
samdanielbrown@gmail.com
fd156de650655cb904d470b2b8246b2cc2f4efc8
1cb7c36a1952d64c2bef1fd88405f656d8dec16e
/mainwindow.cpp
3a26d758239bf3e518f4495f7a8521e2741d3abf
[]
no_license
Huesillo1/SITREN_LUWEN
832e6177b0a6c54ad07fce88e5c4bb56d23eb62b
c1ff26f82605d861f34128f958fc19d0ed45c813
refs/heads/main
2023-07-13T16:41:58.412911
2021-08-27T03:26:41
2021-08-27T03:26:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,346
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> #include <QTableWidget> #include <QTableWidgetItem> #include <algorithm> //Getters & Setters Cajero& MainWindow::getATM() { return ATM; } void MainWindow::setATM(Cajero &value) { ATM = value; } int MainWindow::getId() const { return id; } void MainWindow::setId(int value) { id = value; } //Metodos Propios //Metodos Form MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow), id(0), idTarjeta(0) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_actionAgregar_Usuario_triggered() { UsuariosWindow *u = new UsuariosWindow; // MainWindow *m = this; //u->setM(m); Cajero *cajero = new Cajero; cajero = &ATM; u->setCajeroActual(cajero); u->show(); } void MainWindow::on_actionMostrarUsuarios_triggered() { MostrarUsuariosWindow *muw = new MostrarUsuariosWindow; Cajero *cajero = new Cajero; cajero = &ATM; muw->setCajero(cajero); muw->llenarTabla(cajero->getUsuarios()); muw->show(); } void MainWindow::on_btnRecargar_clicked() { SeleccionUsuarioWindow *s = new SeleccionUsuarioWindow; Cajero *cajero = new Cajero; int *idCard = new int; idCard = &idTarjeta; cajero = &ATM; s->setCajero(cajero); s->setIdTarjeta(idCard); s->show(); } void MainWindow::on_btnComprarTarjeta_clicked() { if(!ATM.isUsuariosEmpty()){ ComprarTarjetaWindow *c = new ComprarTarjetaWindow; Cajero *cajero = new Cajero; int *idCard = new int; idCard = &idTarjeta; cajero = &ATM; c->setCajero(cajero); c->llenarComboBox(cajero->getUsuarios()); c->setIdTarjeta(idCard); c->show(); }else{ QMessageBox::warning(this,"Advertencia","Antes de poder comprar una tarjeta debes registrar al menos un usuario."); } } void MainWindow::on_btnUniviaje_clicked() { IngresarDineroWindow *i = new IngresarDineroWindow; Cajero *cajero = new Cajero; int *idActual = new int; idActual = &id; cajero = &ATM; i->setCajero(cajero); i->setCantidadPago(10); i->setWindowTitle("Pago Univiaje"); i->setProcedencia("Univiaje"); i->setIdUniviaje(idActual); i->cargarDatos(); i->show(); }
[ "luis.gonzalez7504@alumnos.udg.mx" ]
luis.gonzalez7504@alumnos.udg.mx
42e2c0d043df452dccc5ae0481f6365624fa3933
b28db0869f6452c67a405ec9f04e54e5908204b7
/ext/mytorch/list_to_map.h
1b43b47f6fa8fcee0dc2b0a0c651b0e3f770b86d
[ "MIT" ]
permissive
purplesnail/StableViewSynthesis
3af749d3570c65280972b0abc6d3e2e65b1a068b
a49cd865719816d5fb884507c47e42e56d143136
refs/heads/main
2023-04-30T21:55:41.340930
2021-05-19T08:11:47
2021-05-19T08:11:47
368,764,083
0
0
MIT
2021-05-19T06:18:27
2021-05-19T06:18:27
null
UTF-8
C++
false
false
2,352
h
#pragma once #include <co_math.h> #include <common.h> #include <torch_common.h> #include <torch_tensor.h> template <typename T> struct ListToMapForward { const Tensor2<T> features; // n_elems x channels const Tensor1<int> tgtidx; // n_elems Tensor4<T> out_sum; // batch_size x channels x height x width Tensor4<T> out_mask; // batch_size x 1 x height x width ListToMapForward(const Tensor2<T> features, const Tensor1<int> tgtidx, Tensor4<T> out_sum, Tensor4<T> out_mask) : features(features), tgtidx(tgtidx), out_sum(out_sum), out_mask(out_mask) {} CPU_GPU_FUNCTION void operator()(long idx) { // idx \in [0, n_elems] const long channels = out_sum.shape[1]; const long height = out_sum.shape[2]; const long width = out_sum.shape[3]; // tgtidx = bidx * height * width + h * width + w const int tgtidx_ = tgtidx(idx); const int w = tgtidx_ % width; const int h = (tgtidx_ / width) % height; const int bidx = tgtidx_ / (height * width); for (long c = 0; c < channels; ++c) { co_atomic_add(out_sum.ptridx(bidx, c, h, w), features(idx, c)); } out_mask(bidx, 0, h, w) = 1; } }; template <typename T> struct ListToMapBackward { const Tensor4<T> grad_out_sum; // batch_size x channels x height x width const Tensor1<int> tgtidx; // n_elems Tensor2<T> grad_features; // n_elems x channels ListToMapBackward(const Tensor4<T> grad_out_sum, const Tensor1<int> tgtidx, Tensor2<T> grad_features) : grad_out_sum(grad_out_sum), tgtidx(tgtidx), grad_features(grad_features) {} CPU_GPU_FUNCTION void operator()(long idx) { // idx \in [0, n_elems] const long channels = grad_out_sum.shape[1]; const long height = grad_out_sum.shape[2]; const long width = grad_out_sum.shape[3]; // tgtidx = bidx * height * width + h * width + w const int tgtidx_ = tgtidx(idx); const int w = tgtidx_ % width; const int h = (tgtidx_ / width) % height; const int bidx = tgtidx_ / (height * width); for (long c = 0; c < channels; ++c) { grad_features(idx, c) = grad_out_sum(bidx, c, h, w); } } };
[ "david.hafner@intel.com" ]
david.hafner@intel.com
48b6866dc94a948c9e669ffeb6cf3a5a025a1978
c591b56220405b715c1aaa08692023fca61f22d4
/Vishal/Milestone 27 (BST)/Set-2/Merge_two_BST.cpp
d298e5ddb6ac995ec62cfbdf28f12db37602ff62
[]
no_license
Girl-Code-It/Beginner-CPP-Submissions
ea99a2bcf8377beecba811d813dafc2593ea0ad9
f6c80a2e08e2fe46b2af1164189272019759935b
refs/heads/master
2022-07-24T22:37:18.878256
2021-11-16T04:43:08
2021-11-16T04:43:08
263,825,293
37
105
null
2023-06-05T09:16:10
2020-05-14T05:39:40
C++
UTF-8
C++
false
false
1,913
cpp
void inorder(Node *root) { if (root != NULL) { inorder(root->left); cout<<root->data<<" "; inorder(root->right); } } void merge(Node *root1, Node *root2) { if (root1 == NULL) { inorder(root2); return; } if (root2 == NULL) { inorder(root1); return ; } Node *current1 = root1,*current2 = root2; stack<Node*> s1,s2; while (current1 || !s1.empty()|| current2|| !s2.empty()) { if (current1 || current2) { if (current1) { s1.push(current1); current1 = current1->left; } if (current2) { s2.push(current2); current2 = current2->left; } } else { if (s1.empty()) { while (!s2.empty()) { current2 = s2.pop(); current2->left = NULL; inorder(current2); } return ; } if (s2.empty()) { while (!s1.empty()) { current1 = s1.pop(); current1->left = NULL; inorder(current1); } return ; } current1 = s1.pop(); current2 = s2.pop(); if (current1->data < current2->data) { cout<< current1->data <<" "; current1 = current1->right; s2.push(current2); current2 = NULL; } else { cout<< current2->data <<" "; current2 = current2->right; s1.push(current1); current1 = NULL; } } } }
[ "rajputvishal33786@gmail.com" ]
rajputvishal33786@gmail.com
3af0515fc881d23299e4ae4fd003f6099487f69c
f1e2c56ff0e12cdb951807b36a24c080243c87e9
/2016-2021 Miami University/CSE 543 High Performance Computing/08. Homework 2/box-muller_omp.cpp
48eb432206c366e1c0ac00d83bc1ad66c4903dc7
[ "MIT" ]
permissive
0x326/academic-code-portfolio
b5fd0cc55f59b082454486bb5d4278edba504daf
c2248aa287a07abbb9e5548107ec87aa7632f247
refs/heads/master
2023-04-13T05:57:16.366630
2023-03-16T18:43:11
2023-03-16T18:43:11
91,472,765
1
1
null
null
null
null
UTF-8
C++
false
false
2,720
cpp
// // Created by john on 10/9/20. // #include <iostream> #include <cstdlib> #include <cmath> #include <omp.h> #define RUNLENGTH 20000000 #define N 100 struct drand48_data state; #pragma omp threadprivate(state) void doBoxMuller(double &sample_mean, double &sample_standard_deviation, const double population_mean, const double population_standard_deviation) { double sample_sum = 0; double sample_sum_squared = 0; // Not sum of squares. Equal to: pow(x1, 2) + pow(x2, 2) + ... #pragma omp parallel for default(none) shared(population_mean, population_standard_deviation) reduction(+:sample_sum, sample_sum_squared) for (int i = 0; i < RUNLENGTH / 2; i++) { // Generate uniform random numbers double uniform_random_1, uniform_random_2; drand48_r(&state, &uniform_random_1); drand48_r(&state, &uniform_random_2); // Transform into Normal distribution double gaussian_random_1 = sqrt(-2 * log(uniform_random_1)) * cos(2 * M_PI * uniform_random_2); double gaussian_random_2 = sqrt(-2 * log(uniform_random_1)) * sin(2 * M_PI * uniform_random_2); // Transform Gaussian distribution based on mu and sigma gaussian_random_1 = population_mean + population_standard_deviation * gaussian_random_1; gaussian_random_2 = population_mean + population_standard_deviation * gaussian_random_2; // Save numbers sample_sum += gaussian_random_1 + gaussian_random_2; sample_sum_squared += (gaussian_random_1 * gaussian_random_1) + (gaussian_random_2 * gaussian_random_2); } sample_mean = sample_sum / RUNLENGTH; // I believe we should be dividing by RUNLENGTH - 1 sample_standard_deviation = sqrt(sample_sum_squared / RUNLENGTH - (sample_mean * sample_mean)); } int main(const int argc, const char *argv[]) { // Parse args if (argc != 2) { std::cerr << "Usage: " << argv[0] << " SEED" << std::endl; std::cerr << " SEED: The seed to use for the random number generator" << std::endl; return -1; } const int seed = std::stoi(argv[1]); #pragma omp parallel default(none) shared(seed) srand48_r(seed + 23 * omp_get_thread_num(), &state); const double population_mean = 42; const double population_standard_deviation = 5; double sample_mean, sample_standard_deviation; for (int i = 1; i <= N; i++) { doBoxMuller(sample_mean, sample_standard_deviation, population_mean, population_standard_deviation); std::cout << "Run " << i << ":" << " sample_mean = " << sample_mean << " sample_standard_deviation = " << sample_standard_deviation << std::endl; } return 0; }
[ "0x326@users.noreply.github.com" ]
0x326@users.noreply.github.com
8558ed4c2deb17bab1dee04d2abc2f75300367bb
0233477eeb6d785b816ee017cf670e2830bdd209
/SDK/SoT_BP_scar_05_Desc_classes.hpp
9a3bb1b30209b27ed545e69a444f05e432a4d0a5
[]
no_license
compy-art/SoT-SDK
a568d346de3771734d72463fc9ad159c1e1ad41f
6eb86840a2147c657dcd7cff9af58b382e72c82a
refs/heads/master
2020-04-17T02:33:02.207435
2019-01-13T20:55:42
2019-01-13T20:55:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
678
hpp
#pragma once // Sea of Thieves (1.4) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_scar_05_Desc_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_scar_05_Desc.BP_scar_05_Desc_C // 0x0000 (0x00E0 - 0x00E0) class UBP_scar_05_Desc_C : public UClothingDesc { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("BlueprintGeneratedClass BP_scar_05_Desc.BP_scar_05_Desc_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
6af97f4452886d7671176f8afdb9afa4cac94b0c
c7f3db94cc3d69cd9a2ae24aa3c69cd767b28672
/must_rma/src/externals/GTI/system-builder/weaver/calls/CallIdInput.h
c1dd0d626d4c5f3d3343d0da137e9d68bea6a10c
[]
no_license
RWTH-HPC/must-rma-correctness22-supplemental
10683ff20339098a45a35301dbee6b31d74efaec
04cb9fe5f0dcb05ea67880209accf19c5e0dda25
refs/heads/main
2023-04-14T20:48:36.684589
2022-08-10T20:28:43
2022-11-18T03:33:05
523,105,966
0
0
null
null
null
null
UTF-8
C++
false
false
2,545
h
/* This file is part of GTI (Generic Tool Infrastructure) * * Copyright (C) * 2008-2019 ZIH, Technische Universitaet Dresden, Federal Republic of Germany * 2008-2019 Lawrence Livermore National Laboratories, United States of America * 2013-2019 RWTH Aachen University, Federal Republic of Germany * * See the LICENSE file in the package base directory for details */ /** * @file CallIdInput.h * @see gti::weaver::CallIdInput * * @author Tobias Hilbrich * @date 07.01.2011 */ #ifndef CALLIDINPUT_H #define CALLIDINPUT_H #include <string> #include <vector> #include "Input.h" #include "Call.h" #include "Printable.h" namespace gti { namespace weaver { namespace calls { /** * An input to an operation or analysis which * is a unique id that identifies an API call. * (Unique among all specified API calls) */ class CallIdInput : public Input, virtual public Printable { public: /** * Invalid object Constructor. */ CallIdInput ( ); /** * Proper Constructor. */ CallIdInput (Call* call); /** * Empty Destructor */ virtual ~CallIdInput ( ); /** * Returns the argument used as input. * @return argument. */ int getCallId (void) const; /** * Prints a string that implements this input. * For a call argument this it the argument * name, for an operation input this is the * result variable name (which needs to be * created with a per call unique name). * @return string */ std::string getName ( ) const; /** * Returns the data type of this input. * @return string */ std::string getType ( ) const; /** * Hook method for printing, * in order to enable the "<<" operator. * @param out ostream to use. * @return ostream after printing. */ virtual std::ostream& print (std::ostream& out) const; /** * Returns the name of the DOT node from * which this input comes, either an * operation name or the given call name * followed by a column and the argument * name. * @param callName name of the from which * this is input. * @return name of DOT node. */ virtual std::string getDotInputNodeName (std::string callName); protected: Call *myTargetCall; /**< The call whose name is used as input. */ }; } /*namespace calls*/ } /*namespace weaver*/ } /*namespace gti*/ #endif // CALLIDINPUT_H
[ "schwitanski@itc.rwth-aachen.de" ]
schwitanski@itc.rwth-aachen.de
b1421daf5fbda761ae2c2b859e0f253ec306a4cf
1515c63756f36da0e4e4bc5cc4da5b3459336202
/Behaviors/MoveForward.cpp
b090db494b43d0a3b1d48fef77700159244c353b
[]
no_license
kinglavi/lastYearProject
9167f309a3eafeb0826e285093b184745da21d30
be9dc20b34741fe49758dc12b12f27c75fc9712e
refs/heads/master
2021-01-17T18:19:24.818423
2016-07-26T18:03:59
2016-07-26T18:03:59
64,243,226
0
0
null
null
null
null
UTF-8
C++
false
false
434
cpp
/* * MoveForward.cpp * * Created on: May 26, 2015 * Author: colman */ #include "MoveForward.h" #define FORWARD_SPEED 0.5 MoveForward::MoveForward(Robot *robot) : Behavior(robot) { strBehaviorName = "MoveForward"; } bool MoveForward::startCond() { return !checkObstacleInFront(0); } bool MoveForward::stopCond() { return checkObstacleInFront(0); } void MoveForward::action() { _robot->setSpeed(FORWARD_SPEED, 0); }
[ "klavior@gmail.com" ]
klavior@gmail.com
5c5c0a422bdd3d127201232a23733ce9ee0470a2
e5b98edd817712e1dbcabd927cc1fee62c664fd7
/Classes/commonData/dictData/DictArenaBattleReward/DictArenaBattleRewardManager.h
eba3b85660ebb500621ecc208471f2ba930f6185
[]
no_license
yuangu/project
1a49092221e502bd5f070d7de634e4415c6a2314
cc0b354aaa994c0ee2d20d1e3d74da492063945f
refs/heads/master
2020-05-02T20:09:06.234554
2018-12-18T01:56:36
2018-12-18T01:56:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
634
h
#ifndef __DictArenaBattleRewardManager__ #define __DictArenaBattleRewardManager__ #include "cocos2d.h" USING_NS_CC; using namespace std; #include "DictArenaBattleReward.h" #include "editor-support/spine/Json.h" class DictArenaBattleRewardManager { public: ~DictArenaBattleRewardManager(); void destroyInstance(); void setConfigData(Json* json); static DictArenaBattleRewardManager* getInstance(); DictArenaBattleReward* getData(int id); Vector<DictArenaBattleReward*>* getDataList(); private: static DictArenaBattleRewardManager* _instance; Map<string,Ref*> data_list; protected: DictArenaBattleRewardManager(){}; }; #endif
[ "chenyanbin@ixianlai.com" ]
chenyanbin@ixianlai.com
8065c32106ae8183ecf7ad8a13b806d48de70821
17ee62e07da65ef3a163951107bb63aca9aa0673
/programme_capteurs_bluetooth/main.cpp
fdfe8f52bd2909afde34acae8e6eece5dc356a65
[]
no_license
PauLegrand/Drone-instrumente-2021
3f1838f293487f176016828183da1ebf2b63f690
221742b0c5c382653005231f0843ae9b68edad37
refs/heads/main
2023-06-14T12:25:10.953599
2021-07-03T17:26:28
2021-07-03T17:26:28
382,666,343
0
0
null
2021-07-03T17:25:19
2021-07-03T16:50:47
null
UTF-8
C++
false
false
8,464
cpp
#include "mbed.h" #include "string.h" #include <cstdio> #include "DHT.h" #include "LSM6DS33.h" #include "GPS.h" #define N 100 #define SAMPLE 1000 #define GAIN 0.004375 //valeur datasheet LSM6DS33 /*structure de l'acceleromètre + gyro*/ struct Gyro{ double x=0, y=0, z=0, v=0; }; /*structure de l'acceleromètre + gyro*/ struct struct_GPS{ char lat[20] = {0}, lon[20] = {0}, alt[20] = {0}; }; /*declaration des pins*/ static UnbufferedSerial bt (PA_9, PA_10, 9600); static BufferedSerial GPS(PA_2, PB_4,9600); //UART2 utilisé pour l'USB du µc AnalogIn lum (A2);//pin capteur de luminosité AnalogIn son (A0); // pin capteur de son DHT sensor (A1,SEN11301P); // pin capteur température et humidité LSM6DS33 acc (PB_7, PB_6); // pin Gyroscope Timer timer; /*declaration des fonctions*/ struct_GPS getGPS (void); Gyro getGyro(double offsetx, double offsety, double offsetz); float getMaxSon (void); int main(){ //buffer d'envoie des valeurs char L[50] = ""; char S[50] = ""; char T[50] = ""; char H[50] = ""; char X[50] = ""; char Y[50] = ""; char Z[50] = ""; char V[50] = ""; char A[50] = ""; char G[50] = ""; char I[50] = ""; //buffer de reception char buffer[3]; //valeur du gyro + acc struct Gyro gyro; //valeur de GPS struct struct_GPS gps; //Variable capteurs analogiques double V_lum, V_son, V_temp, V_hum; int erreur; //variables gyro double offsetx=0, offsety=0, offsetz=0; /*GPS.set_baud(9600); bt.baud(9000); GPS.set_blocking(false); bt.set_blocking(false);*/ acc.begin(); //calcule de l'offset moyen des 3 axes du gyroscope for (int i=0; i<SAMPLE; i++){ acc.readGyro(); offsetx += acc.gx; offsety += acc.gy; offsetz += acc.gz; printf("%f\n\r", acc.gx); } offsetx /= SAMPLE; offsety /= SAMPLE; offsetz /= SAMPLE; printf("offeset x : %f", offsetx); printf("offeset y : %f", offsety); printf("offeset z : %f", offsetz); while(1){ //recupération des valeurs des capteurs V_lum = lum.read()*1000; V_son = getMaxSon(); erreur = sensor.readData(); if (erreur == 0) { V_temp = sensor.ReadTemperature(CELCIUS); V_hum = sensor.ReadHumidity(); } gyro = getGyro(offsetx, offsety, offsetz); //gps = getGPS(); //envoie les données des capteurs quand il est autorisé par android studio if(bt.readable()){ bt.read((void *)&buffer, 2); } if (buffer[0] == '1'){ buffer[0] = 0; //mise en forme des valeurs sprintf(S, "S %0.2f/", V_son); sprintf(L, "L %0.2f/", V_lum); sprintf(T, "T %0.2f/", V_temp); sprintf(X, "X %0.2f/", gyro.x); sprintf(Y, "Y %0.2f/", gyro.y); sprintf(Z, "Z %0.2f/", gyro.z); sprintf(V, "V %0.2f/", gyro.v); strcat(A, gps.alt); strcat(G, gps.lon); strcat(I, gps.lat); printf("%s",A); //envoi des valeurs bt.write((void *) L, strlen(L)); wait_us(50000); bt.write((void *) S, strlen(S)); wait_us(50000); bt.write((void *) T, strlen(T)); wait_us(50000); bt.write((void *) H, strlen(H)); wait_us(50000); bt.write((void *) X, strlen(X)); wait_us(50000); bt.write((void *) Y, strlen(Y)); wait_us(50000); bt.write((void *) Z, strlen(Z)); wait_us(50000); bt.write((void *) V, strlen(V)); wait_us(50000); bt.write((void *) A, strlen(A)); wait_us(50000); bt.write((void *) G, strlen(G)); wait_us(50000); bt.write((void *) I, strlen(I)); printf("send\n\r"); } } } float getMaxSon (void){ float max_son = 0; double tab_son[N]; //Récupération du capteur de son + calcule du max for (int i=0;i<N;i++){ tab_son[i]= son.read(); } max_son = tab_son[0]; for (int j=1;j<N;j++) { if(tab_son[j]>=max_son) max_son = tab_son[j]; } return max_son; } Gyro getGyro(double offsetx, double offsety, double offsetz) { double rate_gyr_x = 0, rate_gyr_y = 0, rate_gyr_z = 0; double gyroXangle=0, gyroYangle=0, gyroZangle=0; double gxx, gyy, gzz; double time_exec = 0; double axx, ayy, azz; double vx, vy, V; struct Gyro gyro; timer.start(); //récupération des valeurs du gyro - offset moyen acc.readGyro(); gxx = acc.gx - offsetx; gyy = acc.gy - offsety; gzz = acc.gz - offsetz; time_exec = timer.elapsed_time().count(); //calcule de l'angle de l'axe X if(gxx >= 1 | gxx <= -1){ //convertion des valeurs brute en angle rate_gyr_x = gxx * GAIN; gyroXangle+=rate_gyr_x*(time_exec/1000); //conditionnement de l'angle entre 0° et 360° if(gyroXangle > 360) gyroXangle = 0; else if (gyroXangle < 0) gyroXangle = 360; } //calcule de l'angle de l'axe Y if(gyy >= 1 | gyy <= -1){ rate_gyr_y = gyy * GAIN; gyroYangle+=rate_gyr_y*(time_exec/1000); if(gyroYangle > 360) gyroYangle = 0; else if (gyroYangle < 0) gyroYangle = 360; } //calcule de l'angle de l'axe Z if(gzz >= 1 | gzz <= -1){ rate_gyr_z = gzz * GAIN; gyroZangle += rate_gyr_z*(time_exec/1000); if(gyroZangle > 360) gyroZangle = 0; else if (gyroZangle < 0) gyroZangle = 360; } timer.reset(); //calcule de l'accéleration acc.readAccel(); axx = acc.ax; ayy = acc.ay; azz = acc.az; vx = vx + axx*9.8*1/104; vy = vy + ayy*9.8*1/104; V = sqrt(vx*vx+vy*vy); //attribution des valeurs à la structure gyro.v = V; gyro.x = gyroXangle; gyro.y = gyroYangle; gyro.z = gyroZangle; return gyro; } struct_GPS getGPS (void){ donneGPS myGPS; struct struct_GPS gps; int i = 0; char buffer[256] = {0}; char envoi[256] = {0}; int nb_byte = GPS.read((void*)&buffer[0], 1); char dollar[] = "$"; if(GPS.readable()) { //reset du buffer for(i=0; i<256;i++) { buffer[i] = {0}; } //lecture du GPS do{ GPS.read((void*)&buffer[0], 1); } while(strcmp(buffer, dollar)!= 0); //tri et mise en forme des données for(i=1; i<100 ; i++) { while(!GPS.readable()); GPS.read((void*)&buffer[i], 1); printf("Buffer[%d] = %s\r\n",i,(char*)&buffer[i]); wait_us(1000); if((strcmp(&buffer[i], "\r") == 0 || strcmp(&buffer[i], "$") == 0) && strlen(buffer) > 60) //buffer[i] == 10 || buffer[i] == 36) { strcpy(envoi, buffer); if(((envoi[3]) == 'G') && ((envoi[4]) == 'G') && ((envoi[5]) == 'A') && (strchr(envoi, '*') != 0) ) { myGPS.formatGGA(envoi); printf("Valeur de la longitude : %s\r\n", myGPS.getGGA().LONG); printf("Valeur de l'altitude : %s\r\n", myGPS.getGGA().ALT); printf("Valeur de Latitude : %s\r\n",myGPS.getGGA().LAT); } } } } strcpy(gps.lon, myGPS.getGGA().LONG); strcpy(gps.lat, myGPS.getGGA().LAT); strcpy(gps.alt, myGPS.getGGA().ALT); return gps; }
[ "noreply@github.com" ]
noreply@github.com
1012bb80112bd5deb45dbcf2a03fe9b359059df7
09866ba376f9aa53ab6d129e2ff4f89076664c6d
/Source/RTSProject/Plugins/DaedalicTestAutomationPlugin/Source/DaedalicTestAutomationPlugin/Public/DaeTestTriggerBox.h
7821dad7adfcd7ee300945b9b6c01512d3d7c838
[ "MIT" ]
permissive
JaredP94/ue4-rts
c05dee7f6b94fbed6343b0b04df8d921421f9cee
242aa314ea8a4ac4145af214399d2ecb6c25234c
refs/heads/develop
2021-05-17T22:53:11.999359
2020-12-20T19:48:54
2020-12-20T19:48:54
250,988,884
1
1
MIT
2020-12-20T19:48:55
2020-03-29T08:45:49
C++
UTF-8
C++
false
false
660
h
#pragma once #include <CoreMinimal.h> #include <Engine/TriggerBox.h> #include "DaeTestTriggerBox.generated.h" /** Trigger box to be used in automated tests. */ UCLASS() class DAEDALICTESTAUTOMATIONPLUGIN_API ADaeTestTriggerBox : public ATriggerBox { GENERATED_BODY() public: virtual void BeginPlay() override; /** Whether this trigger box has been triggered at least once. */ UFUNCTION(BlueprintPure) bool WasTriggered() const; private: /** Whether this trigger box has been triggered at least once. */ bool bWasTriggered; UFUNCTION() void OnActorBeginOverlapBroadcast(AActor* OverlappedActor, AActor* OtherActor); };
[ "dev@npruehs.de" ]
dev@npruehs.de
18bab6ded4bd5a49368285fd00cff79f4431f163
a15b4fdc03653228349bc529f76d040e31e0de9f
/inst/include/pbbam/internal/Compare.inl
4eb5ccfa52ae77fa7bb0d0845d3a070ab5eb9018
[]
no_license
evolvedmicrobe/pbbamr
a2dffeb2d2db3ab2d1383dd53211453adc767d78
22385446ab61631bd4eeeb58be0946f2d87f0c92
refs/heads/master
2020-06-28T18:43:42.364734
2017-10-02T19:18:22
2017-10-02T19:18:22
47,782,578
2
0
null
2016-01-21T00:55:07
2015-12-10T19:21:44
C++
UTF-8
C++
false
false
3,053
inl
// Copyright (c) 2014-2015, Pacific Biosciences of California, Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted (subject to the limitations in the // disclaimer below) provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of Pacific Biosciences nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE // GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY PACIFIC // BIOSCIENCES AND ITS CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL PACIFIC BIOSCIENCES OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF // USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. // // File Description /// \file Compare.inl /// \brief Inline implementations for the Compare class & inner classes. // // Author: Derek Barnett #include "pbbam/Compare.h" namespace PacBio { namespace BAM { namespace internal { template <typename T, T> struct MemberFnProxy; template<typename T, typename R, typename... Args, R (T::*fn)(Args...)const> struct MemberFnProxy<R (T::*)(Args...)const, fn> { static R call(const T& obj, Args&&... args) { return (obj.*fn)(std::forward<Args>(args)...); } }; } // namespace internal template<typename ValueType, typename Compare::MemberFunctionBaseHelper<ValueType>::MemberFnType fn, typename CompareType> inline bool Compare::MemberFunctionBase<ValueType, fn, CompareType>::operator()(const BamRecord& lhs, const BamRecord& rhs) const { using MemberFnType = typename Compare::MemberFunctionBaseHelper<ValueType>::MemberFnType; using Proxy = internal::MemberFnProxy<MemberFnType, fn>; CompareType cmp; return cmp(Proxy::call(lhs), Proxy::call(rhs)); } inline bool Compare::None::operator()(const BamRecord&, const BamRecord&) const { return false; } } // namespace BAM } // namespace PacBio
[ "spamavoid@outlook.com" ]
spamavoid@outlook.com
03c0cd092b981f2574bcaf06e91d6dff2987b634
6d6c567d706f2deb98b64447e46928b6dbbd5677
/checkPermission.cpp
f984ec201f6b9413500eab30f24fb85ff37b854f
[]
no_license
mxito3/IDGenerator
1b28f1c4c3cfd4b839cdec2f57a5d83e223a6109
363543383e07513c0c8dca946b10044f69f41d5e
refs/heads/master
2020-04-29T21:23:55.071998
2019-03-19T03:02:18
2019-03-19T03:02:18
176,411,735
0
0
null
null
null
null
UTF-8
C++
false
false
2,930
cpp
#include "checkPermission.h" string checkPermission::generateMD5(const char* password) { unsigned char md[MD5_DIGEST_LENGTH]; unsigned char* buffer_md5 = MD5((unsigned char*)password, strlen(password), md); char buf[32]; string result; for (int i = 0; i < MD5_DIGEST_LENGTH; i++) { sprintf(buf, "%02x", buffer_md5[i]); result.append( buf ); // ss << hex << (unsigned int)(result[i]); } return result; } bool checkPermission::check(string md5String) { bool result = false; std::vector<string> source; const char * filename = "/home/yapie/github/gketh/permissionController/cipherText.out"; std::ifstream file; file.open(filename,ios::in); if (file.is_open()) { std::string line; while (getline(file, line)) { source.push_back(line); } } else { cout<<"cant open "<<filename<<endl; } file.close(); if (search(source, md5String)) { result = true; } return result; } bool checkPermission::search(std::vector<std::string> source, std::string needFind) { bool result = false; for (unsigned int i = 0; i < source.size(); i++) { if (source[i] == needFind) { result = true; break; } } return result; } size_t WriteCallback(char *contents, size_t size, size_t nmemb, void *userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } bool checkPermission::checkUser(string userId, string password) { CURL* curl; CURLcode res; std::string readBuffer; /* In windows, this will init the winsock stuff */ curl_global_init(CURL_GLOBAL_ALL); /* get a curl handle */ curl = curl_easy_init(); if (curl) { /* First set the URL that is about to receive our POST. This URL can just as well be a https:// URL if that is what should receive the data. */ curl_easy_setopt(curl, CURLOPT_URL, "http://47.99.188.146:9999/api/user/"); /* Now specify the POST data */ char data[1024]; snprintf(data, sizeof(data), "password=%s&userId=%s", &password[0], &userId[0]); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl,CURLOPT_WRITEDATA, &readBuffer); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if (res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); /* always cleanup */ curl_easy_cleanup(curl); std::cout<<readBuffer; } curl_global_cleanup(); if(readBuffer == "true\n") { return true; } else { return false; } }
[ "1477311729@qq.com" ]
1477311729@qq.com
0697cc4c0ac0cfb969db57a67ff26c8074a2b54b
b52bb0b1d05f6063e18d18d304cedec1abd36a95
/graph1/DFS_SSTACK.cpp
83f80621df01e1530502bc0296aef619549b575d
[]
no_license
inzamamtoha/ProblemSolving_Algorithms
67f556f0cd8d7b6a9861ce8b4694d070745c0aed
52c6f4dd302539f8f1a3a14004c41083364c4361
refs/heads/master
2020-04-05T09:00:07.660770
2018-11-08T16:56:36
2018-11-08T16:56:36
156,738,275
0
0
null
null
null
null
UTF-8
C++
false
false
1,553
cpp
#include<bits/stdc++.h> #define pb push_back #define N 10000 using namespace std; vector<int>edge[N]; vector<int>cost[N]; int parent[1000]; void dfs(int source,int destination) { int i,j,k,u,v; int visited[1000],distance[1000]; memset(distance,-1,sizeof(distance)); memset(visited,-1,sizeof(distance)); stack<int>st; distance[source]=0; visited[source]=1; st.push(source); //printf("toha"); while(!st.empty()) { u=st.top(); st.pop(); for(i=0;i<edge[u].size();i++) { if(distance[edge[u][i]]==-1) { distance[edge[u][i]]=distance[u]+1; parent[edge[u][i]] = u; st.push(edge[u][i]); } } } cout<<"shortest distance: "<<distance[destination]<<endl;//shoretsest path distance cout<<"shortest path: "; cout<<destination<<" "; while(parent[destination]!=source && source!=destination) { int x = parent[destination]; cout<<x<<" "; destination=x; } cout<<source<<endl; } int main() { freopen("1.txt","r",stdin); int i,j,x,y,n,e; cin>>n>>e; for(i=0;i<e;i++) { cin>>x>>y; edge[x].push_back(y); edge[y].push_back(x); //cost[x].pb(1); //cost[y].pb(1);//undirected graph a cost always 1 } /*for(j=1;j<=n;j++) { cout<<edge[j].size()<<" size"<<endl; }*/ dfs(1,7); return 0; }
[ "inzamam.csedu@gmail.com" ]
inzamam.csedu@gmail.com
08432f078d9b83f6d4ea1ca0da5627f1dcbffcc7
ca72e6d7511c445ef7536e902bd45c18404cb3b7
/thrift/lib/cpp2/async/StreamCallbacks.h
23c737a6acba7768c04bf8c695ddeaa7e9c8f22c
[ "Apache-2.0" ]
permissive
xuning97/fbthrift
2e6d35dcde4a9fa764ad80e8bcd60b81665f3144
7ec76e3870bcf2f0f8258a0612d31aa903fdac3a
refs/heads/master
2021-03-14T10:39:58.084522
2020-03-12T02:57:46
2020-03-12T03:00:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,117
h
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <memory> #include <utility> #include <folly/ExceptionWrapper.h> #include <folly/io/IOBuf.h> #include <folly/io/async/EventBase.h> #include <thrift/lib/thrift/gen-cpp2/RpcMetadata_types.h> namespace apache { namespace thrift { struct FirstResponsePayload { FirstResponsePayload(std::unique_ptr<folly::IOBuf> p, ResponseRpcMetadata md) : payload(std::move(p)), metadata(std::move(md)) {} std::unique_ptr<folly::IOBuf> payload; ResponseRpcMetadata metadata; }; struct StreamPayload { StreamPayload(std::unique_ptr<folly::IOBuf> p, StreamPayloadMetadata md) : payload(std::move(p)), metadata(std::move(md)) {} std::unique_ptr<folly::IOBuf> payload; StreamPayloadMetadata metadata; }; struct HeadersPayload { HeadersPayload(HeadersPayloadContent p, HeadersPayloadMetadata md) : payload(std::move(p)), metadata(std::move(md)) {} HeadersPayloadContent payload; HeadersPayloadMetadata metadata; }; class StreamClientCallback; class StreamServerCallback { public: virtual ~StreamServerCallback() = default; FOLLY_NODISCARD virtual bool onStreamRequestN(uint64_t) = 0; virtual void onStreamCancel() = 0; FOLLY_NODISCARD virtual bool onSinkHeaders(HeadersPayload&&) { return true; } virtual void resetClientCallback(StreamClientCallback&) = 0; }; struct StreamServerCallbackCancel { void operator()(StreamServerCallback* streamServerCallback) noexcept { streamServerCallback->onStreamCancel(); } }; using StreamServerCallbackPtr = std::unique_ptr<StreamServerCallback, StreamServerCallbackCancel>; class ChannelServerCallback { public: virtual ~ChannelServerCallback() = default; virtual void onStreamRequestN(uint64_t) = 0; virtual void onStreamCancel() = 0; virtual void onSinkNext(StreamPayload&&) = 0; virtual void onSinkError(folly::exception_wrapper) = 0; virtual void onSinkComplete() = 0; }; class SinkServerCallback { public: virtual ~SinkServerCallback() = default; virtual void onSinkNext(StreamPayload&&) = 0; virtual void onSinkError(folly::exception_wrapper) = 0; virtual void onSinkComplete() = 0; virtual void onStreamCancel() = 0; }; class StreamClientCallback { public: virtual ~StreamClientCallback() = default; // StreamClientCallback must remain alive until onFirstResponse or // onFirstResponseError callback runs. FOLLY_NODISCARD virtual bool onFirstResponse( FirstResponsePayload&&, folly::EventBase*, StreamServerCallback*) = 0; virtual void onFirstResponseError(folly::exception_wrapper) = 0; FOLLY_NODISCARD virtual bool onStreamNext(StreamPayload&&) = 0; virtual void onStreamError(folly::exception_wrapper) = 0; virtual void onStreamComplete() = 0; FOLLY_NODISCARD virtual bool onStreamHeaders(HeadersPayload&&) { return true; } virtual void resetServerCallback(StreamServerCallback&) = 0; }; class ChannelClientCallback { public: virtual ~ChannelClientCallback() = default; // ChannelClientCallback must remain alive until onFirstResponse or // onFirstResponseError callback runs. virtual void onFirstResponse( FirstResponsePayload&&, folly::EventBase*, ChannelServerCallback*) = 0; virtual void onFirstResponseError(folly::exception_wrapper) = 0; virtual void onStreamNext(StreamPayload&&) = 0; virtual void onStreamError(folly::exception_wrapper) = 0; virtual void onStreamComplete() = 0; virtual void onSinkRequestN(uint64_t) = 0; virtual void onSinkCancel() = 0; }; class SinkClientCallback { public: virtual ~SinkClientCallback() = default; virtual void onFirstResponse( FirstResponsePayload&&, folly::EventBase*, SinkServerCallback*) = 0; virtual void onFirstResponseError(folly::exception_wrapper) = 0; virtual void onFinalResponse(StreamPayload&&) = 0; virtual void onFinalResponseError(folly::exception_wrapper) = 0; virtual void onSinkRequestN(uint64_t) = 0; }; namespace detail { struct EncodedError : std::exception { explicit EncodedError(std::unique_ptr<folly::IOBuf> buf) : encoded(std::move(buf)) {} EncodedError(const EncodedError& oth) : encoded(oth.encoded->clone()) {} EncodedError& operator=(const EncodedError& oth) { encoded = oth.encoded->clone(); return *this; } EncodedError(EncodedError&&) = default; EncodedError& operator=(EncodedError&&) = default; std::unique_ptr<folly::IOBuf> encoded; }; } // namespace detail } // namespace thrift } // namespace apache
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
628a8dcf5fc2183afaee472803434c8ec8010ca0
ca0f40ce5b93083d83ec26f473a3bad432fa173c
/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp
0d31f121832b933350a55d88ea5ffeb606d11047
[]
no_license
rynnokung/SunWellCore
74d48ebfe2b688dd3cacefc2af3dc6203953aeac
0f464e1847f733fb979116e1bc7b052b2cab14da
refs/heads/master
2021-01-21T05:23:19.518555
2016-07-10T19:59:57
2016-07-10T19:59:57
58,862,729
3
0
null
2016-07-10T19:59:58
2016-05-15T13:22:39
C++
UTF-8
C++
false
false
22,248
cpp
/* REWRITTEN FROM SCRATCH BY PUSSYWIZARD, IT OWNS NOW! */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "violet_hold.h" #include "Player.h" #define CLEANUP_CHECK_INTERVAL 5000 #define SPAWN_TIME 20000 enum vYells { CYANIGOSA_SAY_SPAWN = 3, SAY_SINCLARI_1 = 0 }; class instance_violet_hold : public InstanceMapScript { public: instance_violet_hold() : InstanceMapScript("instance_violet_hold", 608) { } InstanceScript* GetInstanceScript(InstanceMap* pMap) const { return new instance_violet_hold_InstanceMapScript(pMap); } struct instance_violet_hold_InstanceMapScript : public InstanceScript { instance_violet_hold_InstanceMapScript(Map* pMap) : InstanceScript(pMap) {} uint32 m_auiEncounter[MAX_ENCOUNTER]; bool CLEANED; uint8 EncounterStatus; uint32 uiFirstBoss, uiSecondBoss; std::string str_data; EventMap events; uint8 GateHealth; uint8 WaveCount; uint8 PortalLocation; bool bAchiev; bool bDefensesUsed; std::vector<uint64> GO_ActivationCrystalGUID; uint64 GO_MainGateGUID; uint64 GO_MoraggCellGUID; uint64 GO_ErekemCellGUID; uint64 GO_ErekemRightGuardCellGUID; uint64 GO_ErekemLeftGuardCellGUID; uint64 GO_IchoronCellGUID; uint64 GO_LavanthorCellGUID; uint64 GO_XevozzCellGUID; uint64 GO_ZuramatCellGUID; std::set<uint64> trashMobs; uint64 NPC_SinclariGUID; uint64 NPC_GuardGUID[4]; uint64 NPC_PortalGUID; uint64 NPC_DoorSealGUID; uint64 NPC_MoraggGUID; uint64 NPC_ErekemGUID; uint64 NPC_ErekemGuardGUID[2]; uint64 NPC_IchoronGUID; uint64 NPC_LavanthorGUID; uint64 NPC_XevozzGUID; uint64 NPC_ZuramatGUID; uint64 NPC_CyanigosaGUID; void Initialize() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); CLEANED = false; EncounterStatus = NOT_STARTED; uiFirstBoss = 0; uiSecondBoss = 0; events.Reset(); events.RescheduleEvent(EVENT_CHECK_PLAYERS, 0); GateHealth = 100; WaveCount = 0; PortalLocation = 0; bDefensesUsed = false; GO_ActivationCrystalGUID.clear(); GO_MainGateGUID = 0; GO_MoraggCellGUID = 0; GO_ErekemCellGUID = 0; GO_ErekemRightGuardCellGUID = 0; GO_ErekemLeftGuardCellGUID = 0; GO_IchoronCellGUID = 0; GO_LavanthorCellGUID = 0; GO_XevozzCellGUID = 0; GO_ZuramatCellGUID = 0; NPC_SinclariGUID = 0; memset(&NPC_GuardGUID, 0, sizeof(NPC_GuardGUID)); NPC_PortalGUID = 0; NPC_DoorSealGUID = 0; NPC_MoraggGUID = 0; NPC_ErekemGUID = 0; NPC_ErekemGuardGUID[0] = NPC_ErekemGuardGUID[1] = 0; NPC_IchoronGUID = 0; NPC_LavanthorGUID = 0; NPC_XevozzGUID = 0; NPC_ZuramatGUID = 0; NPC_CyanigosaGUID = 0; } bool IsEncounterInProgress() const { return false; } void OnCreatureCreate(Creature* creature) { switch(creature->GetEntry()) { case NPC_SINCLARI: NPC_SinclariGUID = creature->GetGUID(); break; case NPC_VIOLET_HOLD_GUARD: for (uint8 i=0; i<4; ++i) if (NPC_GuardGUID[i] == 0) { NPC_GuardGUID[i] = creature->GetGUID(); break; } break; case NPC_DEFENSE_DUMMY_TARGET: creature->ApplySpellImmune(0, IMMUNITY_ID, SPELL_ARCANE_LIGHTNING, true); break; case NPC_TELEPORTATION_PORTAL: NPC_PortalGUID = creature->GetGUID(); break; case NPC_PRISON_DOOR_SEAL: NPC_DoorSealGUID = creature->GetGUID(); break; // BOSSES BELOW: case NPC_XEVOZZ: NPC_XevozzGUID = creature->GetGUID(); break; case NPC_LAVANTHOR: NPC_LavanthorGUID = creature->GetGUID(); break; case NPC_ICHORON: NPC_IchoronGUID = creature->GetGUID(); break; case NPC_ZURAMAT: NPC_ZuramatGUID = creature->GetGUID(); break; case NPC_EREKEM: NPC_ErekemGUID = creature->GetGUID(); break; case NPC_EREKEM_GUARD: if (NPC_ErekemGuardGUID[0] == 0) NPC_ErekemGuardGUID[0] = creature->GetGUID(); else NPC_ErekemGuardGUID[1] = creature->GetGUID(); break; case NPC_MORAGG: NPC_MoraggGUID = creature->GetGUID(); break; case NPC_CYANIGOSA: NPC_CyanigosaGUID = creature->GetGUID(); break; } } void OnGameObjectCreate(GameObject* go) { switch(go->GetEntry()) { case GO_ACTIVATION_CRYSTAL: HandleGameObject(0, false, go); // make go not used yet go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); // not useable at the beginning GO_ActivationCrystalGUID.push_back(go->GetGUID()); break; case GO_MAIN_DOOR: GO_MainGateGUID = go->GetGUID(); break; // BOSS GATES BELOW: case GO_EREKEM_GUARD_1_DOOR: GO_ErekemLeftGuardCellGUID = go->GetGUID(); break; case GO_EREKEM_GUARD_2_DOOR: GO_ErekemRightGuardCellGUID = go->GetGUID(); break; case GO_EREKEM_DOOR: GO_ErekemCellGUID = go->GetGUID(); break; case GO_ZURAMAT_DOOR: GO_ZuramatCellGUID = go->GetGUID(); break; case GO_LAVANTHOR_DOOR: GO_LavanthorCellGUID = go->GetGUID(); break; case GO_MORAGG_DOOR: GO_MoraggCellGUID = go->GetGUID(); break; case GO_ICHORON_DOOR: GO_IchoronCellGUID = go->GetGUID(); break; case GO_XEVOZZ_DOOR: GO_XevozzCellGUID = go->GetGUID(); break; } } void SetData(uint32 type, uint32 data) { switch(type) { case DATA_ACTIVATE_DEFENSE_SYSTEM: { if (data) bDefensesUsed = true; const Position pos = {1919.09546f, 812.29724f, 86.2905f, M_PI}; instance->SummonCreature(NPC_DEFENSE_SYSTEM, pos, 0, 6499); } break; case DATA_START_INSTANCE: if (EncounterStatus == NOT_STARTED) { EncounterStatus = IN_PROGRESS; if (Creature* c = instance->GetCreature(NPC_SinclariGUID)) c->AI()->Talk(SAY_SINCLARI_1); events.RescheduleEvent(EVENT_GUARDS_FALL_BACK, 4000); } break; case DATA_PORTAL_DEFEATED: events.RescheduleEvent(EVENT_SUMMON_PORTAL, 3000); break; case DATA_PORTAL_LOCATION: PortalLocation = data; break; case DATA_DECRASE_DOOR_HEALTH: if (GateHealth>0) --GateHealth; if (GateHealth==0) { CLEANED = false; InstanceCleanup(); } DoUpdateWorldState(WORLD_STATE_VH_PRISON_STATE, (uint32)GateHealth); break; case DATA_RELEASE_BOSS: if (WaveCount == 6) StartBossEncounter(uiFirstBoss); else StartBossEncounter(uiSecondBoss); break; case DATA_BOSS_DIED: if (WaveCount == 6) m_auiEncounter[0] = DONE; else if (WaveCount == 12) m_auiEncounter[1] = DONE; else if (WaveCount == 18) { m_auiEncounter[2] = DONE; EncounterStatus = DONE; HandleGameObject(GO_MainGateGUID, true); DoUpdateWorldState(WORLD_STATE_VH_SHOW, 0); if (Creature* c = instance->GetCreature(NPC_SinclariGUID)) { c->DespawnOrUnsummon(); c->SetRespawnTime(3); } } SaveToDB(); if (WaveCount < 18) events.RescheduleEvent(EVENT_SUMMON_PORTAL, 35000); break; case DATA_FAILED: CLEANED = false; InstanceCleanup(); break; case DATA_ACHIEV: bAchiev = data ? true : false; break; } } void SetData64(uint32 type, uint64 data) { switch(type) { case DATA_ADD_TRASH_MOB: trashMobs.insert(data); break; case DATA_DELETE_TRASH_MOB: if (!CLEANED) trashMobs.erase(data); break; } } uint32 GetData(uint32 type) const { switch(type) { case DATA_ENCOUNTER_STATUS: return (uint32)EncounterStatus; case DATA_WAVE_COUNT: return (uint32)WaveCount; case DATA_PORTAL_LOCATION: return PortalLocation; case DATA_FIRST_BOSS_NUMBER: return uiFirstBoss; case DATA_SECOND_BOSS_NUMBER: return uiSecondBoss; } return 0; } uint64 GetData64(uint32 identifier) const { switch(identifier) { case DATA_TELEPORTATION_PORTAL_GUID: return NPC_PortalGUID; case DATA_DOOR_SEAL_GUID: return NPC_DoorSealGUID; case DATA_EREKEM_GUID: return NPC_ErekemGUID; case DATA_EREKEM_GUARD_1_GUID: return NPC_ErekemGuardGUID[0]; case DATA_EREKEM_GUARD_2_GUID: return NPC_ErekemGuardGUID[1]; case DATA_ICHORON_GUID: return NPC_IchoronGUID; } return 0; } void StartBossEncounter(uint8 uiBoss) { Creature* pBoss = NULL; switch(uiBoss) { case BOSS_MORAGG: HandleGameObject(GO_MoraggCellGUID, true); pBoss = instance->GetCreature(NPC_MoraggGUID); if (pBoss) pBoss->GetMotionMaster()->MovePoint(0, BossStartMove1); break; case BOSS_EREKEM: HandleGameObject(GO_ErekemCellGUID, true); HandleGameObject(GO_ErekemRightGuardCellGUID, true); HandleGameObject(GO_ErekemLeftGuardCellGUID, true); pBoss = instance->GetCreature(NPC_ErekemGUID); if (pBoss) pBoss->GetMotionMaster()->MovePoint(0, BossStartMove2); if (Creature* pGuard1 = instance->GetCreature(NPC_ErekemGuardGUID[0])) { pGuard1->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); pGuard1->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); pGuard1->GetMotionMaster()->MovePoint(0, BossStartMove21); } if (Creature* pGuard2 = instance->GetCreature(NPC_ErekemGuardGUID[1])) { pGuard2->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); pGuard2->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); pGuard2->GetMotionMaster()->MovePoint(0, BossStartMove22); } break; case BOSS_ICHORON: HandleGameObject(GO_IchoronCellGUID, true); pBoss = instance->GetCreature(NPC_IchoronGUID); if (pBoss) pBoss->GetMotionMaster()->MovePoint(0, BossStartMove3); break; case BOSS_LAVANTHOR: HandleGameObject(GO_LavanthorCellGUID, true); pBoss = instance->GetCreature(NPC_LavanthorGUID); if (pBoss) pBoss->GetMotionMaster()->MovePoint(0, BossStartMove4); break; case BOSS_XEVOZZ: HandleGameObject(GO_XevozzCellGUID, true); pBoss = instance->GetCreature(NPC_XevozzGUID); if (pBoss) pBoss->GetMotionMaster()->MovePoint(0, BossStartMove5); break; case BOSS_ZURAMAT: HandleGameObject(GO_ZuramatCellGUID, true); pBoss = instance->GetCreature(NPC_ZuramatGUID); if (pBoss) pBoss->GetMotionMaster()->MovePoint(0, BossStartMove6); break; } if (pBoss) { pBoss->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); pBoss->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); pBoss->SetReactState(REACT_AGGRESSIVE); if (WaveCount == 6 && m_auiEncounter[0] == DONE || WaveCount == 12 && m_auiEncounter[1] == DONE) pBoss->SetLootMode(0); } } void Update(uint32 diff) { events.Update(diff); switch( events.GetEvent() ) { case 0: break; case EVENT_CHECK_PLAYERS: { if( DoNeedCleanup(false) ) InstanceCleanup(); events.RepeatEvent(CLEANUP_CHECK_INTERVAL); } break; case EVENT_GUARDS_FALL_BACK: { for (uint8 i=0; i<4; ++i) if (Creature* c = instance->GetCreature(NPC_GuardGUID[i])) { c->SetReactState(REACT_PASSIVE); c->CombatStop(); c->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); c->GetMotionMaster()->MovePoint(0, guardMovePosition); } events.PopEvent(); events.RescheduleEvent(EVENT_GUARDS_DISAPPEAR, 5000); } break; case EVENT_GUARDS_DISAPPEAR: { for (uint8 i=0; i<4; ++i) if (Creature* c = instance->GetCreature(NPC_GuardGUID[i])) c->SetVisible(false); events.PopEvent(); events.RescheduleEvent(EVENT_SINCLARI_FALL_BACK, 2000); } break; case EVENT_SINCLARI_FALL_BACK: { if (Creature* c = instance->GetCreature(NPC_SinclariGUID)) { c->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); c->GetMotionMaster()->MovePoint(0, sinclariOutsidePosition); } SetData(DATA_ACTIVATE_DEFENSE_SYSTEM, 0); events.PopEvent(); events.RescheduleEvent(EVENT_START_ENCOUNTER, 4000); } break; case EVENT_START_ENCOUNTER: { if (Creature* c = instance->GetCreature(NPC_DoorSealGUID)) c->RemoveAllAuras(); // just to be sure... GateHealth = 100; HandleGameObject(GO_MainGateGUID, false); DoUpdateWorldState(WORLD_STATE_VH_SHOW, 1); DoUpdateWorldState(WORLD_STATE_VH_PRISON_STATE, (uint32)GateHealth); DoUpdateWorldState(WORLD_STATE_VH_WAVE_COUNT, (uint32)WaveCount); for (std::vector<uint64>::iterator itr = GO_ActivationCrystalGUID.begin(); itr != GO_ActivationCrystalGUID.end(); ++itr) if (GameObject* go = instance->GetGameObject(*itr)) { HandleGameObject(0, false, go); // not used yet go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); // make it useable } events.PopEvent(); events.RescheduleEvent(EVENT_SUMMON_PORTAL, 4000); } break; case EVENT_SUMMON_PORTAL: ++WaveCount; DoUpdateWorldState(WORLD_STATE_VH_WAVE_COUNT, (uint32)WaveCount); SetData(DATA_PORTAL_LOCATION, (GetData(DATA_PORTAL_LOCATION) + urand(1, 5))%6); if (Creature* c = instance->GetCreature(NPC_SinclariGUID)) { if (WaveCount%6 != 0) c->SummonCreature(NPC_TELEPORTATION_PORTAL, PortalLocations[GetData(DATA_PORTAL_LOCATION)], TEMPSUMMON_CORPSE_DESPAWN); else if (WaveCount == 6 || WaveCount == 12) // first or second boss { if (!uiFirstBoss || !uiSecondBoss) { uiFirstBoss = urand(1,6); do { uiSecondBoss = urand(1,6); } while (uiFirstBoss==uiSecondBoss); SaveToDB(); } c->SummonCreature(NPC_TELEPORTATION_PORTAL, MiddleRoomPortalSaboLocation, TEMPSUMMON_CORPSE_DESPAWN); } else // cyanigossa { if (Creature* cyanigosa = c->SummonCreature(NPC_CYANIGOSA, CyanigosasSpawnLocation, TEMPSUMMON_DEAD_DESPAWN)) { cyanigosa->CastSpell(cyanigosa, SPELL_CYANIGOSA_BLUE_AURA, false); cyanigosa->AI()->Talk(CYANIGOSA_SAY_SPAWN); cyanigosa->GetMotionMaster()->MoveJump(MiddleRoomLocation.GetPositionX(), MiddleRoomLocation.GetPositionY(), MiddleRoomLocation.GetPositionZ(), 10.0f, 20.0f); } events.RescheduleEvent(EVENT_CYANIGOSSA_TRANSFORM, 10000); } } events.PopEvent(); break; case EVENT_CYANIGOSSA_TRANSFORM: if (Creature* c = instance->GetCreature(NPC_CyanigosaGUID)) { c->RemoveAurasDueToSpell(SPELL_CYANIGOSA_BLUE_AURA); c->CastSpell(c, SPELL_CYANIGOSA_TRANSFORM, 0); events.RescheduleEvent(EVENT_CYANIGOSA_ATTACK, 2500); } events.PopEvent(); break; case EVENT_CYANIGOSA_ATTACK: if (Creature* c = instance->GetCreature(NPC_CyanigosaGUID)) c->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); events.PopEvent(); break; } } void OnPlayerEnter(Player* plr) { if( DoNeedCleanup(plr->IsAlive()) ) InstanceCleanup(); if (EncounterStatus == IN_PROGRESS) { plr->SendUpdateWorldState(WORLD_STATE_VH_SHOW, 1); plr->SendUpdateWorldState(WORLD_STATE_VH_PRISON_STATE, (uint32)GateHealth); plr->SendUpdateWorldState(WORLD_STATE_VH_WAVE_COUNT, (uint32)WaveCount); } else plr->SendUpdateWorldState(WORLD_STATE_VH_SHOW, 0); events.RescheduleEvent(EVENT_CHECK_PLAYERS, CLEANUP_CHECK_INTERVAL); } bool DoNeedCleanup(bool enter) { uint8 aliveCount = 0; Map::PlayerList const &pl = instance->GetPlayers(); for( Map::PlayerList::const_iterator itr = pl.begin(); itr != pl.end(); ++itr ) if( Player* plr = itr->GetSource() ) if( plr->IsAlive() && !plr->IsGameMaster() && !plr->HasAura(27827)/*spirit of redemption aura*/ ) ++aliveCount; bool need = enter ? aliveCount<=1 : aliveCount==0; if( !need && CLEANED ) CLEANED = false; return need; } void InstanceCleanup() { if( CLEANED ) return; CLEANED = true; // reset defense crystals for (std::vector<uint64>::iterator itr = GO_ActivationCrystalGUID.begin(); itr != GO_ActivationCrystalGUID.end(); ++itr) if (GameObject* go = instance->GetGameObject(*itr)) { HandleGameObject(0, false, go); // not used yet go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); // not useable at the beginning } // reset positions of Sinclari and Guards if (Creature* c = instance->GetCreature(NPC_SinclariGUID)) { c->DespawnOrUnsummon(); c->SetRespawnTime(3); } for (uint8 i=0; i<4; ++i) if (Creature* c = instance->GetCreature(NPC_GuardGUID[i])) { c->DespawnOrUnsummon(); c->SetRespawnTime(3); if (m_auiEncounter[MAX_ENCOUNTER-1] == DONE) c->SetVisible(false); else c->SetVisible(true); c->SetReactState(REACT_AGGRESSIVE); } // remove portal if any if (Creature* c = instance->GetCreature(NPC_PortalGUID)) c->DespawnOrUnsummon(); NPC_PortalGUID = 0; // remove trash for (std::set<uint64>::iterator itr = trashMobs.begin(); itr != trashMobs.end(); ++itr) if (Creature* c = instance->GetCreature(*itr)) c->DespawnOrUnsummon(); trashMobs.clear(); // clear door seal damaging auras: if (Creature* c = instance->GetCreature(NPC_DoorSealGUID)) c->RemoveAllAuras(); // open main gate HandleGameObject(GO_MainGateGUID, true); if (m_auiEncounter[MAX_ENCOUNTER-1] != DONE) // instance not finished { // close all cells HandleGameObject(GO_MoraggCellGUID, false); HandleGameObject(GO_ErekemCellGUID, false); HandleGameObject(GO_ErekemRightGuardCellGUID, false); HandleGameObject(GO_ErekemLeftGuardCellGUID, false); HandleGameObject(GO_IchoronCellGUID, false); HandleGameObject(GO_LavanthorCellGUID, false); HandleGameObject(GO_XevozzCellGUID, false); HandleGameObject(GO_ZuramatCellGUID, false); // respawn bosses if (Creature* c = instance->GetCreature(NPC_MoraggGUID)) { c->DespawnOrUnsummon(); c->SetRespawnTime(3); c->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); } if (Creature* c = instance->GetCreature(NPC_MoraggGUID)) { c->DespawnOrUnsummon(); c->SetRespawnTime(3); c->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); } if (Creature* c = instance->GetCreature(NPC_ErekemGUID)) { c->DespawnOrUnsummon(); c->SetRespawnTime(3); c->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); } if (Creature* c = instance->GetCreature(NPC_ErekemGuardGUID[0])) { c->DespawnOrUnsummon(); c->SetRespawnTime(3); c->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); } if (Creature* c = instance->GetCreature(NPC_ErekemGuardGUID[1])) { c->DespawnOrUnsummon(); c->SetRespawnTime(3); c->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); } if (Creature* c = instance->GetCreature(NPC_IchoronGUID)) { c->DespawnOrUnsummon(); c->SetRespawnTime(3); c->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); } if (Creature* c = instance->GetCreature(NPC_LavanthorGUID)) { c->DespawnOrUnsummon(); c->SetRespawnTime(3); c->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); } if (Creature* c = instance->GetCreature(NPC_XevozzGUID)) { c->DespawnOrUnsummon(); c->SetRespawnTime(3); c->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); } if (Creature* c = instance->GetCreature(NPC_ZuramatGUID)) { c->DespawnOrUnsummon(); c->SetRespawnTime(3); c->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_NPC); } if (Creature* c = instance->GetCreature(NPC_CyanigosaGUID)) { c->DespawnOrUnsummon(); } } // reinitialize variables and events DoUpdateWorldState(WORLD_STATE_VH_SHOW, 0); EncounterStatus = NOT_STARTED; GateHealth = 100; WaveCount = 0; bDefensesUsed = false; if (m_auiEncounter[MAX_ENCOUNTER-1] == DONE) EncounterStatus = DONE; events.Reset(); events.RescheduleEvent(EVENT_CHECK_PLAYERS, CLEANUP_CHECK_INTERVAL); } bool CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* source, Unit const* target = NULL, uint32 miscvalue1 = 0) { switch(criteria_id) { case CRITERIA_DEFENSELESS: return GateHealth == 100 && !bDefensesUsed; case CRITERIA_A_VOID_DANCE: case CRITERIA_DEHYDRATION: return bAchiev; } return false; } std::string GetSaveData() { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << "V H " << m_auiEncounter[0] << ' ' << m_auiEncounter[1] << ' ' << m_auiEncounter[2] << ' ' << uiFirstBoss << ' ' << uiSecondBoss; str_data = saveStream.str(); OUT_SAVE_INST_DATA_COMPLETE; return str_data; } void Load(const char* in) { EncounterStatus = NOT_STARTED; CLEANED = false; events.Reset(); events.RescheduleEvent(EVENT_CHECK_PLAYERS, 0); if (!in) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(in); char dataHead1, dataHead2; uint32 data0, data1, data2, data3, data4; std::istringstream loadStream(in); loadStream >> dataHead1 >> dataHead2 >> data0 >> data1 >> data2 >> data3 >> data4; if (dataHead1 == 'V' && dataHead2 == 'H') { m_auiEncounter[0] = data0; m_auiEncounter[1] = data1; m_auiEncounter[2] = data2; uiFirstBoss = data3; uiSecondBoss = data4; for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) if (m_auiEncounter[i] == IN_PROGRESS) m_auiEncounter[i] = NOT_STARTED; if (m_auiEncounter[MAX_ENCOUNTER-1] == DONE) EncounterStatus = DONE; } else OUT_LOAD_INST_DATA_FAIL; OUT_LOAD_INST_DATA_COMPLETE; } }; }; void AddSC_instance_violet_hold() { new instance_violet_hold(); }
[ "phil19-94@hotmail.fr" ]
phil19-94@hotmail.fr
357047dd6b7280379a148c13532715f48746e786
630acfe003ad5305ff091e9ca968e3ed0464476e
/src/event_loop.cc
47ef09025977af22925c3334eddfd416de237465
[]
no_license
inhzus/lotta
7bc7091c8aedd0e199abd3cdf337d9026811da6e
058186feb88020631a647d54614ef4731ca3a93a
refs/heads/master
2020-09-07T04:47:18.496433
2019-12-03T09:35:23
2019-12-03T09:35:23
220,659,721
2
0
null
null
null
null
UTF-8
C++
false
false
4,100
cc
// // Created by suun on 11/7/19. // #include "lotta/event_loop.h" #include "lotta/channel.h" #include "lotta/poller.h" #include "lotta/socket.h" #include "lotta/timer.h" #include "lotta/timer_queue.h" #include "lotta/utils/this_thread.h" #include "lotta/utils/logging.h" #include <sys/eventfd.h> namespace lotta { thread_local EventLoop *t_eventLoopThisThread = nullptr; const int kPollTimeout = 5 * 1000; int createEventFd() { int fd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); if (fd < 0) { SPDLOG_CRITICAL("event fd fails to initialize"); } return fd; } EventLoop::EventLoop() : looping_(false), quit_(false), threadId_(utils::this_thread::id()), poller_(Poller::get(this)), wakeupFd_(createEventFd()), wakeChannel_(std::make_unique<Channel>(this, wakeupFd_)), doingFuncQueue_(false), timerQueue_(std::make_unique<TimerQueue>(this)) { SPDLOG_TRACE("EventLoop {} created in thread {}", static_cast<void *>(this), threadId_); if (t_eventLoopThisThread) { SPDLOG_TRACE("another EventLoop {} exists", (void *) t_eventLoopThisThread); } else { t_eventLoopThisThread = this; } wakeChannel_->setReadCallback(std::bind(&EventLoop::handleWakeup, this)); wakeChannel_->enableReading(); } EventLoop::~EventLoop() { t_eventLoopThisThread = nullptr; wakeChannel_->disableEvents(); wakeChannel_->remove(); socket::close(wakeupFd_); } void EventLoop::loop() { assertTheSameThread(); looping_ = true; quit_ = false; SPDLOG_TRACE("EventLoop {} looping", static_cast<void *>(this)); while (!quit_) { activeChannels_.clear(); poller_->poll(kPollTimeout, activeChannels_); for (auto channel : activeChannels_) { channel->handleEvent(); } doFuncQueue(); } SPDLOG_TRACE("EventLoop {} stops", static_cast<void *>(this)); looping_ = false; } void EventLoop::quit() { quit_ = true; if (!isTheSameThread()) { wakeup(); } } void EventLoop::updateChannel(Channel *channel) { assertTheSameThread(); poller_->updateChannel(channel); } void EventLoop::removeChannel(Channel *channel) { assertTheSameThread(); poller_->removeChannel(channel); } void EventLoop::exec(EventLoop::Function f) { if (isTheSameThread()) { f(); } else { pushQueue(std::move(f)); } } void EventLoop::pushQueue(EventLoop::Function f) { { std::lock_guard guard(funcQueueMtx_); funcQueue_.push_back(std::move(f)); } // iff in the same thread & not doing funcQueue (aka activeChannel callbacks) if ((!isTheSameThread()) | doingFuncQueue_) { wakeup(); } } void EventLoop::doFuncQueue() { std::vector<Function> functions; doingFuncQueue_ = true; { std::lock_guard guard(funcQueueMtx_); functions.swap(funcQueue_); } for (Function &func : functions) { func(); } doingFuncQueue_ = false; } std::weak_ptr<Timer> EventLoop::runAfter( EventLoop::Function func, double interval) { Timer::time_point point = std::chrono::time_point_cast<Timer::duration>( Timer::clock::now() + std::chrono::duration<double>(interval)); return timerQueue_->addTimer(std::move(func), point, 0); } std::weak_ptr<Timer> EventLoop::runEvery( EventLoop::Function func, double interval) { Timer::time_point point = std::chrono::time_point_cast<Timer::duration>( Timer::clock::now() + std::chrono::duration<double>(interval)); return timerQueue_->addTimer(std::move(func), point, interval); } void EventLoop::cancel(const std::weak_ptr<Timer> &timer) { timerQueue_->cancel(timer); } void EventLoop::assertTheSameThread() const { if (!isTheSameThread()) { SPDLOG_CRITICAL("not in the same thread of EventLoop"); assert(isTheSameThread()); } } bool EventLoop::isTheSameThread() const { return threadId_ == utils::this_thread::id(); } void EventLoop::wakeup() { uint64_t tmp = 1; auto n = socket::write(wakeupFd_, &tmp, sizeof(tmp)); SPDLOG_ERRNO_IF(n != sizeof(tmp)); } void EventLoop::handleWakeup() { uint64_t tmp; auto n = socket::read(wakeupFd_, &tmp, sizeof(tmp)); SPDLOG_ERRNO_IF(n != sizeof(tmp)); } }
[ "inhzus@gmail.com" ]
inhzus@gmail.com
a2cfb938a33348819b31441bf402b708b675b7d1
647a740253a604da280f3a278969c9aba1a50381
/src/trace_processor/containers/bit_vector_benchmark.cc
b4a0c276ee5af657e6d9725d4920e4709bae739c
[ "Apache-2.0" ]
permissive
zakerinasab/perfetto
db4471b9759286143e4fdb50c097196babfad29c
7f86589d1522ce8bfc59f6b569ca52496a53eb79
refs/heads/master
2020-12-07T05:58:32.918688
2020-01-08T14:37:52
2020-01-08T17:19:59
195,857,570
0
0
NOASSERTION
2019-07-16T21:14:19
2019-07-08T17:29:15
C++
UTF-8
C++
false
false
6,144
cc
// Copyright (C) 2019 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <random> #include <benchmark/benchmark.h> #include "src/trace_processor/containers/bit_vector.h" namespace { using perfetto::trace_processor::BitVector; bool IsBenchmarkFunctionalOnly() { return getenv("BENCHMARK_FUNCTIONAL_TEST_ONLY") != nullptr; } void BitVectorArgs(benchmark::internal::Benchmark* b) { b->Arg(64); if (!IsBenchmarkFunctionalOnly()) { b->Arg(512); b->Arg(8192); b->Arg(123456); b->Arg(1234567); } } } // namespace static void BM_BitVectorAppendTrue(benchmark::State& state) { BitVector bv; for (auto _ : state) { bv.AppendTrue(); benchmark::ClobberMemory(); } } BENCHMARK(BM_BitVectorAppendTrue); static void BM_BitVectorAppendFalse(benchmark::State& state) { BitVector bv; for (auto _ : state) { bv.AppendFalse(); benchmark::ClobberMemory(); } } BENCHMARK(BM_BitVectorAppendFalse); static void BM_BitVectorSet(benchmark::State& state) { static constexpr uint32_t kRandomSeed = 42; std::minstd_rand0 rnd_engine(kRandomSeed); uint32_t size = static_cast<uint32_t>(state.range(0)); BitVector bv; for (uint32_t i = 0; i < size; ++i) { if (rnd_engine() % 2) { bv.AppendTrue(); } else { bv.AppendFalse(); } } static constexpr uint32_t kPoolSize = 1024 * 1024; std::vector<bool> bit_pool(kPoolSize); std::vector<uint32_t> row_pool(kPoolSize); for (uint32_t i = 0; i < kPoolSize; ++i) { bit_pool[i] = rnd_engine() % 2; row_pool[i] = rnd_engine() % size; } uint32_t pool_idx = 0; for (auto _ : state) { bv.Set(row_pool[pool_idx]); pool_idx = (pool_idx + 1) % kPoolSize; benchmark::ClobberMemory(); } } BENCHMARK(BM_BitVectorSet)->Apply(BitVectorArgs); static void BM_BitVectorClear(benchmark::State& state) { static constexpr uint32_t kRandomSeed = 42; std::minstd_rand0 rnd_engine(kRandomSeed); uint32_t size = static_cast<uint32_t>(state.range(0)); BitVector bv; for (uint32_t i = 0; i < size; ++i) { if (rnd_engine() % 2) { bv.AppendTrue(); } else { bv.AppendFalse(); } } static constexpr uint32_t kPoolSize = 1024 * 1024; std::vector<uint32_t> row_pool(kPoolSize); for (uint32_t i = 0; i < kPoolSize; ++i) { row_pool[i] = rnd_engine() % size; } uint32_t pool_idx = 0; for (auto _ : state) { bv.Clear(row_pool[pool_idx]); pool_idx = (pool_idx + 1) % kPoolSize; benchmark::ClobberMemory(); } } BENCHMARK(BM_BitVectorClear)->Apply(BitVectorArgs); static void BM_BitVectorIndexOfNthSet(benchmark::State& state) { static constexpr uint32_t kRandomSeed = 42; std::minstd_rand0 rnd_engine(kRandomSeed); uint32_t size = static_cast<uint32_t>(state.range(0)); BitVector bv; for (uint32_t i = 0; i < size; ++i) { if (rnd_engine() % 2) { bv.AppendTrue(); } else { bv.AppendFalse(); } } static constexpr uint32_t kPoolSize = 1024 * 1024; std::vector<uint32_t> row_pool(kPoolSize); uint32_t set_bit_count = bv.GetNumBitsSet(); for (uint32_t i = 0; i < kPoolSize; ++i) { row_pool[i] = rnd_engine() % set_bit_count; } uint32_t pool_idx = 0; for (auto _ : state) { benchmark::DoNotOptimize(bv.IndexOfNthSet(row_pool[pool_idx])); pool_idx = (pool_idx + 1) % kPoolSize; } } BENCHMARK(BM_BitVectorIndexOfNthSet)->Apply(BitVectorArgs); static void BM_BitVectorGetNumBitsSet(benchmark::State& state) { static constexpr uint32_t kRandomSeed = 42; std::minstd_rand0 rnd_engine(kRandomSeed); uint32_t size = static_cast<uint32_t>(state.range(0)); uint32_t count = 0; BitVector bv; for (uint32_t i = 0; i < size; ++i) { bool value = rnd_engine() % 2; if (value) { bv.AppendTrue(); } else { bv.AppendFalse(); } if (value) count++; } uint32_t res = count; for (auto _ : state) { benchmark::DoNotOptimize(res &= bv.GetNumBitsSet()); } PERFETTO_CHECK(res == count); } BENCHMARK(BM_BitVectorGetNumBitsSet)->Apply(BitVectorArgs); static void BM_BitVectorResize(benchmark::State& state) { static constexpr uint32_t kRandomSeed = 42; std::minstd_rand0 rnd_engine(kRandomSeed); static constexpr uint32_t kPoolSize = 1024 * 1024; static constexpr uint32_t kMaxSize = 1234567; std::vector<bool> resize_fill_pool(kPoolSize); std::vector<uint32_t> resize_count_pool(kPoolSize); for (uint32_t i = 0; i < kPoolSize; ++i) { resize_fill_pool[i] = rnd_engine() % 2; resize_count_pool[i] = rnd_engine() % kMaxSize; } uint32_t pool_idx = 0; BitVector bv; for (auto _ : state) { bv.Resize(resize_count_pool[pool_idx], resize_fill_pool[pool_idx]); pool_idx = (pool_idx + 1) % kPoolSize; benchmark::ClobberMemory(); } } BENCHMARK(BM_BitVectorResize); static void BM_BitVectorUpdateSetBits(benchmark::State& state) { static constexpr uint32_t kRandomSeed = 42; std::minstd_rand0 rnd_engine(kRandomSeed); uint32_t size = static_cast<uint32_t>(state.range(0)); BitVector bv; BitVector picker; for (uint32_t i = 0; i < size; ++i) { bool value = rnd_engine() % 2; if (value) { bv.AppendTrue(); bool picker_value = rnd_engine() % 2; if (picker_value) { picker.AppendTrue(); } else { picker.AppendFalse(); } } else { bv.AppendFalse(); } } for (auto _ : state) { state.PauseTiming(); BitVector copy = bv.Copy(); state.ResumeTiming(); copy.UpdateSetBits(picker); benchmark::ClobberMemory(); } } BENCHMARK(BM_BitVectorUpdateSetBits)->Apply(BitVectorArgs);
[ "lalitm@google.com" ]
lalitm@google.com
7e0a2e78f54f3e8793e9e5ce04461debe9d29f18
eafc5ac599f2e96c3ca61612abb109eba2abe655
/conjugateHeat/planeWall2D/0/topAir/k
f0b1aff7fba6b53633c751ea9e844920a45913a7
[]
no_license
kohyun/OpenFOAM_MSc_Thesis_Project
b651eb129611d41dbb4d3b08a2dec0d4db7663b3
11f6b69c23082b3b47b04963c5fc87b8ab4dd08d
refs/heads/master
2023-03-17T22:34:57.127580
2019-01-12T07:41:07
2019-01-12T07:41:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,461
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0/topAir"; object k; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [ 0 2 -2 0 0 0 0 ]; internalField uniform 0.1; boundaryField { topAir_top { type symmetryPlane; value uniform 0; } leftLet { type inletOutlet; value uniform 0.1; inletValue uniform 0.1; } rightLet { type fixedValue; value uniform 0.1; } frontAndBack { type empty; } topAir_to_wall { type compressible::kqRWallFunction; value uniform 0.1; } } // ************************************************************************* //
[ "ali@ali-Inspiron-1525.(none)" ]
ali@ali-Inspiron-1525.(none)
799e1507a1390230ef59d3f6a760502f76e3cc4c
336a3d835cb069233ffff4edafcc6fdebf9f1bc9
/BankEmi.cpp
e1f8ab3d72faa32d866033f7feb5f72eadbf5195
[]
no_license
AlejandroFernandez-13/PP2-Project
92b07ccb65311795f329f83d4ea5d35ff637b35c
6b27bb7e2d0f3f05b574a36b652d7b1b16c2f6dc
refs/heads/main
2023-04-12T21:13:02.475843
2021-05-03T04:26:46
2021-05-03T04:26:46
363,815,484
0
0
null
null
null
null
UTF-8
C++
false
false
4,946
cpp
#include <cstdlib> #include <sstream> #include <iostream> #include <iomanip> #include "BankEmi.h" #include "BankProfile.h" BankEmi::BankEmi(const string HOST, const string USER, const string PASSWORD, const string DATABASE) { db_conn = mysql_init(NULL); if (!db_conn) message("MySQL initialization failed! "); db_conn = mysql_real_connect(db_conn, HOST.c_str(), USER.c_str(), PASSWORD.c_str(), DATABASE.c_str(), 0, NULL, 0); if (!db_conn) message("Connection Error! "); } BankEmi::~BankEmi() { mysql_close(db_conn); } BankProfile* BankEmi::getAccount(int acno) { BankProfile* b = NULL; MYSQL_RES* rset; MYSQL_ROW row; stringstream sql; sql << "SELECT * FROM bank_account WHERE acc_no=" << acno; if (!mysql_query(db_conn, sql.str().c_str())) { b = new BankProfile(); rset = mysql_use_result(db_conn); row = mysql_fetch_row(rset); b->setAccountNumber(atoi(row[0])); b->setFirstName(row[1]); b->setLastName(row[2]); b->setBalance(atof(row[3])); } mysql_free_result(rset); return b; } void BankEmi::withdraw(int acno, double amount) { BankProfile* b = getAccount(acno); if (b != NULL) { if (b->getBalance() < amount) message("Cannot withdraw. Try lower amount."); else { b->setBalance(b->getBalance() - amount); stringstream sql; sql << "UPDATE bank_account SET balance=" << b->getBalance() << " WHERE acc_no=" << acno; if (!mysql_query(db_conn, sql.str().c_str())) { message("Cash withdraw successful. Balance updated."); } else { message("Cash deposit unsuccessful! Update failed"); } } } } void BankEmi::deposit(int acno, double amount) { stringstream sql; sql << "UPDATE bank_account SET balance=balance+" << amount << " WHERE acc_no=" << acno; if (!mysql_query(db_conn, sql.str().c_str())) { message("Cash deposit successful. Balance updated."); } else { message("Cash deposit unsuccessful! Update failed"); } } void BankEmi::createAccount(BankProfile* ba) { stringstream ss; ss << "INSERT INTO bank_account(acc_no, fname, lname, balance)" << "values (" << ba->getAccountNumber() << ", '" << ba->getFirstName() + "','" << ba->getLastName() << "'," << ba->getBalance() << ")"; if (mysql_query(db_conn, ss.str().c_str())) message("Failed to create account! "); else message("Account creation successful."); } void BankEmi::closeAccount(int acno) { stringstream ss; ss << "DELETE FROM bank_account WHERE acc_no=" << acno; if (mysql_query(db_conn, ss.str().c_str())) message("Failed to close account! "); else message("Account close successful."); } void BankEmi::message(string msg) { cout << msg << endl; } void BankEmi::printAllAccounts() { MYSQL_RES* rset; MYSQL_ROW rows; string sql = "SELECT * FROM bank_account"; if (mysql_query(db_conn, sql.c_str())) { message("Error printing all accounts! "); return; } rset = mysql_use_result(db_conn); cout << left << setw(10) << setfill('-') << left << '+' << setw(21) << setfill('-') << left << '+' << setw(21) << setfill('-') << left << '+' << setw(21) << setfill('-') << '+' << '+' << endl; cout << setfill(' ') << '|' << left << setw(9) << "Account" << setfill(' ') << '|' << setw(20) << "First Name" << setfill(' ') << '|' << setw(20) << "Last Name" << setfill(' ') << '|' << right << setw(20) << "Balance" << '|' << endl; cout << left << setw(10) << setfill('-') << left << '+' << setw(21) << setfill('-') << left << '+' << setw(21) << setfill('-') << left << '+' << setw(21) << setfill('-') << '+' << '+' << endl; if (rset) { while ((rows = mysql_fetch_row(rset))) { cout << setfill(' ') << '|' << left << setw(9) << rows[0] << setfill(' ') << '|' << setw(20) << rows[1] << setfill(' ') << '|' << setw(20) << rows[2] << setfill(' ') << '|' << right << setw(20) << rows[3] << '|' << endl; } cout << left << setw(10) << setfill('-') << left << '+' << setw(21) << setfill('-') << left << '+' << setw(21) << setfill('-') << left << '+' << setw(21) << setfill('-') << '+' << '+' << endl; } mysql_free_result(rset); }
[ "noreply@github.com" ]
noreply@github.com
129073011076fdf67130ab683045f59dd5b08e74
e9ffcda8241659a6ec70cec8d72e21df3e5b39d8
/FamilyTree.cpp
159394a93b9dc1fe72d6bcae7a9706dd7663c79b
[ "MIT" ]
permissive
oriyahipert/ANCESTOR-TREE
ebd6e9a0dcb1c724d38456ddea49a590656f9066
0609edc9dac5bf081683d09a84b1195641183bf1
refs/heads/master
2022-05-23T15:50:15.014270
2020-04-23T16:24:29
2020-04-23T16:24:29
255,097,259
0
0
null
null
null
null
UTF-8
C++
false
false
8,719
cpp
#include "FamilyTree.hpp" #include <iostream> using namespace family; Tree:: Tree (string s) { this->root = new Node(s); } Tree& Tree::addFather(string name, string father) { addF(root, name,father,0,-1); return *this; } void Tree::addF(Node* child, string name, string father,int a, int b) { if(search(root , name) == NULL) { throw(""); } if(child == NULL){return;} if (child->getName() == name) { if(child->getFather() != NULL) { __throw_runtime_error("there is alredy a father"); } else { a++; child->addFatherNode(father); child->getFather()->setLevel(a); child->getFather()->setGender(0); return; } } else { a++; if(child->getFather() != NULL) { addF(child->getFather(), name, father,a,0); } if(child->getMother() != NULL) { addF(child->getMother(), name, father,a,0); } } // __throw_out_of_range(""); } Tree& Tree::addMother(string name, string mother) { addM(root, name,mother,0,1); return *this; } void Tree::addM(Node* child, string name, string mother,int a,int b) { if(search(root , name) == NULL) { throw(""); } if(child == NULL){return;} if (child->getName() == name) { if(child->getMother() != NULL) { __throw_out_of_range("there is alredy a mother"); } else { a++; child->addMotherNode(mother); child->getMother()->setLevel(a); child->getMother()->setGender(1); return; } } else { a++; if(child->getFather() != NULL) { addM(child->getFather(), name, mother,a,1); } if(child-> getMother() != NULL) { addM(child->getMother(), name, mother,a,1); } } } string Tree:: relation(string name) { // a private cases for root-grandfather/grandmother Node* temp = new Node(""); if(root->getName() == name){return "me";} if(root->getFather() != NULL) { temp = root->getFather(); if((temp->getName() == name) && (temp->getGender() == 0)){return "father";} if((temp->getFather() != NULL) && (temp->getFather()->getName() == name) && (temp->getFather()->getGender() == 0)){return "grandfather";} if((temp->getMother() != NULL) && (temp->getMother()->getName() == name) && (temp->getMother()->getGender() == 1)){return "grandmother";} } if(root->getMother() != NULL) { temp = root->getMother(); if((temp->getName() == name) && (temp->getGender() == 1)){return "mother";} if((temp->getFather() != NULL) && (temp->getFather()->getName() == name) && (temp->getFather()->getGender() == 0)){return "grandfather";} if((temp->getMother() != NULL) && (temp->getMother()->getName() == name) && (temp->getMother()->getGender() == 1)){return "grandmother";} } // the other cases, for all the 'great-' int level = -1; int gender = -1; relationHelp(name , root , &level , &gender); if(level == -1 && gender == -1){return "unrelated";} if(gender == 0) { string s = "great-"; string s1 = "grandfather"; for(int i = 1; i < level-2; i++) { s += s; } return s.append(s1); } else { string s = "great-"; string s1 = "grandmother"; for(int i = 1; i < level-2; i++) { s += s; } return s.append(s1); } } void Tree:: relationHelp(string name, Node* root , int* level , int* gender) { if(root == NULL){return;} if(root->getName() == name) { *level = root->getLevel(); *gender = root->getGender(); return; } relationHelp(name, root->getFather() , level , gender); relationHelp(name , root->getMother() , level , gender); } string Tree::find(string name) { if(root != NULL && name=="me"){return root->getName();} if((root->getFather() != NULL) && (name == "father")){return root->getFather()->getName();} if((root->getMother() != NULL) && (name == "mother")){return root->getMother()->getName();} if ((root->getMother() != NULL) && (root->getMother()->getMother() != NULL) && (name == "grandmother")){return root->getMother()->getMother()->getName();} if((root->getFather() != NULL) && (root->getFather()->getFather() != NULL) && (name=="grandfather")){return root->getFather()->getFather()->getName();} string tag = ""; findHelp(name, root , &tag); if(tag == "") { throw(""); } return tag; } void Tree::findHelp(string name, Node* root , string* tag) { if(root == NULL){return;} if ((root->getMother() != NULL) && (root->getMother()->getMother() != NULL) && (name == "grandmother")) { *tag = root->getMother()->getMother()->getName(); return; } if((root->getFather() != NULL) && (root->getFather()->getFather() != NULL) && (name=="grandfather")) { *tag = root->getFather()->getFather()->getName(); return; } if((root->getFather() != NULL) && (root->getFather()->getMother() != NULL) && (name=="grandmother")) { *tag = root->getFather()->getMother()->getName(); return; } if ((root->getMother() != NULL) && (root->getMother()->getFather() != NULL) && (name == "grandfather")) { *tag = root->getMother()->getFather()->getName(); return; } if((name!="grandmother" && name!="grandfather") && (name.length()<6 || name.substr(0,6)!="great-")) throw(""); if(root->getMother() != NULL) { if(name != "grandmother" && name != "grandfather") { findHelp(name.substr(6),root->getMother() , tag); } } if(root->getFather() != NULL) { if(name != "grandmother" && name != "grandfather" && *tag == "") { findHelp(name.substr(6),root->getFather() , tag); } } } void Tree::remove(string name){ if (root->getName() == name) { throw("you cant delete the root"); } // Node* temp = search(root,name); if (search(root,name) == NULL) { throw("this name is not exist"); } else { removeHelp(name , root); } } void Tree::removeHelp(string name , Node* root) { if(root->getFather() != NULL && root->getFather()->getName() == name) { deleteTree(root->getFather()); root->removeFather(); return; } else if(root->getMother() != NULL && root->getMother()->getName() == name) { deleteTree(root->getMother()); // root->setMother(NULL); root->removeMother(); return; } else { if(root->getFather() != NULL) { removeHelp(name , root->getFather()); } if(root->getMother() != NULL) { removeHelp(name , root->getMother()); } } } void Tree::deleteTree(Node* root) //this function was taken from "GeeksForGeeks", https://www.geeksforgeeks.org/write-a-c-program-to-delete-a-tree/ { if(root != NULL) { if(root != NULL) { if(root->getFather() != NULL) { root->removeFather(); } if(root->getMother() != NULL) { // deleteTree(root->getMother()); root->removeMother(); } } } } void Tree::display(){ printPreorder(root); } void Tree::printPreorder(Node* root) // this function was taken from "GeeksForGeeks", https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/?ref=rp { if (root == NULL) return; /* first print data of node */ cout << root->getName() << " "; /* then recur on left sutree */ printPreorder(root->getFather()); /* now recur on right subtree */ printPreorder(root->getMother()); } Node* Tree::search(Node* root, string name) { Node* temp=new Node(""); if (root==NULL){ return root; } if (root->getName() == name){ return root; } else{ temp=search(root->getFather(),name); if(temp==NULL){ temp=search(root->getMother(),name); } } return temp; }
[ "noreply@github.com" ]
noreply@github.com
8174748248e5acce63f96951da6500a7a2d4a25f
58cd29467c422b32b53c7d83a771d6600fc98a4d
/src/Renderers/Shaders/ShaderChunk/clearcoat_normal_fragment_begin.glsl.h
b586927fa6f15d4ca9b2f794b75fed64a3dcb507
[]
no_license
yudhcq/ThreeWasm
c2f0c121bb2d9558a022e4d3fc64f16500ab18ed
6a8cc52ef9e4b3a1b4e49e84c2d934a69bf87e8b
refs/heads/master
2023-01-29T08:53:26.430109
2020-11-11T05:39:02
2020-11-11T05:39:02
286,633,241
1
0
null
null
null
null
UTF-8
C++
false
false
93
h
#pragma once namespace Three::Renderers { class clearcoat_normal_fragment_begin.glsl{ }; }
[ "yudhcq@163.com" ]
yudhcq@163.com
cfb20c55ad8942a1260708d0b7bdefb575d1a8ee
1084faed40b796eddae76bad339591aac4afbb14
/Estrella.h
7ca657f7275b66edd4959e57478b4f642c15bccc
[]
no_license
nicontrerasc8/Juego-del-superh-roe
803ab77353edc23d33d678c5f5c7fec5920acf88
ddc773b15188345aedba7627c5f16d2b524f22cb
refs/heads/main
2023-08-15T08:57:44.247742
2021-10-11T18:07:12
2021-10-11T18:07:12
416,035,349
0
0
null
null
null
null
UTF-8
C++
false
false
183
h
#pragma once #include "Figura.h" class Estrella : public Figura { public: Estrella(); ~Estrella(); void Mover(int WindowWidth, int WindowHeight); void Imprimir(); };
[ "noreply@github.com" ]
noreply@github.com
8106ed10ef89c97a9d0f14c94d5d675222c7d7c5
128806ed2426185c3ec231db7238a6ba21ff2a31
/CPPSourceCodes/TestUnitsNew/TestUnitsNew/ZoneMsgDispatcher.cpp
5ded526a941262e85cf499814884abda8878144b
[]
no_license
DanSuRii/dansuri-testcodes
2b0d77bf26c9c9a95b3154a402fa08ca33906f9b
41f536b9643f35dbf49b53aba41b1c6fbad0d65e
refs/heads/master
2021-01-23T15:53:59.242730
2018-02-23T14:52:12
2018-02-23T14:52:12
33,680,074
0
0
null
null
null
null
UTF-8
C++
false
false
393
cpp
#include "stdafx.h" #include "Work.h" #include "boost/bind.hpp" #include <windows.h> #include <vector> #include "ZoneMsgDispatcher.h" bool Unhandled(GameWorld::CVtZoneServer*, CVSock*, char*, DWORD) { return false; } CZoneMsgDispatcher::CZoneMsgDispatcher( Vector::CVtZoneBase* pOwner ) : m_pOwner(pOwner) , m_fnUnhandled( boost::bind(Unhandled, nullptr, nullptr, nullptr, 0 )) { }
[ "dansuri2@gmail.com" ]
dansuri2@gmail.com
c842b5e04758a4cef3f51a5d38bb2264401d6f42
193948bdcb243be09b446c2fff95d2fb5137f806
/src/swganh_core/object/weapon/weapon_message_builder.h
5b3e2fcc4f96c0c48a8c672be150f39a8ac78b1b
[ "MIT" ]
permissive
J-N/swganh
cfe40ea4f5fc46bb0472a28580005db3106226bf
d0816baad6812531355880bae53f0f797bbcceba
refs/heads/master
2020-04-08T07:18:33.521031
2012-10-11T16:51:04
2012-10-11T16:51:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,245
h
// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #ifndef SWGANH_OBJECT_WEAPON_WEAPON_MESSAGE_BUILDER_H_ #define SWGANH_OBJECT_WEAPON_WEAPON_MESSAGE_BUILDER_H_ #include "swganh_core/object/tangible/tangible_message_builder.h" namespace swganh { namespace object { class Weapon; class WeaponMessageBuilder : public swganh::object::TangibleMessageBuilder { public: WeaponMessageBuilder(swganh::EventDispatcher* dispatcher) : TangibleMessageBuilder(dispatcher) { RegisterEventHandlers(); } virtual void RegisterEventHandlers(); virtual void SendBaselines(const std::shared_ptr<Weapon>& weapon, const std::shared_ptr<swganh::observer::ObserverInterface>& controller); // baselines static swganh::messages::BaselinesMessage BuildBaseline3(const std::shared_ptr<Weapon>& weapon); static swganh::messages::BaselinesMessage BuildBaseline6(const std::shared_ptr<Weapon>& weapon); private: typedef swganh::ValueEvent<std::shared_ptr<Weapon>> WeaponEvent; }; }} // swganh::object #endif // SWGANH_OBJECT_TANGIBLE_TANGIBLE_MESSAGE_BUILDER_H_
[ "im.kyle@gmail.com" ]
im.kyle@gmail.com
0db52eea675ad39aba2d370944c9a0a92b7b1ece
55217a6b62c6487fc62da89960e865ed844390d7
/src/cs499rProgram.hpp
25c4a6366ebe74f284e2b0060c474f06da836957
[]
no_license
gabadie/cs499r
b2a602b4a39bdd9c179f5728af5cf08413363572
ad21aff63e73bc3e94838e1d288911fdeb090f0f
refs/heads/master
2020-12-25T19:15:40.605607
2014-12-12T23:23:02
2014-12-12T23:23:02
24,373,902
0
0
null
null
null
null
UTF-8
C++
false
false
616
hpp
#ifndef _H_CS499R_PROGRAM #define _H_CS499R_PROGRAM /* * All the following programs kCS499RXXX are const var that contain cs499rXXX.cl's * but already preproccessed... * * Only cs499r*.cl files listed in cs499rProgram.flist are available here, * otherwise you might have a link time error for an unknown constant. */ extern char const * const kCS499RProgramPathTracer; extern char const * const kCS499RProgramDebugNormal; extern char const * const kCS499RProgramRayStats; extern char const * const kCS499RProgramDownscale; extern char const * const kCS499RProgramTargetMultiply; #endif // _H_CS499R_PROGRAM
[ "guillaume.abadie@gmail.com" ]
guillaume.abadie@gmail.com
9b19967caa497e9ed412985f3d77eb5a151ffc66
cdb2c696bbbd4b85ef215b7c2114f5a47464cefa
/modules/support/view/dsps_view.cpp
5317bd3a7dc6a0175461764d0d4d8be03b9b6371
[ "Apache-2.0" ]
permissive
philippe44/esp-dsp
46fd2728042688972a33628e2b0e8431efaf9aea
8b082c1071497d49346ee6ed55351470c1cb4264
refs/heads/master
2021-01-05T01:04:04.135482
2020-02-20T16:41:37
2020-02-20T16:41:37
240,823,228
3
0
Apache-2.0
2020-02-16T03:09:56
2020-02-16T03:09:56
null
UTF-8
C++
false
false
3,501
cpp
#include "dsps_view.h" #include <math.h> #include "esp_log.h" #include <limits> void dsps_view(const float *data, int32_t len, int width, int height, float min, float max, char view_char) { uint8_t *view_data = new uint8_t[width * height]; float *view_data_min = new float[width]; float *view_data_max = new float[width]; // for (int y = 0; y < height ; y++) { for (int x = 0 ; x < width ; x++) { view_data[y * width + x] = ' '; } } for (int i = 0 ; i < width ; i++) { view_data_min[i] = max; view_data_max[i] = min; } float x_step = (float)(width) / (float)len; float y_step = (float)(height - 1) / (max - min); float data_min = std::numeric_limits<float>::max(); float data_max = std::numeric_limits<float>::min(); int min_pos = 0; int max_pos = 0; for (int i = 0 ; i < len ; i++) { int x_pos = i * x_step; if (data[i] < view_data_min[x_pos]) { view_data_min[x_pos] = data[i]; } if (data[i] > view_data_max[x_pos]) { view_data_max[x_pos] = data[i]; } if (view_data_min[x_pos] < min) { view_data_min[x_pos] = min; } if (view_data_max[x_pos] > max) { view_data_max[x_pos] = max; } ESP_LOGD("view", "for i=%i, x_pos=%i, max=%f, min=%f, data=%f", i, x_pos, view_data_min[x_pos], view_data_max[x_pos], data[i]); if (data[i] > data_max) { data_max = data[i]; max_pos = i; } if (data[i] < data_min) { data_min = data[i]; min_pos = i; } } ESP_LOGI("view", "Data min[%i] = %f, Data max[%i] = %f", min_pos, data_min, max_pos, data_max); ESP_LOGD("view", "y_step = %f", y_step); for (int x = 0 ; x < width ; x++) { int y_count = (view_data_max[x] - view_data_min[x]) * y_step + 1; ESP_LOGD("view", "For x= %i y_count=%i ,min =%f, max=%f, ... ", x, y_count, view_data_min[x], view_data_max[x]); for (int y = 0 ; y < y_count ; y++) { int y_pos = (max - view_data_max[x]) * y_step + y; ESP_LOGD("view", " %i, ", y_pos); view_data[y_pos * width + x] = view_char; } ESP_LOGD("view", " "); } // Simple output // for (int i=0 ; i< len ; i++) // { // float x_step = (float)(width-1)/(float)len; // float y_step = (float)(height-1)/(max - min); // int x_pos = i*x_step; // int y_pos = data[i]*y_step; // if (data[i] >= max) y_pos = 0; // if (data[i] <= min) y_pos = height-1; // view_data[y_pos*width + x_pos] = view_char; // printf("For data[%i]=%f, x_pos%i, y_pos=%i\n", i, data[i], x_pos, y_pos); // } // printf("\n"); printf(" "); for (int x = 0 ; x < width ; x++) { printf("_"); } printf("\n"); for (int y = 0; y < height ; y++) { printf("%i", y % 10); for (int x = 0 ; x < width ; x++) { printf("%c", view_data[y * width + x]); } printf("|\n"); } printf(" "); for (int x = 0 ; x < width ; x++) { printf("%i", x % 10); } printf("\n"); ESP_LOGI("view", "Plot: Length=%i, min=%f, max=%f", len, min, max); delete view_data; delete view_data_min; delete view_data_max; } void dsps_view_spectrum(const float *data, int32_t len, float min, float max) { dsps_view(data, len, 64, 10, min, max, '|'); }
[ "Dmitry@espressif.com" ]
Dmitry@espressif.com
a5d5f7c32aedd2a0b1d09187c4ff6c92587eff27
29874f964cfe6c69ed261a7864b1c4ebc13c846d
/Utils/DragDropImpl.h
2adb58e2898ebeb5a78f338cf3e3b76a0c0f165f
[]
no_license
cdp0516/Duilib
0984148f65418352bfe9053d7924ac2d077199a0
49725bc33b4e8939a840095df7bb8c86029e7c7e
refs/heads/master
2020-07-04T04:19:25.340684
2017-01-20T05:35:44
2017-01-20T05:35:44
74,109,114
0
0
null
2017-01-20T05:35:45
2016-11-18T08:12:29
C++
UTF-8
C++
false
false
8,191
h
// IDataObjectImpl.h: interface for the CIDataObjectImpl class. /************************************************************************** THIS CODE AND INFORMATION IS PROVIDED 'AS IS' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. Author: Leon Finker 1/2001 **************************************************************************/ #ifndef __DRAGDROPIMPL_H__ #define __DRAGDROPIMPL_H__ #include <shlobj.h> #include <vector> namespace DuiLib { typedef std::vector<FORMATETC> FormatEtcArray; typedef std::vector<FORMATETC*> PFormatEtcArray; typedef std::vector<STGMEDIUM*> PStgMediumArray; /////////////////////////////////////////////////////////////////////////////////////////////// class UILIB_API CEnumFormatEtc : public IEnumFORMATETC { private: ULONG m_cRefCount; FormatEtcArray m_pFmtEtc; unsigned int m_iCur; public: CEnumFormatEtc(const FormatEtcArray& ArrFE); CEnumFormatEtc(const PFormatEtcArray& ArrFE); //IUnknown members STDMETHOD(QueryInterface)(REFIID, void FAR* FAR*); STDMETHOD_(ULONG, AddRef)(void); STDMETHOD_(ULONG, Release)(void); //IEnumFORMATETC members STDMETHOD(Next)(ULONG, LPFORMATETC, ULONG FAR *); STDMETHOD(Skip)(ULONG); STDMETHOD(Reset)(void); STDMETHOD(Clone)(IEnumFORMATETC FAR * FAR*); }; /////////////////////////////////////////////////////////////////////////////////////////////// class UILIB_API CIDropSource : public IDropSource { long m_cRefCount; public: bool m_bDropped; CIDropSource::CIDropSource():m_cRefCount(0),m_bDropped(false) {} //IUnknown virtual HRESULT STDMETHODCALLTYPE QueryInterface( /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); virtual ULONG STDMETHODCALLTYPE AddRef( void); virtual ULONG STDMETHODCALLTYPE Release( void); //IDropSource virtual HRESULT STDMETHODCALLTYPE QueryContinueDrag( /* [in] */ BOOL fEscapePressed, /* [in] */ DWORD grfKeyState); virtual HRESULT STDMETHODCALLTYPE GiveFeedback( /* [in] */ DWORD dwEffect); }; /////////////////////////////////////////////////////////////////////////////////////////////// class UILIB_API CIDataObject : public IDataObject//,public IAsyncOperation { CIDropSource* m_pDropSource; long m_cRefCount; PFormatEtcArray m_ArrFormatEtc; PStgMediumArray m_StgMedium; public: CIDataObject(CIDropSource* pDropSource); ~CIDataObject(); void CopyMedium(STGMEDIUM* pMedDest, STGMEDIUM* pMedSrc, FORMATETC* pFmtSrc); //IUnknown virtual HRESULT STDMETHODCALLTYPE QueryInterface( /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); virtual ULONG STDMETHODCALLTYPE AddRef( void); virtual ULONG STDMETHODCALLTYPE Release( void); //IDataObject virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetData( /* [unique][in] */ FORMATETC __RPC_FAR *pformatetcIn, /* [out] */ STGMEDIUM __RPC_FAR *pmedium); virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetDataHere( /* [unique][in] */ FORMATETC __RPC_FAR *pformatetc, /* [out][in] */ STGMEDIUM __RPC_FAR *pmedium); virtual HRESULT STDMETHODCALLTYPE QueryGetData( /* [unique][in] */ FORMATETC __RPC_FAR *pformatetc); virtual HRESULT STDMETHODCALLTYPE GetCanonicalFormatEtc( /* [unique][in] */ FORMATETC __RPC_FAR *pformatectIn, /* [out] */ FORMATETC __RPC_FAR *pformatetcOut); virtual /* [local] */ HRESULT STDMETHODCALLTYPE SetData( /* [unique][in] */ FORMATETC __RPC_FAR *pformatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pmedium, /* [in] */ BOOL fRelease); virtual HRESULT STDMETHODCALLTYPE EnumFormatEtc( /* [in] */ DWORD dwDirection, /* [out] */ IEnumFORMATETC __RPC_FAR *__RPC_FAR *ppenumFormatEtc); virtual HRESULT STDMETHODCALLTYPE DAdvise( /* [in] */ FORMATETC __RPC_FAR *pformatetc, /* [in] */ DWORD advf, /* [unique][in] */ IAdviseSink __RPC_FAR *pAdvSink, /* [out] */ DWORD __RPC_FAR *pdwConnection); virtual HRESULT STDMETHODCALLTYPE DUnadvise( /* [in] */ DWORD dwConnection); virtual HRESULT STDMETHODCALLTYPE EnumDAdvise( /* [out] */ IEnumSTATDATA __RPC_FAR *__RPC_FAR *ppenumAdvise); //IAsyncOperation //virtual HRESULT STDMETHODCALLTYPE SetAsyncMode( // /* [in] */ BOOL fDoOpAsync) //{ // return E_NOTIMPL; //} // //virtual HRESULT STDMETHODCALLTYPE GetAsyncMode( // /* [out] */ BOOL __RPC_FAR *pfIsOpAsync) //{ // return E_NOTIMPL; //} // //virtual HRESULT STDMETHODCALLTYPE StartOperation( // /* [optional][unique][in] */ IBindCtx __RPC_FAR *pbcReserved) //{ // return E_NOTIMPL; //} // //virtual HRESULT STDMETHODCALLTYPE InOperation( // /* [out] */ BOOL __RPC_FAR *pfInAsyncOp) //{ // return E_NOTIMPL; //} // //virtual HRESULT STDMETHODCALLTYPE EndOperation( // /* [in] */ HRESULT hResult, // /* [unique][in] */ IBindCtx __RPC_FAR *pbcReserved, // /* [in] */ DWORD dwEffects) //{ // return E_NOTIMPL; //} }; /////////////////////////////////////////////////////////////////////////////////////////////// class UILIB_API CIDropTarget : public IDropTarget { DWORD m_cRefCount; bool m_bAllowDrop; struct IDropTargetHelper *m_pDropTargetHelper; FormatEtcArray m_formatetc; FORMATETC* m_pSupportedFrmt; protected: HWND m_hTargetWnd; public: CIDropTarget(HWND m_hTargetWnd = NULL); virtual ~CIDropTarget(); void AddSuportedFormat(FORMATETC& ftetc) { m_formatetc.push_back(ftetc); } void SetTargetWnd(HWND hWnd) { m_hTargetWnd = hWnd; } //return values: true - release the medium. false - don't release the medium virtual bool OnDrop(FORMATETC* pFmtEtc, STGMEDIUM& medium,DWORD *pdwEffect) = 0; virtual HRESULT STDMETHODCALLTYPE QueryInterface( /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); virtual ULONG STDMETHODCALLTYPE AddRef( void) { return ++m_cRefCount; } virtual ULONG STDMETHODCALLTYPE Release( void); bool QueryDrop(DWORD grfKeyState, LPDWORD pdwEffect); virtual HRESULT STDMETHODCALLTYPE DragEnter( /* [unique][in] */ IDataObject __RPC_FAR *pDataObj, /* [in] */ DWORD grfKeyState, /* [in] */ POINTL pt, /* [out][in] */ DWORD __RPC_FAR *pdwEffect); virtual HRESULT STDMETHODCALLTYPE DragOver( /* [in] */ DWORD grfKeyState, /* [in] */ POINTL pt, /* [out][in] */ DWORD __RPC_FAR *pdwEffect); virtual HRESULT STDMETHODCALLTYPE DragLeave( void); virtual HRESULT STDMETHODCALLTYPE Drop( /* [unique][in] */ IDataObject __RPC_FAR *pDataObj, /* [in] */ DWORD grfKeyState, /* [in] */ POINTL pt, /* [out][in] */ DWORD __RPC_FAR *pdwEffect); }; class UILIB_API CDragSourceHelper { IDragSourceHelper* pDragSourceHelper; public: CDragSourceHelper() { if(FAILED(CoCreateInstance(CLSID_DragDropHelper, NULL, CLSCTX_INPROC_SERVER, IID_IDragSourceHelper, (void**)&pDragSourceHelper))) pDragSourceHelper = NULL; } virtual ~CDragSourceHelper() { if( pDragSourceHelper!= NULL ) { pDragSourceHelper->Release(); pDragSourceHelper=NULL; } } // IDragSourceHelper HRESULT InitializeFromBitmap(HBITMAP hBitmap, POINT& pt, // cursor position in client coords of the window RECT& rc, // selected item's bounding rect IDataObject* pDataObject, COLORREF crColorKey=GetSysColor(COLOR_WINDOW)// color of the window used for transparent effect. ) { if(pDragSourceHelper == NULL) return E_FAIL; SHDRAGIMAGE di; BITMAP bm; GetObject(hBitmap, sizeof(bm), &bm); di.sizeDragImage.cx = bm.bmWidth; di.sizeDragImage.cy = bm.bmHeight; di.hbmpDragImage = hBitmap; di.crColorKey = crColorKey; di.ptOffset.x = pt.x - rc.left; di.ptOffset.y = pt.y - rc.top; return pDragSourceHelper->InitializeFromBitmap(&di, pDataObject); } HRESULT InitializeFromWindow(HWND hwnd, POINT& pt,IDataObject* pDataObject) { if(pDragSourceHelper == NULL) return E_FAIL; return pDragSourceHelper->InitializeFromWindow(hwnd, &pt, pDataObject); } }; } #endif //__DRAGDROPIMPL_H__
[ "cdp0516@163.com" ]
cdp0516@163.com
2b01ec3973237a1b3d240aa134d7076cdff9cbb0
4a4f7519db3e10911e42d842dfc290a69249c498
/MSCL/source/mscl/MicroStrain/Wireless/DeliveryStopFlags.h
1ef96258bbfc773f960c8cd9af20951716b0947f
[ "MIT" ]
permissive
ezhangle/MSCL
b41ae0b3e2124c050c18ed21cac83c2bd686b284
c74c1faddc40a070dd0555c1c42a38a44dc7476b
refs/heads/master
2021-07-09T16:58:41.216070
2017-10-04T18:09:41
2017-10-04T18:09:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,322
h
/******************************************************************************* Copyright(c) 2015-2017 LORD Corporation. All rights reserved. MIT Licensed. See the included LICENSE.txt for a copy of the full MIT License. *******************************************************************************/ #pragma once #include "mscl/Types.h" namespace mscl { //Class: DeliveryStopFlags // The delivery stop flags indicate which stops on the pipeline act on the application data class DeliveryStopFlags { public: //Constructor: DeliveryStopFlags // Initializes a DeliveryStopFlags object DeliveryStopFlags(); //Constructor: DeliveryStopFlags // Initializes a DeliveryStopFlags object given specific values DeliveryStopFlags(bool pc, bool appBoard, bool linkBoard, bool baseStation); public: //Variable: pc // A stop flag representing the pc bool pc: 1; //only occupy 1 bit //Variable: appBoard // A stop flag representing the appBoard bool appBoard: 1; //only occupy 1 bit //Variable: linkBoard // A stop flag representing the linkBoard bool linkBoard: 1; //only occupy 1 bit //Variable: baseStation // A stop flag representing the baseStation bool baseStation: 1; //only occupy 1 bit public: //Operator: == // Checks that two DeliveryStopFlags objects are equal // //Returns: // true if the two DeliveryStopFlags are identical, false otherwise bool operator==(const DeliveryStopFlags& src) const; //Operator: != // Checks that two DeliveryStopFlags objects are not equal // //Returns: // true if the two DeliveryStopFlags are not identical, false otherwise bool operator!=(const DeliveryStopFlags& src) const; //Function: compare // Checks that two DeliveryStopFlags are identical // //Returns: // true if the two DeliveryStopFlags are identical, false otherwise bool compare(const DeliveryStopFlags& src) const; //Function: fromInvertedByte // Sets all the stop flags based on the inverted (ASPP v1) byte value passed in // //Parameters: // dsf - The inverted (ASPP v1) delivery stop flag byte static DeliveryStopFlags fromInvertedByte(uint8 dsf); //Function: fromByte // Sets all the stop flags based on the byte value passed in // //Parameters: // dsf - The delivery stop flag byte static DeliveryStopFlags fromByte(uint8 dsf); //Function: toInvertedByte // Gets the inverted (ASPP v1) delivery stop flag byte value based on the current stop flags set // //Returns: // The inverted (ASPP v1) delivery stop flag byte built from the current set stop flags uint8 toInvertedByte() const; //Function: toByte // Gets the delivery stop flag byte value based on the current stop flags set // //Returns: // The delivery stop flag byte built from the current set stop flags uint8 toByte() const; }; }
[ "richard.stoneback@lord.com" ]
richard.stoneback@lord.com
c0735afae05aa5b74298895b9bed87de717cee4f
4d4d34781ac604db86594e44df49a785593941c5
/piscinecpp/d04/ex02/includes/ISpaceMarine.hpp
06bac8fe6fdbc818e1829d0312b163803676a48b
[]
no_license
TermanEmil/cursus42
77d02a7e95bf20bdb4ae2c4596ce04637e4fec19
22df434c769d31cca02d2cc3c88b9f134c6298df
refs/heads/master
2021-08-08T04:23:02.094607
2017-11-09T15:13:22
2017-11-09T15:13:22
105,514,521
0
0
null
null
null
null
UTF-8
C++
false
false
355
hpp
#ifndef ISPACEMARINE_HPP # define ISPACEMARINE_HPP # include <iostream> # include <string> //Interface class ISpaceMarine { public: virtual ~ISpaceMarine (void) {}; virtual ISpaceMarine * clone() const = 0; virtual void battleCry (void) const = 0; virtual void rangedAttack (void) const = 0; virtual void meleeAttack (void) const = 0; }; #endif
[ "terman.emil@gmail.com" ]
terman.emil@gmail.com
a44394ae3c799ab5c5490a155aec606920b4819f
bd46a58f5f4305051252800ad3a4f76381789f4f
/mainwindow.cpp
e1139c9a7494d916d9e0428408672f1d99431e4e
[]
no_license
ORBAT/epidemic
0cb88723c21cab4a83daa61a4ef5e0e1cc9a2f0a
7c42cee56e9d151c3d9ebe3147a5053509f8c036
refs/heads/master
2021-01-06T20:37:44.036315
2010-06-30T15:06:52
2010-06-30T15:06:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,982
cpp
#include <ctime> #include <QDebug> #include <QTimer> #include <QDateTime> #include "mainwindow.h" #include "ui_mainwindow.h" #include "city.h" #include "pathogen.h" #include "mdiplot.h" #include "world.h" #include "citycontroller.h" // debugging. remove when done #include "badtesting.h" namespace QtEpidemy { MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), m_world(new World(this)), ui(new Ui::MainWindow) { ui->setupUi(this); additionalUiSetup(); CityController* m_cityController = m_world->getCityController(); m_cityController->createCity("Helsinki", 500000, Position(60.17,24.94)); m_cityController->createCity("Stockholm",1700000, Position(59.33, 18.07)); City *c = m_cityController->getCity("Helsinki"); City *s = m_cityController->getCity("Stockholm"); MdiPlot *mp = NULL; if(c) { mp = new MdiPlot(c, 100, QDateTime::currentDateTime()); mp->showStatistic(CS_INFECTED); mp->showStatistic(CS_RECOVERED); mp->showStatistic(CS_D_INFECTIONS); mp->showStatistic(CS_D_INF_DEATHS); mp->showStatistic(CS_D_INF_RECOVER); ui->centralWidget->addSubWindow(mp, Qt::SubWindow); } connectActions(); BadTesting t; t.doTests(); } void MainWindow::connectActions() { connect(ui->actionStart, SIGNAL(triggered()), m_world, SLOT(start())); connect(ui->actionPause, SIGNAL(triggered()), m_world, SLOT(pause())); } void MainWindow::additionalUiSetup() { this->setWindowState(Qt::WindowMaximized); ui->tblCityData->setModel(m_world->getCityController()->getModel()); // ui->tblCityData->horizontalHeader()-> // setResizeMode(QHeaderView::ResizeToContents); } MainWindow::~MainWindow() { delete ui; } void MainWindow::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } } void QtEpidemy::MainWindow::on_actionInfect_city_Derp_triggered() { CityController *m_cityController = m_world->getCityController(); QtEpidemy::City *c = m_cityController-> getCities() .at(qrand()%m_cityController->getCities().size()); QtEpidemy::Pathogen *p = new QtEpidemy::Pathogen(0.99, 0.0000001, 10, this); if(c) { c->setPathogen(p); c->addInfected(1); } } void QtEpidemy::MainWindow::on_actionAdd_random_city_triggered() { qsrand(time(NULL)); QString cityName = QString("%1CityName").arg(time(NULL), 0, 16); int pop = qrand()%100000000; qreal x = qrand()%100; qreal y = qrand()%100; m_world->getCityController()->createCity(cityName, pop, Position(x,y)); }
[ "tomeklof+github@gmail.com" ]
tomeklof+github@gmail.com
2400705e249fb36bb7c2b18fd55d69f17c2b4850
1648128e870c5101fb3455cd42459c057229cfd8
/Math/MathUtil.hpp
d0db5d00844150dbf7db8d219f3724d12be78f07
[ "MIT" ]
permissive
dvijayak/pen31ope
73041ad50ea1fabc1ae32c9e40d0a48a3ad8a7cb
dc07e5f1405d668c8ab0b1514035d97b78744519
refs/heads/master
2021-01-07T05:01:31.252406
2020-12-13T02:51:43
2020-12-13T10:41:29
241,586,171
0
0
null
null
null
null
UTF-8
C++
false
false
190
hpp
#ifndef MathUtil_hpp #define MathUtil_hpp #include <algorithm> float Clamp (float const value, float const min, float const max) { return std::min(std::max(value, min), max); } #endif
[ "daniel.vijayakumar@mappedin.ca" ]
daniel.vijayakumar@mappedin.ca
f06369beee630add6067008b31dba8a487ef2083
c71d9862169295dd650390ca44f2ebeb2e6740af
/src/gui/painting/qcolormap_qpa.cpp
6129984f336ab471c4942edfdbb498197bdae746
[]
no_license
maoxingda/qt-src
d23c8d0469f234f89fdcbdbe6f3d50fa16e7a0e3
e01aee06520bf526975b0bedafe78eb003b5ead6
refs/heads/master
2020-04-14T00:05:16.292626
2019-01-05T05:49:42
2019-01-05T05:49:42
163,524,224
1
0
null
null
null
null
UTF-8
C++
false
false
7,133
cpp
/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qcolormap.h" #include "qcolor.h" #include "qpaintdevice.h" #include "private/qapplication_p.h" #include "private/qgraphicssystem_p.h" QT_BEGIN_NAMESPACE class QColormapPrivate { public: inline QColormapPrivate() : ref(1), mode(QColormap::Direct), depth(0), numcolors(0) { } QAtomicInt ref; QColormap::Mode mode; int depth; int numcolors; }; static QColormapPrivate *screenMap = 0; void QColormap::initialize() { screenMap = new QColormapPrivate; QPlatformIntegration *pi = QApplicationPrivate::platformIntegration(); QList<QPlatformScreen*> screens = pi->screens(); screenMap->depth = screens.at(0)->depth(); if (screenMap->depth < 8) { screenMap->mode = QColormap::Indexed; screenMap->numcolors = 256; } else { screenMap->mode = QColormap::Direct; screenMap->numcolors = -1; } } void QColormap::cleanup() { delete screenMap; screenMap = 0; } QColormap QColormap::instance(int /*screen*/) { return QColormap(); } QColormap::QColormap() : d(screenMap) { d->ref.ref(); } QColormap::QColormap(const QColormap &colormap) :d (colormap.d) { d->ref.ref(); } QColormap::~QColormap() { if (!d->ref.deref()) delete d; } QColormap::Mode QColormap::mode() const { return d->mode; } int QColormap::depth() const { return d->depth; } int QColormap::size() const { return d->numcolors; } #ifndef QT_QWS_DEPTH16_RGB #define QT_QWS_DEPTH16_RGB 565 #endif static const int qt_rbits = (QT_QWS_DEPTH16_RGB/100); static const int qt_gbits = (QT_QWS_DEPTH16_RGB/10%10); static const int qt_bbits = (QT_QWS_DEPTH16_RGB%10); static const int qt_red_shift = qt_bbits+qt_gbits-(8-qt_rbits); static const int qt_green_shift = qt_bbits-(8-qt_gbits); static const int qt_neg_blue_shift = 8-qt_bbits; static const int qt_blue_mask = (1<<qt_bbits)-1; static const int qt_green_mask = (1<<(qt_gbits+qt_bbits))-(1<<qt_bbits); static const int qt_red_mask = (1<<(qt_rbits+qt_gbits+qt_bbits))-(1<<(qt_gbits+qt_bbits)); static const int qt_red_rounding_shift = qt_red_shift + qt_rbits; static const int qt_green_rounding_shift = qt_green_shift + qt_gbits; static const int qt_blue_rounding_shift = qt_bbits - qt_neg_blue_shift; inline ushort qt_convRgbTo16(QRgb c) { const int tr = qRed(c) << qt_red_shift; const int tg = qGreen(c) << qt_green_shift; const int tb = qBlue(c) >> qt_neg_blue_shift; return (tb & qt_blue_mask) | (tg & qt_green_mask) | (tr & qt_red_mask); } inline QRgb qt_conv16ToRgb(ushort c) { const int r=(c & qt_red_mask); const int g=(c & qt_green_mask); const int b=(c & qt_blue_mask); const int tr = r >> qt_red_shift | r >> qt_red_rounding_shift; const int tg = g >> qt_green_shift | g >> qt_green_rounding_shift; const int tb = b << qt_neg_blue_shift | b >> qt_blue_rounding_shift; return qRgb(tr,tg,tb); } uint QColormap::pixel(const QColor &color) const { QRgb rgb = color.rgba(); if (d->mode == QColormap::Direct) { switch(d->depth) { case 16: return qt_convRgbTo16(rgb); case 24: case 32: { const int r = qRed(rgb); const int g = qGreen(rgb); const int b = qBlue(rgb); const int red_shift = 16; const int green_shift = 8; const int red_mask = 0xff0000; const int green_mask = 0x00ff00; const int blue_mask = 0x0000ff; const int tg = g << green_shift; #ifdef QT_QWS_DEPTH_32_BGR if (qt_screen->pixelType() == QScreen::BGRPixel) { const int tb = b << red_shift; return 0xff000000 | (r & blue_mask) | (tg & green_mask) | (tb & red_mask); } #endif const int tr = r << red_shift; return 0xff000000 | (b & blue_mask) | (tg & green_mask) | (tr & red_mask); } } } //XXX //return qt_screen->alloc(qRed(rgb), qGreen(rgb), qBlue(rgb)); return 0; } const QColor QColormap::colorAt(uint pixel) const { if (d->mode == Direct) { if (d->depth == 16) { pixel = qt_conv16ToRgb(pixel); } const int red_shift = 16; const int green_shift = 8; const int red_mask = 0xff0000; const int green_mask = 0x00ff00; const int blue_mask = 0x0000ff; #ifdef QT_QWS_DEPTH_32_BGR if (qt_screen->pixelType() == QScreen::BGRPixel) { return QColor((pixel & blue_mask), (pixel & green_mask) >> green_shift, (pixel & red_mask) >> red_shift); } #endif return QColor((pixel & red_mask) >> red_shift, (pixel & green_mask) >> green_shift, (pixel & blue_mask)); } #if 0 // XXX Q_ASSERT_X(int(pixel) < qt_screen->numCols(), "QColormap::colorAt", "pixel out of bounds of palette"); return QColor(qt_screen->clut()[pixel]); #endif return QColor(); } const QVector<QColor> QColormap::colormap() const { return QVector<QColor>(); } QColormap &QColormap::operator=(const QColormap &colormap) { qAtomicAssign(d, colormap.d); return *this; } QT_END_NAMESPACE
[ "39357378+maoxingda@users.noreply.github.com" ]
39357378+maoxingda@users.noreply.github.com
f4715ba51d191cd262d3db92b9b9811cfd27b42c
a800fd8147dd402ca886d109ccf68ecd286ffadd
/Playlist - Undo Redo Options/ActionUpdate.cpp
0efaf7d6c1c87ca8155a1bcfc0493804a85ecee4
[]
no_license
ramonaghilea/Object-Oriented-Programming
1cff2361b5d0e77afd4af3608606ee05dc2cc20d
1477255b4e6c09bd327c1aef457efa75ace65f4f
refs/heads/master
2023-01-06T19:27:59.517132
2020-10-12T08:08:47
2020-10-12T08:08:47
297,977,657
0
0
null
null
null
null
UTF-8
C++
false
false
180
cpp
#include "ActionUpdate.h" void ActionUpdate::executeUndo() { this->repository.updateSong(oldSong); } void ActionUpdate::executeRedo() { this->repository.updateSong(newSong); }
[ "ramonaghilea9@gmail.com" ]
ramonaghilea9@gmail.com
99bd4cf20d6f8d90bfc6206ec9d79967a140a375
fa5b582ea330470071c36f8aa0269b4a79ba211e
/src/main/avikodak/sites/projecteuler/powerfuldigitsum.h
11e3198c2374cc7de137bebbec16bab477732e32
[]
no_license
umairsajid/algos_v2
a5cb68a9163cb5483e7b5bd410acbd38115db423
a3aea98a698b9723693dcb23794be09fbc4e7cd5
refs/heads/master
2020-12-26T00:36:12.711989
2015-12-17T05:34:11
2015-12-17T05:34:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,517
h
/**************************************************************************************************************************************************** * File Name : powerfuldigitsum.h * File Location : D:\projects\cpp\algos_v2\src\main\avikodak\sites\projecteuler\powerfuldigitsum.h * Created on : Jul 31, 2015 :: 2:42:22 PM * Author : avikodak * Testing Status : Tested * URL : https://projecteuler.net/problem=56 ****************************************************************************************************************************************************/ /****************************************************************************************************************************************************/ /* NAMESPACE DECLARATION AND IMPORTS */ /****************************************************************************************************************************************************/ using namespace std; using namespace __gnu_cxx; /****************************************************************************************************************************************************/ /* INCLUDES */ /****************************************************************************************************************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <numeric> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <lib/constants/constants.h> #include <lib/ds/commonds.h> #include <lib/ds/linkedlistds.h> #include <lib/ds/graphds.h> #include <lib/ds/mathds.h> #include <lib/ds/treeds.h> #include <lib/utils/arrayutil.h> #include <lib/utils/avltreeutil.h> #include <lib/utils/bplustreeutil.h> #include <lib/utils/btreeutil.h> #include <lib/utils/commonutil.h> #include <lib/utils/dillutil.h> #include <lib/utils/graphutil.h> #include <lib/utils/mathutil.h> #include <lib/utils/redblacktreeutil.h> #include <lib/utils/sillutil.h> #include <lib/utils/treeutil.h> #include <lib/utils/twofourtreeutil.h> /****************************************************************************************************************************************************/ /* USER DEFINED CONSTANTS */ /****************************************************************************************************************************************************/ /****************************************************************************************************************************************************/ /* MAIN CODE START */ /****************************************************************************************************************************************************/ #ifndef POWERFULDIGITSUM_H_ #define POWERFULDIGITSUM_H_ //Tested unsigned int getSumOfDigits(vector<unsigned int> userInput){ unsigned int sum = 0; for(unsigned int counter = 0;counter < userInput.size();counter++){ sum += userInput[counter]; } return sum; } //Tested vector<unsigned int> getUINTInVector(unsigned int number){ vector<unsigned int> userInput; while(number){ userInput.push_back(number%10); number /=10; } reverse(userInput.begin(),userInput.end()); return userInput; } //Tested vector<unsigned int> sum(vector<vector<unsigned int> > userInputs){ vector<unsigned int> result; if(userInputs.size() == 0){ return result; } reverse(userInputs[0].begin(),userInputs[0].end()); result = userInputs[0]; unsigned int firstCrawler,secondCrawler,sum = 0,carry =0; for(unsigned int counter = 1;counter < userInputs.size();counter++){ reverse(userInputs[counter].begin(),userInputs[counter].end()); firstCrawler = secondCrawler = carry = 0; while(firstCrawler < result.size() && secondCrawler < userInputs[counter].size()){ sum = result[firstCrawler] + userInputs[counter][secondCrawler] + carry; result[firstCrawler] = sum%10; firstCrawler++; secondCrawler++; carry = sum/10; } while(firstCrawler < result.size()){ sum = result[firstCrawler] + carry; result[firstCrawler] = sum%10; carry = sum/10; firstCrawler++; } while(secondCrawler < userInputs[counter].size()){ sum = userInputs[counter][secondCrawler] + carry; result.push_back(sum%10); carry = sum/10; secondCrawler++; } while(carry){ result.push_back(carry%10); carry /= 10; } } reverse(result.begin(),result.end()); return result; } //Tested vector<unsigned int> multiply(vector<unsigned int> userInput,unsigned int digit){ vector<unsigned int> result; reverse(userInput.begin(),userInput.end()); unsigned int carry = 0,product; for(unsigned int counter = 0;counter < userInput.size();counter++){ product = userInput[counter] * digit + carry; result.push_back(product%10); carry = product/10; } while(carry){ result.push_back(carry%10); carry /= 10; } reverse(result.begin(),result.end()); return result; } //Tested vector<unsigned int> multiply(vector<unsigned int> firstUserInput,vector<unsigned int> secondUserInput){ reverse(secondUserInput.begin(),secondUserInput.end()); vector<unsigned int> result,temp; vector<vector<unsigned int> > input; for(unsigned int outerCounter = 0;outerCounter < secondUserInput.size();outerCounter++){ temp = multiply(firstUserInput,secondUserInput[outerCounter]); if(result.size() == 0){ result = temp; }else{ for(unsigned int innerCounter = 0;innerCounter < outerCounter;innerCounter++){ temp.push_back(0); } input.clear(); input.push_back(result); input.push_back(temp); result = sum(input); } } return result; } //Tested vector<unsigned int> largepow(unsigned int base,unsigned int power){ vector<unsigned int> number = getUINTInVector(base); vector<unsigned int> result = number; for(unsigned int counter = 2;counter <= power;counter++){ result = multiply(result,number); } return result; } //Tested //Ans : 972 void maxSumDigits(){ unsigned int maxSum = 0; for(unsigned int outerCounter = 2;outerCounter < 100;outerCounter++){ for(unsigned int innerCounter = 1;innerCounter < 100;innerCounter++){ maxSum = max(maxSum,getSumOfDigits(largepow(outerCounter,innerCounter))); } } cout << maxSum << endl; } #endif /* POWERFULDIGITSUM_H_ */ /****************************************************************************************************************************************************/ /* MAIN CODE END */ /****************************************************************************************************************************************************/
[ "avinashk@vaycayhero.com" ]
avinashk@vaycayhero.com
a01452344e65bb8d038c0189ebb5f24e312a8545
c26cadb15ecf4a002bcf1e2ecfb58eb28d2fd200
/include/h5basegui/hlinetool.h
e223c010105e215500d20d71ffabbbb5829db530
[]
no_license
rcshuangw/graph
2464ff4e32aefc65ccf74f316ab95f34787fbbf5
8c67966faacd0d956a03d47ab11881832b197c76
refs/heads/master
2020-04-30T00:11:14.998410
2019-06-28T01:49:13
2019-06-28T01:49:13
176,496,571
0
0
null
null
null
null
UTF-8
C++
false
false
639
h
#ifndef HLINETOOL_H #define HLINETOOL_H #include "h5drawtool.h" class H5BASEGUI_EXPORT HLineTool: public HDrawTool { public: HLineTool(HDrawManager* manager,DrawShape objShape,const QString& name,const QString& uuid); virtual ~HLineTool(); public: virtual void clear(); virtual void onEvent(HEvent& event); virtual void onMousePressEvent(QMouseEvent* event, QVariant &data); virtual void onMouseMoveEvent(QMouseEvent* event, QVariant &data); virtual void onMouseReleaseEvent(QMouseEvent* event, QVariant &data); private: QPointF m_ptStPoint; QPointF m_ptCurPoint; bool m_bDrawStart; }; #endif // HLINETOOL_H
[ "rcswhuang@163.com" ]
rcswhuang@163.com
b10cd1b419d7be375222726021e643c879695e25
983a5b6cb32ca1c7e06ac8b8e47ac6d5a44b7802
/include/chart_downloader.hpp
e0db6229b1989e7d2f68f6ec7be0a66d08f39709
[]
no_license
signet-marigold/chartdisplay
59e46dc3e3901757fa63c3fd18e3c5f1f1cae54b
f8a67b14f2019cf1db8f8796797b3ed3eb3b2c5b
refs/heads/master
2023-08-21T10:29:06.372209
2021-11-01T01:38:49
2021-11-01T01:38:49
423,302,947
0
0
null
null
null
null
UTF-8
C++
false
false
287
hpp
/* Chart Display * * 2021 Alexander Nathan Hack <alex@anhack.xyz> * * Mar, 16th 2021 * Version 0.0.1 (Alpha) * chart_downloader.hpp */ #ifndef CHART_DOWNLOADER_HPP #define CHART_DOWNLOADER_HPP #include "chartdisplay.hpp" int json_test(void); #endif // CHART_DOWNLOADER_HPP
[ "me@alexanderhack.com" ]
me@alexanderhack.com
e24499ed9e1a4f1e5496a426f75f770c5e01e3be
a224a772a243691a66aa55f13f9e62c1e92ad97d
/chapter4/Global.h
47f42e8b57ab9b07c9706d6061139f73d633feef
[]
no_license
Howard725/EssentialC-
80a6d182f94aee93c4bf96dce40a17abfbf96ae1
a2e5ac4384d7dbaeddeec9ce31e634f7fff40ea3
refs/heads/master
2021-01-10T17:52:08.472014
2016-03-04T14:26:38
2016-03-04T14:26:38
49,573,602
0
0
null
null
null
null
UTF-8
C++
false
false
1,269
h
// // Created by Administrator on 2015/12/30. // #ifndef CHAPTER4_GLOBAL_H #define CHAPTER4_GLOBAL_H #include <String> using namespace std; class Global { public: static void program_name( const string& npn ){ _program_name = npn; } static string program_name(){ return _program_name; } static void version_stamp( const string & nvs ){ _version_stamp = nvs; } static string version_stamp() { return _version_stamp; } static void version_number( int nval ){ _version_number = nval; } static int version_number() { return _version_number; } static void tests_run( int nval ){ _tests_run = nval; } static int tests_run() { return _tests_run; } static void tests_passed( int nval ) { _tests_passed = nval; } static int tests_passed() { return _tests_passed; } private: static string _program_name; static string _version_stamp; static int _version_number; static int _tests_run; static int _tests_passed; }; /*string Global::_program_name; string Global::_version_stamp; int Global::_version_number; int Global::_tests_run; int Global::_tests_passed;*/ #endif //CHAPTER4_GLOBAL_H
[ "wangren725@163.com" ]
wangren725@163.com
e9ed2640f493b241a93ec35fd6617cddb671d417
7e2abbf295b09d07331402c78bc0df8a242b7e07
/admin.h
5b6997a233c78b04cd55e7da7f37a8512bca4c23
[]
no_license
ValeriaGrigoruants/Platform-for-learning-programming
c5f7c1987b2cae830efd62295bad80afb189c632
3d1515463c35bd3f4699521125b864c9cbb255b8
refs/heads/master
2020-04-14T22:12:47.481531
2018-12-04T17:39:07
2018-12-04T17:39:07
164,154,853
0
0
null
null
null
null
UTF-8
C++
false
false
748
h
#ifndef ADMIN_H #define ADMIN_H #include <QDialog> #include <addstudent.h> #include <mistakeplace.h> #include <fixlecture.h> #include <allresults.h> #include <deletetest.h> namespace Ui { class Admin; } class Admin : public QDialog { Q_OBJECT signals: void firstWindow(); public: explicit Admin(QWidget *parent = nullptr); ~Admin(); private slots: void on_back_clicked(); void on_test_clicked(); void on_student_clicked(); void on_edit_clicked(); void on_results_clicked(); void on_delete_test_clicked(); private: Ui::Admin *ui; MistakePlace *newtest; AddStudent *new_student; FixLecture *fix_lecture; AllResults *result; DeleteTest *del_test; }; #endif // ADMIN_H
[ "valergrig260857@gmail.com" ]
valergrig260857@gmail.com
7e91f711dc27bbf31560fc7b0dde2571d345aa83
a1091ad42e6a07b6fbb6fe876feb03547a8da1eb
/MITK-superbuild/ep/include/ITK-4.7/itkLabelOverlayFunctor.h
10f7a36829831434491f2ff72b7ba26582437343
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Sotatek-TuyenLuu/DP2
bc61866fe5d388dd11209f4d02744df073ec114f
a48dd0a41c788981009c5ddd034b0e21644c8077
refs/heads/master
2020-03-10T04:59:52.461184
2018-04-12T07:19:27
2018-04-12T07:19:27
129,206,578
1
0
null
null
null
null
UTF-8
C++
false
false
4,217
h
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkLabelOverlayFunctor_h #define __itkLabelOverlayFunctor_h #include "itkLabelToRGBFunctor.h" namespace itk { namespace Functor { /** \class LabelOverlayFunctor * \brief Functor for applying a colormap to a label image and combine it * with a grayscale image * * This functor class used internally by LabelOverlayImageFilter * * This code was contributed in the Insight Journal paper: * "The watershed transform in ITK - discussion and new developments" * by Beare R., Lehmann G. * http://hdl.handle.net/1926/202 * http://www.insight-journal.org/browse/publication/92 * * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, * INRA de Jouy-en-Josas, France. * * \sa LabelOverlayImageFilter LabelToRGBFunctor * * \ingroup ITKImageFusion */ template< typename TInputPixel, typename TLabel, typename TRGBPixel > class LabelOverlayFunctor { public: LabelOverlayFunctor() { // provide some default value for external use (outside // LabelOverlayFunctorImageFilter) Inside LabelOverlayFunctorImageFilter, // the values are always initialized m_Opacity = 1.0; m_BackgroundValue = NumericTraits< TLabel >::ZeroValue(); } inline TRGBPixel operator()(const TInputPixel & p1, const TLabel & p2) const { TRGBPixel rgbPixel; NumericTraits<TRGBPixel>::SetLength(rgbPixel, 3); if ( p2 == m_BackgroundValue ) { // value is background // return a gray pixel with the same intensity than the input pixel typename TRGBPixel::ValueType p = static_cast< typename TRGBPixel::ValueType >( p1 ); rgbPixel[0] = p; rgbPixel[1] = p; rgbPixel[2] = p; return rgbPixel; } // taint the input pixel with the colored one returned by // the color functor. TRGBPixel opaque = m_RGBFunctor(p2); // the following has been unrolled due to a bug with apple's // llvm-gcc-4.2 build 5658 const double p1_blend= p1 * ( 1.0 - m_Opacity ); rgbPixel[0] = static_cast< typename TRGBPixel::ValueType >( opaque[0] * m_Opacity + p1_blend ); rgbPixel[1] = static_cast< typename TRGBPixel::ValueType >( opaque[1] * m_Opacity + p1_blend ); rgbPixel[2] = static_cast< typename TRGBPixel::ValueType >( opaque[2] * m_Opacity + p1_blend ); return rgbPixel; } bool operator!=(const LabelOverlayFunctor & l) const { bool areDifferent = l.m_Opacity != m_Opacity || l.m_BackgroundValue != m_BackgroundValue || l.m_RGBFunctor != m_RGBFunctor; return areDifferent; } bool operator==(const LabelOverlayFunctor & l) const { return !(*this != l); } ~LabelOverlayFunctor() {} void SetOpacity(double opacity) { m_Opacity = opacity; } void SetBackgroundValue(TLabel v) { m_BackgroundValue = v; m_RGBFunctor.SetBackgroundValue(v); } void ResetColors() { m_RGBFunctor.ResetColors(); } unsigned int GetNumberOfColors() const { return m_RGBFunctor.GetNumberOfColors(); } /** type of the color component */ typedef typename TRGBPixel::ComponentType ComponentType; void AddColor(ComponentType r, ComponentType g, ComponentType b) { m_RGBFunctor.AddColor(r, g, b); } protected: private: double m_Opacity; TLabel m_BackgroundValue; typename Functor::LabelToRGBFunctor< TLabel, TRGBPixel > m_RGBFunctor; }; } // end namespace functor } // end namespace itk #endif
[ "tuyen.luu@sotatek.com" ]
tuyen.luu@sotatek.com
4680a0f63c81cc525cc9bb297d92985fd4eb910f
6a674745a019e7c47e3c9c1df5649892c2a0df0f
/AI/8_puzzle.cpp
681159d611e2580b14a719175d6270cbcbca81fc
[]
no_license
rajdosi/SemVII
54da30f6879082cf500bab23a46d636ffd24bac0
edc43490c0ec31d1180af47e64bcae33d65c8c53
refs/heads/master
2021-01-10T05:39:16.444748
2015-12-11T09:11:42
2015-12-11T09:11:42
47,812,925
0
0
null
null
null
null
UTF-8
C++
false
false
4,257
cpp
#include<bits/stdc++.h> using namespace std; struct got{ string imp; got * arya,*rob,*jon,*sansa; got * ned; }*mad_king; string goal_state; queue <string> bfs_queue; queue <int> bfs_queue_blanks; queue <int> bfs_count; queue <struct got *> many_faced_god; map<string, bool> my_map; void lynna(struct got * tywin){ if(tywin==mad_king) return ; lynna(tywin->ned); cout<<tywin->imp<<endl; } void bfs(string input,int blank_position,int count , got * spider ) { my_map[input]=true; // cout<<input<<endl; if(input==goal_state){ cout<<"SUCCESS."<<endl; cout<<"No of Steps :: "<<count<<endl; cout<<"Path::"<<endl; lynna(spider); exit(0); } struct got *ramsay; if(blank_position-3 >= 0){ input[blank_position]=input[blank_position-3]; input[blank_position-3]='0'; if(my_map.find(input)== my_map.end()){ bfs_queue.push(input); bfs_queue_blanks.push(blank_position-3); bfs_count.push(count+1); ramsay = new got; ramsay->imp = input; ramsay->ned = spider; spider->arya=ramsay; many_faced_god.push(ramsay); } else spider->arya=NULL; input[blank_position-3]=input[blank_position]; input[blank_position]='0'; } else spider->arya=NULL; if(blank_position+3 <= 8){ input[blank_position]=input[blank_position+3]; input[blank_position+3]='0'; if(my_map.find(input)== my_map.end()){ bfs_queue.push(input); bfs_queue_blanks.push(blank_position+3); bfs_count.push(count+1); ramsay = new got; ramsay->imp = input; ramsay->ned = spider; spider->sansa=ramsay; many_faced_god.push(ramsay); } else spider->sansa=NULL; input[blank_position+3]=input[blank_position]; input[blank_position]='0'; } else spider->sansa=NULL; if(blank_position%3 != 0){ input[blank_position]=input[blank_position-1]; input[blank_position-1]='0'; if(my_map.find(input)== my_map.end()){ bfs_queue.push(input); bfs_queue_blanks.push(blank_position-1); bfs_count.push(count+1); ramsay = new got; ramsay->imp = input; ramsay->ned = spider; spider->rob=ramsay; many_faced_god.push(ramsay); } else spider->rob=NULL; input[blank_position-1]=input[blank_position]; input[blank_position]='0'; } else spider->rob=NULL; if((blank_position+1)%3 != 0){ input[blank_position]=input[blank_position+1]; input[blank_position+1]='0'; if(my_map.find(input)== my_map.end()){ bfs_queue.push(input); bfs_queue_blanks.push(blank_position+1); bfs_count.push(count+1); ramsay = new got; ramsay->imp = input; ramsay->ned = spider; spider->jon=ramsay; many_faced_god.push(ramsay); } else spider->jon=NULL; input[blank_position+1]=input[blank_position]; input[blank_position]='0'; } else spider->jon=NULL; string temp=bfs_queue.front(); int pos=bfs_queue_blanks.front(); int cou=bfs_count.front(); struct got * valar_morghulis = new got; valar_morghulis = many_faced_god.front(); bfs_queue.pop(); bfs_queue_blanks.pop(); bfs_count.pop(); many_faced_god.pop(); bfs(temp,pos,cou,valar_morghulis); } int main() { string current_state; cout<<"Enter current state row wise."<<endl; cin>>current_state; cout<<"Enter goal state roe wise."<<endl; cin>>goal_state; int i; for(i=0;i<9;i++) { if(current_state[i]=='0') break; } mad_king = new got; mad_king->ned=NULL; mad_king->imp=current_state; bfs(current_state,i,0,mad_king); return 0; }
[ "rajdosi10@gmail.com" ]
rajdosi10@gmail.com
fcf95c3f4bf7a3f14e9a423fa2ecab0606276814
f8d11be9234a116f2e57c23c72bee2b3160412d2
/Source/Sem6/Public/BoxAIGenerator.h
c1d7e212a928f13c64f6c8bc095021cd51dc0297
[]
no_license
renkin4/PewPewRobot
75768f216c76bb0bc0f267b6719319350ecb4dc4
3fea5f97e344215ecf2ab6a785f842cd8e32b3b9
refs/heads/master
2021-08-20T11:02:30.894969
2017-11-29T00:19:46
2017-11-29T00:19:46
107,755,508
1
0
null
null
null
null
UTF-8
C++
false
false
1,023
h
// YangIsAwesome #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "MyType.h" #include "BoxAIGenerator.generated.h" class AMyBox; class ACharacter_Base; UCLASS() class SEM6_API ABoxAIGenerator : public AActor { GENERATED_UCLASS_BODY() public: // Sets default values for this actor's properties ABoxAIGenerator(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; /*Spawn Location*/ UPROPERTY(EditAnywhere, BlueprintReadWrite,Category = "Spawn Location") TArray<FSpawnLocation> SpawnLocation; UPROPERTY(EditDefaultsOnly, Category = "Spawn Location") TSubclassOf<AMyBox> BoxToSpawn; UPROPERTY(EditDefaultsOnly, Category = "Spawn Location") TSubclassOf<ACharacter_Base> AIToSpawn; void SpawnBoxOrAI(); FTimerHandle SpawnHandler; UPROPERTY(EditAnywhere, Category = "Spawn Location") float DelayOnEachSpawn; UPROPERTY(EditDefaultsOnly, Category = "Spawn Location") float PercentageToSpawnBox; /*-------------------*/ };
[ "yangah9991@gmail.com" ]
yangah9991@gmail.com
8bcf3ccffbbcee004f50641035f30d1cbfc4c152
f87f54346adcdc370cc9c02c0d6db04900da6980
/ArduinoCode/main/main.ino
594486fffc5954382cc9af22944ed69258799fce
[]
no_license
jessymathault/CNC
e0a34f806b7e76f92154a521a8538f60e16c21a3
b5cfae01c727a1121fe10d109c26c0f57f399cbd
refs/heads/main
2023-01-09T20:30:30.492574
2020-11-10T03:07:57
2020-11-10T03:07:57
311,528,730
0
0
null
null
null
null
UTF-8
C++
false
false
6,443
ino
// rechanger le baudrate à 115200 #include "Arduino.h" #include <assert.h> #include <math.h> #include "Constants.h" #include "CNC.h" #include "Leds.h" #include "LimitSwitches.h" #include "ManualEncoders.h" #include "MotorEncoders.h" #include "PID.h" #include "PWMs.h" #include "CNC_Communication.h" //Périphériques Leds* leds = new Leds(51, 50, 52); LimitSwitches* switches = new LimitSwitches(29, 30, 31, 32, 33, 34, 35, 36, 37, 40, 38, 39); //ORDRE IMPORTANT PWMs* pwms = new PWMs(7, 6, 9, 8, 4, 5); MotorEncoders* encoders = new MotorEncoders(43, 42, 41); ManualEncoders* manualEncoders = new ManualEncoders(44, 45, 46, 47, 48, 49); CNC_Communication uart; //La classe CNC agit comme controller CNC* cnc = new CNC(pwms, encoders, switches, leds); boolean everythingIsOk = true; #define boutonRouge A0 long boutonCheck = 0; boolean boutonOk = true; boolean boutonHadProblem = false; volatile boolean l; //TC1 ch 0 void TC3_Handler() { TC_GetStatus(TC1, 0); digitalWrite(13, l = !l); Serial.print(cnc->encoders->getXPosition()); Serial.print(" "); Serial.print(cnc->encoders->getYPosition()); Serial.print(" "); Serial.print(cnc->encoders->getZPosition()); Serial.print(" "); Serial.print(cnc->getCurrentState()); Serial.print(" "); } void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq, uint32_t frequency) { pmc_set_writeprotect(false); pmc_enable_periph_clk((uint32_t)irq); TC_Configure(tc, channel, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4); uint32_t rc = VARIANT_MCK/128/frequency; //128 because we selected TIMER_CLOCK4 above TC_SetRA(tc, channel, rc/2); //50% high, 50% low TC_SetRC(tc, channel, rc); TC_Start(tc, channel); tc->TC_CHANNEL[channel].TC_IER=TC_IER_CPCS; tc->TC_CHANNEL[channel].TC_IDR=~TC_IER_CPCS; NVIC_EnableIRQ(irq); } void setup() { uart.init(115200); leds->init(); switches->init(); encoders->init(); manualEncoders->init(); pwms->init(); cnc->init(); startTimer(TC1, 0, TC3_IRQn, 5); //TC1 channel 0, the IRQ for that channel and the desired frequency pinMode(13, OUTPUT); digitalWrite(13, LOW); pinMode(boutonRouge, INPUT); } void loop() { if ((switches->anyIsPressed())&&(everythingIsOk)) { cnc->setCurrentState(E_ERROR); } if ((millis() - boutonCheck) > 1000) { boutonOk = (analogRead(boutonRouge)>400); } if (boutonOk == false){ cnc->setCurrentState(E_ERROR); boutonHadProblem = true; } if ((boutonOk)&&(boutonHadProblem == true)){ cnc->setCurrentState(E_IDLE); boutonHadProblem = false; leds->setRedLed(false); } if ((E_CNC_STATES)cnc->getCurrentState() == E_ERROR) { everythingIsOk = false; leds->setRedLed(true); cnc->stop(); cnc->setXTarget(encoders->getXPosition(), 1, true); cnc->setYTarget(encoders->getYPosition(), 1, true); cnc->setZTarget(encoders->getZPosition(), 1, true); if (switches->pxLimit()){ cnc->setXTarget((encoders->getXPosition()+40), 0.05, true); } else if (switches->nxLimit()){ cnc->setXTarget((encoders->getXPosition()-40), 0.05, true); } else if (switches->pyLimit()){ cnc->setYTarget((encoders->getYPosition()+40), 0.05, true); } else if (switches->nyLimit()){ cnc->setYTarget((encoders->getYPosition()-40), 0.05, true); } else if (switches-> pzLimit()){ cnc->setZTarget((encoders->getZPosition()-40), 0.05, true); } else if (switches->nzLimit()){ cnc->setZTarget((encoders->getZPosition()+40), 0.05, true); } return; } else if ((E_CNC_STATES)cnc->getCurrentState() == E_BUSY) { leds->setYellowLed(true); leds->setGreenLed(false); cnc->lockedLoop(); } else if ((E_CNC_STATES)cnc->getCurrentState() == E_IDLE) { leds->setYellowLed(false); leds->setGreenLed(true); everythingIsOk = true; encoders->setXDirection(0); encoders->setYDirection(0); encoders->setZDirection(0); // manual control long goalx = encoders->getXPosition(); long goaly = encoders->getYPosition(); long goalz = encoders->getZPosition(); long tempx = manualEncoders->getlastXCounter(); if (manualEncoders->getXCounter() != tempx){ goalx += (manualEncoders->getXCounter()-tempx)*10; cnc->setXTarget(goalx, 1, true); } long tempy = manualEncoders->getlastYCounter(); if (manualEncoders->getYCounter() != tempy){ goaly += (manualEncoders->getYCounter()-tempy)*10; cnc->setYTarget(goaly, 1, true); } long tempz = manualEncoders->getlastZCounter(); if (manualEncoders->getZCounter() != tempz){ goalz += (manualEncoders->getZCounter()-tempz)*5; cnc->setZTarget(goalz, 1, true); } } else{ cnc->stop(); assert(0); //Unknown state } } long Xpos = 0; long Ypos = 0; long Zpos = 0; //Appelé à chaque loop() si le buffer du UART a des données void serialEvent() { //Get command int header = Serial.parseInt(); if(header != 255){ cnc->stop(); } long action = Serial.parseInt(); long xf = Serial.parseInt(); long yf = Serial.parseInt(); long zf = Serial.parseInt(); float vt = Serial.parseFloat(); float r = Serial.parseFloat(); float thetaI = Serial.parseFloat(); float thetaF = Serial.parseFloat(); long milli = Serial.parseInt(); int footer = Serial.parseInt(); if(footer != 254){ cnc->stop(); } //Parse command if (action == -1){ cnc->stop(); } else if(action == 0 || action == 28){ cnc->golinear(xf, 0.2, yf, 0.2, zf, 0.2); } else if(action == 1){ long xi = encoders->getXPosition(); long yi = encoders->getYPosition(); long zi = encoders->getZPosition(); float tTot = (sqrt(sq(xf-xi)+sq(zf-zi)+sq(yf-yi)))/vt; float vx = abs((xf-xi)/tTot); float vy = abs((yf-yi)/tTot); float vz = abs((zf-zi)/tTot); cnc->golinear(xf, vx, yf, vy, zf, vz); } else if(action == 2){ //assert(thetaF > thetaI); float vAng = vt/(r); cnc->goCircular(thetaI, thetaF, 90, 90, r, vAng, false); } else if(action == 3){ //assert(thetaF < thetaI); float vAng = vt/(r); cnc->goCircular(thetaI, thetaF, 90, 90, r, vAng, true); } else if(action == 4){ //Serial.println("Dwell unsupported atm"); } else if(action == 92){ cnc->setPosition(xf, yf, zf); } }
[ "noreply@github.com" ]
noreply@github.com
c55184ee7d0a2e638cba0a2160ec299bdbdfd5e9
2333500195314d8e80708a67f2bf2b148dc37107
/d02/ex00/Fixed.cpp
69c4062e3d00bd42b9572b45dad3e524fb415be1
[]
no_license
Neanti/42cpp
ff080fdd5e318e5dfd8bdad2076ff4b0437758ea
1cd60911c57c0ad1bbaa663107bf92d410f0c11f
refs/heads/master
2023-02-18T15:58:58.737053
2021-01-22T08:33:11
2021-01-22T08:33:11
327,668,641
0
0
null
null
null
null
UTF-8
C++
false
false
719
cpp
#include "Fixed.hpp" Fixed::Fixed() { std::cout << "Default Constructor Called !" << std::endl; this->value = 0; return; } Fixed::~Fixed() { std::cout << "Destructor Called !" << std::endl; return; } Fixed::Fixed(Fixed const &f) { std::cout << "Copy Constructor Called !" << std::endl; this->value = f.getRawBits(); return; } void Fixed::operator=(const Fixed &f) { std::cout << "Assignation Operator Called !" << std::endl; this->value = f.getRawBits(); return; } void Fixed::setRawBits(const int raw) { this->value = raw; return; } int Fixed::getRawBits() const { std::cout << "getRawBits member function Called !" << std::endl; return this->value; }
[ "augay@e3r11p10.42.fr" ]
augay@e3r11p10.42.fr
d8d03450f8d7d6abf52080fbec558731a589e740
785de383d14defe7ff1524dc12267405c0bb58f3
/MinePlugin/Private/MinePluginCommands.cpp
6f33baebd851becc2b51ec7bcf8487e42793d8a2
[]
no_license
stucafall66/UE4_MineSweeperPlugin
3a664f652e0afe2bef87788a5f1e8c905d9a7713
76592c37572df8373f043d6538fb60e17e1749c6
refs/heads/main
2023-04-21T05:45:52.679738
2021-04-13T17:10:07
2021-04-13T17:10:07
354,946,125
0
0
null
null
null
null
UTF-8
C++
false
false
328
cpp
#include "MinePluginCommands.h" #include "MinePlugin.h" #define LOCTEXT_NAMESPACE "FMinePluginModule" void FMinePluginCommands::RegisterCommands() { UI_COMMAND(OpenWidgetCommand, "OpenWIdgetCommand", "The command to open mine widget", EUserInterfaceActionType::Button, FInputGesture()); } #undef LOCTEXT_NAMESPACE
[ "noreply@github.com" ]
noreply@github.com
68b81de628ab6d402a83c70149985babbfbd5be5
55aa92fdb2c8c7d4ba628b0eeb7dd1da5ae7e623
/cw/New folder (5)/ratinamaze.cpp
d888917790c592b7df7f16ebd50639e2930701df
[]
no_license
anchal441/codes
b587a86609b1727c0b3acb285582dc6d7385cf68
9e5d1f3779b5b1ac684440ee4b57d18dc470abbb
refs/heads/master
2020-03-26T10:53:08.932830
2018-08-15T13:21:02
2018-08-15T13:21:02
144,819,304
0
0
null
null
null
null
UTF-8
C++
false
false
253
cpp
#include <bits/stdc++.h> using namespace std; int n_size=10; bool printpath(char board[][n_size],int m,int n){ if() } int main(){ char board[][n_size]={ "...."; ".xx."; ".x.x"; "...."; } int m=n=0; printpath(board,0,0); }
[ "noreply@github.com" ]
noreply@github.com
54b65c42e800e68c70155e6a53df7b519c66308c
aad28fa1140e713c8591db5a383ac5f6605f743b
/172 Серебряная медаль/Серебряная медаль.cpp
b095fbe6acf5ef3ecaa0596183cf906e8f7d7cee
[]
no_license
DaniilMuntyan/Solutions_e-olymp
d7ad45357d4f999c853efefcd47c39bc17e33664
7a318572e13f2e6103a2ade49c8ce9c5210caad9
refs/heads/master
2021-02-28T15:22:58.506994
2020-03-07T21:42:50
2020-03-07T21:42:50
245,708,666
3
0
null
null
null
null
UTF-8
C++
false
false
427
cpp
#include <bits/stdc++.h> using namespace std; int n; vector <int> a; int i,j; int main() { ios_base::sync_with_stdio(0); cin >> n; for(i=0;i<n;i++) { cin >> j; a.push_back(j); } sort(a.rbegin(),a.rend()); j=0; i=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) if(a[i] != a[j]) { cout << a[j] << endl; return 0; } } }
[ "daniilmuntjan@gmail.com" ]
daniilmuntjan@gmail.com
89e1c445aeeff8c3bdf0f0d489fbffd0fa486460
cb7504c5408aebc7ebd33430bd70dd3207fe94c5
/Project1/Zombie.h
9f9bbc495d723a1528e431addd67aaf502484251
[]
no_license
Uchka08/CS32-Project1
434a8dfbe97096eac9ac47cc4ed67d773d8b8b96
50e20c56773bacfda5e29c303fc4e11e24aa980d
refs/heads/master
2022-04-07T06:39:32.802978
2019-02-13T21:23:18
2019-02-13T21:23:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
519
h
// // Zombie.h // Project1 // // Created by christopher kha on 1/11/19. // Copyright © 2019 christopher kha. All rights reserved. // #ifndef Zombie_h #define Zombie_h class Arena; class Zombie { public: // Constructor Zombie(Arena* ap, int r, int c); // Accessors int row() const; int col() const; // Mutators void move(); bool getAttacked(int dir); private: Arena* m_arena; int m_row; int m_col; int m_health; }; #endif /* Zombie_h */
[ "christopherkha@Chriss-Computer.local" ]
christopherkha@Chriss-Computer.local
964365418f4685de0ab5fbae7f9ee076d98bdf7b
56162fb08e9e69b96966dcba347108ccf909c288
/src/touchwidgetcontroller.h
2ee8f17f3687de4c3fb7e607ef6336cd9eb8d86f
[]
no_license
dpkay/fingerglass
90ae3b180bb224b86310812e5e61f3c0a6f5c73d
e15c79faa7d86583ffbb494012bf624905a6b337
refs/heads/master
2021-01-01T16:19:32.566858
2012-07-28T16:03:52
2012-07-28T16:03:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,674
h
#ifndef touchwidgetcontroller_h__ #define touchwidgetcontroller_h__ class TouchWidgetController; #include <QTouchEvent> #include "scenetouchpoint.h" #include "pointwidgetconnection.h" #include "timesingleton.h" #include "timed.h" #include "widgetattachment.h" enum TouchWidgetType { NullType, MapWidgetType, TargetWidgetType, WaypointWidgetType, HandleWidgetType, TouchDisplayWidgetType, MagnifyingWidgetType }; class TouchWidgetController : public QObject, public Timed { Q_OBJECT public: TouchWidgetController(TouchWidgetType type); ~TouchWidgetController(); typedef QTouchEvent::TouchPoint TouchPoint; // touch event handling. virtual void touchPointPressed(SceneTouchPoint * p) = 0; virtual void touchPointMoved(SceneTouchPoint * p) = 0; virtual void touchPointReleased(SceneTouchPoint * p) = 0; virtual bool acceptTouchPoint(const SceneTouchPoint & p) const = 0; virtual bool forwardTouchPoint(const SceneTouchPoint & p) const = 0; // widget <--> touchpoint management PointWidgetConnection * connectToTouchPoint(SceneTouchPoint * p, bool mutual = true); void disconnectFromTouchPoint(SceneTouchPoint * p, bool mutual = true); const QMap<int, PointWidgetConnection *> & touchPointConnections() const; PointWidgetConnection * touchPointConnection( SceneTouchPoint * stp ); PointWidgetConnection * touchPointConnection( int point_id ); PointWidgetConnection * singlePressedTouchPointConnection() const; int numPressedTouchPoints() const; TouchWidgetType type() const; // for stuff like magnifying glasses //virtual void transformTouches(QMap<int, TouchPoint> * touches) const; // from Timed virtual void timeStep(); const QList<WidgetAttachment *> & attachments() const { return _attachments; }; void attach(WidgetAttachment * wa) { _attachments << wa; connect(wa, SIGNAL(close()), this, SLOT(detach())); } public slots: void detach() { WidgetAttachment * sender_attachment = dynamic_cast<WidgetAttachment *>(QObject::sender()); Q_ASSERT(sender_attachment != NULL); _attachments.removeOne(sender_attachment); delete sender_attachment; Q_ASSERT(!_attachments.contains(sender_attachment)); } signals: void closed(); //void registerTouchForward(int id); protected: void close(); void startClosingTimer(int closing_delay); void stopClosingTimer(); bool isClosingTimerRunning() { return _closing_timer != NULL; } bool debug_closingTimerConsistent(); private: QTime * _closing_timer; int _closing_delay; bool _closing_timer_needs_unsubscription; QMap<int, PointWidgetConnection *> _touch_point_connections; TouchWidgetType _type; QList<WidgetAttachment *> _attachments; }; #endif // touchwidget_h__
[ "dominik.kaeser@gmail.com" ]
dominik.kaeser@gmail.com
a8709394d7570373ae255e4d6bdcdac63dcd9ec7
79480c26f13a7dd2d4c2d182b0b537f00c76f40e
/Relay_test/Relay_test.ino
dceaba1547371996d9bfa1e9315b4d1e97d6d87c
[]
no_license
RealmL/PWD_Opener
4c12a7d6e302c892b40a5fb6fa753d0cde907059
f492d90c2ad3aa532af7c272deacfe393dd0ed16
refs/heads/master
2021-04-12T07:48:48.933375
2017-06-09T05:06:18
2017-06-09T05:06:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
242
ino
int SigPin=8;//信号引脚 void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: digitalWrite(SigPin,LOW); delay(1000); digitalWrite(SigPin,HIGH); delay(1000); }
[ "497386856@qq.com" ]
497386856@qq.com
335b753fde4c454b6e9cac77270d25cdd26199af
6ee7742d38f473ac3ba35e12e6d61a2a2c3c0001
/Control/UIAnimation.h
5f1659afd959fdb38051d548af46238bbceaf924
[ "MIT" ]
permissive
wyrover/DuiLib-wyrover
51826759f07606bdc3ac009ce4e8a08dc4b294ff
b40237a6a9b6678acf26b04da36953e7ad1d0974
refs/heads/master
2021-01-10T01:17:38.556373
2016-04-01T09:02:46
2016-04-01T09:02:46
55,213,831
2
1
null
null
null
null
UTF-8
C++
false
false
2,387
h
#ifndef __UIANIMATION_H__ #define __UIANIMATION_H__ #pragma once //class vector; #include <vector> namespace DuiLib { class CUIAnimation; class CControlUI; class UILIB_API IUIAnimation { public: virtual ~IUIAnimation() { NULL; } virtual BOOL StartAnimation(int nElapse, int nTotalFrame, int nAnimationID = 0, BOOL bLoop = FALSE) = 0; virtual VOID StopAnimation(int nAnimationID = 0) = 0; virtual BOOL IsAnimationRunning(int nAnimationID) = 0; virtual int GetCurrentFrame(int nAnimationID = 0) = 0; virtual BOOL SetCurrentFrame(int nFrame, int nAnimationID = 0) = 0; virtual VOID OnAnimationStep(int nTotalFrame, int nCurFrame, int nAnimationID) = 0; virtual VOID OnAnimationStart(int nAnimationID, BOOL bFirstLoop) = 0; virtual VOID OnAnimationStop(int nAnimationID) = 0; virtual VOID OnAnimationElapse(int nAnimationID) = 0; }; struct UILIB_API AnimationData { public: AnimationData() {} AnimationData(int nElipse, int nFrame, int nID, BOOL bLoop) { m_bFirstLoop = TRUE; m_nCurFrame = 0; m_nElapse = nElipse; m_nTotalFrame = nFrame; m_bLoop = bLoop; m_nAnimationID = nID; } //protected: public: friend class CDUIAnimation; int m_nAnimationID; int m_nElapse; int m_nTotalFrame; int m_nCurFrame; BOOL m_bLoop; BOOL m_bFirstLoop; }; class UILIB_API CUIAnimation: public IUIAnimation { public: CUIAnimation(CControlUI* pOwner); ~CUIAnimation(); virtual BOOL StartAnimation(int nElapse, int nTotalFrame, int nAnimationID = 0, BOOL bLoop = FALSE); virtual VOID StopAnimation(int nAnimationID = 0); virtual BOOL IsAnimationRunning(int nAnimationID); virtual int GetCurrentFrame(int nAnimationID = 0); virtual BOOL SetCurrentFrame(int nFrame, int nAnimationID = 0); virtual VOID OnAnimationStart(int nAnimationID, BOOL bFirstLoop) {}; virtual VOID OnAnimationStep(int nTotalFrame, int nCurFrame, int nAnimationID) {}; virtual VOID OnAnimationStop(int nAnimationID) {}; virtual VOID OnAnimationElapse(int nAnimationID); protected: BOOL GetAnimationDataByID(int nAnimationID, AnimationData& data); void RemoveAni(int nAnimationID); protected: CControlUI* m_pControl; std::vector<AnimationData> m_arAnimations; }; } // namespace DuiLib #endif // __UIANIMATION_H__
[ "wyrover@gmail.com" ]
wyrover@gmail.com
ea7a453b3fcceff061c20d48ecbcfdc0519c8551
375440c04dbcbb9db855c3235af2a298b5aa8b5a
/src/app.h
6999f8cba7bc329c17b920ccc74d158ce45f80a9
[ "Apache-2.0" ]
permissive
jonnymind/bursts
657d1f68731e0b88e30b27ec4f31043fb69ac3ee
aef8d2482996b2ac7db736471eaddea839cf9ed2
refs/heads/master
2020-07-23T16:26:13.337014
2019-09-10T22:05:22
2019-09-10T22:05:22
207,628,284
0
0
null
null
null
null
UTF-8
C++
false
false
668
h
/* BurstS - Lightweight Microservice Application Server FILE: app.h ------------------------------------------------------------------- (C) Copyright 2019 - Giancarlo Niccolai Licensed under the Apache 2.0 License. */ #ifndef BURSTS_APP_H #define BURSTS_APP_H /** Wrapper for the burst application. */ class BurstSApp { public: BurstSApp() noexcept; BurstSApp(const BurstSApp &)=delete; BurstSApp(BurstSApp&& )=delete; ~BurstSApp(); void init( int argc, char* argv[] ); void usage(); int run(); static BurstSApp* get() { return m_theApp; } private: static BurstSApp* m_theApp; }; #endif /* end of app.h */
[ "gc@niccolai.cc" ]
gc@niccolai.cc
116c71ed9b1bb3ef0118d68491c7efa0fde5d1ec
b776cbc6e9e7bffa49054a313611783f5a742321
/models/Box.cpp
8762ae0f7837492cb3753bd39d6ddc56b1e730df
[]
no_license
Gagerdude/raytracer
8ce17a1d780e51223b02e24e80fc508a1b1e6f73
e9b886dc66301b3b7c99e10eed573b7737d989b1
refs/heads/master
2020-05-29T11:18:54.859417
2019-07-29T17:29:28
2019-07-29T17:29:28
189,111,953
0
0
null
null
null
null
UTF-8
C++
false
false
1,656
cpp
#include "Box.h" #include "RectangleXY.h" #include "RectangleXZ.h" #include "RectangleYZ.h" #include "Wrapper.h" Box::Box(){ } Box::Box(const vec3& min_corner, const vec3& max_corner, Material* material){ m_min_corner = min_corner; m_max_corner = max_corner; m_material = material; Model** m_box = new Model*[6]; m_box[0] = new RectangleXY(m_min_corner.x(), m_max_corner.x(), m_min_corner.y(), m_max_corner.y(), m_min_corner.z(), new Wrapper(m_material)); m_box[1] = new RectangleXY(m_min_corner.x(), m_max_corner.x(), m_min_corner.y(), m_max_corner.y(), m_max_corner.z(), new Wrapper(m_material)); m_box[2] = new RectangleXZ(m_min_corner.x(), m_max_corner.x(), m_min_corner.z(), m_max_corner.z(), m_min_corner.y(), new Wrapper(m_material)); m_box[3] = new RectangleXZ(m_min_corner.x(), m_max_corner.x(), m_min_corner.z(), m_max_corner.z(), m_max_corner.y(), new Wrapper(m_material)); m_box[4] = new RectangleYZ(m_min_corner.y(), m_max_corner.y(), m_min_corner.z(), m_max_corner.z(), m_min_corner.x(), new Wrapper(m_material)); m_box[5] = new RectangleYZ(m_min_corner.y(), m_max_corner.y(), m_min_corner.z(), m_max_corner.z(), m_max_corner.x(), new Wrapper(m_material)); m_box_scene = new Scene(m_box, 6); delete[] m_box; } Box::~Box(){ delete m_box_scene; delete m_material; } bool Box::hit(const Ray& r, double t_min, double t_max, hit_record& rec) const{ return m_box_scene->hit(r, t_min, t_max, rec); } bool Box::bounding_box(double time_start, double time_end, AxisAlignedBoundingBox& box) const{ box = AxisAlignedBoundingBox(m_min_corner, m_max_corner); return true; }
[ "gagerdude@gmail.com" ]
gagerdude@gmail.com
d5a53fdf3cb53d6bebf43352757c01d8f529bbee
c676ee306d649197ed7ad8c4adc9a21ab48975db
/Source/LibNetSocket/NetSocket.cpp
68d92c706454d176f0b43d37d76e26f93670d00f
[]
no_license
w5762847/hmx_linux
5f4dd6e2e832818c9cbeb5d8d95274cccd4f8760
6935a976381407292cc3bc6a6ed371f2e8221536
refs/heads/master
2020-08-31T16:43:12.162040
2017-04-29T07:20:11
2017-04-29T07:20:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,986
cpp
#include "NetSocket.h" #include "NetServer.h" /*------------------------------------------------------------------- * @Brief : Scoket数据处理类 * * @Author:hzd 2012/04/03 *------------------------------------------------------------------*/ NetSocket::NetSocket(io_service& rIo_service,int32 nMaxRecivedSize,int32 nMaxSendoutSize,int32 nMaxRecivedCacheSize,int32 nMaxSendoutCacheSize):tcp::socket(rIo_service) , m_cHeadBuffer(buffer(m_arrRecvBuffer, PACKAGE_HEADER_SIZE)) , m_cBodyBuffer(buffer(m_arrRecvBuffer + PACKAGE_HEADER_SIZE, nMaxRecivedSize - PACKAGE_HEADER_SIZE)) , m_cSendBuffer(buffer(m_arrSendBuffer, nMaxSendoutSize)) , m_cTimer(rIo_service) , m_cCloseTimer(rIo_service) , m_eRecvStage(REVC_FSRS_NULL) , m_nBodyLen(0) , m_bSending(false) , m_nMaxRecivedSize(nMaxRecivedSize) , m_nMaxSendoutSize(nMaxSendoutSize) , m_nTimeout(0) , m_errorCode(-1) , m_bBreakUpdateIo(false) , m_bEnventClose(false) { static uint32 nSocketIncreseID = 1; static uint64 nSocketIncreseLongID = 1LL; m_nID = nSocketIncreseID++; m_nLongID = nSocketIncreseLongID++; m_cIBuffer.InitBuffer(nMaxRecivedCacheSize); m_cOBuffer.InitBuffer(nMaxSendoutCacheSize); } NetSocket::~NetSocket() { } uint32 NetSocket::SID() { return m_nID; } uint64 NetSocket::SLongID() { return m_nLongID; } void NetSocket::ReadHead() { async_read(*this, m_cHeadBuffer, transfer_exactly(PACKAGE_HEADER_SIZE), boost::bind(&NetSocket::RecvMsg, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); TimeoutStart(); } void NetSocket::ReadBody() { async_read(*this, m_cBodyBuffer, transfer_exactly(m_nBodyLen), boost::bind(&NetSocket::RecvMsg, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); TimeoutStart(); } void NetSocket::Disconnect() { m_cCloseTimer.cancel(); m_cCloseTimer.expires_from_now(boost::posix_time::seconds(0)); m_cCloseTimer.async_wait(boost::bind(&NetSocket::HandleClose, this, boost::asio::placeholders::error)); } void NetSocket::HandleClose(const boost::system::error_code& error) { #ifdef WIN32 #else try { boost::system::error_code ec; shutdown(socket_base::shutdown_both, ec); } catch (...) { } #endif // WIN32 try { boost::asio::socket_base::linger option(true, 0); boost::system::error_code ec1; set_option(option, ec1); boost::system::error_code ec2; tcp::socket::close(ec2); /* 这个不会再收到消息回调 end */ } catch(...) { } } EMsgRead NetSocket::ReadMsg(NetMsgSS** pMsg,int32& nSize) { if (m_bBreakUpdateIo) { printf("[WARRING]:m_bBreakUpdateIo==========true\n"); return MSG_READ_WAITTING; } if (m_cIBuffer.GetLen() < PACKAGE_HEADER_SIZE) { return MSG_READ_WAITTING; } void* buf = m_cIBuffer.GetStart(); memcpy(&nSize,buf,PACKAGE_HEADER_SIZE); if (m_cIBuffer.GetLen() < nSize + PACKAGE_HEADER_SIZE) { return MSG_READ_REVCING; } *pMsg = (NetMsgSS*)((char*)buf + PACKAGE_HEADER_SIZE); return MSG_READ_OK; } void NetSocket::RemoveMsg(uint32 nLen) { m_cIBuffer.RemoveBuffer(nLen); } void NetSocket::RecvMsg(const boost::system::error_code& ec, size_t bytes_transferred) { TimeoutCancel(); if(ec) { printf("[ERROR]:Recv error msg,%s\n",ec.message().c_str()); AddEventLocalClose(); m_errorCode = ESOCKET_EXIST_REMOTE; return; } switch(m_eRecvStage) { case REVC_FSRS_HEAD: { ASSERT(bytes_transferred == PACKAGE_HEADER_SIZE); memcpy(&m_nBodyLen,m_arrRecvBuffer,PACKAGE_HEADER_SIZE); if((uint32) m_nBodyLen < sizeof(NetMsgC) || m_nBodyLen > m_nMaxRecivedSize) { printf("[ERROR]:Recv data length,bodylen:%d, maxLimitLength:%d\n",m_nBodyLen,m_nMaxRecivedSize); AddEventLocalClose(); m_errorCode = ESOCKET_EXIST_PACK_LENGTH_ERROR; m_nBodyLen = 0; return; } bool bResult = m_cIBuffer.Write(m_arrRecvBuffer, PACKAGE_HEADER_SIZE); if(!bResult) { printf("[ERROR]:Write too much data to buffer\n"); AddEventLocalClose(); m_errorCode = ESOCKET_EXIST_WRITE_TOO_DATA; return; } m_eRecvStage = REVC_FSRS_BODY; ReadBody(); } break; case REVC_FSRS_BODY: { bool bResult = m_cIBuffer.Write(m_arrRecvBuffer + PACKAGE_HEADER_SIZE, m_nBodyLen); if(!bResult) { printf("[ERROR]:Write too much data to buffer\n"); AddEventLocalClose(); m_errorCode = ESOCKET_EXIST_WRITE_TOO_DATA; return; } m_eRecvStage = REVC_FSRS_HEAD; ReadHead(); } break; default: { ASSERT(0); } break; } } void NetSocket::Clear() { m_bSending = false; m_nBodyLen = 0; m_eRecvStage = REVC_FSRS_NULL; m_cIBuffer.ClearBuffer(); m_cOBuffer.ClearBuffer(); m_bBreakUpdateIo = false; m_bEnventClose = false; } void NetSocket::ParkMsg(const NetMsgSS* pMsg,int32 nLength) { ASSERT(nLength < 65336); { char arrLen[PACKAGE_HEADER_SIZE]; memcpy(arrLen, &nLength, PACKAGE_HEADER_SIZE); m_cOBuffer.Write(arrLen, PACKAGE_HEADER_SIZE); m_cOBuffer.Write((char*)pMsg, nLength); } } void NetSocket::ParkMsg(const NetMsgC* pMsg, int32 nLength) { char arrLen[PACKAGE_HEADER_SIZE]; memcpy(arrLen, &nLength, PACKAGE_HEADER_SIZE); m_cOBuffer.Write(arrLen, PACKAGE_HEADER_SIZE); m_cOBuffer.Write((char*)pMsg, nLength); } void NetSocket::SendMsg() { if(m_bSending) return; if(int nLen = m_cOBuffer.ReadRemove(&m_arrSendBuffer,m_nMaxSendoutSize)) { m_bSending = true; async_write(*this, m_cSendBuffer, transfer_exactly(nLen), boost::bind(&NetSocket::SendMsg, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } void NetSocket::SendMsg(const boost::system::error_code& ec, size_t bytes_transferred) { if(ec) { printf("[ERROR]:Send msg data error\n"); AddEventLocalClose(); m_errorCode = ESCOKET_EXIST_SEND_CONNECT_INVAILD; return; } if(int nLen = m_cOBuffer.ReadRemove(&m_arrSendBuffer,m_nMaxSendoutSize)) { async_write(*this, m_cSendBuffer, transfer_exactly(nLen), boost::bind(&NetSocket::SendMsg, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { m_bSending = false; } } void NetSocket::HandleWait(const boost::system::error_code& error) { if(error) { return; } printf("[INFO]:That is timeout!\n"); AddEventLocalClose(); m_errorCode = ESOCKET_EXIST_TIMEOUT; } void NetSocket::Run() { m_eRecvStage = REVC_FSRS_HEAD; ReadHead(); } const string NetSocket::GetIp() { return remote_endpoint().address().to_string(); } uint16 NetSocket::GetPort() { return remote_endpoint().port(); } void NetSocket::OnEventColse() { printf("[WARRING]:OnEventColse\n"); AddEventLocalClose(); m_errorCode = ESOCKET_EXIST_LOCAL; } void NetSocket::SetTimeout(int32 nTimeout) { ASSERT(nTimeout > -1); m_nTimeout = nTimeout; } void NetSocket::TimeoutStart() { if(m_nTimeout) { m_cTimer.cancel(); m_cTimer.expires_from_now(boost::posix_time::seconds(m_nTimeout)); m_cTimer.async_wait(boost::bind(&NetSocket::HandleWait, this, boost::asio::placeholders::error)); } } void NetSocket::TimeoutCancel() { if(m_nTimeout) { m_cTimer.cancel(); } } int32 NetSocket::ErrorCode(std::string& error) { switch (m_errorCode) { case ESOCKET_EXIST_NULL: error = "未知"; break; case ESOCKET_EXIST_LOCAL: error = "本地主动断开"; break; case ESOCKET_EXIST_REMOTE: error = "远程主动断开"; break; case ESOCKET_EXIST_TIMEOUT: error = "超时"; break; case ESOCKET_EXIST_PACK_LENGTH_ERROR: error = "数据长度错误"; break; case ESOCKET_EXIST_WRITE_TOO_DATA: error = "写入数据过多"; break; case ESCOKET_EXIST_SEND_CONNECT_INVAILD: error = "发时连接无效"; break; default: error = "未知"; break; } return m_errorCode; } void NetSocket::BreakUpdateIO() { m_bBreakUpdateIo = true; } void NetSocket::UnBreakUpdateIO() { m_bBreakUpdateIo = false; } void NetSocket::AddEventLocalClose() { m_bEnventClose = true; } bool NetSocket::HadEventClose() { bool ret = m_bEnventClose; m_bEnventClose = false; return ret; }
[ "huangzuduan@qq.com" ]
huangzuduan@qq.com
bb2752f17b3dc593c9c55d9c1daa3eca5636c408
5d7d8c65b464204eaa125a057b9375dca9d7f531
/CheckersAI/src/Checkers/Piece.h
01545e225a12334f9144286893176d76201c0ffc
[]
no_license
Hamad-AM/CheckersAI
050cc698c0d720e679e532fee23e0ca1e37f3f86
c8955f2e4a418c37807052da74cf849a274b0b33
refs/heads/master
2022-12-22T18:25:31.564669
2020-09-22T20:40:55
2020-09-22T20:40:55
289,733,424
0
0
null
null
null
null
UTF-8
C++
false
false
151
h
#pragma once #include <string> #include "Color.h" struct Piece { Color color; bool king = false; Piece(Color colorIn) : color(colorIn) {} };
[ "areebhamad.m@gmail.com" ]
areebhamad.m@gmail.com
4f7d2bfbf96b02c07afdda6f90d799bbe0042b20
404547b1ec3237f02342fe65e957f32851ce1495
/Game/ge_stategraphactiontrigger.h
c0b3193b7dc522a0d536fb8943155a7a93997392
[]
no_license
Adanos-Gotoman/GenomeSDK-R
c5e3a5d57c4fb721b15bb7f572454f2a3021561a
cf87f21fca83b37d2e186fb69b083b72932f9c8c
refs/heads/master
2023-03-16T07:05:00.799421
2021-02-19T16:07:09
2021-02-19T16:07:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,145
h
#ifndef GE_STATEGRAPHACTIONTRIGGER_H_INCLUDED #define GE_STATEGRAPHACTIONTRIGGER_H_INCLUDED class GE_DLLIMPORT gCStateGraphActionTrigger : public gCStateGraphAction { GE_DECLARE_PROPERTY_OBJECT( gCStateGraphActionTrigger, gCStateGraphAction ) public: virtual bEResult Create( void ); protected: virtual void Destroy( void ); public: virtual bEResult PostInitializeProperties( void ); public: virtual ~gCStateGraphActionTrigger( void ); public: virtual void GetDescription( bCString & ) const; public: virtual void GetActionDescription( bCString & ) const; public: virtual void OnEnter( void ); public: virtual GEBool OnProcess( void ); public: virtual void OnExit( void ); protected: GE_DECLARE_PROPERTY( GEFloat, m_fTimeOffset, TimeOffset ) GE_DECLARE_PROPERTY( GEI32, m_i32TriggerTargetIndex, TriggerTargetIndex ) GE_DECLARE_PROPERTY( GEBool, m_bUnTriggerOnExit, UnTriggerOnExit ) GEBool __FIXME_002D; GE_PADDING( 2 ) protected: void Invalidate( void ); }; GE_ASSERT_SIZEOF( gCStateGraphActionTrigger, 0x0030 ) #endif
[ "gothicgame29@gmail.com" ]
gothicgame29@gmail.com
c498bc02549fdfcede0cd9b867c91d7101dab18e
1df3c1b7881fe800ecbf05b3ee6202a4509d305b
/Nap1/LAION.cpp
62bfef8622d158cd0640285fc491965f795d64b0
[]
no_license
marc-andrade/tecnicasDeProgramacao1
ac2fe5195a3cba315a3d103a3bb641c79f812e30
029c210fbd85ad9d547c5c7833ebc6cda72f859e
refs/heads/main
2023-06-27T16:26:42.372115
2021-08-02T21:56:40
2021-08-02T21:56:40
392,104,575
0
0
null
null
null
null
UTF-8
C++
false
false
957
cpp
#include <stdio.h> int main(void) { int idade; float peso; char pc, sexo, gest; printf("Digite sua idade:\n"); scanf("%d", &idade); printf("Quanto voce pesa?\n"); scanf("%f", &peso); printf("Voce tem problemas cardiacos? [S/N]\n"); scanf(" %c", &pc); printf("Qual o seu sexo? [M/F]\n"); scanf(" %c", &sexo); if (idade >= 16 && idade <= 69){ if (peso >= 50 && peso <= 100){ if (pc == 'N'){ if (sexo == 'M'){ printf("Autorizado!"); } if (sexo == 'F'){ printf("Voce esta gestante? [S/N]\n"); scanf(" %c", &gest); } if (gest == 'N'){ printf("Autorizado!"); } else { printf("Nao autorizado!"); } } else { printf("Nao autorizado!"); } } else { printf("Nao autorizado!"); } } else { printf("Nao autorizado!"); } return 0; }
[ "marcos_q_andrade@hotmail.com" ]
marcos_q_andrade@hotmail.com
bd7b263655038adebef33d81057062bac5a15d93
f38ee0ba6797166700af0ef936ce9252ac172780
/Data Strucure/QuickSort.cpp
6ca933e6c1b8708584b1fe2ff32fa545efbece42
[]
no_license
ankitaugale23/Data-Structures
c6f40b03603a016813e7ecdcdf43572a86c0edd9
87eb1a70c64b840fea2237fe6dc5d14c842dd1d4
refs/heads/master
2021-06-12T21:15:16.788704
2020-04-09T14:58:18
2020-04-09T14:58:18
254,400,745
7
0
null
null
null
null
UTF-8
C++
false
false
714
cpp
#include<iostream> using namespace std; int Partition(int *A, int start,int end) { int pivot=A[end]; int partIndex=start; for(int i=start;i<end;i++) { if(A[i]<=pivot) { swap(A[i],A[partIndex]); partIndex++; } } swap(A[partIndex],A[end]);//To place the pivot in correct position return partIndex; } void QuickSort(int *A,int start,int end) { if(start<end) { int partIndex=Partition(A,start,end); QuickSort(A,start,partIndex-1); QuickSort(A,partIndex+1,end); } } int main() { int A[10]; cout<<"Enter the elemnts in array"; for(int i=0;i<5;i++) { cin>>A[i]; } QuickSort(A,0,4); for(int i=0;i<5;i++) { cout<<A[i]; } }
[ "noreply@github.com" ]
noreply@github.com
4a987417d6e49c9d9f2f0b6c7c052294f71650d7
c84de8a55a6e97017c0d1e61694c024233db1076
/Quick Sort/main.cpp
267e35d3018d8a996f781d9ec4689e41feae63c1
[]
no_license
TreyJean/Sorting-Algorithms
7d9fdc6a201a3a6122ecc693c96c5c1a5af49c6d
95ae6cd2d743c4565539102ac0d1452cb14a242f
refs/heads/main
2022-12-24T16:53:00.749190
2020-10-08T06:00:36
2020-10-08T06:00:36
300,710,939
0
0
null
null
null
null
UTF-8
C++
false
false
914
cpp
// Quick Sort // Time Complexity: O(nlog(n)) #include<iostream> using namespace std; void swap(int* x, int* y) { int temp = *x; *x = *y; *y = temp; } int partition(int arr[], int start, int end) { int pivot, index; index = start; pivot = end; for(int i=index; i<end; i++) { if(arr[i] < arr[pivot]) { swap(&arr[i], &arr[index++]); } } swap(&arr[pivot], &arr[index]); return index; } void quick_sort(int arr[], int start, int end) { int pivot_index; if(start < end) { pivot_index = partition(arr, start, end); quick_sort(arr, start, pivot_index - 1); quick_sort(arr, pivot_index + 1, end); } } int main() { const int size = 10; int data[size] = {2,7,1,4,8,3,0,9,5,6}; int temp; for(int i=0; i < size; i++) { cout << data[i] << " "; } cout << endl; quick_sort(data, 0, size - 1); for(int i=0; i < size; i++) { cout << data[i] << " "; } cout << endl; return 0; }
[ "treyjean127@gmail.com" ]
treyjean127@gmail.com
f85722985b6f25db6adec6f260ae27d64c0cc33c
c8e970c6df5d1ce8a415571b9764364af9fc5a9e
/main.cpp
61b935fd1521b324a6b892cf443ce07f2971bf04
[]
no_license
benjaminmerchin/ft_containers
8726eac96d77e4f9c9dbf17dea558271526ff0af
7ab3b16152fcfd91e2e779881dc05da1b8de9c85
refs/heads/main
2023-08-26T19:37:02.478432
2021-11-02T23:27:11
2021-11-02T23:27:11
398,277,223
2
1
null
null
null
null
UTF-8
C++
false
false
19,579
cpp
#include "vector.hpp" #include "stack.hpp" #include "map.hpp" #include <vector> #include <map> #include <stack> #include <list> #include <iostream> #include <utility> #if STD #define NS std #else #define NS ft #endif #if TEST template <typename T, typename U> void print_all(NS::map<T,U> &mp) {mp.print_all();} #else template <typename T, typename U> void print_all(NS::map<T,U> &mp) {(void)mp;} #endif template <typename T> void printSize(NS::vector<T> const &vct, bool print_content = 1) { std::cout << "size: " << vct.size() << std::endl; std::cout << "capacity: " << vct.capacity() << std::endl; std::cout << "max_size: " << vct.max_size() << std::endl; if (print_content) { typename NS::vector<T>::const_iterator it = vct.begin(); typename NS::vector<T>::const_iterator ite = vct.end(); std::cout << std::endl << "Content is:" << std::endl; for (; it != ite; ++it) std::cout << "- " << *it << std::endl; } } template<typename type> struct MyAlloc : std::allocator<type> { type * allocate(size_t size) { return new type[size]; } void deallocate(type * ptr, size_t) { delete [] ptr; } }; void ft_insert() { NS::vector<int> myvector (3,100); NS::vector<int>::iterator it; it = myvector.begin(); it = myvector.insert ( it , 200 ); myvector.insert (it,2,300); // "it" no longer valid, get a new one: it = myvector.begin(); NS::vector<int> anothervector (2,400); myvector.insert (it+2,anothervector.begin(),anothervector.end()); int myarray [] = { 501,502,503 }; myvector.insert (myvector.begin(), myarray, myarray+3); std::cout << "myvector contains:"; for (it=myvector.begin(); it<myvector.end(); it++) std::cout << ' ' << *it; std::cout << '\n'; /* */ } void ft_swap() { int x=10, y=20; // x:10 y:20 std::swap(x,y); // x:20 y:10 NS::vector<int> foo (4,x), bar (6,y); // foo:4x20 bar:6x10 NS::swap(foo,bar); // foo:6x10 bar:4x20 std::cout << "foo contains:"; for (NS::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; } void ft_reverse_iterator() { NS::vector<int> myvector; for (int i=0; i<10; i++) myvector.push_back(i); typedef NS::vector<int>::iterator iter_type; // ? 0 1 2 3 4 5 6 7 8 9 ? iter_type from (myvector.begin()); // ^ // ------> iter_type until (myvector.end()); // ^ // NS::reverse_iterator<iter_type> rev_until (from); // ^ // <------ NS::reverse_iterator<iter_type> rev_from (until); // std::cout << "myvector:"; while (rev_from != rev_until) std::cout << ' ' << *rev_from++; std::cout << '\n'; } void ft_reverse_iterator_2() { std::vector<int> myvector; for (int i=0; i<10; i++) myvector.push_back(i); // myvector: 0 1 2 3 4 5 6 7 8 9 typedef std::vector<int>::iterator iter_type; std::reverse_iterator<iter_type> rev_iterator = myvector.rend(); rev_iterator -= 4; std::cout << "rev_iterator now points to: " << *rev_iterator << '\n'; } void ft_reverse_iterator_3() { std::vector<int> myvector; for (int i=0; i<10; i++) myvector.push_back(i); // myvector: 0 1 2 3 4 5 6 7 8 9 typedef std::vector<int>::iterator iter_type; std::reverse_iterator<iter_type> rev_iterator; rev_iterator = myvector.rend() - 3; std::cout << "myvector.rend()-3 points to: " << *rev_iterator << '\n'; } void ft_reverse_iterator_relational_operator() { std::vector<int> myvector; for (int i=0; i<10; i++) myvector.push_back(i); typedef std::vector<int>::iterator iter_type; // ? 9 8 7 6 5 4 3 2 1 0 ? iter_type from (myvector.begin()); // ^ // ------> iter_type until (myvector.end()); // ^ // std::reverse_iterator<iter_type> rev_until (from); // ^ // <------ std::reverse_iterator<iter_type> rev_from (until); // ^ std::cout << "myvector:"; while (rev_from != rev_until) std::cout << ' ' << *rev_from++; std::reverse_iterator<iter_type> rev_it; rev_it = 3 + myvector.rbegin(); std::cout << " - 4th elem: " << *rev_it << '\n'; } void ft_reserve() { NS::vector<int>::size_type sz; NS::vector<int> foo; sz = foo.capacity(); std::cout << "making foo grow: "; for (int i=0; i<100; ++i) { foo.push_back(i); if (sz!=foo.capacity()) { sz = foo.capacity(); std::cout << sz << ' '; } } NS::vector<int> bar; sz = bar.capacity(); bar.reserve(100); // this is the only difference with foo above std::cout << "|making bar grow: "; for (int i=0; i<100; ++i) { bar.push_back(i); if (sz!=bar.capacity()) { sz = bar.capacity(); std::cout << sz << ' '; } } std::cout << std::endl; } void ft_rbegin() { NS::vector<int> myvector (5); // 5 default-constructed ints int i=0; NS::vector<int>::reverse_iterator rit = myvector.rbegin(); for (; rit!= myvector.rend(); ++rit) *rit = ++i; std::cout << "myvector contains:"; for (NS::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; } void ft_rend() { NS::vector<int> myvector (5); // 5 default-constructed ints NS::vector<int>::reverse_iterator rit = myvector.rbegin(); int i=0; for (rit = myvector.rbegin(); rit!= myvector.rend(); ++rit) *rit = ++i; std::cout << "myvector contains:"; for (NS::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; } void ft_constructor() { // constructors used in the same order as described above: NS::vector<int> first; // DEFAULT NS::vector<int> second (4,100); // four ints with value 100 FILL NS::vector<int> fourth (second); // COPY NS::vector<int> third (second.begin(),second.end()); // RANGE // the iterator constructor can also be used to construct from arrays: int myints[] = {16,2,77,29}; NS::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) ); std::cout << "The contents of fifth are:"; for (NS::vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; /* */ } template <class T> void print_vector(NS::vector<T> myvector) { for (unsigned long i=0; i<myvector.size(); ++i) std::cout << myvector[i] << ' '; std::cout << '\n'; } void ft_test() { NS::vector<int> vct(7); NS::vector<int> vct_two(4); NS::vector<int> vct_three; NS::vector<int> vct_four; for (unsigned long int i = 0; i < vct.size(); ++i) vct[i] = (vct.size() - i) * 3; for (unsigned long int i = 0; i < vct_two.size(); ++i) vct_two[i] = (vct_two.size() - i) * 5; printSize(vct); printSize(vct_two); vct_three.assign(vct.begin(), vct.end()); vct.assign(vct_two.begin(), vct_two.end()); vct_two.assign(2, 42); vct_four.assign(4, 21); std::cout << "\t### After assign(): ###" << std::endl; printSize(vct); /* */ NS::vector<char> characters; characters.assign(5, 'a'); for (unsigned long i=0; i<characters.size(); ++i) std::cout << characters[i] << ' '; std::cout << '\n'; const std::string extra(6, 'b'); characters.assign(extra.begin(), extra.end()); for (unsigned long i=0; i<characters.size(); ++i) std::cout << characters[i] << ' '; std::cout << '\n'; } void basic_tests() { std::vector<int> a; std::cout << "size:" << a.size() << "\tcapacity:" << a.capacity() << "\tmax_size:" << a.max_size() << std::endl; a.push_back(time(0)%3); a.push_back(time(0)%15); a.push_back(time(0)%10); a.push_back(time(0)%9); a.push_back(time(0)%7); typedef std::vector<int>::iterator iterator; for (iterator it_a = a.begin(); it_a != a.end(); ++it_a) std::cout << *it_a << ' '; std::cout << std::endl; std::cout << "size:" << a.size() << "\tcapacity:" << a.capacity() << std::endl; a.resize(4); std::cout << "size:" << a.size() << "\tcapacity:" << a.capacity() << std::endl; std::cout << "------------------\n"; NS::vector<int> b(2, 3); std::cout << "size:" << b.size() << "\tcapacity:" << b.capacity() << "\tmax_size:" << b.max_size() << std::endl; b.push_back(time(0)%3); b.push_back(time(0)%14); b.push_back(time(0)%10); std::cout << "size:" << b.size() << "\tcapacity:" << b.capacity() << std::endl; for (unsigned int i = 0; i < b.size(); i++) std::cout << b[i] << ' '; std::cout << std::endl; for (NS::vector<int>::iterator it = b.begin() ; it != b.end(); ++it) std::cout << *it << ' '; std::cout << std::endl; std::cout << "------------------\n"; NS::vector<int> c(2, 3); c.assign(7, 100); NS::vector<int>::iterator iter = c.begin(); (void)iter; for (unsigned int i = 0; i < c.size(); i++) std::cout << c[i] << ' '; std::cout << std::endl; int myints[] = {1776,7,4};(void)myints; NS::vector<int> d; std::cout << "------------------\n"; NS::vector<int> myvector_2 (3,100); NS::vector<int>::iterator it; it = myvector_2.begin(); it = myvector_2.insert ( it , 200 ); myvector_2.insert (it,2,300); // "it" no longer valid, get a new one: it = myvector_2.begin() + 1; NS::vector<int> anothervector (myvector_2.begin(), myvector_2.end()); myvector_2.insert (it+2,anothervector.begin(),anothervector.end()); int myarray [] = { 501,502,503 }; myvector_2.insert (myvector_2.begin(), myarray, myarray+3); std::cout << "myvector_2 contains:"; for (it=myvector_2.begin(); it<myvector_2.end(); it++) std::cout << ' ' << *it; std::cout << '\n'; /* */ } void ft_erase() { NS::vector<int> myvector; // set some values (from 1 to 10) for (int i=1; i<=10; i++) myvector.push_back(i); // erase the 6th element myvector.erase (myvector.begin()+5); // erase the first 3 elements: myvector.erase (myvector.begin(),myvector.begin()+3); std::cout << "myvector contains:"; for (unsigned i=0; i<myvector.size(); ++i) std::cout << ' ' << myvector[i]; std::cout << '\n'; NS::vector<int>::iterator it = myvector.begin() + 2; (void)it; } void test_list() { basic_tests(); ft_insert(); std::cout << "myvector contains: 501 502 503 300 300 400 400 200 100 100 100" << std::endl; ft_swap(); std::cout << "foo contains: 10 10 10 10 10 10" << std::endl; #if __APPLE__ std::cout << "is_integral w/ float: " << std::boolalpha << NS::is_integral<float>::value << std::endl; std::cout << "is_integral w/ int: " << std::boolalpha << NS::is_integral<int>::value << std::endl; #endif ft_reverse_iterator(); std::cout << "myvector: 9 8 7 6 5 4 3 2 1 0" << std::endl; ft_reverse_iterator_2(); std::cout << "rev_iterator now points to: 3" << std::endl; ft_reverse_iterator_3(); std::cout << "myvector.rend()-3 points to: 2" << std::endl; ft_reverse_iterator_relational_operator(); std::cout << "myvector: 9 8 7 6 5 4 3 2 1 0 - 4th elem: 6" << std::endl; ft_reserve(); std::cout << "making foo grow: 1 2 4 8 16 32 64 128 |making bar grow: 100" << std::endl; ft_rbegin(); std::cout << "myvector contains: 5 4 3 2 1" << std::endl; ft_rend(); std::cout << "myvector contains: 5 4 3 2 1 " << std::endl; ft_constructor(); std::cout << "The contents of fifth are: 16 2 77 29" << std::endl; ft_insert(); std::cout << "myvector contains: 501 502 503 300 300 400 400 200 100 100 100" << std::endl; ft_erase(); std::cout << "myvector contains: 4 5 7 8 9 10" << std::endl; /* */ } void stack_size() { NS::stack<int> myints; std::cout << "0. size: " << myints.size() << '\t'; for (int i=0; i<5; i++) myints.push(i); std::cout << "1. size: " << myints.size() << '\t'; myints.pop(); std::cout << "2. size: " << myints.size() << '\n'; std::cout << "0. size: 0\t1. size: 5\t2. size: 4" << std::endl; } void stack_push() { { NS::stack<int> mystack; for (int i=0; i<5; ++i) mystack.push(i); std::cout << "Popping out elements..."; while (!mystack.empty()) { std::cout << ' ' << mystack.top(); mystack.pop(); } std::cout << '\n'; std::cout << "Popping out elements... 4 3 2 1 0" << std::endl; } { NS::stack<int> mystack; NS::stack<int> mystack2; std::cout << std::boolalpha << (mystack == mystack2) << std::endl; mystack.push(1); std::cout << std::boolalpha << (mystack == mystack2) << std::endl; } } void pair_constructor() { NS::pair <std::string,double> product1; // default constructor NS::pair <std::string,double> product2 ("tomatoes",2.30); // value init NS::pair <std::string,double> product3 (product2); // copy constructor (void)product1; (void)product2; (void)product3; product1 = NS::make_pair(std::string("lightbulbs"),0.99); // using make_pair (move) product2.first = "shoes"; // the type of first is string product2.second = 39.90; // the type of second is double std::cout << "The price of " << product1.first << " is $" << product1.second << '\n'; std::cout << "The price of " << product2.first << " is $" << product2.second << '\n'; std::cout << "The price of " << product3.first << " is $" << product3.second << '\n'; std::pair <std::string,int> planet, homeplanet; planet = std::make_pair("Earth",6371); homeplanet = planet; std::cout << "Home planet: " << homeplanet.first << '\n'; std::cout << "Planet size: " << homeplanet.second << '\n'; /* */ NS::pair<int,char> foo (10,'z'); NS::pair<int,char> bar (90,'a'); if (foo==bar) std::cout << "foo and bar are equal\n"; if (foo!=bar) std::cout << "foo and bar are not equal\n"; if (foo< bar) std::cout << "foo is less than bar\n"; if (foo> bar) std::cout << "foo is greater than bar\n"; if (foo<=bar) std::cout << "foo is less than or equal to bar\n"; if (foo>=bar) std::cout << "foo is greater than or equal to bar\n"; } void map_std() { std::map<int,int> b; b.insert(std::pair<int,int>(4, 106)); b.insert(std::pair<int,int>(1, 106)); b.insert(std::pair<int,int>(0, 106)); b.insert(std::pair<int,int>(2, 106)); b.insert(std::pair<int,int>(10, 106)); b.insert(std::pair<int,int>(9, 106)); b.insert(std::pair<int,int>(11, 106)); std::map<int, int>::iterator it = b.begin(); std::map<int, int>::iterator ite = b.end(); for (; it != ite; it++) std::cout << it->first << ' ' << it->second << std::endl; std::cout << "---------------------------------\n"; } void map_find() { NS::map<char,int> mymap; NS::map<char,int>::iterator it; (void)it; (void)mymap; mymap['a']=50; mymap['b']=100; mymap['c']=150; mymap['d']=200; it = mymap.find('b'); if (it != mymap.end()) mymap.erase (it); /* */ // print content: std::cout << "elements in mymap: "; std::cout << "a => " << mymap.find('a')->second << ' '; std::cout << "c => " << mymap.find('c')->second << ' '; std::cout << "d => " << mymap.find('d')->second << '\n'; std::cout << "elements in mymap: a => 50 c => 150 d => 200\n"; } void map_count() { NS::map<char,int> mymap; char c; mymap ['a']=101; mymap ['c']=202; mymap ['f']=303; for (c='a'; c<'h'; c++) { std::cout << c; if (mymap.count(c)>0) std::cout << "0 "; else std::cout << "1 "; } std::cout << std::endl; std::cout << "a0 b1 c0 d1 e1 f0 g1 \n"; /* */ } void map_erase() { NS::map<char,int> mymap; NS::map<char,int>::iterator it; // insert some values: for (int i = 0; i < 10; i++) mymap.insert(NS::pair<char, int>(i + 'a', i * 10)); print_all<char,int>(mymap); it=mymap.find('b'); mymap.erase (it); // erasing by iterator mymap.erase ('c'); // erasing by key it=mymap.find ('e'); mymap.erase ( it, mymap.end() ); // erasing by range // show content: std::cout << "testing erase: "; for (it=mymap.begin(); it!=mymap.end(); ++it) std::cout << it->first << " => " << it->second << ' '; std::cout << std::endl; std::cout << "testing erase: a => 10 d => 40\n"; } void map_operator() { NS::map<char,std::string> mymap; mymap['a']="an element"; mymap['b']="another element"; mymap['c']=mymap['b']; std::cout << "mymap['a'] is " << mymap['a'] << '\n'; std::cout << "mymap['b'] is " << mymap['b'] << '\n'; std::cout << "mymap['c'] is " << mymap['c'] << '\n'; std::cout << "mymap['d'] is " << mymap['d'] << '\n'; std::cout << "mymap now contains " << mymap.size() << " elements.\n"; } void map_empty() { NS::map<char,int> mymap; mymap['a']=10; mymap['b']=20; mymap['c']=30; while (!mymap.empty()) { std::cout << mymap.begin()->first << " => " << mymap.begin()->second << ' '; mymap.erase(mymap.begin()); //error here } std::cout << std::endl; std::cout << "a => 10 b => 20 c => 30\n"; } void map_upper_bound() { NS::map<char,int> mymap; NS::map<char,int>::iterator itlow,itup; mymap['a']=20; mymap['b']=40; mymap['c']=60; mymap['d']=80; mymap['e']=100; itlow=mymap.lower_bound ('b'); // itlow points to b itup=mymap.upper_bound ('d'); // itup points to e (not d!) mymap.erase(itlow,itup); // erases [itlow,itup) // print content: for (NS::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it) std::cout << it->first << " => " << it->second << ' '; std::cout << std::endl; std::cout << "a => 20 e => 100 \n"; } void map_marc_erase() { NS::map<int, int> mp; for (unsigned int i = 0; i < 10; ++i) mp.insert(NS::pair<int, int>(i, i*10)); print_all<int, int>(mp); mp.erase(++mp.begin()); mp.erase(mp.begin()); mp.erase(--mp.end()); mp.erase(mp.begin(), ++mp.begin()); print_all<int, int>(mp); mp.erase(mp.begin(), ++(++(++mp.begin()))); mp.erase(--(--(--mp.end())), --mp.end()); mp[10] = 100; mp[11] = 110; mp.erase(--(--(--mp.end())), mp.end()); print_all<int, int>(mp); mp[12] = 120; mp[13] = 130; mp[14] = 140; mp[15] = 150; mp.erase(mp.begin(), mp.end()); print_all<int, int>(mp); /* */ } int main() { map_marc_erase(); test_list(); map_find(); map_count(); map_erase(); map_operator(); std::cout << "---------------------------------\n"; map_upper_bound(); map_empty(); ft_test(); stack_size(); stack_push(); pair_constructor(); map_std(); std::cout << "---------------------------------\n"; /* */ NS::map<int, int> a; a.insert(NS::pair<int,int>(5, 104)); a.insert(NS::pair<int,int>(1, 103)); a.insert(NS::pair<int,int>(8, 100)); a.insert(NS::pair<int,int>(6, 100)); a.insert(NS::pair<int,int>(11, 106)); a.insert(NS::pair<int,int>(-100, 106)); a.insert(NS::pair<int,int>(8, 106)); //already inserted a.erase(5); print_all<int, int>(a); /* */ a.erase(2); a.erase(3); a.erase(1); a.erase(4); std::cout << "---------------------------------\n"; print_all<int, int>(a); std::cout << "---------------------------------\n"; a.insert(NS::pair<int,int>(4, 106)); a.insert(NS::pair<int,int>(3, 106)); a.insert(NS::pair<int,int>(3, 106)); print_all<int, int>(a); std::string str = "ok 42"; char * writable = new char[str.size() + 1]; (void)writable; std::cout << "---------------------------------\n"; NS::map<int, int>::iterator it = a.begin(); NS::map<int, int>::iterator it_end = a.end(); std::cout << "size: " << a.size() << std::endl; for (;it != it_end; it++) { std::cout << it->first << ' '; } std::cout << std::endl; std::cout << "---------------------------------\n"; NS::map<int, int> b; b = a; NS::map<int, int>::iterator it_b = b.begin(); NS::map<int, int>::iterator it_end_b = b.end(); std::cout << "size: " << b.size() << std::endl; for (;it_b != it_end_b; it_b++) { std::cout << it_b->first << ' '; } std::cout << std::endl; std::cout << "---------------------------------\n"; return 0; }
[ "benjaminmerchin@gmail.com" ]
benjaminmerchin@gmail.com
b8699a88841ef69d7c80229e2864230c64ce8706
17f418cedc5d7db95ad25311974d822671819fe8
/Hackerrank - Grading Students.cpp
28fef27d6fa8f03d4e78d96040b848d773e26858
[]
no_license
hendptr/Competetive-Programming
c0029c61144dcba93af71d25c7b9f1d59becac02
862e22ada9c39deed20f2a0216ed406aa3162472
refs/heads/master
2022-11-30T06:24:40.878416
2020-07-20T03:10:16
2020-07-20T03:10:16
260,623,075
1
0
null
null
null
null
UTF-8
C++
false
false
310
cpp
#include <cmath> #include <iostream> int main() { int n, tmp_grade; std::cin >> n; while(n-->0) { std::cin >> tmp_grade; if (tmp_grade >= 38 && tmp_grade % 5 > 2) tmp_grade += 5 - (tmp_grade % 5); std::cout << tmp_grade << '\n'; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
3d66734346343ca7837b0c014867047d426e6362
66deb611781cae17567efc4fd3717426d7df5e85
/pcmanager/src/src_kclear/fcache/src/fcacheimp.cpp
857400501f4c06983f7d84e882972dc9799dabf4
[ "Apache-2.0" ]
permissive
heguoxing98/knoss-pcmanager
4671548e14b8b080f2d3a9f678327b06bf9660c9
283ca2e3b671caa85590b0f80da2440a3fab7205
refs/heads/master
2023-03-19T02:11:01.833194
2020-01-03T01:45:24
2020-01-03T01:45:24
504,422,245
1
0
null
2022-06-17T06:40:03
2022-06-17T06:40:02
null
GB18030
C++
false
false
20,789
cpp
#include "stdafx.h" #include "fcacheimp.h" #include <shlobj.h> #include "kscbase/kscconv.h" ////////////////////////////////////////////////////////////////////////// CFCacheImpl::CFCacheImpl(char cVol) : m_dwRefCount(0) , m_pDbConnect(NULL) { if (!PrepareDbFile(cVol)) throw "error"; } CFCacheImpl::~CFCacheImpl() { } ////////////////////////////////////////////////////////////////////////// BOOL CFCacheImpl::PrepareDbFile(char cVol) { BOOL retval = FALSE; CHAR szAppData[MAX_PATH] = { 0 }; CStringA strCacheName; BOOL bRetCode; strCacheName.Format("%c.cache", cVol); bRetCode = ::SHGetSpecialFolderPathA(NULL, szAppData, CSIDL_COMMON_APPDATA, TRUE); if (!bRetCode) goto clean0; ::PathAppendA(szAppData, "kingsoft"); if (::GetFileAttributesA(szAppData) == INVALID_FILE_ATTRIBUTES) { ::CreateDirectoryA(szAppData, NULL); } ::PathAppendA(szAppData, "kclear"); if (::GetFileAttributesA(szAppData) == INVALID_FILE_ATTRIBUTES) { ::CreateDirectoryA(szAppData, NULL); } ::PathAppendA(szAppData, "fcache"); if (::GetFileAttributesA(szAppData) == INVALID_FILE_ATTRIBUTES) { ::CreateDirectoryA(szAppData, NULL); } ::PathAppendA(szAppData, strCacheName); m_strDbPath = szAppData; retval = TRUE; clean0: return retval; } ////////////////////////////////////////////////////////////////////////// STDMETHODIMP_(ULONG) CFCacheImpl::AddRef() { return ++m_dwRefCount; } STDMETHODIMP_(ULONG) CFCacheImpl::Release() { ULONG retval = --m_dwRefCount; if (!retval) delete this; return retval; } STDMETHODIMP CFCacheImpl::QueryInterface(REFIID riid, void **ppvObject) { HRESULT hr = E_FAIL; if (!ppvObject) { hr = E_INVALIDARG; goto clean0; } if (__uuidof(IFCache) == riid) { *ppvObject = static_cast<IFCache*>(this); } else { hr = E_NOINTERFACE; goto clean0; } reinterpret_cast<IUnknown*>(*ppvObject)->AddRef(); hr = S_OK; clean0: return hr; } ////////////////////////////////////////////////////////////////////////// BOOL CFCacheImpl::Initialize() { BOOL retval = FALSE; int nRetCode = -1; char* szError = NULL; nRetCode = sqlite3_open(m_strDbPath, &m_pDbConnect); if (nRetCode) goto clean0; nRetCode = sqlite3_exec(m_pDbConnect, "create table files(path TEXT, ext TEXT, size BIGINT)", NULL, NULL, &szError); nRetCode = sqlite3_exec(m_pDbConnect, "create table exts(ext TEXT, size BIGINT, count BIGINT)", NULL, NULL, &szError); nRetCode = sqlite3_exec(m_pDbConnect, "create table top100(path TEXT, size BIGINT)", NULL, NULL, &szError); nRetCode = sqlite3_exec(m_pDbConnect, "create table info(size BIGINT, count BIGINT)", NULL, NULL, &szError); nRetCode = sqlite3_exec(m_pDbConnect, "create table cache(time BIGINT, full INTEGER)", NULL, NULL, &szError); retval = TRUE; clean0: return retval; } BOOL CFCacheImpl::UnInitialize() { if (m_pDbConnect) { sqlite3_close(m_pDbConnect); m_pDbConnect = NULL; } return TRUE; } BOOL CFCacheImpl::BeginAdd() { BOOL retval = FALSE; int nRetCode; char* szError = NULL; if (!m_pDbConnect) goto clean0; nRetCode = sqlite3_exec(m_pDbConnect, "begin transaction", NULL, NULL, &szError); if (nRetCode) goto clean0; retval = TRUE; clean0: return retval; } BOOL CFCacheImpl::EndAdd() { BOOL retval = FALSE; int nRetCode; char* szError = NULL; if (!m_pDbConnect) goto clean0; nRetCode = sqlite3_exec(m_pDbConnect, "commit transaction", NULL, NULL, &szError); if (nRetCode) goto clean0; retval = TRUE; clean0: return retval; } BOOL CFCacheImpl::CancelAdd() { BOOL retval = FALSE; int nRetCode; char* szError = NULL; if (!m_pDbConnect) goto clean0; nRetCode = sqlite3_exec(m_pDbConnect, "rollback transaction", NULL, NULL, &szError); if (nRetCode) goto clean0; retval = TRUE; clean0: return retval; } BOOL CFCacheImpl::AddFile( LPCWSTR lpFilePath, ULONGLONG qwFileSize ) { BOOL retval = FALSE; int nRetCode; char* szError = NULL; CStringA strSql; CStringW strFilePath; CStringW strExt; int nExt; if (!m_pDbConnect) goto clean0; if (!lpFilePath) goto clean0; strFilePath = lpFilePath; strFilePath.MakeLower(); nExt = strFilePath.ReverseFind(_T('.')); if (nExt != -1 && nExt > strFilePath.ReverseFind(_T('\\'))) { strExt = strFilePath.Right(strFilePath.GetLength() - nExt); } if (strExt.IsEmpty()) { strExt = _T(".n/a"); } strSql.Format("insert into files values('%s', '%s', %I64d)", KUTF16_To_UTF8(strFilePath), KUTF16_To_UTF8(strExt), qwFileSize); nRetCode = sqlite3_exec(m_pDbConnect, strSql, NULL, NULL, &szError); if (nRetCode) goto clean0; retval = TRUE; clean0: return retval; } BOOL CFCacheImpl::DelFile(LPCWSTR lpFilePath) { BOOL retval = FALSE; int nRetCode; char* szError = NULL; CStringA strSql; CStringW strFilePath; int nExt; CStringW strExt; sqlite3_stmt* pStmt = NULL; ULONGLONG qwSize; if (!m_pDbConnect) goto clean0; if (!lpFilePath) goto clean0; strFilePath = lpFilePath; strFilePath.MakeLower(); nExt = strFilePath.ReverseFind(_T('.')); if (nExt != -1 && nExt > strFilePath.ReverseFind(_T('\\'))) { strExt = strFilePath.Right(strFilePath.GetLength() - nExt); } if (strExt.IsEmpty()) { strExt = _T(".n/a"); } // 获得大小 strSql.Format("select size from files where path = '%s'", KUTF16_To_UTF8(strFilePath)); nRetCode = sqlite3_prepare(m_pDbConnect, strSql, -1, &pStmt, 0); if (nRetCode) goto clean0; nRetCode = sqlite3_step(pStmt); if (SQLITE_ROW != nRetCode) goto clean0; qwSize = sqlite3_column_int64(pStmt, 0); // 删除文件 strSql.Format("delete from files where path = '%s'", KUTF16_To_UTF8(strFilePath)); nRetCode = sqlite3_exec(m_pDbConnect, strSql, NULL, NULL, &szError); if (nRetCode) goto clean0; // 从Top100中删除 strSql.Format("delete from top100 where path = '%s'", KUTF16_To_UTF8(strFilePath)); nRetCode = sqlite3_exec(m_pDbConnect, strSql, NULL, NULL, &szError); // 从Exts中去除大小 strSql.Format("insert into exts values('%s', -%I64d, -1)", KUTF16_To_UTF8(strExt), qwSize); nRetCode = sqlite3_exec(m_pDbConnect, strSql, NULL, NULL, &szError); // 从总大小中去除大小 strSql.Format("insert into info values(-%I64d, -1)", qwSize); nRetCode = sqlite3_exec(m_pDbConnect, strSql, NULL, NULL, &szError); retval = TRUE; clean0: if (pStmt) { sqlite3_finalize(pStmt); pStmt = NULL; } return retval; } BOOL CFCacheImpl::DelDir(LPCWSTR lpDir) { BOOL retval = FALSE; int nRetCode; char* szError = NULL; CStringA strSql; CStringW strDir; if (!m_pDbConnect) goto clean0; if (!lpDir) goto clean0; strDir = lpDir; strDir.MakeLower(); strSql.Format("delete from files where path like '%s%s'", KUTF16_To_UTF8(strDir), "%"); nRetCode = sqlite3_exec(m_pDbConnect, strSql, NULL, NULL, &szError); if (nRetCode) goto clean0; retval = TRUE; clean0: return retval; } BOOL CFCacheImpl::GetTotalInfo(ULONGLONG& qwTotalSize, ULONGLONG& qwTotalCount) { BOOL retval = FALSE; int nRetCode; char* szError = NULL; CStringA strSql; sqlite3_stmt* pStmt = NULL; if (!m_pDbConnect) goto clean0; strSql = "select sum(size), sum(count) from info"; nRetCode = sqlite3_prepare(m_pDbConnect, strSql, -1, &pStmt, 0); if (nRetCode) goto clean0; nRetCode = sqlite3_step(pStmt); if (SQLITE_ROW == nRetCode) { qwTotalSize = sqlite3_column_int64(pStmt, 0); qwTotalCount = sqlite3_column_int64(pStmt, 1); if (qwTotalCount && qwTotalSize) { retval = TRUE; goto clean0; } } sqlite3_finalize(pStmt); pStmt = NULL; strSql = "insert into info(size, count) select sum(size), count(size) from files"; nRetCode = sqlite3_exec(m_pDbConnect, strSql, NULL, NULL, &szError); if (nRetCode) goto clean0; strSql = "select size, count from info"; nRetCode = sqlite3_prepare(m_pDbConnect, strSql, -1, &pStmt, 0); if (nRetCode) goto clean0; nRetCode = sqlite3_step(pStmt); if (SQLITE_ROW != nRetCode) goto clean0; qwTotalSize = sqlite3_column_int64(pStmt, 0); qwTotalCount = sqlite3_column_int64(pStmt, 1); retval = TRUE; clean0: if (pStmt) { sqlite3_finalize(pStmt); pStmt = NULL; } return retval; } BOOL CFCacheImpl::Query( IFCacheQueryback* piQueryback, FCacheQueryType queryType, void* pParam1, void* pParam2 ) { BOOL retval = FALSE; int nRetCode; char* szError = NULL; CStringA strSql; sqlite3_stmt* pStmt = NULL; if (!m_pDbConnect) goto clean0; if (!piQueryback) goto clean0; if (enumFQT_Top == queryType) { if (!pParam1) goto clean0; strSql.Format("select path, size from top100 order by size desc limit %d", *(ULONG*)pParam1); nRetCode = sqlite3_prepare(m_pDbConnect, strSql, -1, &pStmt, 0); if (nRetCode) goto clean0; nRetCode = sqlite3_step(pStmt); if (SQLITE_ROW == nRetCode) goto get_data; sqlite3_finalize(pStmt); pStmt = NULL; strSql = "delete from top100"; nRetCode = sqlite3_exec(m_pDbConnect, strSql, NULL, NULL, &szError); strSql = "insert into top100(path, size) select path, size from files order by size desc limit 500"; nRetCode = sqlite3_exec(m_pDbConnect, strSql, NULL, NULL, &szError); if (nRetCode) goto clean0; strSql.Format("select path, size from top100 order by size desc limit %d", *(ULONG*)pParam1); } else if (enumFQT_Ext == queryType) { CStringA strExt; if (!pParam1) goto clean0; if (*(char*)pParam1 == '.') { strExt = (char*)pParam1; } else { strExt = "."; strExt += (char*)pParam1; } strSql.Format("select path, size from files where ext = '%s' order by size desc", strExt); } else if (enumFQT_Zone == queryType) { ULONGLONG qwFrom, qwTo; if (!pParam1 || !pParam2) goto clean0; qwFrom = *(ULONGLONG*)pParam1; qwTo = *(ULONGLONG*)pParam2; strSql.Format("select path, size from files where size >= %I64d and size <= %I64d order by size desc", qwFrom, qwTo); } else if (enumFQT_Word == queryType) { CStringW strWord; if (!pParam1) goto clean0; strWord = (const wchar_t*)pParam1; strSql.Format("select path, size from files where path like '%s%s%s' order by size desc", "%", KUTF16_To_UTF8(strWord), "%"); } strSql.MakeLower(); nRetCode = sqlite3_prepare(m_pDbConnect, strSql, -1, &pStmt, 0); if (nRetCode) goto clean0; nRetCode = sqlite3_step(pStmt); if (nRetCode != SQLITE_ROW) goto clean0; get_data: while (SQLITE_ROW == nRetCode) { CStringA strFilePath = (char*)sqlite3_column_text(pStmt, 0); ULONGLONG qwFileSize = sqlite3_column_int64(pStmt, 1); piQueryback->OnData(queryType, KUTF8_To_UTF16(strFilePath), qwFileSize); nRetCode = sqlite3_step(pStmt); } retval = TRUE; clean0: if (pStmt) { sqlite3_finalize(pStmt); pStmt = NULL; } return retval; } BOOL CFCacheImpl::Clean() { BOOL retval = FALSE; int nRetCode; char* szError = NULL; if (!m_pDbConnect) goto clean0; nRetCode = sqlite3_exec(m_pDbConnect, "delete from files", NULL, NULL, &szError); if (nRetCode) goto clean0; nRetCode = sqlite3_exec(m_pDbConnect, "delete from exts", NULL, NULL, &szError); if (nRetCode) goto clean0; nRetCode = sqlite3_exec(m_pDbConnect, "delete from top100", NULL, NULL, &szError); nRetCode = sqlite3_exec(m_pDbConnect, "delete from info", NULL, NULL, &szError); nRetCode = sqlite3_exec(m_pDbConnect, "delete from cache", NULL, NULL, &szError); retval = TRUE; clean0: return retval; } BOOL CFCacheImpl::GetFileSize( LPCWSTR lpFilePath, ULONGLONG& qwSize ) { BOOL retval = FALSE; int nRetCode; char* szError = NULL; CStringA strSql; CStringW strFilePath; sqlite3_stmt* pStmt = NULL; if (!m_pDbConnect) goto clean0; if (!lpFilePath) goto clean0; strFilePath = lpFilePath; strFilePath.MakeLower(); strSql.Format("select size from files where path = '%s'", KUTF16_To_UTF8(strFilePath)); nRetCode = sqlite3_prepare(m_pDbConnect, strSql, -1, &pStmt, 0); if (nRetCode) goto clean0; nRetCode = sqlite3_step(pStmt); if (SQLITE_ROW != nRetCode) goto clean0; qwSize = sqlite3_column_int64(pStmt, 0); retval = TRUE; clean0: if (pStmt) { sqlite3_finalize(pStmt); pStmt = NULL; } return retval; } BOOL CFCacheImpl::GetDirInfo( LPCWSTR lpDir, ULONGLONG& qwSize, ULONGLONG& qwCount ) { BOOL retval = FALSE; int nRetCode; char* szError = NULL; CStringA strSql; CStringW strDir; sqlite3_stmt* pStmt = NULL; if (!m_pDbConnect) goto clean0; if (!lpDir) goto clean0; strDir = lpDir; strDir.MakeLower(); strSql.Format("select sum(size), count(size) from files where path like '%s\\%s'", KUTF16_To_UTF8(strDir), "%"); nRetCode = sqlite3_prepare(m_pDbConnect, strSql, -1, &pStmt, 0); if (nRetCode) goto clean0; nRetCode = sqlite3_step(pStmt); if (SQLITE_ROW != nRetCode) goto clean0; qwSize = sqlite3_column_int64(pStmt, 0); qwCount = sqlite3_column_int64(pStmt, 1); retval = TRUE; clean0: if (pStmt) { sqlite3_finalize(pStmt); pStmt = NULL; } return retval; } BOOL CFCacheImpl::QueryTopExt( IFCacheQueryback* piQueryback, int nTop ) { BOOL retval = FALSE; int nRetCode; char* szError = NULL; CStringA strSql; sqlite3_stmt* pStmt = NULL; if (!m_pDbConnect) goto clean0; if (!piQueryback) goto clean0; strSql.Format("select ext, sum(size), sum(count) from exts group by ext order by sum(size) desc"); nRetCode = sqlite3_prepare(m_pDbConnect, strSql, -1, &pStmt, 0); if (nRetCode) goto clean0; nRetCode = sqlite3_step(pStmt); if (nRetCode == SQLITE_ROW) goto get_data; sqlite3_finalize(pStmt); pStmt = NULL; strSql.Format("insert into exts(ext, size, count) select ext, sum(size), count(size) from files group by ext order by sum(size) desc limit %d", nTop); nRetCode = sqlite3_exec(m_pDbConnect, strSql, NULL, NULL, &szError); if (nRetCode) goto clean0; strSql.Format("select ext, size, count from exts"); nRetCode = sqlite3_prepare(m_pDbConnect, strSql, -1, &pStmt, 0); if (nRetCode) goto clean0; nRetCode = sqlite3_step(pStmt); if (nRetCode != SQLITE_ROW) goto clean0; get_data: while (SQLITE_ROW == nRetCode) { CStringA strExt = (char*)sqlite3_column_text(pStmt, 0); ULONGLONG qwSize = sqlite3_column_int64(pStmt, 1); ULONGLONG qwCount = sqlite3_column_int64(pStmt, 2); if (strExt.CompareNoCase(".n/a") == 0) { strExt = "N/A"; } piQueryback->OnExtData(KUTF8_To_UTF16(strExt), qwSize, qwCount); nRetCode = sqlite3_step(pStmt); } retval = TRUE; clean0: if (pStmt) { sqlite3_finalize(pStmt); pStmt = NULL; } return retval; } ////////////////////////////////////////////////////////////////////////// BOOL CFCacheImpl::SetCacheInfo( const SYSTEMTIME& scanTime, BOOL bFullCache ) { BOOL retval = FALSE; int nRetCode; char* szError = NULL; CStringA strSql; FILETIME fileTime; LARGE_INTEGER llTime; if (!m_pDbConnect) goto clean0; SystemTimeToFileTime(&scanTime, &fileTime); llTime.LowPart = fileTime.dwLowDateTime; llTime.HighPart = fileTime.dwHighDateTime; strSql = "delete from cache"; nRetCode = sqlite3_exec(m_pDbConnect, strSql, NULL, NULL, &szError); strSql.Format("insert into cache values(%I64d, %d)", llTime.QuadPart, bFullCache ? 1 : 0); nRetCode = sqlite3_exec(m_pDbConnect, strSql, NULL, NULL, &szError); if (nRetCode) goto clean0; retval = TRUE; clean0: return retval; } BOOL CFCacheImpl::GetCacheInfo( SYSTEMTIME& scanTime, BOOL& bFullCache ) { BOOL retval = FALSE; int nRetCode; char* szError = NULL; CStringA strSql; FILETIME fileTime; LARGE_INTEGER llTime; sqlite3_stmt* pStmt = NULL; if (!m_pDbConnect) goto clean0; strSql = "select time, full from cache"; nRetCode = sqlite3_prepare(m_pDbConnect, strSql, -1, &pStmt, 0); if (nRetCode) goto clean0; nRetCode = sqlite3_step(pStmt); if (SQLITE_ROW != nRetCode) goto clean0; llTime.QuadPart = sqlite3_column_int64(pStmt, 0); bFullCache = sqlite3_column_int(pStmt, 1) ? TRUE : FALSE; fileTime.dwLowDateTime = llTime.LowPart; fileTime.dwHighDateTime = llTime.HighPart; FileTimeToSystemTime(&fileTime, &scanTime); retval = TRUE; clean0: if (pStmt) { sqlite3_finalize(pStmt); pStmt = NULL; } return retval; } //////////////////////////////////////////////////////////////////////////
[ "dreamsxin@qq.com" ]
dreamsxin@qq.com