blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
53dea4ae952976b59350d802059074f05e3db401
ed3b7df04010a4256ffff4b77c9887ecd78eb3e0
/PacmanGameInstance.cpp
795e8999dfe5c66667d341d4f2b93f558e3b7fd0
[]
no_license
Xperience8/Pacman
fffd9b7eaaa56e1273c9c90f8da8d4a0b9b5bcb5
bfa09f8fced1cf2cd42a0cbeb813240b6a59187c
refs/heads/master
2021-05-04T10:45:26.188715
2016-09-05T15:59:50
2016-09-05T15:59:50
53,679,603
3
0
null
null
null
null
UTF-8
C++
false
false
354
cpp
// Copyright 2015 Patrick Jurasek. All Rights Reserved. #include "Pacman.h" #include "PacmanGameInstance.h" #include "NavigationSystem/PacmanNavigationSystem.h" void UPacmanGameInstance::Init() { NavigationSystem = NewObject<UPacmanNavigationSystem>(UPacmanNavigationSystem::StaticClass()); GNavigationSystem = NavigationSystem; Super::Init(); }
[ "jurasek.patrik@hotmail.com" ]
jurasek.patrik@hotmail.com
3745f8e268d8371423614905e3e3b0b3cce30b84
05b3c7d89a652eda02c76c86795496019bf49a4d
/Source/Section47/Map/S47TriggerDoor.cpp
23750e7bd3561a92a35cdb3657e2fd6453d62044
[]
no_license
pasqueta/Section47
38ba462884d269bb4a852f63df2ec838a99dfa30
97cdb13908a34931b3f6d0f41da014465f67ecd7
refs/heads/master
2020-11-28T08:19:59.740638
2019-07-23T15:50:18
2019-07-23T15:50:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,284
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "S47TriggerDoor.h" #include "Components/BoxComponent.h" #include "S47Character.h" #include "S47Types.h" #include "S47Room.h" #include "S47RoomLevel.h" #include "GameFramework/CharacterMovementComponent.h" #include "Enemy/S47Enemy.h" AS47TriggerDoor::AS47TriggerDoor() { BoxComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxComponent")); if (RootComponent != nullptr) { BoxComponent->SetupAttachment(RootComponent); } } void AS47TriggerDoor::BeginPlay() { Super::BeginPlay(); if (nullptr != BoxComponent) { BoxComponent->OnComponentBeginOverlap.AddUniqueDynamic(this, &AS47TriggerDoor::OnTriggerEnter); BoxComponent->OnComponentEndOverlap.AddUniqueDynamic(this, &AS47TriggerDoor::OnTriggerExit); } } void AS47TriggerDoor::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (!isOpen && !locked && CharacterList.Num() > 0) { OnOpenDoor(); isOpen = true; } else if (isOpen && (locked || CharacterList.Num() <= 0)) { OnCloseDoor(); isOpen = false; } } void AS47TriggerDoor::SetRoomsAlwaysVisible(bool _visible) { if (nullptr != m_pRoomA && nullptr != m_pRoomA->GetLevelScript()) { m_pRoomA->GetLevelScript()->AlwaysVisible = _visible; } if (nullptr != m_pRoomB && nullptr != m_pRoomB->GetLevelScript()) { m_pRoomB->GetLevelScript()->AlwaysVisible = _visible; } } void AS47TriggerDoor::OnTriggerEnter(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult) { AS47Character* OtherCharacter = Cast<AS47Character>(OtherActor); UCapsuleComponent* OtherCapsule = Cast<UCapsuleComponent>(OtherComp); if (OtherCharacter != nullptr && OtherCapsule != nullptr && OtherCapsule == OtherCharacter->GetCapsuleComponent() && !CharacterList.Contains(OtherCharacter)) { CharacterList.Add(OtherCharacter); AS47Enemy* OtherCharacter = Cast<AS47Enemy>(OtherActor); if (OtherCharacter != nullptr && OtherCharacter->GetCharacterMovement()->CanEverCrouch()) { OtherCharacter->nbDoorEnter++; OtherCharacter->CrouchBP(); } //GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Green, *FString::Printf(TEXT("[%s] Character Enter %s"), GET_NETMODE_TEXT(), *GetNameSafe(OtherCharacter))); } } void AS47TriggerDoor::OnTriggerExit(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { AS47Character* OtherCharacter = Cast<AS47Character>(OtherActor); UCapsuleComponent* OtherCapsule = Cast<UCapsuleComponent>(OtherComp); if (OtherCharacter != nullptr && OtherCapsule != nullptr && OtherCapsule == OtherCharacter->GetCapsuleComponent() && CharacterList.Contains(OtherCharacter)) { CharacterList.Remove(OtherCharacter); AS47Enemy* OtherCharacter = Cast<AS47Enemy>(OtherActor); if (OtherCharacter != nullptr && OtherCharacter->GetCharacterMovement()->CanEverCrouch()) { OtherCharacter->nbDoorEnter--; if (OtherCharacter->nbDoorEnter <= 0) { OtherCharacter->UnCrouchBP(); } } //GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Orange, *FString::Printf(TEXT("[%s] Character Exit %s"), GET_NETMODE_TEXT(), *GetNameSafe(OtherCharacter))); } }
[ "vince.col.colin@gmail.com" ]
vince.col.colin@gmail.com
285f48689df4cf2ae19bc3ad9a252b7a44db517d
8b3e6319a91aaea381ff6dac26ddbe6018b75dd2
/src/consensus/tx_verify.h
7292fc30dd62e2214659fb9f628b3fd0f44c972d
[ "MIT" ]
permissive
JihanSilbert/Titan
9ddd7d57a6fa59501ac748c853ef5ff3a12ba51e
4dfd180ca8518c3ba7160c6cf113eb4e1237c42d
refs/heads/master
2020-08-15T16:07:37.998031
2019-10-19T10:45:49
2019-10-19T10:45:49
215,368,860
0
0
MIT
2019-10-15T18:27:27
2019-10-15T18:27:27
null
UTF-8
C++
false
false
3,900
h
// Copyright (c) 2017-2019 The Bitcoin Core developers // Copyright (c) 2017 The Raven Core developers // Copyright (c) 2018 The Rito Core developers // Copyright (c) 2019 The Titancoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef TTN_CONSENSUS_TX_VERIFY_H #define TTN_CONSENSUS_TX_VERIFY_H #include "amount.h" #include <stdint.h> #include <vector> #include <string> class CBlockIndex; class CCoinsViewCache; class CTransaction; class CValidationState; class CAssetsCache; class CTxOut; class uint256; /** Transaction validation functions */ /** Context-independent validity checks */ bool CheckTransaction(const CTransaction& tx, CValidationState& state, CAssetsCache* assetCache = nullptr, bool fCheckDuplicateInputs=true, bool fMemPoolCheck=false, bool fCheckAssetDuplicate = true, bool fForceDuplicateCheck = true); namespace Consensus { /** * Check whether all inputs of this transaction are valid (no double spends and amounts) * This does not modify the UTXO set. This does not check scripts and sigs. * @param[out] txfee Set to the transaction fee if successful. * Preconditions: tx.IsCoinBase() is false. */ bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee); /** TTN START */ bool CheckTxAssets(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, std::vector<std::pair<std::string, uint256> >& vPairReissueAssets, const bool fRunningUnitTests = false, CAssetsCache* assetsCache=nullptr); /** TTN END */ } // namespace Consensus /** Auxiliary functions for transaction validation (ideally should not be exposed) */ /** * Count ECDSA signature operations the old-fashioned (pre-0.6) way * @return number of sigops this transaction's outputs will produce when spent * @see CTransaction::FetchInputs */ unsigned int GetLegacySigOpCount(const CTransaction& tx); /** * Count ECDSA signature operations in pay-to-script-hash inputs. * * @param[in] mapInputs Map of previous transactions that have outputs we're spending * @return maximum number of sigops required to validate this transaction's inputs * @see CTransaction::FetchInputs */ unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs); /** * Compute total signature operation cost of a transaction. * @param[in] tx Transaction for which we are computing the cost * @param[in] inputs Map of previous transactions that have outputs we're spending * @param[out] flags Script verification flags * @return Total signature operation cost of tx */ int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags); /** * Check if transaction is final and can be included in a block with the * specified height and time. Consensus critical. */ bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime); /** * Calculates the block height and previous block's median time past at * which the transaction will be considered final in the context of BIP 68. * Also removes from the vector of input heights any entries which did not * correspond to sequence locked inputs as they do not affect the calculation. */ std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block); bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair); /** * Check if transaction is final per BIP 68 sequence numbers and can be included in a block. * Consensus critical. Takes as input a list of heights at which tx's inputs (in order) confirmed. */ bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block); #endif // TTN_CONSENSUS_TX_VERIFY_H
[ "info@jccoin.co" ]
info@jccoin.co
06c1bf6098a778d66f61705d2a0bd8d1b494c724
c2f3f4eb99725ac6398e73eef47d8a289ee54de0
/Lesson14-LCD Touch Screen/Lessons/Example08-ShowBMP/ShowBMP/ShowBMP.ino
c71c6b4089bfcc327a93493c2728171c01dfee23
[]
no_license
keywish/keywish-tft-lcd-touch-kit
c1e207b99053e483e77ce38164b8966081bc1208
158f17ce5d482ed54fec52f1c3dc615b46cb3d44
refs/heads/master
2021-09-03T03:54:31.531591
2018-01-05T09:23:36
2018-01-05T09:23:36
115,197,279
1
0
null
null
null
null
UTF-8
C++
false
false
9,484
ino
/*********************************************************************** * When using the BREAKOUT BOARD only, use these 8 data lines to the LCD: * For the Arduino Uno, Duemilanove, Diecimila, etc.: * D0 connects to digital pin 8 (Notice these are * D1 connects to digital pin 9 NOT in order!) * D2 connects to digital pin 2 * D3 connects to digital pin 3 * D4 connects to digital pin 4 * D5 connects to digital pin 5 * D6 connects to digital pin 6 * D7 connects to digital pin 7 * For the Arduino Mega, use digital pins 22 through 29 * (on the 2-row header at the end of the board). ***********************************************************************/ // IMPORTANT: Adafruit_TFTLCD LIBRARY MUST BE SPECIFICALLY // CONFIGURED FOR EITHER THE TFT SHIELD OR THE BREAKOUT BOARD. // SEE RELEVANT COMMENTS IN Adafruit_TFTLCD.h FOR SETUP. //Technical support:goodtft@163.com #include "Adafruit_GFX.h" // Hardware-specific library #include "MCUFRIEND_kbv.h" #include <SD.h> #include <SPI.h> // wiring with UNO or Mega2560: //--------------POWER Pins-------------------------------- // 5V connects to DC 5V // GND connects to Ground // 3V3 do not need to connect(NC) //--------------LCD Display Pins-------------------------- // LCD_RD connects to Analog pin A0 // LCD_WR connects to Analog pin A1 // LCD_RS connects to Analog pin A2 // LCD_CS connects to Analog pin A3 // LCD_RST connects to Analog pin A4 // LCD_D0 connects to digital pin 8 // LCD_D1 connects to digital pin 9 // LCD_D2 connects to digital pin 2 // LCD_D3 connects to digital pin 3 // LCD_D4 connects to digital pin 4 // LCD_D5 connects to digital pin 5 // LCD_D6 connects to digital pin 6 // LCD_D7 connects to digital pin 7 //--------------SD-card fuction Pins ---------------------- //This Connection Only for UNO, Do not support Mega2560 //because they use different Hardware-SPI Pins //SD_SS connects to digital pin 10 //SD_DI connects to digital pin 11 //SD_DO connects to digital pin 12 //SD_SCK connects to digital pin 13 #define LCD_CS A3 // Chip Select goes to Analog 3 #define LCD_CD A2 // Command/Data goes to Analog 2 #define LCD_WR A1 // LCD Write goes to Analog 1 #define LCD_RD A0 // LCD Read goes to Analog 0 #define PIN_SD_CS 10 // Adafruit SD shields and modules: pin 10 #define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin // When using the BREAKOUT BOARD only, use these 8 data lines to the LCD: // For the Arduino Uno, Duemilanove, Diecimila, etc.: // D0 connects to digital pin 8 (Notice these are // D1 connects to digital pin 9 NOT in order!) // D2 connects to digital pin 2 // D3 connects to digital pin 3 // D4 connects to digital pin 4 // D5 connects to digital pin 5 // D6 connects to digital pin 6 // D7 connects to digital pin 7 // For the Arduino Mega, use digital pins 22 through 29 // (on the 2-row header at the end of the board). // Assign human-readable names to some common 16-bit color values: #define BLACK 0x0000 #define BLUE 0x001F #define RED 0xF800 #define GREEN 0x07E0 #define CYAN 0x07FF #define MAGENTA 0xF81F #define YELLOW 0xFFE0 #define WHITE 0xFFFF //Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET); MCUFRIEND_kbv tft; #define MAX_BMP 10 // bmp file num #define FILENAME_LEN 20 // max file name length const int __Gnbmp_height = 320; // bmp hight const int __Gnbmp_width = 240; // bmp width unsigned char __Gnbmp_image_offset = 0; // offset int __Gnfile_num = 4; // num of file char __Gsbmp_files[4][FILENAME_LEN] = // add file name here { "flower.bmp", "tiger.bmp", "tree.bmp", "RedRose.bmp", }; File bmpFile; /*********************************************/ // This procedure reads a bitmap and draws it to the screen // its sped up by reading many pixels worth of data at a time // instead of just one pixel at a time. increading the buffer takes // more RAM but makes the drawing a little faster. 20 pixels' worth // is probably a good place #define BUFFPIXEL 60 // must be a divisor of 240 #define BUFFPIXEL_X3 180 // BUFFPIXELx3 void bmpdraw(File f, int x, int y) { bmpFile.seek(__Gnbmp_image_offset); uint32_t time = millis(); uint8_t sdbuffer[BUFFPIXEL_X3]; // 3 * pixels to buffer for (int i=0; i< __Gnbmp_height; i++) { for(int j=0; j<(240/BUFFPIXEL); j++) { bmpFile.read(sdbuffer, BUFFPIXEL_X3); uint8_t buffidx = 0; int offset_x = j*BUFFPIXEL; unsigned int __color[BUFFPIXEL]; for(int k=0; k<BUFFPIXEL; k++) { __color[k] = sdbuffer[buffidx+2]>>3; // read __color[k] = __color[k]<<6 | (sdbuffer[buffidx+1]>>2); // green __color[k] = __color[k]<<5 | (sdbuffer[buffidx+0]>>3); // blue buffidx += 3; } for (int m = 0; m < BUFFPIXEL; m ++) { tft.drawPixel(m+offset_x, i,__color[m]); } } } Serial.print(millis() - time, DEC); Serial.println(" ms"); } boolean bmpReadHeader(File f) { // read header uint32_t tmp; uint8_t bmpDepth; if (read16(f) != 0x4D42) { // magic bytes missing return false; } // read file size tmp = read32(f); Serial.print("size 0x"); Serial.println(tmp, HEX); // read and ignore creator bytes read32(f); __Gnbmp_image_offset = read32(f); Serial.print("offset "); Serial.println(__Gnbmp_image_offset, DEC); // read DIB header tmp = read32(f); Serial.print("header size "); Serial.println(tmp, DEC); int bmp_width = read32(f); int bmp_height = read32(f); if(bmp_width != __Gnbmp_width || bmp_height != __Gnbmp_height) { // if image is not 320x240, return false return false; } if (read16(f) != 1) return false; bmpDepth = read16(f); Serial.print("bitdepth "); Serial.println(bmpDepth, DEC); if (read32(f) != 0) { // compression not supported! return false; } Serial.print("compression "); Serial.println(tmp, DEC); return true; } /*********************************************/ // These read data from the SD card file and convert them to big endian // (the data is stored in little endian format!) // LITTLE ENDIAN! uint16_t read16(File f) { uint16_t d; uint8_t b; b = f.read(); d = f.read(); d <<= 8; d |= b; return d; } // LITTLE ENDIAN! uint32_t read32(File f) { uint32_t d; uint16_t b; b = read16(f); d = read16(f); d <<= 16; d |= b; return d; } void setup(void) { Serial.begin(9600); Serial.println(F("TFT LCD test")); #ifdef USE_ADAFRUIT_SHIELD_PINOUT Serial.println(F("Using Adafruit 2.4\" TFT Arduino Shield Pinout")); #else Serial.println(F("Using Adafruit 2.4\" TFT Breakout Board Pinout")); #endif Serial.print("TFT size is "); Serial.print(tft.width()); Serial.print("x"); Serial.println(tft.height()); tft.reset(); uint16_t identifier = tft.readID(); if(identifier==0x0101) identifier=0x9341; if(identifier == 0x9325) { Serial.println(F("Found ILI9325 LCD driver")); } else if(identifier == 0x4535) { Serial.println(F("Found LGDP4535 LCD driver")); }else if(identifier == 0x9328) { Serial.println(F("Found ILI9328 LCD driver")); } else if(identifier == 0x7575) { Serial.println(F("Found HX8347G LCD driver")); } else if(identifier == 0x9341) { Serial.println(F("Found ILI9341 LCD driver")); } else if(identifier == 0x8357) { Serial.println(F("Found HX8357D LCD driver")); } else { Serial.print(F("Unknown LCD driver chip: ")); Serial.println(identifier, HEX); Serial.println(F("If using the Adafruit 2.4\" TFT Arduino shield, the line:")); Serial.println(F(" #define USE_ADAFRUIT_SHIELD_PINOUT")); Serial.println(F("should appear in the library header (Adafruit_TFT.h).")); Serial.println(F("If using the breakout board, it should NOT be #defined!")); Serial.println(F("Also if using the breakout, double-check that all wiring")); Serial.println(F("matches the tutorial.")); return; } tft.begin(identifier); tft.fillScreen(BLUE); //Init SD_Card pinMode(10, OUTPUT); if (!SD.begin(10)) { Serial.println("initialization failed!"); tft.setCursor(0, 0); tft.setTextColor(WHITE); tft.setTextSize(1); tft.println("SD Card Init fail."); }else Serial.println("initialization done."); } void loop(void) { for(unsigned char i=0; i<__Gnfile_num; i++) { bmpFile = SD.open(__Gsbmp_files[i]); if (! bmpFile) { Serial.println("didnt find image"); tft.setTextColor(WHITE); tft.setTextSize(1); tft.println("didnt find BMPimage"); while (1); } if(! bmpReadHeader(bmpFile)) { Serial.println("bad bmp"); tft.setTextColor(WHITE); tft.setTextSize(1); tft.println("bad bmp"); return; } bmpdraw(bmpFile, 0, 0); bmpFile.close(); delay(1000); delay(1000); } }
[ "baron@keywish-robot.com" ]
baron@keywish-robot.com
05df86d3d1041bb549f6e6cb27c4fc07f24327b4
e9f3369247da3435cd63f2d67aa95c890912255c
/problem399.cpp
444faf9c2f9463834e309df423265a82a1680eec
[]
no_license
panthitesh6410/problem-solving-C-
27b31a141669b91eb36709f0126be05f241dfb13
24b72fc795b7b5a44e22e5f6ca9faad462a097fb
refs/heads/master
2021-11-15T21:52:33.523503
2021-10-17T16:20:58
2021-10-17T16:20:58
248,523,681
0
0
null
null
null
null
UTF-8
C++
false
false
725
cpp
// Codechef March Cook-Off 2021 Div-3 Problem #include<climits> #include<iostream> using namespace std; bool has_odd_factors(unsigned long long int num){ unsigned long long int count = 0; for(unsigned long long int i=1;i<=num/2;i++){ if(num%i == 0) count++; } if(count % 2 != 0) return true; return false; } int main(){ int t; cin>>t; while(t--){ int guess; // unsigned long long int num = 1; for(unsigned long long int i=1;i<LLONG_MAX;i++){ if(has_odd_factors(i)){ cout<<i; cin>>guess; if(guess == 1) continue; } } } return 0; }
[ "panthitesh6410@gmail.com" ]
panthitesh6410@gmail.com
092d696783ca260cfb912c92194e6a56bbbf32c2
b3814242f60ebb4393e4a105b91ac464078c88a7
/shared/packets/ClientPacketWrapper.hpp
3e3c0b018c2825f371c776a7875e8bf110e7b406
[]
no_license
Techno-coder/SpaceShift
f858402c60637bfa68ff700c29557620cfee0966
ed3a6a041d9d7ea2078242e38998f4f299e59040
refs/heads/master
2021-03-27T13:59:35.785446
2017-09-27T06:56:57
2017-09-27T06:56:57
103,614,271
0
1
null
null
null
null
UTF-8
C++
false
false
464
hpp
#pragma once #include "PacketWrapper.hpp" class ClientPacketWrapper : public PacketWrapper { public: enum class Type : sf::Uint16 { DISCONNECT = 0, AUTHENTICATION_REQUEST = 1, CHECK_ALIVE_RESPONSE = 2, QUICK_JOIN_REQUEST = 3, MOVE_REQUEST = 5 } type = Type::DISCONNECT; private: sf::Uint16 getType() const override { return static_cast<sf::Uint16>(type); } void setType(sf::Uint16 newType) override { type = static_cast<Type>(newType); } };
[ "zhiyuanqi@hotmail.co.nz" ]
zhiyuanqi@hotmail.co.nz
478c12b07cb9d6d4c37e5f804168e9f976eba9fc
9856ad398afbe61f021f46fe1573819ce51fb9dc
/gov2.cc
a711a14884b5390c0432acc9e1146e5603c08bba
[ "MIT" ]
permissive
vteromero/integer-compression-benchmarks
2c62e278e54fa16eea5d9510ba348253411dacd8
03b5a113993b78503ce065e413d9f6a9ce6501da
refs/heads/master
2022-05-24T07:05:01.205250
2022-03-18T11:44:27
2022-03-18T11:44:27
220,762,839
5
0
MIT
2022-03-18T10:50:32
2019-11-10T08:36:40
C++
UTF-8
C++
false
false
10,829
cc
// Copyright (c) 2019 Vicente Romero Calero. All rights reserved. // Licensed under the MIT License. // See LICENSE file in the project root for full license information. #include <algorithm> #include <fstream> #include <string> #include <vector> #include "common.h" #include "benchmark/include/benchmark/benchmark.h" #include "SIMDCompressionAndIntersection/include/binarypacking.h" #include "SIMDCompressionAndIntersection/include/fastpfor.h" #include "SIMDCompressionAndIntersection/include/variablebyte.h" #include "SIMDCompressionAndIntersection/include/varintgb.h" #include "VTEnc/vtenc.h" class Gov2SortedDataSet : public benchmark::Fixture { private: std::ifstream _inFile; char _buffer[4096]; size_t _bufferCount; size_t _bufferOffset; public: void SetUp(const ::benchmark::State& state) {} void TearDown(const ::benchmark::State& state) {} void openFile() { const std::string fileName = GlobalState::dataDirectory + std::string("/gov2.sorted"); _inFile.open(fileName, std::ios::in | std::ios::binary); if (_inFile.fail()) { throw std::logic_error("Failed to open '" + fileName + "'"); } _bufferCount = 0; _bufferOffset = 0; } void closeFile() { _inFile.close(); } void refreshBuffer() { // Here, it is assumed that the file has a size multiple of 4, so there is no // left bytes to copy over when refreshing the buffer. _inFile.read(_buffer, sizeof(_buffer)); if (_inFile.eof()) { throw "End of file"; } _bufferCount = _inFile.gcount(); _bufferOffset = 0; } uint32_t readNextUint32() { if ((_bufferCount - _bufferOffset) < 4) { refreshBuffer(); } uint32_t value; std::memcpy(&value, &(_buffer[_bufferOffset]), sizeof(value)); _bufferOffset += 4; return value; } bool loadNextSet(std::vector<uint32_t>& data) { data.clear(); try { uint32_t len = readNextUint32(); for (size_t i = 0; i < len; ++i) { data.push_back(readNextUint32()); } } catch (...) { return false; } return true; } }; static void benchmarkGov2SortedDataSet( Gov2SortedDataSet* obj, benchmark::State& state, void (*func)( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats )) { CompressionStats stats(state); std::vector<uint32_t> data; for (auto _ : state) { state.PauseTiming(); stats.Reset(); obj->openFile(); state.ResumeTiming(); while (1) { state.PauseTiming(); if (!obj->loadNextSet(data)) break; state.ResumeTiming(); func(data, state, stats); } state.PauseTiming(); obj->closeFile(); state.ResumeTiming(); } stats.SetFinalStats(); } static void encodeWithCopy( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { state.PauseTiming(); std::vector<uint32_t> copyTo(data.size()); state.ResumeTiming(); std::copy(data.begin(), data.end(), copyTo.begin()); state.PauseTiming(); stats.UpdateInputLengthInBytes(data.size() * sizeof(uint32_t)); stats.UpdateEncodedLengthInBytes(data.size() * sizeof(uint32_t)); state.ResumeTiming(); } static void encodeWithVTEnc( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { state.PauseTiming(); std::vector<uint8_t> encoded(vtenc_max_encoded_size32(data.size())); vtenc *handler = vtenc_create(); assert(handler != NULL); vtenc_config(handler, VTENC_CONFIG_ALLOW_REPEATED_VALUES, 0); vtenc_config(handler, VTENC_CONFIG_SKIP_FULL_SUBTREES, 1); vtenc_config(handler, VTENC_CONFIG_MIN_CLUSTER_LENGTH, static_cast<size_t>(state.range(0))); state.ResumeTiming(); vtenc_encode32(handler, data.data(), data.size(), encoded.data(), encoded.size()); state.PauseTiming(); stats.UpdateInputLengthInBytes(data.size() * sizeof(uint32_t)); stats.UpdateEncodedLengthInBytes(vtenc_encoded_size(handler)); vtenc_destroy(handler); state.ResumeTiming(); } static void decodeWithVTEnc( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { state.PauseTiming(); std::vector<uint8_t> encoded(vtenc_max_encoded_size32(data.size())); vtenc *handler = vtenc_create(); assert(handler != NULL); vtenc_config(handler, VTENC_CONFIG_ALLOW_REPEATED_VALUES, 0); vtenc_config(handler, VTENC_CONFIG_SKIP_FULL_SUBTREES, 1); vtenc_config(handler, VTENC_CONFIG_MIN_CLUSTER_LENGTH, static_cast<size_t>(state.range(0))); vtenc_encode32(handler, data.data(), data.size(), encoded.data(), encoded.size()); size_t encodedLength = vtenc_encoded_size(handler); std::vector<uint32_t> decoded(data.size()); state.ResumeTiming(); vtenc_decode32(handler, encoded.data(), encodedLength, decoded.data(), decoded.size()); state.PauseTiming(); if (data != decoded) { throw std::logic_error("equality check failed"); } stats.UpdateInputLengthInBytes(data.size() * sizeof(uint32_t)); stats.UpdateEncodedLengthInBytes(encodedLength); vtenc_destroy(handler); state.ResumeTiming(); } static void encodeWithSIMDCompressionCodec( SIMDCompressionLib::IntegerCODEC& codec, size_t blockSize, std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { state.PauseTiming(); SIMDCompressionUtil comp(codec, blockSize, data); state.ResumeTiming(); comp.Encode(); state.PauseTiming(); stats.UpdateInputLengthInBytes(comp.InputLength() * sizeof(uint32_t)); stats.UpdateEncodedLengthInBytes(comp.EncodedLength() * sizeof(uint32_t)); state.ResumeTiming(); } static void decodeWithSIMDCompressionCodec( SIMDCompressionLib::IntegerCODEC& codec, size_t blockSize, std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { state.PauseTiming(); SIMDCompressionUtil comp(codec, blockSize, data); comp.Encode(); state.ResumeTiming(); comp.Decode(); state.PauseTiming(); comp.EqualityCheck(); stats.UpdateInputLengthInBytes(comp.InputLength() * sizeof(uint32_t)); stats.UpdateEncodedLengthInBytes(comp.EncodedLength() * sizeof(uint32_t)); state.ResumeTiming(); } static void encodeWithDeltaVariableByte( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { SIMDCompressionLib::VByte<true> codec; encodeWithSIMDCompressionCodec(codec, 1, data, state, stats); } static void decodeWithDeltaVariableByte( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { SIMDCompressionLib::VByte<true> codec; decodeWithSIMDCompressionCodec(codec, 1, data, state, stats); } static void encodeWithDeltaVarIntGB( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { SIMDCompressionLib::VarIntGB<true> codec; encodeWithSIMDCompressionCodec(codec, 1, data, state, stats); } static void decodeWithDeltaVarIntGB( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { SIMDCompressionLib::VarIntGB<true> codec; decodeWithSIMDCompressionCodec(codec, 1, data, state, stats); } static void encodeWithDeltaBinaryPacking( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { SIMDCompressionLib::BinaryPacking<SIMDCompressionLib::BasicBlockPacker> codec; encodeWithSIMDCompressionCodec(codec, codec.BlockSize, data, state, stats); } static void decodeWithDeltaBinaryPacking( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { SIMDCompressionLib::BinaryPacking<SIMDCompressionLib::BasicBlockPacker> codec; decodeWithSIMDCompressionCodec(codec, codec.BlockSize, data, state, stats); } static void encodeWithDeltaFastPFor128( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { SIMDCompressionLib::FastPFor<4, true> codec; encodeWithSIMDCompressionCodec(codec, codec.BlockSize, data, state, stats); } static void decodeWithDeltaFastPFor128( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { SIMDCompressionLib::FastPFor<4, true> codec; encodeWithSIMDCompressionCodec(codec, codec.BlockSize, data, state, stats); } static void encodeWithDeltaFastPFor256( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { SIMDCompressionLib::FastPFor<8, true> codec; encodeWithSIMDCompressionCodec(codec, codec.BlockSize, data, state, stats); } static void decodeWithDeltaFastPFor256( std::vector<uint32_t>& data, benchmark::State& state, CompressionStats& stats) { SIMDCompressionLib::FastPFor<8, true> codec; encodeWithSIMDCompressionCodec(codec, codec.BlockSize, data, state, stats); } BENCHMARK_F(Gov2SortedDataSet, Copy)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, encodeWithCopy); } BENCHMARK_DEFINE_F(Gov2SortedDataSet, VTEncEncode)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, encodeWithVTEnc); } BENCHMARK_REGISTER_F(Gov2SortedDataSet, VTEncEncode) ->RangeMultiplier(2)->Range(1, 1<<8); BENCHMARK_DEFINE_F(Gov2SortedDataSet, VTEncDecode)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, decodeWithVTEnc); } BENCHMARK_REGISTER_F(Gov2SortedDataSet, VTEncDecode) ->RangeMultiplier(2)->Range(1, 1<<8); BENCHMARK_F(Gov2SortedDataSet, DeltaVariableByteEncode)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, encodeWithDeltaVariableByte); } BENCHMARK_F(Gov2SortedDataSet, DeltaVariableByteDecode)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, decodeWithDeltaVariableByte); } BENCHMARK_F(Gov2SortedDataSet, DeltaVarIntGBEncode)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, encodeWithDeltaVarIntGB); } BENCHMARK_F(Gov2SortedDataSet, DeltaVarIntGBDecode)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, decodeWithDeltaVarIntGB); } BENCHMARK_F(Gov2SortedDataSet, DeltaBinaryPackingEncode)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, encodeWithDeltaBinaryPacking); } BENCHMARK_F(Gov2SortedDataSet, DeltaBinaryPackingDecode)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, decodeWithDeltaBinaryPacking); } BENCHMARK_F(Gov2SortedDataSet, DeltaFastPFor128Encode)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, encodeWithDeltaFastPFor128); } BENCHMARK_F(Gov2SortedDataSet, DeltaFastPFor128Decode)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, decodeWithDeltaFastPFor128); } BENCHMARK_F(Gov2SortedDataSet, DeltaFastPFor256Encode)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, encodeWithDeltaFastPFor256); } BENCHMARK_F(Gov2SortedDataSet, DeltaFastPFor256Decode)(benchmark::State& state) { benchmarkGov2SortedDataSet(this, state, decodeWithDeltaFastPFor256); }
[ "vteromero@gmail.com" ]
vteromero@gmail.com
8ec1e634de9ae260111539f2229dfbbcebc4d92c
4adc21ab6d15a336fe6d4ae9a2eb375573dc1885
/CvGameCoreDLL_Expansion2/CvArmyAI.cpp
88e1e7129005255a64aac314fbac54bf6f403cf1
[]
no_license
Surfal/Community-Patch-DLL
ec9e3c99c7e276fc7d4cbc1506ff75acabe005fb
6acdb55620175a0cca6197141a3ffaa22aab0203
refs/heads/master
2021-01-21T05:37:06.412814
2015-06-13T20:01:44
2015-06-13T20:01:44
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
19,447
cpp
/* ------------------------------------------------------------------------------------------------------- © 1991-2012 Take-Two Interactive Software and its subsidiaries. Developed by Firaxis Games. Sid Meier's Civilization V, Civ, Civilization, 2K Games, Firaxis Games, Take-Two Interactive Software and their respective logos are all trademarks of Take-Two interactive Software, Inc. All other marks and trademarks are the property of their respective owners. All rights reserved. ------------------------------------------------------------------------------------------------------- */ #include "CvGameCoreDLLPCH.h" #include "CvGlobals.h" #include "CvPlayerAI.h" #include "CvTeam.h" #include "CvArmyAI.h" #include "CvUnit.h" #include "CvGameCoreUtils.h" #include "CvMap.h" #include "CvPlot.h" #include "ICvDLLUserInterface.h" #include "CvAStar.h" #include "CvInfos.h" #include "CvEnumSerialization.h" #include "FStlContainerSerialization.h" // include after all other headers #include "LintFree.h" // Public Functions... /// Constructor CvArmyAI::CvArmyAI() { Reset(0, NO_PLAYER, true); } /// Destructor CvArmyAI::~CvArmyAI() { Uninit(); } /// Initialize void CvArmyAI::Init(int iID, PlayerTypes eOwner, int iOperationID) { //-------------------------------- // Init saved data Reset(iID, eOwner, iOperationID); } /// Deallocate memory void CvArmyAI::Uninit() { m_FormationEntries.clear(); } /// Initializes data members that are serialize void CvArmyAI::Reset(int iID, PlayerTypes eOwner, int iOperationID, bool /* bConstructorCall */) { //-------------------------------- // Uninit class Uninit(); m_iID = iID; m_eOwner = eOwner; m_iOperationID = iOperationID; m_iCurrentX = -1; m_iCurrentY = -1; m_iGoalX = -1; m_iGoalY = -1; m_eDomainType = DOMAIN_LAND; m_iFormationIndex = NO_MUFORMATION; m_eAIState = NO_ARMYAISTATE; m_FormationEntries.clear(); } /// Delete the army void CvArmyAI::Kill() { CvAssert(GetOwner() != NO_PLAYER); CvAssertMsg(GetID() != FFreeList::INVALID_INDEX, "GetID() is not expected to be equal with FFreeList::INVALID_INDEX"); int iUnitID; iUnitID = GetFirstUnitID(); while(iUnitID != ARMY_NO_UNIT) { UnitHandle pThisUnit = GET_PLAYER(GetOwner()).getUnit(iUnitID); if(pThisUnit) { pThisUnit->setArmyID(FFreeList::INVALID_INDEX); } iUnitID = GetNextUnitID(); } m_FormationEntries.clear(); } /// Read from binary data store void CvArmyAI::read(FDataStream& kStream) { // Init saved data Reset(); // Version number to maintain backwards compatibility uint uiVersion; kStream >> uiVersion; MOD_SERIALIZE_INIT_READ(kStream); kStream >> m_iID; kStream >> m_eOwner; kStream >> m_iCurrentX; kStream >> m_iCurrentY; kStream >> m_iGoalX; kStream >> m_iGoalY; kStream >> m_eDomainType; kStream >> m_iFormationIndex; kStream >> m_eAIState; kStream >> m_iOperationID; int iEntriesToRead; kStream >> iEntriesToRead; for(int iI = 0; iI < iEntriesToRead; iI++) { CvArmyFormationSlot slot; kStream >> slot; m_FormationEntries.push_back(slot); } } /// Write to binary data store void CvArmyAI::write(FDataStream& kStream) const { // Current version number uint uiVersion = 1; kStream << uiVersion; MOD_SERIALIZE_INIT_WRITE(kStream); kStream << m_iID; kStream << m_eOwner; kStream << m_iCurrentX; kStream << m_iCurrentY; kStream << m_iGoalX; kStream << m_iGoalY; kStream << m_eDomainType; kStream << m_iFormationIndex; kStream << m_eAIState; kStream << m_iOperationID; kStream << (int)m_FormationEntries.size(); for(uint ui = 0; ui < m_FormationEntries.size(); ui++) { kStream << m_FormationEntries[ui]; } } // ACCESSORS /// Retrieve this army's ID int CvArmyAI::GetID() { return m_iID; } /// Set this army's ID void CvArmyAI::SetID(int iID) { m_iID = iID; } /// Retrieve this army's team TeamTypes CvArmyAI::GetTeam() const { if(GetOwner() != NO_PLAYER) { return GET_PLAYER(GetOwner()).getTeam(); } return NO_TEAM; } /// Retrieve current army state ArmyAIState CvArmyAI::GetArmyAIState() const { return (ArmyAIState) m_eAIState; } /// Set current army state void CvArmyAI::SetArmyAIState(ArmyAIState eNewArmyAIState) { m_eAIState = (int) eNewArmyAIState; } /// Find average speed of units in army int CvArmyAI::GetMovementRate() { int iMovementAverage = 2; // A reasonable default int iNumUnits = 0; int iTotalMovementAllowance = 0; UnitHandle pUnit; pUnit = GetFirstUnit(); while(pUnit) { iNumUnits++; iTotalMovementAllowance += pUnit->baseMoves(); pUnit = GetNextUnit(); } if(iNumUnits > 0) { iMovementAverage = (iTotalMovementAllowance + (iNumUnits / 2)) / iNumUnits; } return iMovementAverage; } /// Get center of mass of units in army (account for world wrap!) CvPlot* CvArmyAI::GetCenterOfMass(DomainTypes eDomainRequired) { CvPlot* pRtnValue = NULL; int iTotalX = 0; int iTotalY = 0; int iNumUnits = 0; UnitHandle pUnit; int iReferenceUnitX = -1; int iWorldWidth = GC.getMap().getGridWidth(); pUnit = GetFirstUnit(); if(pUnit) { iReferenceUnitX = pUnit->getX(); } while(pUnit) { int iUnitX = pUnit->getX(); bool bWorldWrapAdjust = false; int iDiff = iUnitX - iReferenceUnitX; if(abs(iDiff) > (iWorldWidth / 2)) { bWorldWrapAdjust = true; } if(bWorldWrapAdjust) { iTotalX += iUnitX + iWorldWidth; } else { iTotalX += iUnitX; } iTotalY += pUnit->getY(); iNumUnits++; pUnit = GetNextUnit(); } if(iNumUnits > 0) { int iAverageX = (iTotalX + (iNumUnits / 2)) / iNumUnits; if(iAverageX >= iWorldWidth) { iAverageX = iAverageX - iWorldWidth; } int iAverageY = (iTotalY + (iNumUnits / 2)) / iNumUnits; pRtnValue = GC.getMap().plot(iAverageX, iAverageY); } // Domain check if (eDomainRequired != NO_DOMAIN && pRtnValue) { if (pRtnValue->isWater() && eDomainRequired == DOMAIN_LAND || !pRtnValue->isWater() && eDomainRequired == DOMAIN_SEA) { // Find an adjacent plot that works for (int iI = 0; iI < NUM_DIRECTION_TYPES; iI++) { CvPlot *pLoopPlot = plotDirection(pRtnValue->getX(), pRtnValue->getY(), ((DirectionTypes)iI)); if (pLoopPlot != NULL) { if (pLoopPlot->isWater() && eDomainRequired == DOMAIN_SEA || !pLoopPlot->isWater() && eDomainRequired == DOMAIN_LAND) { return pLoopPlot; } } } // Try two plots out if really having problems for (int iDX = -2; iDX <= 2; iDX++) { for (int iDY = -2; iDY <= 2; iDY++) { CvPlot *pLoopPlot = plotXYWithRangeCheck(pRtnValue->getX(), pRtnValue->getY(), iDX, iDY, 2); if (pLoopPlot) { if (plotDistance(pRtnValue->getX(), pRtnValue->getY(), pLoopPlot->getX(), pLoopPlot->getY()) == 2) { if (pLoopPlot->isWater() && eDomainRequired == DOMAIN_SEA || !pLoopPlot->isWater() && eDomainRequired == DOMAIN_LAND) { return pLoopPlot; } } } } } // Give up - just use location of first unit pUnit = GetFirstUnit(); pRtnValue = pUnit->plot(); } } return pRtnValue; } /// Return distance from this plot of unit in army farthest away int CvArmyAI::GetFurthestUnitDistance(CvPlot* pPlot) { int iLargestDistance = 0; UnitHandle pUnit; int iNewDistance; pUnit = GetFirstUnit(); while(pUnit) { iNewDistance = plotDistance(pUnit->getX(), pUnit->getY(), pPlot->getX(), pPlot->getY()); if(iNewDistance > iLargestDistance) { iLargestDistance = iNewDistance; } pUnit = GetNextUnit(); } return iLargestDistance; } // FORMATION ACCESSORS /// Retrieve index of the formation used by this army int CvArmyAI::GetFormationIndex() const { return m_iFormationIndex; } /// Set index of the formation used by this army void CvArmyAI::SetFormationIndex(int iFormationIndex) { CvArmyFormationSlot slot; if(m_iFormationIndex != iFormationIndex) { m_iFormationIndex = iFormationIndex; CvMultiUnitFormationInfo* thisFormation = GC.getMultiUnitFormationInfo(m_iFormationIndex); if(thisFormation) { int iNumSlots = thisFormation->getNumFormationSlotEntries(); // Build all the formation entries m_FormationEntries.clear(); for(int iI = 0; iI < iNumSlots; iI++) { slot.SetUnitID(ARMY_NO_UNIT); slot.SetTurnAtCheckpoint(ARMYSLOT_UNKNOWN_TURN_AT_CHECKPOINT); m_FormationEntries.push_back(slot); } } } } /// How many slots are there in this formation if filled int CvArmyAI::GetNumFormationEntries() const { return m_FormationEntries.size(); } /// How many slots do we currently have filled? int CvArmyAI::GetNumSlotsFilled() const { int iRtnValue = 0; for(unsigned int iI = 0; iI < m_FormationEntries.size(); iI++) { if(m_FormationEntries[iI].m_iUnitID != ARMY_NO_UNIT) { iRtnValue++; } } return iRtnValue; } /// What turn will a unit arrive on target? void CvArmyAI::SetEstimatedTurn(int iSlotID, int iTurns) { int iTurnAtCheckpoint; if(iTurns == ARMYSLOT_NOT_INCLUDING_IN_OPERATION || iTurns == ARMYSLOT_UNKNOWN_TURN_AT_CHECKPOINT) { iTurnAtCheckpoint = iTurns; } else { iTurnAtCheckpoint = GC.getGame().getGameTurn() + iTurns; } m_FormationEntries[iSlotID].SetTurnAtCheckpoint(iTurnAtCheckpoint); } /// What turn will the army as a whole arrive on target? int CvArmyAI::GetTurnAtNextCheckpoint() const { int iRtnValue = ARMYSLOT_NOT_INCLUDING_IN_OPERATION; for(unsigned int iI = 0; iI < m_FormationEntries.size(); iI++) { if(m_FormationEntries[iI].m_iEstimatedTurnAtCheckpoint == ARMYSLOT_UNKNOWN_TURN_AT_CHECKPOINT) { return ARMYSLOT_UNKNOWN_TURN_AT_CHECKPOINT; } else if(m_FormationEntries[iI].m_iEstimatedTurnAtCheckpoint > iRtnValue) { iRtnValue = m_FormationEntries[iI].m_iEstimatedTurnAtCheckpoint; } } return iRtnValue; } /// Recalculate when each unit will arrive on target void CvArmyAI::UpdateCheckpointTurns() { for(unsigned int iI = 0; iI < m_FormationEntries.size(); iI++) { // No reestimate for units being built if(m_FormationEntries[iI].GetUnitID() != ARMY_NO_UNIT) { CvUnit* pUnit = GET_PLAYER(m_eOwner).getUnit(m_FormationEntries[iI].GetUnitID()); CvPlot* pMusterPlot = GC.getMap().plot(GetX(), GetY()); if(pUnit && pMusterPlot) { int iTurnsToReachCheckpoint = TurnsToReachTarget(pUnit, pMusterPlot, true /*bReusePaths*/, true, true); if(iTurnsToReachCheckpoint < MAX_INT) { SetEstimatedTurn(iI, iTurnsToReachCheckpoint); } } } } } /// How many units of this type are in army? int CvArmyAI::GetUnitsOfType(MultiunitPositionTypes ePosition) const { int iRtnValue = 0; for(unsigned int iI = 0; iI < m_FormationEntries.size(); iI++) { if(m_FormationEntries[iI].m_iUnitID != ARMY_NO_UNIT) { CvUnit* pUnit = GET_PLAYER(m_eOwner).getUnit(m_FormationEntries[iI].m_iUnitID); if(pUnit->getMoves() > 0) { CvMultiUnitFormationInfo* thisFormation = GC.getMultiUnitFormationInfo(m_iFormationIndex); if(thisFormation) { const CvFormationSlotEntry& thisSlotEntry = thisFormation->getFormationSlotEntry(iI); if(thisSlotEntry.m_ePositionType == ePosition) { iRtnValue++; } } } } } return iRtnValue; } /// Can all units in this army move on ocean? bool CvArmyAI::IsAllOceanGoing() { UnitHandle pUnit; pUnit = GetFirstUnit(); while(pUnit) { if(pUnit->getDomainType() != DOMAIN_SEA && !pUnit->IsHasEmbarkAbility()) { return false; } // If can move over ocean, not a coastal vessel if(pUnit->isTerrainImpassable(TERRAIN_OCEAN)) { return false; } pUnit = GetNextUnit(); } return true; } // UNIT STRENGTH ACCESSORS /// Total unit power int CvArmyAI::GetTotalPower() { int iRtnValue = 0; int iUnitID; iUnitID = GetFirstUnitID(); while(iUnitID != ARMY_NO_UNIT) { UnitHandle pThisUnit = GET_PLAYER(GetOwner()).getUnit(iUnitID); if(pThisUnit) { iRtnValue += pThisUnit->GetPower(); } iUnitID = GetNextUnitID(); } return iRtnValue; } // POSITION ACCESSORS /// Army's current X position int CvArmyAI::GetX() const { return m_iCurrentX; } /// Army's current Y position int CvArmyAI::GetY() const { return m_iCurrentY; } /// Set current army X position void CvArmyAI::SetX(int iX) { m_iCurrentX = iX; } /// Set current army Y position void CvArmyAI::SetY(int iY) { m_iCurrentY = iY; } /// Set current army position, passing in X and Y void CvArmyAI::SetXY(int iX, int iY) { m_iCurrentX = iX; m_iCurrentY = iY; } /// Retrieve the army's current plot CvPlot* CvArmyAI::Plot() const { return GC.getMap().plotCheckInvalid(m_iCurrentX, m_iCurrentY); } /// Retrieve the army's current area int CvArmyAI::GetArea() const { // try to find what plot we are in CvPlot* pPlot = GC.getMap().plotCheckInvalid(m_iCurrentX, m_iCurrentY); if(pPlot != NULL) { return pPlot->getArea(); } else { // since there is no plot return the invalid index return FFreeList::INVALID_INDEX; } } /// Land or sea army? DomainTypes CvArmyAI::GetDomainType() const { return (DomainTypes) m_eDomainType; } /// Set whether a land or sea army void CvArmyAI::SetDomainType(DomainTypes domainType) { m_eDomainType = domainType; } /// Everyone in the water now? bool CvArmyAI::AreAllInWater() { UnitHandle pUnit; pUnit = GetFirstUnit(); while(pUnit) { if(!pUnit->plot()->isWater()) { return false; } pUnit = GetNextUnit(); } return true; } // GOAL ACCESSORS /// Retrieve target plot for army movement CvPlot* CvArmyAI::GetGoalPlot() const { return GC.getMap().plotCheckInvalid(m_iGoalX, m_iGoalY); } /// Set target plot for army movement void CvArmyAI::SetGoalPlot(CvPlot* pGoalPlot) { CvAssertMsg(pGoalPlot, "Setting army goal to a NULL plot - please show Ed and send save."); if(pGoalPlot) { m_iGoalX = pGoalPlot->getX(); m_iGoalY = pGoalPlot->getY(); } else { m_iGoalX = -1; m_iGoalY = -1; } } /// Retrieve target plot X coordinate int CvArmyAI::GetGoalX() const { return m_iGoalX; } /// Retrieve target plot Y coordinate int CvArmyAI::GetGoalY() const { return m_iGoalY; } /// Set target for army movement using X, Y coordinates void CvArmyAI::SetGoalXY(int iX, int iY) { m_iGoalX = iX; m_iGoalY = iY; } // UNIT HANDLING /// Add a unit to our army (and we know which slot) void CvArmyAI::AddUnit(int iUnitID, int iSlotNum) { CvAssertMsg(iUnitID != ARMY_NO_UNIT,"Expect unit to be non-NULL"); CvPlayer& thisPlayer = GET_PLAYER(m_eOwner); UnitHandle pThisUnit = thisPlayer.getUnit(iUnitID); // remove this unit from an army if it is already in one thisPlayer.removeFromArmy(pThisUnit->getArmyID(), GetID()); m_FormationEntries[iSlotNum].SetUnitID(iUnitID); pThisUnit->setArmyID(GetID()); // Finally, compute when we think this unit will arrive at the next checkpoint CvPlot* pMusterPlot = GC.getMap().plot(GetX(), GetY()); if(pMusterPlot) { int iTurnsToReachCheckpoint = TurnsToReachTarget(pThisUnit, pMusterPlot, true /*bReusePaths*/, true, true); if(iTurnsToReachCheckpoint < MAX_INT) { SetEstimatedTurn(iSlotNum, iTurnsToReachCheckpoint); } } } /// Remove a unit from the army bool CvArmyAI::RemoveUnit(int iUnitToRemoveID) { bool bWasOneOrMoreRemoved = false; CvArmyFormationSlot slot; for(int iI = 0; iI < (int)m_FormationEntries.size(); iI++) { slot = m_FormationEntries[iI]; if(slot.GetUnitID() == iUnitToRemoveID) { UnitHandle pThisUnit = GET_PLAYER(GetOwner()).getUnit(iUnitToRemoveID); if(pThisUnit) { // Clears unit's army ID and erase from formation entries pThisUnit->setArmyID(FFreeList::INVALID_INDEX); m_FormationEntries[iI].SetUnitID(ARMY_NO_UNIT); bWasOneOrMoreRemoved = true; // Tell the associate operation that a unit was lost CvAIOperation* pThisOperation = GET_PLAYER(GetOwner()).getAIOperation(m_iOperationID); if(pThisOperation) { pThisOperation->UnitWasRemoved(GetID(), iI); } } } } return bWasOneOrMoreRemoved; } /// Is this part of an operation that allows units to be poached by tactical AI? bool CvArmyAI::CanTacticalAIInterruptUnit(int /* iUnitId */) const { // If the operation is still assembling, by all means interrupt it if(m_eAIState == ARMYAISTATE_WAITING_FOR_UNITS_TO_REINFORCE || m_eAIState == ARMYAISTATE_WAITING_FOR_UNITS_TO_CATCH_UP) { return true; } if(m_eOwner >=0 && m_eOwner < MAX_PLAYERS) { CvAIOperation* op = GET_PLAYER(m_eOwner).getAIOperation(m_iOperationID); if(op) { return op->CanTacticalAIInterruptOperation(); } } return false; } /// Retrieve units from the army - first call (ARMY_NO_UNIT if none found) int CvArmyAI::GetFirstUnitID() { m_CurUnitIter = m_FormationEntries.begin(); if(m_CurUnitIter == m_FormationEntries.end()) { return ARMY_NO_UNIT; } else { // First entry could not be filled yet while(m_CurUnitIter != m_FormationEntries.end()) { if(m_CurUnitIter->GetUnitID() != ARMY_NO_UNIT) { return m_CurUnitIter->GetUnitID(); } ++m_CurUnitIter; } return ARMY_NO_UNIT; } } /// Retrieve units from the army - subsequent call (ARMY_NO_UNIT if none found) int CvArmyAI::GetNextUnitID() { if(m_CurUnitIter != m_FormationEntries.end()) { ++m_CurUnitIter; while(m_CurUnitIter != m_FormationEntries.end()) { if(m_CurUnitIter->GetUnitID() != ARMY_NO_UNIT) { return m_CurUnitIter->GetUnitID(); } ++m_CurUnitIter; } return ARMY_NO_UNIT; } return ARMY_NO_UNIT; } /// Retrieve units from the army - first call (UnitHandle version) UnitHandle CvArmyAI::GetFirstUnit() { UnitHandle pRtnValue; int iUnitID = GetFirstUnitID(); if(iUnitID != ARMY_NO_UNIT) { pRtnValue = UnitHandle(GET_PLAYER(m_eOwner).getUnit(iUnitID)); FAssertMsg(pRtnValue, "Bogus unit in army - tell Ed"); } return pRtnValue; } /// Retrieve units from the army - subsequent call (UnitHandle version) UnitHandle CvArmyAI::GetNextUnit() { UnitHandle pRtnValue; int iUnitID = GetNextUnitID(); if(iUnitID != ARMY_NO_UNIT) { pRtnValue = UnitHandle(GET_PLAYER(m_eOwner).getUnit(iUnitID)); FAssertMsg(pRtnValue, "Bogus unit in army - tell Ed"); } return pRtnValue; } /// Find first unit who is sitting in this domain UnitHandle CvArmyAI::GetFirstUnitInDomain(DomainTypes eDomain) { UnitHandle pUnit, pCurrentUnit; pCurrentUnit = GetFirstUnit(); while(pCurrentUnit) { if(pCurrentUnit->plot()->isWater() && eDomain == DOMAIN_SEA || !pCurrentUnit->plot()->isWater() && eDomain == DOMAIN_LAND) { return pCurrentUnit; } pCurrentUnit = GetNextUnit(); } return pUnit; } // PER TURN PROCESSING /// Process another turn for the army void CvArmyAI::DoTurn() { // do something with the army DoDelayedDeath(); } /// Kill off the army if waiting to die (returns true if army was killed) bool CvArmyAI::DoDelayedDeath() { if(GetNumSlotsFilled() == 0 && m_eAIState != ARMYAISTATE_WAITING_FOR_UNITS_TO_REINFORCE) { Kill(); return true; } return false; } FDataStream& operator<<(FDataStream& saveTo, const CvArmyAI& readFrom) { readFrom.write(saveTo); return saveTo; } FDataStream& operator>>(FDataStream& loadFrom, CvArmyAI& writeTo) { writeTo.read(loadFrom); return loadFrom; } FDataStream& operator<<(FDataStream& saveTo, const CvArmyFormationSlot& readFrom) { saveTo << readFrom.m_iUnitID; saveTo << readFrom.m_iEstimatedTurnAtCheckpoint; saveTo << readFrom.m_bStartedOnOperation; return saveTo; } FDataStream& operator>>(FDataStream& loadFrom, CvArmyFormationSlot& writeTo) { loadFrom >> writeTo.m_iUnitID; loadFrom >> writeTo.m_iEstimatedTurnAtCheckpoint; loadFrom >> writeTo.m_bStartedOnOperation; return loadFrom; }
[ "thewizardofwas@gmail.com" ]
thewizardofwas@gmail.com
2a089951cc662db9871094177018cda9a2997f2e
0fb13dbb9903873f2a6b9833a6a1fac3e8d23909
/AlphaCipher/Exceptions.h
5764570070a97a317b793c58d1c9bba2d74f9f7d
[]
no_license
Kirusel/4laba-timp
fe8e93366b2024607d36b6d39cbd4bfdcd47617a
c2adc3f57f5d6d1a027cbf2f98e046878a4ceb5f
refs/heads/master
2023-05-14T21:27:54.746485
2021-06-01T11:03:46
2021-06-01T11:03:46
372,798,451
0
0
null
null
null
null
UTF-8
C++
false
false
1,367
h
/** * @class MyExceptions * @author Kirill Koltunov 20PT1 * @date 06/01/21 * @file Exceptions.h * @brief Header file for MyExpections */ #pragma once #include <stdexcept> #include <string> #include <iostream> using namespace std; /// @brief Класс для обработки ошибок class MyExceptions : public invalid_argument { private: int num; ///< атрибут, хранящий код ошибки string correction; ///< атрибут, хранящий информацию об исправлении ошибки public: /// @brief Запрещающий конструктор MyExceptions() = delete; /** @brief Конструктор с параметрами * @param num - целочисленное число, хранящее информацию о коде ошибки * @param error - строка, хранящая описание ошибки. * @param correction - строка, хранящая информацию об исправлении ошибки */ MyExceptions (const string & error, const int &num, const string &fix); /// @brief Предназначен для вывода информации об исправлении ошибки void fix (); /// @brief Предназначен для вывода кода ошибки void code (); };
[ "kirill_koltunov@mail.ru" ]
kirill_koltunov@mail.ru
62e76a6831c97c2982a15bd515998fd4b5313933
68ca8045e4c4b90a2560444fd964335f5bd2c4fc
/Source/Uprising/Public/Weapon/RangedWeapon.h
693a80e4829ccb29a7e105238fd43ace48881c0e
[ "BSD-3-Clause" ]
permissive
jwoo1601/Unknown-Planet-Zeropist
959fbf81e9e639c893fe1877d8e7a5d6ffe176a1
745ed270c9450c81d90a833c22c7845c6536173f
refs/heads/master
2020-12-27T10:02:23.353950
2020-02-03T01:52:48
2020-02-03T01:52:48
237,861,391
0
0
null
null
null
null
UTF-8
C++
false
false
1,165
h
// Copyright 2017 Ground Breaking Games. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Components/ArrowComponent.h" #include "Components/SphereComponent.h" #include "Weapon/Weapon.h" #include "RangedWeapon.generated.h" /** * */ UCLASS(abstract, BlueprintType, Blueprintable) class CLIENT_API ARangedWeapon : public AWeapon { GENERATED_BODY() public: ARangedWeapon(FObjectInitializer const& ObjectInitializer); #if WITH_EDITOR virtual void PostEditChangeProperty(FPropertyChangedEvent &e) override; virtual void PreSave(const class ITargetPlatform* TargetPlatform) override; #endif private: UPROPERTY(EditAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true")) FVector MuzzleOffset; #if WITH_EDITORONLY_DATA UPROPERTY(EditAnywhere, meta = (AllowPrivateAccess = "true")) USphereComponent *MuzzleOffsetEd; UPROPERTY(VisibleAnywhere, meta = (AllowPrivateAccess = "true")) UArrowComponent *LaunchDirectionEd; #endif protected: virtual TSubclassOf<class UAttackType> GetBaseAttackTypeClass_Implementation() const override; public: FORCEINLINE FVector GetMuzzleOffset() const { return MuzzleOffset; } };
[ "jkim504@myseneca.ca" ]
jkim504@myseneca.ca
ae7cc803b76d681fb667f3915bb13ce082a9e673
fd4103e6f5116c776249b00171d8639313f05bc1
/Src/Assembler/AssemView.h
a9fd065f01c7ab7e42b9ea69f15f069161b3e83c
[]
no_license
Wanghuaichen/TransCAD
481f3b4e54cc066dde8679617a5b32ac2041911b
35ca89af456065925984492eb23a0543e3125bb8
refs/heads/master
2020-03-25T03:54:51.488397
2018-06-25T17:38:39
2018-06-25T17:38:39
143,367,529
2
1
null
2018-08-03T02:30:03
2018-08-03T02:30:03
null
UHC
C++
false
false
4,132
h
// AssemView.h : iAssemView 클래스의 인터페이스 #pragma once #include "AssemMacro.h" #include ".\CHoopsView.h" #include ".\AssemApplyConstraintDialog.h" enum AssemModelHandedness { AssemHandednessSetLeft, AssemHandednessSetRight, AssemHandednessSetNone, AssemHandednessNotSet }; enum AssemModelView { AssemPartView, AssemMeshView }; class AssemHView; class AssemDocument; class PmeAssembly; class AssemApplyConstraintDialog; class ASSEM_API AssemView : public CHoopsView { protected: // serialization에서만 만들어집니다. AssemView(); DECLARE_DYNCREATE(AssemView) // 특성 public: AssemDocument* GetDocument() const; AssemHView * GetHView() const; void SetCoordinateSystemHandedness(HandednessMode rightOrLeft, bool emitMessage = true); void SetWindowColor(COLORREF newTopColor, COLORREF newBottomColor, bool emitMessage = true); void SetPolygonHandedness(AssemModelHandedness newHandedness); void SetMarkupColor(COLORREF newColor, bool emitMessage = true); void SetShadowColor(COLORREF newColor); // 작업 private: void ZoomCamera(double factor); void SetInitialCameraPosition(double distance = 1000.0); AssemModelView m_currentView; HC_KEY m_selected_key; BOOL OnGeomHandle; public: virtual void SetOperator(HBaseOperator * pNewOperator); virtual HBaseOperator * GetOperator(void); void FitWorld(void); HC_KEY Selected_key() const { return m_selected_key; } void SelectComponent(HC_KEY hKey); void SetGeomHandleStatus(BOOL val) { OnGeomHandle = val; } // 재정의 public: // virtual void OnDraw(CDC* pDC); // 이 뷰를 그리기 위해 재정의되었습니다. virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // 구현 public: virtual ~AssemView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 메시지 맵 함수를 생성했습니다. protected: DECLARE_MESSAGE_MAP() public: virtual void OnInitialUpdate(); protected: virtual void OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView); public: afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnViewPan(); afx_msg void OnUpdateViewPan(CCmdUI *pCmdUI); afx_msg void OnViewOrbit(); afx_msg void OnUpdateViewOrbit(CCmdUI *pCmdUI); afx_msg void OnViewZoomIn(); afx_msg void OnViewZoomOut(); afx_msg void OnViewZoomToWindow(); afx_msg void OnUpdateViewZoomToWindow(CCmdUI *pCmdUI); afx_msg void OnViewFront(); afx_msg void OnViewBack(); afx_msg void OnViewLeft(); afx_msg void OnViewRight(); afx_msg void OnViewTop(); afx_msg void OnViewBottom(); afx_msg void OnViewWireframe(); afx_msg void OnUpdateViewWireframe(CCmdUI *pCmdUI); afx_msg void OnViewFlatShading(); afx_msg void OnUpdateViewFlatShading(CCmdUI *pCmdUI); afx_msg void OnViewGouroudShadihg(); afx_msg void OnUpdateViewGouroudShadihg(CCmdUI *pCmdUI); afx_msg void OnViewPhongShading(); afx_msg void OnUpdateViewPhongShading(CCmdUI *pCmdUI); afx_msg void OnViewHiddenLine(); afx_msg void OnUpdateViewHiddenLine(CCmdUI *pCmdUI); afx_msg void OnViewActiveSketchViewpoint(); afx_msg void OnViewDefaultViewpoint(); afx_msg void OnViewZoomAll(); afx_msg void OnUpdateMeshGeneration(CCmdUI *pCmdUI); afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point); //afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnRButtonDown(UINT nFlags, CPoint point); // Added by YK protected: AssemApplyConstraintDialog * m_pDialog; public: void CreateConstraintDialog( PmeStdAssemblyConstraintType type ); void DestroyActiveDialog( void ); afx_msg void OnApplyCoaxial(); afx_msg void OnApplyIncidence(); afx_msg void OnAppyParallel(); afx_msg void OnApplyPerpendicular(); afx_msg void OnApplyDistance(); afx_msg void OnApplyAngle(); }; #ifndef _DEBUG // AssemView.cpp의 디버그 버전 inline AssemDocument* AssemView::GetDocument() const { return reinterpret_cast<AssemDocument*>(m_pDocument); } #endif
[ "kyk5415@gmail.com" ]
kyk5415@gmail.com
2169f06ebd5435ba02aab661bc5de2998ed9f931
8de2b74ec67494a917e25f7fd93ce707b2cebca9
/Library/include/Disposition.h
61bd7e46d16ddc539802d38586ee083f4d7747cf
[ "BSD-2-Clause" ]
permissive
dwhobrey/MindCausalModellingLibrary
fffa5db6420bc66446f8989e172997f2f641bc32
797d716e785d2dcd5c373ab385c20d3a74bbfcb0
refs/heads/master
2021-01-10T12:25:04.194940
2020-02-10T07:01:03
2020-02-10T07:01:03
49,404,942
0
0
null
null
null
null
UTF-8
C++
false
false
3,093
h
#pragma once namespace Plato { class ClassTypeInfo; class Identifier; class Container; class Path; class Bundle; /// <summary> /// Base class for modelling dispositions. /// </summary> /// <remarks> /// <para> /// Dispositions (DIDs) are modelled as classes that take dynamic bundles of inputs and outputs. /// DIDs can be born or die, and can be superposed in regions. /// </para> /// <para> /// Dispositions (DIDs) are modelled as classes that take dynamic bundles of inputs and outputs. /// DIDs can be born or die, and can be superposed in regions. /// </para> /// <para> /// Permitted operations: AddBundle, AddConnection, AddConverter, AddAlias, AddLink, AddLocation. /// But not: AddFlow, AddRegion. /// </para> /// <para> /// The container holds Bundles for the categories of inputs and outputs. /// </para> /// </remarks> class Disposition : public Container { #pragma region // Class variables. public: /// <summary> /// Class type information. /// </summary> static const ClassTypeInfo* TypeInfo; /// <summary> /// Gets the class type info for the dynamic class instance type. /// </summary> virtual const ClassTypeInfo* GetClassTypeInfo() const { return TypeInfo; } /// <summary> /// The kinds of properties this container can hold. /// </summary> static const ClassTypeInfo::HashSet* PropertyTypes; #pragma endregion public: /// <summary> /// Indicates if this DID is superimposed in the region. /// </summary> bool IsSuperposed; /// <summary> /// Tells model that output doesn't vary if input remains same. /// </summary> bool IsInputSafe; #pragma region // Constructors. public: /// <summary> /// Create a new disposition. /// </summary> /// <param name="creator">The element that created this element.</param> /// <param name="parent">The hierarchical parent of this element.</param> /// <param name="elementName">The name of the element.</param> /// <param name="scope">The scope of the element.</param> Disposition(Container* creator = NULL, Container* parent = NULL, Identifier& elementName = Identifier::Generate("Disposition"), PropertyScopesEnum scope = PropertyScopes::Public); /// <summary> /// Deallocate object. /// </summary> virtual ~Disposition(); #pragma endregion public: /// <summary> /// Called by the simulator to update DIDs state. /// Equivalent to one epoch in simulated time. /// </summary> virtual void Update(); private: friend class InitializerCatalogue; /// <summary> /// The class initializer. /// </summary> static void Initializer(); /// <summary> /// The class finalizer. /// </summary> static void Finalizer(); }; }
[ "dwhobrey@outlook.com" ]
dwhobrey@outlook.com
26ac65ac6359f8ae81b7c0efa9625f955223c911
dddbd2d53246c1fbe956598a40530f502d2663e8
/src/engine/Mesh.hpp
6528341d351ef455096c7447c9d5e9ca3f73779a
[ "Apache-2.0" ]
permissive
planteater8/shadowfox-engine
0f89c83802d2c9d2224a7d02615794ecc21ab369
dee6791038613ccebc7113bc9d2939159174df1f
refs/heads/master
2021-01-21T01:05:39.050520
2013-02-06T22:51:51
2013-02-06T22:51:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,388
hpp
/****************************************************************************** * * ShadowFox Engine Source * Copyright (C) 2012-2013 by ShadowFox Studios * Created: 2012-07-19 by Taylor Snead * * 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 "stdafx.hpp" // External // Internal #include "Material.hpp" #include "Vertex.hpp" #include "Component.hpp" namespace sfs { /** @addtogroup Engine * @{ */ /** @addtogroup Rendering * @{ */ /** The Mesh class that holds a 3D mesh and possibly an animated skeleton. * @remarks * This class controls a Mesh as defined by the 3d importing library. * It handles holding a list of vertices, bones, faces, etc. It also * holds a list of animations and things involving that. Keep in mind * that this class isn't used directly for MeshRendering for Entities. * The MeshRenderer class is used for that, and MeshRenderer has functions * to manage changing the model and animset of the Mesh, and for attaching * children mesh to it (possible, not sure yet) * @todo * Be sure this works fully in conjuction with the importers Mesh classes. * Have this display as-is (ONLY for debug purposes; Later, require an Entity with MeshRenderer and SceneNode) */ class Mesh : public Component { friend class Renderer; public: Mesh(); ~Mesh(); virtual void Init(); virtual void Update(); virtual void OnDestroy(); void SetInput(string path); void SetTexture(string name); vector<Vertex> vertices; vector<uint32_t> indices; Material material; protected: string file = ""; uint32_t vertexBuffer = 0; uint32_t indexBuffer = 0; uint32_t matrixId = 0; bool castShadows = true; bool receiveShadows = true; bool initialized = false; private: }; /// @} /// @} }
[ "taylorsnead@gmail.com" ]
taylorsnead@gmail.com
d42057cec2a4ceaba79e03d4a74626bcee4145e8
e1bcc690199ce42049923747b55cd6d3bc061dcc
/kernel/include/memory/heap.hpp
5e833f65b510bb5f9c05342c750713246474ba9a
[]
no_license
jasoncouture/CustomOS
7cb9dbd311b676c63fa4b4378042b918ee34a816
77edd7702453ceabeaf6165db80609a2f3fab057
refs/heads/main
2023-04-02T12:52:33.015130
2021-03-28T04:39:30
2021-03-28T04:39:30
343,938,650
5
1
null
null
null
null
UTF-8
C++
false
false
887
hpp
#pragma once #include <stddef.h> #include <stdint.h> #include <memory/pageallocator.hpp> #include <memory/paging/virtualaddressmanager.hpp> enum HeapSegmentFlag { IsFree = 0, Valid = 1 }; struct HeapSegment { size_t Length; HeapSegment* Next; HeapSegment* Previous; uint8_t Flags; void CombineWithNext(); void CombineWithPrevious(); bool GetFlag(HeapSegmentFlag flag); void SetFlag(HeapSegmentFlag flag); void SetFlag(HeapSegmentFlag flag, bool value); void ClearFlag(HeapSegmentFlag flag); HeapSegment* Split(size_t size); void* Address(); }__attribute__((packed)); void* kmalloc(size_t size); void* calloc(size_t count, size_t size); void* malloc(size_t size); void* realloc(void* pointer, size_t size); void free(void* address); void InitializeHeap(VirtualAddressManager *virtualAddressManager, PageAllocator *pageAllocator);
[ "jasonc@alertr.info" ]
jasonc@alertr.info
882edd9353385949fd53187f189035ed6805f8d0
d2bd315e9f5ad3c4bf5894c1bfe3c8357042ad7f
/비전프로그래밍/14주차/CV_20193148_14_1.cpp
a7bc7d2894c50d8ce7f94264d9af3ae0e156a152
[]
no_license
bluebluerabbit/School_3.1
6007939717aa67ad58eadff88cf9532dc6867cb8
a36f9b6d21eff95a226f58344c11884e3863ca23
refs/heads/main
2023-08-04T05:16:30.811280
2021-09-23T06:37:58
2021-09-23T06:37:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,275
cpp
#include <opencv2/opencv.hpp> using namespace cv; using namespace std; void read_trainData(string fn, Mat& trainingData, Mat& lables) { FileStorage fs(fn, FileStorage::READ); CV_Assert(fs.isOpened()); fs["TrainingData"] >> trainingData; fs["classes"] >> lables; fs.release(); trainingData.convertTo(trainingData, CV_32FC1); } Ptr<ml::SVM> SVM_create(int type, int max_iter, double epsilon) { Ptr<ml::SVM> svm = ml::SVM::create(); svm->setType(ml::SVM::C_SVC); svm->setKernel(ml::SVM::LINEAR); svm->setGamma(1); svm->setC(1); TermCriteria criteria(type, max_iter, epsilon); svm->setTermCriteria(criteria); return svm; } int classify_plates(Ptr<ml::SVM> svm, vector<Mat> candi_img) { for (int i = 0; i < (int)candi_img.size(); i++) { Mat onerow = candi_img[i].reshape(1, 1); onerow.convertTo(onerow, CV_32F); Mat results; svm->predict(onerow, results); if (results.at<float>(0) == 1) return i; } return -1; } Mat preprocessing(Mat image) { Mat gray, th_img, morph; Mat kernel(5, 15, CV_8UC1, Scalar(1)); cvtColor(image, gray, COLOR_BGR2GRAY); blur(gray, gray, Size(5, 5)); Sobel(gray, gray, CV_8U, 1, 0, 3); threshold(gray, th_img, 120, 255, THRESH_BINARY); morphologyEx(th_img, morph, MORPH_CLOSE, kernel); return morph; } bool vertify_plate(RotatedRect mr) { float size = mr.size.area(); float aspect = (float)mr.size.height / mr.size.width; if (aspect < 1) aspect = 1 / aspect; bool ch1 = size > 2000 && size < 30000; bool ch2 = aspect > 1.3 && aspect < 6.4; return ch1 && ch2; } void find_candidates(Mat img, vector<RotatedRect>& candidates) { vector< vector< Point> > contours; findContours(img.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); for (int i = 0; i < (int)contours.size(); i++) { RotatedRect rot_rect = minAreaRect(contours[i]); if (vertify_plate(rot_rect)) { candidates.push_back(rot_rect); } } } void draw_rotatedRect(Mat& img, RotatedRect mr, Scalar color, int thickness = 2) { Point2f pts[4]; mr.points(pts); for (int i = 0; i < 4; ++i) { line(img, pts[i], pts[(i + 1) % 4], color, thickness); } } void refine_candidate(Mat image, RotatedRect& candi) { Mat fill(image.size() + Size(2, 2), CV_8UC1, Scalar(0)); Scalar dif1(25, 25, 25), dif2(25, 25, 25); int flags = 4 + 0xff00; flags += FLOODFILL_FIXED_RANGE + FLOODFILL_MASK_ONLY; vector<Point2f> rand_pt(15); randn(rand_pt, 0, 7); Rect img_rect(Point(0, 0), image.size()); for (int i = 0; i < rand_pt.size(); i++) { Point2f seed = candi.center + rand_pt[i]; if (img_rect.contains(seed)) { Rect a = Rect(); floodFill(image, fill, seed, Scalar(), &a, dif1, dif2, flags); } } vector<Point> fill_pts; for (int i = 0; i < fill.rows; i++) { for (int j = 0; j < fill.cols; j++) { if (fill.at<uchar>(i, j) == 255) fill_pts.push_back(Point(j, i)); } } candi = minAreaRect(fill_pts); } void rotate_plate(Mat image, Mat& corp_img, RotatedRect candi) { float aspect = (float)candi.size.width / candi.size.height; float angle = candi.angle; if (aspect < 1) { swap(candi.size.width, candi.size.height); angle += 90; } Mat rotmat = getRotationMatrix2D(candi.center, angle, 1); warpAffine(image, corp_img, rotmat, image.size(), INTER_CUBIC); getRectSubPix(corp_img, candi.size, candi.center, corp_img); } vector<Mat> make_candidates(Mat image, vector<RotatedRect>& candidates) { vector<Mat> candidates_img; for (int i = 0; i < (int)candidates.size();) { refine_candidate(image, candidates[i]); if (vertify_plate(candidates[i])) { Mat corp_img; rotate_plate(image, corp_img, candidates[i]); cvtColor(corp_img, corp_img, COLOR_BGR2GRAY); resize(corp_img, corp_img, Size(144, 28), 0, 0, INTER_CUBIC); candidates_img.push_back(corp_img); i++; } else { candidates.erase(candidates.begin() + i); } } return candidates_img; } int main() { Mat trainingData, labels; read_trainData("SVMDATA.xml", trainingData, labels); Ptr<ml::SVM> svm = SVM_create(TermCriteria::MAX_ITER, 1000, 0); svm->train(trainingData, ml::ROW_SAMPLE, labels); // 학습수행 //Ptr<ml::SVM> svm = ml::StatModel::load<ml::SVM>("../SVMtrain.xml"); int car_no; cout << "차량 영상 번호 (0-20) : "; cin >> car_no; string fn = format("image/test_car/%02d.jpg", car_no); Mat image = imread(fn, 1); CV_Assert(image.data); Mat morph = preprocessing(image); vector<RotatedRect> candidates; find_candidates(morph, candidates); vector<Mat> candidate_img = make_candidates(image, candidates); int plate_no = classify_plates(svm, candidate_img); if (plate_no >= 0) draw_rotatedRect(image, candidates[plate_no], Scalar(0, 255, 0), 2); imshow("번호판영상", candidate_img[plate_no]); imshow("image", image); waitKey(); return 0; }
[ "jinjoo021@naver.com" ]
jinjoo021@naver.com
24141b14318920d7d7574e5adc57d49dc773caf7
e7af25e1e1f1bc5e222ac3487869023cc06f2986
/inference/inference/examples/AudioToWords.h
38d028dc1faa625baee2644b7c294e27312920ee
[ "BSD-3-Clause" ]
permissive
samin9796/wav2letter
688d92297eccb6b1cd37b0a950018c73bc62c3bf
6fdb54bbc37938c1663d9d263a3d33a5cc3168d9
refs/heads/master
2022-09-12T00:13:20.135436
2020-06-03T02:20:51
2020-06-03T02:22:20
269,457,835
1
0
NOASSERTION
2020-06-04T20:23:26
2020-06-04T20:23:26
null
UTF-8
C++
false
false
1,542
h
/** * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <istream> #include <memory> #include <ostream> #include <string> #include "inference/decoder/Decoder.h" #include "inference/module/nn/nn.h" namespace w2l { namespace streaming { // @inputAudioStream is a 16KHz wav file. void audioStreamToWordsStream( std::istream& inputAudioStream, std::ostream& outputWordsStream, std::shared_ptr<streaming::Sequential> dnnModule, std::shared_ptr<const DecoderFactory> decoderFactory, const DecoderOptions& decoderOptions, int nTokens); // @inputFileName is a 16KHz wav file. // @errorStream file errors are written to errorStream. void audioFileToWordsFile( const std::string& inputFileName, const std::string& outputFileName, std::shared_ptr<streaming::Sequential> dnnModule, std::shared_ptr<const DecoderFactory> decoderFactory, const DecoderOptions& decoderOptions, int nTokens, std::ostream& errorStream); // @inputFileName is a 16KHz wav file. // Errors are throws as exceptions. void audioFileToWordsFile( const std::string& inputFileName, const std::string& outputFileName, std::shared_ptr<streaming::Sequential> dnnModule, std::shared_ptr<const DecoderFactory> decoderFactory, const DecoderOptions& decoderOptions, int nTokens); } // namespace streaming } // namespace w2l
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
54683f1a8fe3559b9faeb3e34937ce9e89507163
7392076e8104a58ff40e14c2b301fbcb74da9bcb
/.svn/pristine/0c/0c10641f428f606ce4c687c6816a45f10df462c2.svn-base
403b390c0dd6ee221a6b8c64ed3b369f4924259e
[]
no_license
mengxuxin/lotter
58414d4707dcf517f479f26e5ed6a0c2b925e3e6
785102eb077ef398aea9edae2ab54856db49422d
refs/heads/master
2021-01-20T14:34:53.105135
2017-02-22T04:13:22
2017-02-22T04:13:22
82,759,501
0
0
null
null
null
null
UTF-8
C++
false
false
1,392
#ifndef CLOADLOTTERYDATA_H #define CLOADLOTTERYDATA_H #include <QByteArray> #include <QVector> #include <QMutex> #include <QImage> /*! 人员信息类 主要是人名和照片 */ struct SPeopleInfo { public: QString m_strName; //人员名字 QByteArray m_pictureba; //人员照片二进制流 int m_lotteryGrade = -1; //几等奖 持久化考虑,存储中奖人员名单, 默认为-1 未中奖 QImage m_image; }; /*! 奖池人员类:总共人员,待抽奖人员,已抽奖人员 已抽奖人员的持久化 对外接口: 获取待抽奖人员列表 */ class CLotteryData { public: static CLotteryData *instance(); static void releaseInstance(); void removeOnePeople(const SPeopleInfo &people); /** * @brief 加载人员信息 */ void loadData(); /** * @brief 获取待抽奖人员列表 * 返回之前做一次洗牌 * @return 待抽奖人员列表 */ QVector<SPeopleInfo> &getWaitLotteryPeoples(); SPeopleInfo p; private: CLotteryData(); private: static QMutex mutex; static CLotteryData* s_Instance; private: QVector<SPeopleInfo> m_lotteryPeoples; //全部抽奖人员 QVector<SPeopleInfo> m_waitLotteryPeoples; //待抽奖人员 QVector<SPeopleInfo> m_lotteryedPeoples; //已中奖人员 }; #endif // CLOADLOTTERYDATA_H
[ "mengxuxin@163.com" ]
mengxuxin@163.com
0ba508cdcde0de23809c24cf732bd04e2d3864d2
342b769878fef1b452487c022b067a40aea1f9fa
/src/undistortImage.cpp
c83da4a15b0eb492cf6ca99efd29157d9fd03792
[]
no_license
yupengfei8421/SLAM
1b2551beb4e474d95bf7f644b74e2fd691f4326d
2f39badc9c3db095d3be7d7ce9ea93b53563a67f
refs/heads/main
2023-03-31T10:48:55.703211
2021-04-05T02:42:14
2021-04-05T02:42:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,854
cpp
#include <opencv2/opencv.hpp> #include <string> using namespace std; string image_file = "../cmake-build-debug/distorted.png"; // 请确保路径正确 int main(int argc, char **argv) { // 本程序实现去畸变部分的代码。尽管我们可以调用OpenCV的去畸变,但自己实现一遍有助于理解。 // 畸变参数 double k1 = -0.28340811, k2 = 0.07395907, p1 = 0.00019359, p2 = 1.76187114e-05; // 内参 double fx = 458.654, fy = 457.296, cx = 367.215, cy = 248.375; cv::Mat image = cv::imread(image_file, 0); // 图像是灰度图,CV_8UC1 int rows = image.rows, cols = image.cols; cv::Mat image_undistort = cv::Mat(rows, cols, CV_8UC1); // 去畸变以后的图 // 计算去畸变后图像的内容 for (int v = 0; v < rows; v++) { for (int u = 0; u < cols; u++) { // 按照公式,计算点(u,v)对应到畸变图像中的坐标(u_distorted, v_distorted) double x = (u - cx) / fx, y = (v - cy) / fy; double r = sqrt(x * x + y * y); double x_distorted = x * (1 + k1 * r * r + k2 * r * r * r * r) + 2 * p1 * x * y + p2 * (r * r + 2 * x * x); double y_distorted = y * (1 + k1 * r * r + k2 * r * r * r * r) + p1 * (r * r + 2 * y * y) + 2 * p2 * x * y; double u_distorted = fx * x_distorted + cx; double v_distorted = fy * y_distorted + cy; // 赋值 (最近邻插值) if (u_distorted >= 0 && v_distorted >= 0 && u_distorted < cols && v_distorted < rows) { image_undistort.at<uchar>(v, u) = image.at<uchar>((int) v_distorted, (int) u_distorted); } else { image_undistort.at<uchar>(v, u) = 0; } } } // 画图去畸变后图像 cv::imshow("distorted", image); cv::imshow("undistorted", image_undistort); cv::waitKey(); cv::imwrite("../cmake-build-debug/undistorted.png", image_undistort); return 0; }
[ "120153710@qq.com" ]
120153710@qq.com
4f9a5bcd04735c024c6a0c531be9d953a66d4ee5
9239ce416eb9dd4eb0a80fa1e7edc9cd4dcc8821
/Graphics/Group.cpp
edfff75a2cad075694510fcac782abe56afd183a
[]
no_license
GKaszewski/Brick-Engine
c7b49ee171d432dff28439dcc0d885af71763201
4055c71cd06e54877a3755d680bc13fc567cd26d
refs/heads/master
2022-06-13T14:28:38.119529
2021-08-14T14:11:25
2021-08-14T14:11:25
228,939,536
0
0
null
null
null
null
UTF-8
C++
false
false
597
cpp
#include "Group.hpp" Group::Group() : m_drawables{} { } void Group::draw(sf::RenderTarget& target, sf::RenderStates states) const { for (const auto& drawable : m_drawables) { target.draw(drawable, states); } } const sf::Drawable& Group::operator[](std::size_t index) { return m_drawables[index]; } std::size_t Group::push_back(const sf::Drawable& drawable) { m_drawables.push_back(drawable); return m_drawables.size() - 1; } const sf::Drawable& Group::pop_back() { const auto& drawable = m_drawables.back(); m_drawables.pop_back(); return drawable; }
[ "gabrielkaszewski@gmail.com" ]
gabrielkaszewski@gmail.com
bc620a075208aa4d771d47fd11ccb973ebe8118c
b503a9cb9537047c618660684433935ffec54e0e
/Codeforces/1040D.cpp
6b24fc69acd48ab6a530b9228f49d57475351230
[]
no_license
mayank98/OnlinePractice
0aa4499b769ebe4e0cb83ad7c9b4742e097af592
dd169e03e0abe5c2b8d415a54b570dc1d0689e77
refs/heads/master
2021-01-21T14:28:11.264413
2018-10-17T08:01:42
2018-10-17T08:01:42
95,284,004
0
0
null
null
null
null
UTF-8
C++
false
false
1,083
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define MOD 1000000007 int main() { ios_base::sync_with_stdio(false); cout.tie(0); cin.tie(0); // memset(dp,-1,sizeof(dp)); // cout << fixed << setprecision(16); ll n,k; cin >> n >> k; ll l=1,r=n,mid; string response; default_random_engine generator; while(true) { if(r-l+1==4*k) { uniform_int_distribution <ll> distribution(l,r); ll num=distribution(generator); cout << num << " " << num << flush; cin >> response; if(response=="Yes") return 0; } mid=(l+r)/2; cout << max((ll)1,l-k) << " " << min(mid+k,n) << flush; cin >> response; if(response=="Yes") { l=max((ll)1,l-k); r=min(mid+k,n); if(l==r) return 0; } else if(response=="No") { l=max((ll)1,mid-k); r=min(r+k,n); } else return 0; } }
[ "mayankgupta18198@gmail.com" ]
mayankgupta18198@gmail.com
1ee7173fb1dbf0a0beb1f4c35cbd25a639c5bf73
258eabbb32dea482e339d9486f09ac87a950f2dd
/ROV2021/Motor.cpp
82ad1cf106ad3a45d4c3b8a7de5e5708a28d1564
[]
no_license
AndrewGrishchenko/MATE2021
fc938c236bc6b6f3d91b29efc5d8f4d44cade95d
444c697e720b0054fe500e7a98e11cd2a209e4bf
refs/heads/main
2023-04-18T18:50:52.484336
2021-05-08T02:25:53
2021-05-08T02:25:53
310,301,159
0
0
null
null
null
null
UTF-8
C++
false
false
191
cpp
#include "Motor.h" bool Motor::get_inverse() { return m_is_inverse; } void Motor::set_inverse(bool inverse) { m_is_inverse = inverse; } int8_t Motor::get_power() { return m_power; }
[ "andrew26080537@gmail.com" ]
andrew26080537@gmail.com
59630de2cdcae909379ce75c388b80fda055942d
32a6ac6cbec63296ba68838ad4699b995810c6cd
/compiled/cpp_stl_11/ts_packet_header.h
ec29bd3a886a275b0b37bd07a5bfbd385079e461
[ "MIT" ]
permissive
smarek/ci_targets
a33696ddaa97daa77c0aecbdfb20c67546c729bc
c5edee7b0901fd8e7f75f85245ea4209b38e0cb3
refs/heads/master
2022-12-01T22:54:38.478115
2020-08-10T13:36:36
2020-08-19T07:12:14
286,483,420
0
0
MIT
2020-08-10T13:30:22
2020-08-10T13:30:21
null
UTF-8
C++
false
false
2,171
h
#pragma once // This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild #include "kaitai/kaitaistruct.h" #include <stdint.h> #include <memory> #if KAITAI_STRUCT_VERSION < 9000L #error "Incompatible Kaitai Struct C++/STL API: version 0.9 or later is required" #endif /** * describes the first 4 header bytes of a TS Packet header */ class ts_packet_header_t : public kaitai::kstruct { public: enum adaptation_field_control_enum_t { ADAPTATION_FIELD_CONTROL_ENUM_RESERVED = 0, ADAPTATION_FIELD_CONTROL_ENUM_PAYLOAD_ONLY = 1, ADAPTATION_FIELD_CONTROL_ENUM_ADAPTATION_FIELD_ONLY = 2, ADAPTATION_FIELD_CONTROL_ENUM_ADAPTATION_FIELD_AND_PAYLOAD = 3 }; ts_packet_header_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent = nullptr, ts_packet_header_t* p__root = nullptr); private: void _read(); public: ~ts_packet_header_t(); void _clean_up(); private: uint8_t m_sync_byte; bool m_transport_error_indicator; bool m_payload_unit_start_indicator; bool m_transport_priority; uint64_t m_pid; uint64_t m_transport_scrambling_control; adaptation_field_control_enum_t m_adaptation_field_control; uint64_t m_continuity_counter; std::string m_ts_packet_remain; ts_packet_header_t* m__root; kaitai::kstruct* m__parent; public: uint8_t sync_byte() const { return m_sync_byte; } bool transport_error_indicator() const { return m_transport_error_indicator; } bool payload_unit_start_indicator() const { return m_payload_unit_start_indicator; } bool transport_priority() const { return m_transport_priority; } uint64_t pid() const { return m_pid; } uint64_t transport_scrambling_control() const { return m_transport_scrambling_control; } adaptation_field_control_enum_t adaptation_field_control() const { return m_adaptation_field_control; } uint64_t continuity_counter() const { return m_continuity_counter; } std::string ts_packet_remain() const { return m_ts_packet_remain; } ts_packet_header_t* _root() const { return m__root; } kaitai::kstruct* _parent() const { return m__parent; } };
[ "kaitai-bot@kaitai.io" ]
kaitai-bot@kaitai.io
090f2a7d24edaa30bfdae194162cba83ed387385
cc99f8aac33b56f040a7be3dbc4c90812df1d40d
/Directx9sdk/Samples/C++/DirectPlay/Maze/MazeConsoleClient/Main.cpp
c9d5c7c72cbb92c3a8eb8eb34e14e4d63ffee934
[]
no_license
Kiddinglife/t3d
a71231f298646fc57b145783f0935914ae29fdf1
bec8ed964588611ebf4d11bb4518a7ab92958a38
refs/heads/main
2023-03-02T06:07:18.513787
2021-02-14T10:12:16
2021-02-14T10:12:16
338,776,439
0
0
null
null
null
null
UTF-8
C++
false
false
1,942
cpp
//---------------------------------------------------------------------------- // File: main.cpp // // Desc: This is a DirectPlay 8 client/server sample. The client comes in two flavors. // A console based version, and a D3D client. The D3D client can optionally // be run as screen saver by simply copying mazeclient.exe to your // \winnt\system32\ and renaming it to mazeclient.scr. This will make // it a screen saver that will be detected by the display control panel. // // Copyright (c) 1999-2001 Microsoft Corp. All rights reserved. //----------------------------------------------------------------------------- #define STRICT #define D3D_OVERLOADS #include <windows.h> #include <D3DX8.h> #include <dplay8.h> #include "DXUtil.h" #include "SyncObjects.h" #include "IMazeGraphics.h" #include "DummyConnector.h" #include "MazeApp.h" #include "MazeServer.h" #include "ConsoleGraphics.h" #include "MazeApp.h" CMazeApp g_MazeApp; CConsoleGraphics g_ConsoleGraphics; //----------------------------------------------------------------------------- // Name: // Desc: //----------------------------------------------------------------------------- int __cdecl main( int argc, TCHAR* argv[] ) { // Verify Unicode compatibility. #ifdef UNICODE { if( GetVersion() & 0x80000000 ) // High bit enabled for Win95/98/Me { MessageBox( NULL, TEXT("You're attemping to run a Unicode application") TEXT(" in a Windows 9x/Me environment.") TEXT("\nPlease recompile this application in ANSI mode.") TEXT("\n\nThe program will now exit."), TEXT("Compatibility Error"), MB_OK | MB_ICONERROR ); return 0; } } #endif //UNICODE if( FAILED( g_MazeApp.Create( &g_ConsoleGraphics ) ) ) return 0; return g_MazeApp.Run( 0 ); }
[ "jake.zhang.work@gmail.com" ]
jake.zhang.work@gmail.com
7e165a784e494154d2c77f6e0eee68b286d65045
4ab8222ddf686742de4ea5fc18a8ea0a37072661
/Engine/Engine/Player.cpp
9efb07c9dbdb127a2843a9a8280a716f00f29eb5
[]
no_license
ParkSunW00/DroppingCat
e1be609fbe3df4cdb862efcbe6c4c7873ccf26bd
6ad3a29de1288c4188fd38489d18011b4ba8392d
refs/heads/master
2023-01-14T13:13:11.101546
2020-11-09T04:45:43
2020-11-09T04:45:43
288,142,691
0
1
null
null
null
null
UTF-8
C++
false
false
710
cpp
#include "stdafx.h" #include "Player.h" Player::Player() { isClick = false; playerAnimation = new Animation(2); playerAnimation->AddFrame("Resource/cat1.png"); playerAnimation->AddFrame("Resource/cat2.png"); AddChild(playerAnimation); rect = playerAnimation->getRect(); } Player::~Player() { } void Player::Render() { Object::Render(); playerAnimation->Render(); } void Player::Update(float dTime) { if (isClick) { playerAnimation->Update(dTime); if (playerAnimation->getIsFinalSrite()) { isClick = false; playerAnimation->setIsFinalSprite(false); } } } void Player::setIsClicked(bool isClicked) { this->isClick = isClicked; } bool Player::getIsClicked() { return isClick; }
[ "jinwon11022@naver.com" ]
jinwon11022@naver.com
262087a1e275b84be37f34f36905a138c2bf1500
cff6f556d9da38e465d65145eb3f4a08115ad4bf
/main.cpp
9ae13d8d9ab52faae9adbf96204bb4910baa1bd0
[ "MIT" ]
permissive
bibi-the-brave/QONTAINER
3888d1882fa6d981207939645db0d860f6ebe7c3
81ca5920febcff88ac1dffd75b82c89bf0e56842
refs/heads/master
2020-05-22T20:08:10.852813
2019-07-25T16:13:53
2019-07-25T16:13:53
186,504,647
3
0
null
null
null
null
UTF-8
C++
false
false
579
cpp
/* * Andrea Favero * 1125545 * andrea.favero.8@studenti.unipd.it */ #include <QApplication> #include <QIcon> #include <QStyle> #include <QDesktopWidget> #include <memory> #include "finestraprincipale.h" #include "contenitore.h" #include "persona.h" #include "allenamento.h" #include "deepptr.h" int main(int argc, char *argv[]) { Contenitore<std::shared_ptr<Persona>> cp; Contenitore<DeepPtr<Allenamento>> ca; QApplication a(argc, argv); a.setWindowIcon(QIcon(":/immagini/logo.svg")); FinestraPrincipale p(ca,cp); p.show(); return a.exec(); }
[ "andrea.favero96@gmail.com" ]
andrea.favero96@gmail.com
b15cb2412b7e95050c331f008feadcee292db42a
98db7c4cd61029506aa7add98f1082d53844d7bb
/main.cpp
d3cf1bc6a9602ceafc6c7a6d98fc13753a42f509
[]
no_license
wolf088/git_Calculation
acd91c39c51ecdf436bca8655c334a9281c98fd3
c0038de0a818c358b636b60779c4e15fb9c519d8
refs/heads/master
2020-07-26T07:16:58.723366
2019-09-23T09:58:42
2019-09-23T09:58:42
208,575,814
0
0
null
null
null
null
UTF-8
C++
false
false
929
cpp
#include <iostream> #include "calc.hpp" using namespace std; int main(){ Calculation ins; int num; char mark; //演算子 //1つ目の数の入力 cout << "1つ目の数を入力してください:"; cin >> num; ins.setNum1(num); //演算子の入力 cout << "演算子を入力してください(+:加算、-:減算、*:乗算、/:除算):"; cin >> mark; //2つ目の数の入力 cout << "2つ目の数を入力してください:"; cin >> num; ins.setNum2(num); //演算 if (mark == '+'){ cout << "答:" << ins.add() << endl; } else if (mark == '-'){ cout << "答:" << ins.sub() << endl; } else if (mark == '*'){ cout << "答:" << ins.mul() << endl; } else if (mark == '/'){ cout << "答:" << ins.div() << endl; } return 0; }
[ "takayoshi-jean@akane.waseda.jp" ]
takayoshi-jean@akane.waseda.jp
e83ed7323d709c1d2ab9c95e1eb10bb351f8c51d
1f63dde39fcc5f8be29f2acb947c41f1b6f1683e
/Boss2D/addon/tensorflow-1.2.1_for_boss/tensorflow/compiler/xla/service/cpu/runtime_matmul.cc
332f4216dc7b970cb985719ef82d5aa82bb86d3d
[ "Apache-2.0", "MIT" ]
permissive
koobonil/Boss2D
09ca948823e0df5a5a53b64a10033c4f3665483a
e5eb355b57228a701495f2660f137bd05628c202
refs/heads/master
2022-10-20T09:02:51.341143
2019-07-18T02:13:44
2019-07-18T02:13:44
105,999,368
7
2
MIT
2022-10-04T23:31:12
2017-10-06T11:57:07
C++
UTF-8
C++
false
false
3,082
cc
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/compiler/xla/service/cpu/runtime_matmul.h" #define EIGEN_USE_THREADS #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/compiler/xla/executable_run_options.h" #include "tensorflow/core/platform/types.h" using tensorflow::int32; using tensorflow::int64; namespace { template <typename T> void MatMul(const void* run_options_ptr, T* out, T* lhs, T* rhs, int64 m, int64 n, int64 k, int32 transpose_lhs, int32 transpose_rhs) { const xla::ExecutableRunOptions* run_options = static_cast<const xla::ExecutableRunOptions*>(run_options_ptr); int64 lhs_rows = m; int64 lhs_cols = k; if (transpose_lhs) { std::swap(lhs_rows, lhs_cols); } int64 rhs_rows = k; int64 rhs_cols = n; if (transpose_rhs) { std::swap(rhs_rows, rhs_cols); } const Eigen::TensorMap<Eigen::Tensor<const T, 2>, Eigen::Aligned> A( lhs, lhs_rows, lhs_cols); const Eigen::TensorMap<Eigen::Tensor<const T, 2>, Eigen::Aligned> B( rhs, rhs_rows, rhs_cols); Eigen::TensorMap<Eigen::Tensor<T, 2>, Eigen::Aligned> C(out, m, n); typedef typename Eigen::Tensor<T, 2>::DimensionPair DimPair; int lhs_contract_dim = transpose_lhs ? 0 : 1; int rhs_contract_dim = transpose_rhs ? 1 : 0; const Eigen::array<DimPair, 1> dims({ DimPair(lhs_contract_dim, rhs_contract_dim) }); // Matrix multiply is a special case of the "contract" operation where // the contraction is performed along dimension 1 of the lhs and dimension // 0 of the rhs. C.device(*run_options->intra_op_thread_pool()) = A.contract(B, dims); } } // namespace void __xla_cpu_runtime_EigenMatMulF32(const void* run_options_ptr, float* out, float* lhs, float* rhs, int64 m, int64 n, int64 k, int32 transpose_lhs, int32 transpose_rhs) { MatMul<float>(run_options_ptr, out, lhs, rhs, m, n, k, transpose_lhs, transpose_rhs); } void __xla_cpu_runtime_EigenMatMulF64(const void* run_options_ptr, double* out, double* lhs, double* rhs, int64 m, int64 n, int64 k, int32 transpose_lhs, int32 transpose_rhs) { MatMul<double>(run_options_ptr, out, lhs, rhs, m, n, k, transpose_lhs, transpose_rhs); }
[ "slacealic@gmail.com" ]
slacealic@gmail.com
409082d4d51087b2c1dff1f9e63d99e0c95f8d08
204c3945a0a38786ea1717fd360bce63ff451b48
/src/main.cpp
f1fb447f7ab9676bc097132a2f53792392c752cd
[]
no_license
valentinpi/named-chess
4eb493c172952a29531fee22815e815b214790c3
45b545636797ee7075f04b2d9918380830df2eb4
refs/heads/master
2021-07-06T16:08:48.141963
2020-10-03T16:12:07
2020-10-03T16:12:07
189,845,405
2
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
#include "Game.hpp" int main(int argc, char *argv[]) { (void) argc; (void) argv; Game game(720, 720); if (!game.is_initialized()) return EXIT_FAILURE; game.run(); return EXIT_SUCCESS; }
[ "valentinpickel@gmx.de" ]
valentinpickel@gmx.de
87096f38a6f60b27370e8e18dcef55c0a922d79e
435b7d2980bbc80718e562ec78d835975dd21b20
/include/viewpoint_interface/layouts/twinned_pip.hpp
b696913b2282413beb744ac2e82f697b003c4328
[]
no_license
Lualmoba/camera_viewpoint_interface
e35163c44811d975623896539b32502f5d7b762d
e165270c40f52695dd3704218272a0c44b92f3d7
refs/heads/main
2023-07-04T21:04:16.932301
2021-08-19T19:33:19
2021-08-19T19:33:19
318,031,392
0
0
null
null
null
null
UTF-8
C++
false
false
5,650
hpp
#ifndef __LAYOUT_TWINNED_PIP_HPP__ #define __LAYOUT_TWINNED_PIP_HPP__ #include "viewpoint_interface/layout.hpp" namespace viewpoint_interface { struct TwinnedPipParams { uint start_primary_display = 0; uint start_pip_display = 1; uint max_num_displays = 2; int pip_window_dims[2] = { 400, 225 }; int pip_aspect_ratio[2] = { 16, 9 }; }; class TwinnedPipLayout final : public Layout { public: TwinnedPipLayout(DisplayManager &displays, TwinnedPipParams params=TwinnedPipParams()) : Layout(LayoutType::TWINNED_PIP, displays), parameters_(params), keep_aspect_ratio_(true), pip_enabled_(true) { setNumDisplaysForRole(1, LayoutDisplayRole::Primary); setNumDisplaysForRole(1, LayoutDisplayRole::Secondary); addDisplayByIxAndRole(parameters_.start_primary_display, LayoutDisplayRole::Primary); addDisplayByIxAndRole(parameters_.start_pip_display, LayoutDisplayRole::Secondary); } virtual void displayLayoutParams() override { drawDisplaysList(parameters_.max_num_displays); drawDraggableRing(); ImGui::Separator(); ImGui::Text("Picture-in-Picture Settings:\n"); uint max_size(600); int start_pip_dims[2] = { parameters_.pip_window_dims[0], parameters_.pip_window_dims[1] }; bool pip_dims_changed(ImGui::DragInt2("Dimensions", parameters_.pip_window_dims, 1.0f, 100, max_size)); bool ar_changed(ImGui::Checkbox("Keep Aspect Ratio", &keep_aspect_ratio_)); if (keep_aspect_ratio_) { ImGui::Text("Aspect Ratio"); ImGui::SameLine(); ar_changed = ImGui::InputInt2("##PiP AR", parameters_.pip_aspect_ratio) || ar_changed; if (pip_dims_changed || ar_changed) { float aspect_ratio = (float)parameters_.pip_aspect_ratio[0] / parameters_.pip_aspect_ratio[1]; // Clamp both axes to max_size int max_width(max_size), max_height(max_size); if (aspect_ratio > 1.0) { // Width is largest max_height = max_size * (1.0 / aspect_ratio); } else { // Height is largest or same max_width = max_size * aspect_ratio; } if (parameters_.pip_window_dims[0] > max_width || parameters_.pip_window_dims[1] > max_height) { parameters_.pip_window_dims[0] = max_width; parameters_.pip_window_dims[1] = max_height; } else { if (parameters_.pip_window_dims[1]-start_pip_dims[1] != 0) { // Height changed parameters_.pip_window_dims[0] = parameters_.pip_window_dims[1] * aspect_ratio; } else { // Width changed aspect_ratio = 1.0 / aspect_ratio; parameters_.pip_window_dims[1] = parameters_.pip_window_dims[0] * aspect_ratio; } } } } } virtual void draw() override { addLayoutComponent(LayoutComponent::Type::Primary); if (pip_enabled_) { addLayoutComponent(LayoutComponent::Type::Pic_In_Pic, LayoutComponent::Spacing::Floating, LayoutComponent::ComponentPositioning_Top_Right, (float)(parameters_.pip_window_dims[0]), (float)(parameters_.pip_window_dims[1])); } drawLayoutComponents(); std::map<std::string, bool> states; states["Robot"] = !clutching_; states["Suction"] = grabbing_; displayStateValues(states); } virtual void handleKeyInput(int key, int action, int mods) override { // TODO: Add function to swap active primary with active secondary if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_P: { pip_enabled_ = !pip_enabled_; } break; case GLFW_KEY_RIGHT: { toNextDisplay(LayoutDisplayRole::Primary); toNextDisplay(LayoutDisplayRole::Secondary); } break; case GLFW_KEY_LEFT: { toPrevDisplay(LayoutDisplayRole::Primary); toPrevDisplay(LayoutDisplayRole::Secondary); } break; case GLFW_KEY_UP: { toPrevDisplay(LayoutDisplayRole::Secondary); toPrevDisplay(LayoutDisplayRole::Primary); } break; case GLFW_KEY_DOWN: { toNextDisplay(LayoutDisplayRole::Secondary); toNextDisplay(LayoutDisplayRole::Primary); } break; default: { } break; } } } virtual void handleStringInput(std::string input) override { LayoutCommand command(translateStringInputToCommand(input)); switch(command) { case LayoutCommand::TOGGLE: { toNextDisplay(LayoutDisplayRole::Primary); toNextDisplay(LayoutDisplayRole::Secondary); } break; default: {} break; } } private: TwinnedPipParams parameters_; bool keep_aspect_ratio_, pip_enabled_; }; } // viewpoint_interface #endif //__LAYOUT_TWINNED_PIP_HPP__
[ "lamolina@wisc.edu" ]
lamolina@wisc.edu
1adb38ebf42597c19e081587a4cd2c5c4e00e207
b7d8ed5e3c607d2530f6a7752d9c916587c0374a
/扎实基础训练/啤酒与饮料.cpp
282f831b5da25cd98373ac31ecb9e3a1e417196b
[]
no_license
small-Qing/lanqiaobei
8c38b16e861116ae05fcc20c4927d2c81908b0fd
09e60eba65a95a8cce802074b3574c07e888c784
refs/heads/master
2020-04-27T23:55:18.690593
2019-03-10T08:39:07
2019-03-10T08:39:07
174,796,510
0
0
null
null
null
null
UTF-8
C++
false
false
349
cpp
#include<bits/stdc++.h> using namespace std; #define mem(a,b) memset(a,b,sizeof(a)) const double eps=3e-8; const int mod=10; const int maxn=2e5; bool vis[11]; const double mon=82.3; int main(){ for(int i=0;i<=35;i++){ double y=(mon-2.3*i)/1.9; if(i>=y)continue; if(fabs(y-(int)y)<eps)cout<<i<<endl; } return 0; }
[ "13055200916@163.com" ]
13055200916@163.com
12140f64c2e06e61f74e2216a41a59a796466660
1bbb19e305a39a046c50e046dbb574f6b321b8dd
/altimetro/altimetro.ino
9c7cc19378d590ebbbeb1ee66b49ac0a1a579e49
[]
no_license
car13romani/arduino
22b36ab9be7eb8a854488727396e2b2d137dae14
96924dc511d0a5867b87fbdab51318a06127606f
refs/heads/master
2019-07-11T19:22:37.895698
2017-11-16T17:26:01
2017-11-16T17:26:01
110,992,920
2
0
null
null
null
null
UTF-8
C++
false
false
2,324
ino
#include <LiquidCrystal.h> //Biblioteca do LCD #include <BME280.h> // Biblioteca do Sensor #include <Wire.h> // Biblioteca I2C #define SERIAL_BAUD 115200 LiquidCrystal lcd(12, 11, 5, 4, 3, 2); BME280 bme; void printBME280Data(Stream * client); void printBME280CalculatedData(Stream* client); void setup(){ lcd.begin(16, 2); //Inicia o LCD com dimensões 16x2(Colunas x Linhas) lcd.setCursor(0, 0); //Posiciona o cursor na primeira coluna(0) e na primeira linha(0) do LCD lcd.print("Inicializando!"); //Escreve no LCD "Olá Garagista!" while(!bme.begin()){ lcd.setCursor(0, 0); //Posiciona o cursor na primeira coluna(0) e na primeira linha(0) do LCD lcd.print("ERRO NO SENSOR!"); //Escreve no LCD "Olá Garagista!" } //lcd.setCursor(0, 1); //Posiciona o cursor na primeira coluna(0) e na segunda linha(1) do LCD //lcd.print("LabdeGaragem"); //Escreve no LCD "LabdeGaragem" } void loop() { for(int i = 0; i<2; i++){ lcd.setCursor(0, i); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD lcd.print(" "); } float temp(NAN), hum(NAN), pres(NAN); uint8_t pressureUnit(3); // unit: B000 = Pa, B001 = hPa, B010 = Hg, B011 = atm, B100 = bar, B101 = torr, B110 = N/m^2, B111 = psi bme.ReadData(pres, temp, hum, true, pressureUnit); // Parameters: (float& pressure, float& temp, float& humidity, bool celsius = false, uint8_t pressureUnit = 0x0) float altitude = bme.CalculateAltitude(true); //True = Sistema Metrico lcd.setCursor(0, 0); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD lcd.print("Temp: "); lcd.setCursor(6, 0); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD lcd.print(temp); lcd.setCursor(15, 0); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD lcd.print("C"); lcd.setCursor(0, 1); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD lcd.print("Alti: "); lcd.setCursor(6, 1); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD lcd.print(altitude); lcd.setCursor(15, 1); //Posiciona o cursor na décima quarta coluna(13) e na segunda linha(1) do LCD lcd.print("m"); delay(1000); }
[ "car13romani@gmail.com" ]
car13romani@gmail.com
4edabc48c38c7b88cdd2e24670a8837e16ed3a84
382eb97bb79478130f83d50877148188ec7ff51a
/interface/src/ui/ChatMessageArea.h
57199538fdd8dd566a8341f607c5c0011ce2ea28
[ "Apache-2.0" ]
permissive
rabedik/hifi
d6cb72e9426d69714b06a3f842b2a4919f52ed18
08986dcb17ece932f567ab27cf1f0b1fdecf41e1
refs/heads/master
2021-01-16T20:55:40.135499
2015-08-28T23:36:00
2015-08-28T23:36:00
41,653,396
1
0
null
2015-08-31T03:17:57
2015-08-31T03:17:56
null
UTF-8
C++
false
false
821
h
// // ChatMessageArea.h // interface/src/ui // // Created by Ryan Huffman on 4/11/14. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_ChatMessageArea_h #define hifi_ChatMessageArea_h #include <QTextBrowser> const int CHAT_MESSAGE_LINE_HEIGHT = 130; class ChatMessageArea : public QTextBrowser { Q_OBJECT public: ChatMessageArea(bool useFixedHeight = true); virtual void setHtml(const QString& html); public slots: void updateLayout(); void setSize(const QSize& size); signals: void sizeChanged(QSize newSize); protected: virtual void wheelEvent(QWheelEvent* event); bool _useFixedHeight; }; #endif // hifi_ChatMessageArea_h
[ "ryanhuffman@gmail.com" ]
ryanhuffman@gmail.com
70821965864aed27b356328c67710d8dc9f23a96
27ea8c9a3f62e4a9daeb4b68fe911a991a0a3de0
/espnow-slave-conf-espresso-lite1/espnow-slave-conf-espresso-lite1/espnow-slave-conf-espresso-lite1.ino
7da7248014cb41ce89007b6b7e72d0f1ac6ba471
[ "MIT" ]
permissive
cmmakerclub/esp-now-config-manager
184d906f13aeae0ac3a315e45d52346fbe0dcae5
fe2f21ab471119051c0261eb18d64a29b6a77df0
refs/heads/master
2021-08-31T23:44:01.954007
2017-12-23T15:05:23
2017-12-23T15:05:23
106,809,170
1
3
null
2017-10-19T07:02:58
2017-10-13T10:09:21
Arduino
UTF-8
C++
false
false
4,645
ino
#define CMMC_USE_ALIAS #include <Arduino.h> #include <ArduinoJson.h> #include <ESP8266WiFi.h> #include <CMMC_Utils.h> #include <CMMC_SimplePair.h> #include <CMMC_Config_Manager.h> #include <CMMC_ESPNow.h> #include <CMMC_BootMode.h> #include <CMMC_LED.h> #include <CMMC_TimeOut.h> #include <DHT.h> #include "FS.h" #include "data_type.h" extern "C" { #include <espnow.h> #include <user_interface.h> } #define LED_PIN 5 #define DHTPIN 12 #define DEFAULT_DEEP_SLEEP_S 60 uint8_t selective_button_pin = 2; uint32_t wait_button_pin_ms = 1; uint8_t master_mac[6]; uint8_t self_mac[6]; int dhtType = 22; int mode; CMMC_SimplePair simplePair; CMMC_Config_Manager configManager; CMMC_ESPNow espNow; CMMC_LED led(LED_PIN, LOW); DHT *dht; bool sp_flag_done = false; void evt_callback(u8 status, u8* sa, const u8* data) { if (status == 0) { char buf[13]; Serial.printf("[CSP_EVENT_SUCCESS] STATUS: %d\r\n", status); Serial.printf("WITH KEY: "); CMMC::dump(data, 16); Serial.printf("WITH MAC: "); CMMC::dump(sa, 6); CMMC::macByteToString(data, buf); CMMC::printMacAddress((uint8_t*)buf); configManager.add_field("mac", buf); configManager.commit(); Serial.println("DONE..."); sp_flag_done = true; } else { Serial.printf("[CSP_EVENT_ERROR] %d: %s\r\n", status, (const char*)data); } } void load_config() { configManager.load_config([](JsonObject * root) { Serial.println("[user] json loaded.."); if (root->containsKey("mac")) { String macStr = String((*root)["mac"].as<const char*>()); Serial.printf("Loaded mac %s\r\n", macStr.c_str()); CMMC::convertMacStringToUint8(macStr.c_str(), master_mac); CMMC::printMacAddress(master_mac); Serial.println(); } }); } void init_espnow() { uint8_t* slave_addr = CMMC::getESPNowSlaveMacAddress(); memcpy(self_mac, slave_addr, 6); espNow.init(NOW_MODE_SLAVE); espNow.on_message_sent([](uint8_t *macaddr, u8 status) { led.toggle(); Serial.println(millis()); Serial.printf("sent status %lu\r\n", status); }); espNow.on_message_recv([](uint8_t * macaddr, uint8_t * data, uint8_t len) { led.toggle(); Serial.printf("GOT sleepTime = %lu\r\n", data[0]); if (data[0] == 0) data[0] = 30; goSleep(data[0]); }); } void init_simple_pair() { simplePair.begin(SLAVE_MODE, evt_callback); simplePair.start(); CMMC_TimeOut ct; ct.timeout_ms(3000); while (1) { if (ct.is_timeout()) { if (sp_flag_done && digitalRead(selective_button_pin) == LOW) { ct.yield(); Serial.println("YIELDING..."); } else { Serial.println("timeout"); ESP.reset(); } } led.toggle(); delay(50L + (250 * sp_flag_done)); } } void setup() { Serial.begin(57600); led.init(); configManager.init("/config98.json"); selective_button_pin = 2; wait_button_pin_ms = 1; dhtType = 11; dht = new DHT(DHTPIN, dhtType); dht->begin(); CMMC_BootMode bootMode(&mode, selective_button_pin); bootMode.init(); bootMode.check([](int mode) { if (mode == BootMode::MODE_CONFIG) { init_simple_pair(); } else if (mode == BootMode::MODE_RUN) { load_config(); init_espnow(); } else { // unhandled } }, wait_button_pin_ms); } CMMC_SENSOR_T packet; void read_sensor() { packet.battery = analogRead(A0); memcpy(packet.to, master_mac, 6); memcpy(packet.from, self_mac, 6); //CMMC::printMacAddress(packet.from); //CMMC::printMacAddress(packet.to); packet.sum = CMMC::checksum((uint8_t*) &packet, sizeof(packet) - sizeof(packet.sum)); float h = dht->readHumidity(); float t = dht->readTemperature(); if (isnan(h) || isnan(t)) { h = 0.0; t = 0.0; } else { packet.temperature = t * 100; packet.humidity = h * 100; } packet.ms = millis(); // Serial.printf("%lu - %02x\r\n", packet.battery, packet.battery); // Serial.printf("%lu - %02x\r\n", packet.temperature, packet.temperature); // Serial.printf("%lu - %02x\r\n", packet.humidity, packet.humidity); } auto timeout_cb = []() { Serial.println("TIMEOUT..."); goSleep(DEFAULT_DEEP_SLEEP_S); }; void loop() { read_sensor(); if (master_mac[0] == 0x00 && master_mac[1] == 0x00) { goSleep(DEFAULT_DEEP_SLEEP_S); } else { espNow.enable_retries(true); Serial.println(millis()); espNow.send(master_mac, (u8*)&packet, sizeof (packet), timeout_cb, 3000); } delay(100); } void goSleep(uint32_t deepSleepS) { //Serial.printf("\r\nGo sleep for .. %lu seconds. \r\n", deepSleepS); ESP.deepSleep(deepSleepS * 1e6); }
[ "nat@cmmc.io" ]
nat@cmmc.io
2ecb6e0b420a06fb6da555507e63907253744ed6
40e1027a911cfbdea24d933d90d7038d3242b8f7
/CPP Projects/RAND.CPP
d8c9701720994d0f00bcb549a65b6cfdffd83c38
[]
no_license
vinodkotiya/Basics-of-C-for-Beginners
3f8154fa59f34e480480e9d4d0d391339ef41faa
d4be50ab9796c789e76bbffaa79475838b1316e0
refs/heads/main
2023-06-03T06:44:32.426242
2021-06-19T05:39:27
2021-06-19T05:39:27
378,332,591
0
0
null
null
null
null
UTF-8
C++
false
false
263
cpp
#include<iostream.h> #include<conio.h> #include<stdlib.h> #include<dos.h> void main() { clrscr(); char s; while(!kbhit()){s = 65+ random(8); if(s == 'B') s = 'S'; else if(s == 'C') s= 'J'; else if(s == 'E') s ='K'; cout<<s; delay(500);} getch(); }
[ "vinodkotiya@gmail.com" ]
vinodkotiya@gmail.com
99fe7313624ab0d404df9bce78f8e0be211b03ad
7146e34d91b9df8dce7ece9c06d9622c8ad95d02
/question_112 Path Sum.cc
77af5596b854179a2ac801197b96f2eeb3990f57
[]
no_license
snakeDling/LeetCode
5dcc45b26a6532e83f98a8c900018c128feab7a1
ecfdfe45e6987930d65150c6c7a4b1d1bf898f71
refs/heads/master
2021-01-15T16:29:13.372453
2018-06-19T07:16:00
2018-06-19T07:16:00
10,665,814
2
0
null
null
null
null
UTF-8
C++
false
false
765
cc
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool hasPathSum(TreeNode *root, int sum) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root == NULL) return false; if(root->left == NULL && root->right == NULL) return sum - root->val == 0; if(root->left != NULL) if(hasPathSum(root->left, sum - root->val)) return true; if(root->right != NULL) return hasPathSum(root->right, sum - root->val); else return false; } };
[ "228156980@qq.com" ]
228156980@qq.com
0a505a8e0020e100e1a0d83f1d5470ebe0dfaf00
4ab592fb354f75b42181d5375d485031960aaa7d
/DES_GOBSTG/DES_GOBSTG/Class/Player.cpp
2a59e185a0d1e2d558f110407142b35f07c87400
[]
no_license
CBE7F1F65/cca610e2e115c51cef211fafb0f66662
806ced886ed61762220b43300cb993ead00949dc
b3cdff63d689e2b1748e9cd93cedd7e8389a7057
refs/heads/master
2020-12-24T14:55:56.999923
2010-07-23T04:24:59
2010-07-23T04:24:59
32,192,699
0
0
null
null
null
null
UTF-8
C++
false
false
36,505
cpp
#include "../header/Player.h" #include "../header/Process.h" #include "../header/BGLayer.h" #include "../header/SE.h" #include "../header/PlayerBullet.h" #include "../header/Item.h" #include "../header/Enemy.h" #include "../header/Bullet.h" #include "../header/Chat.h" #include "../header/BossInfo.h" #include "../header/EffectIDDefine.h" #include "../header/SpriteItemManager.h" #include "../header/FrontDisplayName.h" #include "../header/FrontDisplay.h" #include "../header/EventZone.h" #include "../header/BResource.h" #include "../header/Scripter.h" #include "../header/GameInput.h" #include "../header/GameAI.h" #define _GAMERANK_MIN 8 #define _GAMERANK_MAX 22 #define _GAMERANK_ADDINTERVAL 9000 #define _GAMERANK_STAGEOVERADD -8 #define _PL_SHOOTCHARGEINFI_1 8 #define _PL_SHOOTCHARGEINFI_2 47 #define _PL_SHOOTCHARGEINFI_3 63 #define _PL_SHOOTCHARGEINFI_4 127 #define _PLAYER_DEFAULETCARDLEVEL_(X) (X?9:8) #define _PLAYER_DEFAULETBOSSLEVEL_(X) (X?9:8) #define _CARDLEVEL_ADDINTERVAL 3600 #define _BOSSLEVEL_ADDINTERVAL 3600 #define _CARDLEVEL_MAX 16 #define _BOSSLEVEL_MAX 16 #define _PLAYER_LIFECOSTMAX 2880 #define _PLAYER_COMBOHITMAX 999 #define _PLAYER_SHOOTPUSHOVER 9 #define _PLAYER_SHOOTNOTPUSHOVER 9 #define _PL_SPELLBONUS_BOSS_1 100000 #define _PL_SPELLBONUS_BOSS_2 300000 #define _PL_SPELLBONUS_BOSS_3 500000 Player Player::p[M_PL_MATCHMAXPLAYER]; float Player::lostStack = 0; bool Player::able = false; BYTE Player::rank = _GAMERANK_MIN; int Player::lilycount = 0; DWORD Player::alltime = 0; BYTE Player::raisespellstopplayerindex = 0; BYTE Player::round = 0; #define _PL_MERGETOPOS_X_(X) (M_GAMESQUARE_CENTER_X_(X)) #define _PL_MERGETOPOS_Y (M_GAMESQUARE_BOTTOM - 64) #define _PL_SHOOTINGCHARGE_1 0x01 #define _PL_SHOOTINGCHARGE_2 0x02 #define _PL_SHOOTINGCHARGE_3 0x04 #define _PL_SHOOTINGCHARGE_4 0x08 #define _PL_CHARGEZONE_R_2 188.0f #define _PL_CHARGEZONE_R_3 252.0f #define _PL_CHARGEZONE_R_4 444.5f #define _PL_CHARGEZONE_MAXTIME_2 49 #define _PL_CHARGEZONE_MAXTIME_3 65 #define _PL_CHARGEZONE_MAXTIME_4 129 Player::Player() { effGraze.exist = false; effChange.exist = false; effInfi.exist = false; effCollapse.exist = false; effMerge.exist = false; effBorder.exist = false; effBorderOn.exist = false; effBorderOff.exist = false; sprite = NULL; spdrain = NULL; nowID = 0; ID_sub_1 = 0; ID_sub_2 = 0; } Player::~Player() { SpriteItemManager::FreeSprite(&sprite); SpriteItemManager::FreeSprite(&spdrain); } void Player::ClearSet(BYTE _round) { x = PL_MERGEPOS_X_(playerindex); y = PL_MERGEPOS_Y; round = _round; for(int i=0;i<PL_SAVELASTMAX;i++) { lastx[i] = x; lasty[i] = y; lastmx[i] = x; lastmy[i] = y; } timer = 0; angle = 0; flag = PLAYER_MERGE; bSlow = false; bCharge = false; bDrain = false; bInfi = true; hscale = 1.0f; vscale = 1.0f; alpha = 0xff; diffuse = 0xffffff; mergetimer = 0; shottimer = 0; collapsetimer = 0; shoottimer = 0; draintimer = 0; chargetimer = 0; slowtimer = 0; fasttimer = 0; playerchangetimer = 0; costlifetimer = 0; shootchargetimer = 0; shootingchargeflag = 0; nowshootingcharge = 0; fExPoint = 0; nGhostPoint = 0; nBulletPoint = 0; nSpellPoint = 0; nLifeCost = 0; fCharge = 0; if (_round == 0) { fChargeMax = PLAYER_CHARGEONE; winflag = 0; } cardlevel = _PLAYER_DEFAULETCARDLEVEL_(_round); bosslevel = _PLAYER_DEFAULETBOSSLEVEL_(_round); nowcardlevel = cardlevel; nowbosslevel = bosslevel; infitimer = 0; rechargedelaytimer = 0; infireasonflag = 0; shootpushtimer = 0; shootnotpushtimer = 0; spellstoptimer = 0; speedfactor = 1.0f; // add // initlife = PLAYER_DEFAULTINITLIFE; exist = true; nComboHit = 0; nComboHitOri = 0; nComboGage = 0; nBounceAngle = 0; drainx = x; drainy = y; drainheadangle = 0; draintimer = 0; drainhscale = 1; drainvscale = 0; draincopyspriteangle = 0; if (effGraze.exist) { effGraze.Stop(true); effGraze.MoveTo(x, y, 0, true); } if (effChange.exist) { effChange.Stop(true); effChange.MoveTo(x, y, 0, true); } if (effInfi.exist) { effInfi.Stop(true); effInfi.MoveTo(x, y, 0, true); } if (effCollapse.exist) { effCollapse.Stop(true); effCollapse.MoveTo(x, y, 0, true); } if (effMerge.exist) { effMerge.Stop(true); effMerge.MoveTo(x, y, 0, true); } if (effBorder.exist) { effBorder.Stop(true); effBorder.MoveTo(x, y, 0, true); } if (effBorderOn.exist) { effBorderOn.Stop(true); effBorderOn.MoveTo(x, y, 0, true); } if (effBorderOff.exist) { effBorderOff.Stop(true); effBorderOff.MoveTo(x, y, 0, true); } changePlayerID(nowID, true); setShootingCharge(0); esChange.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERCHANGE, SpriteItemManager::GetIndexByName(SI_PLAYER_SHOTITEM), x, y, 0, 3.0f); esChange.colorSet(0x7fffffff, BLEND_ALPHAADD); esChange.chaseSet(EFFSP_CHASE_PLAYER_(playerindex), 0, 0); esShot.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERSHOT, SpriteItemManager::GetIndexByName(SI_PLAYER_SHOTITEM), x, y, 0, 1.2f); esShot.colorSet(0xccff0000); esShot.chaseSet(EFFSP_CHASE_PLAYER_(playerindex), 0, 0); esPoint.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERPOINT, SpriteItemManager::GetIndexByName(SI_PLAYER_POINT), x, y); esPoint.chaseSet(EFFSP_CHASE_PLAYER_(playerindex), 0, 0); esCollapse.valueSet(EFFSPSET_PLAYERUSE, EFFSP_PLAYERCOLLAPSE, SpriteItemManager::GetIndexByName(SI_PLAYER_SHOTITEM), x, y); esCollapse.actionSet(0, 0, 160); esCollapse.colorSet(0x80ffffff); } void Player::ClearRound(BYTE round/* =0 */) { raisespellstopplayerindex = 0xff; if (round) { rank += _GAMERANK_STAGEOVERADD; if (rank < _GAMERANK_MIN) { rank = _GAMERANK_MIN; } AddLilyCount(-1000); for (int i=0; i<M_PL_MATCHMAXPLAYER; i++) { p[i].valueSet(i, round); } } else { rank = _GAMERANK_MIN; lilycount = 0; alltime = 0; } } //add void Player::valueSet(BYTE _playerindex, BYTE round) { playerindex = _playerindex; nowID = ID; ClearSet(round); initFrameIndex(); UpdatePlayerData(); SetDrainSpriteInfo(x, y); nLife = initlife; if (round == 0) { lostStack = 0; } setFrame(PLAYER_FRAME_STAND); effGraze.valueSet(EFF_PL_GRAZE, playerindex, *this); effGraze.Stop(); effChange.valueSet(EFF_PL_CHANGE, playerindex, *this); effChange.Stop(); effInfi.valueSet(EFF_PL_INFI, playerindex, *this); effInfi.Stop(); effCollapse.valueSet(EFF_PL_COLLAPSE, playerindex, *this); effCollapse.Stop(); effMerge.valueSet(EFF_PL_MERGE, playerindex, *this); effMerge.Stop(); effBorder.valueSet(EFF_PL_BORDER, playerindex, *this); effBorder.Stop(); effBorderOn.valueSet(EFF_PL_BORDERON, playerindex, *this); effBorderOn.Stop(); effBorderOff.valueSet(EFF_PL_BORDEROFF, playerindex, *this); effBorderOff.Stop(); SetAble(true); } bool Player::Action() { alltime++; AddLostStack(); for (int i=0; i<M_PL_MATCHMAXPLAYER; i++) { if (gametime % _CARDLEVEL_ADDINTERVAL == 0) { p[i].AddCardBossLevel(1, 0); } if (gametime % _BOSSLEVEL_ADDINTERVAL == 0) { p[i].AddCardBossLevel(0, 1); } DWORD stopflag = Process::mp.GetStopFlag(); bool binstop = FRAME_STOPFLAGCHECK_PLAYERINDEX_(stopflag, i, FRAME_STOPFLAG_PLAYER); bool binspellstop = FRAME_STOPFLAGCHECK_PLAYERINDEX_(stopflag, i, FRAME_STOPFLAG_PLAYERSPELL); GameInput::gameinput[i].updateActiveInput(binspellstop); if (p[i].exist) { if (!binstop && !binspellstop) { p[i].action(); } else if (binspellstop) { p[i].actionInSpellStop(); } else { p[i].actionInStop(); } if (!p[i].exist) { return false; } } } if (gametime % _GAMERANK_ADDINTERVAL == 0) { rank++; if (rank > _GAMERANK_MAX) { rank = _GAMERANK_MAX; } } AddLilyCount(0, true); return true; } void Player::action() { float nowspeed = 0; timer++; alpha = 0xff; if(timer == 1) flag |= PLAYER_MERGE; //savelast if(lastmx[0] != x || lastmy[0] != y) { for(int i=PL_SAVELASTMAX-1;i>0;i--) { lastmx[i] = lastmx[i-1]; lastmy[i] = lastmy[i-1]; } lastmx[0] = x; lastmy[0] = y; } for(int i=PL_SAVELASTMAX-1;i>0;i--) { lastx[i] = lastx[i-1]; lasty[i] = lasty[i-1]; } lastx[0] = x; lasty[0] = y; //AI // GameAI::ai[playerindex].UpdateBasicInfo(x, y, speed, slowspeed, BResource::bres.playerdata[nowID].collision_r); GameAI::ai[playerindex].SetMove(); // if(flag & PLAYER_MERGE) { if(Merge()) { flag &= ~PLAYER_MERGE; } } if(flag & PLAYER_SHOT) { if(Shot()) { flag &= ~PLAYER_SHOT; } } if (flag & PLAYER_COSTLIFE) { if (CostLife()) { flag &= ~PLAYER_COSTLIFE; } } if(flag & PLAYER_COLLAPSE) { if(Collapse()) { flag &= ~PLAYER_COLLAPSE; return; } } if(flag & PLAYER_SLOWCHANGE) { if(SlowChange()) { flag &= ~PLAYER_SLOWCHANGE; } } if(flag & PLAYER_FASTCHANGE) { if(FastChange()) { flag &= ~PLAYER_FASTCHANGE; } } if(flag & PLAYER_PLAYERCHANGE) { if(PlayerChange()) { flag &= ~PLAYER_PLAYERCHANGE; } } if(flag & PLAYER_SHOOT) { if(Shoot()) { flag &= ~PLAYER_SHOOT; } } if(flag & PLAYER_BOMB) { if(Bomb()) { flag &= ~PLAYER_BOMB; } } if(flag & PLAYER_DRAIN) { if(Drain()) { flag &= ~PLAYER_DRAIN; } } if (flag & PLAYER_CHARGE) { if (Charge()) { flag &= ~PLAYER_CHARGE; } } if(flag & PLAYER_GRAZE) { if(Graze()) { flag &= ~PLAYER_GRAZE; } } nLifeCost++; if (nLifeCost > _PLAYER_LIFECOSTMAX) { nLifeCost = _PLAYER_LIFECOSTMAX; } if (rechargedelaytimer) { rechargedelaytimer--; } if (shootchargetimer) { Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSHOOTCHARGEONE, playerindex); PlayerBullet::BuildShoot(playerindex, nowID, shootchargetimer, true); shootchargetimer--; } if (infitimer > 0) { infitimer--; bInfi = true; } else if (infitimer == PLAYER_INFIMAX) { bInfi = true; } else { bInfi = false; } if (nComboGage) { nComboGage--; if (nComboGage == PLAYER_COMBORESET) { AddComboHit(-1, true); } else if (!nComboGage) { AddSpellPoint(-1); } } for (list<EventZone>::iterator it=EventZone::ezone[playerindex].begin(); it!=EventZone::ezone[playerindex].end(); it++) { if (it->timer < 0) { continue; } if ((it->type) & EVENTZONE_TYPEMASK_PLAYER) { if (it->isInRect(x, y, r)) { if (it->type & EVENTZONE_TYPE_PLAYERDAMAGE) { DoShot(); } if (it->type & EVENTZONE_TYPE_PLAYEREVENT) { } if (it->type & EVENTZONE_TYPE_PLAYERSPEED) { speedfactor = it->power; } } } } //input if(!(flag & PLAYER_SHOT || flag & PLAYER_COLLAPSE)) { if (GameInput::GetKey(playerindex, KSI_SLOW)) { bSlow = true; flag &= ~PLAYER_FASTCHANGE; if (GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_DOWN)) { if (!(flag & PLAYER_SLOWCHANGE)) { slowtimer = 0; flag |= PLAYER_SLOWCHANGE; } } } else { bSlow = false; flag &= ~PLAYER_SLOWCHANGE; if (GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_UP)) { if (!(flag & PLAYER_FASTCHANGE)) { fasttimer = 0; flag |= PLAYER_FASTCHANGE; } } } if(bSlow) { nowspeed = slowspeed; } else { nowspeed = speed; } nowspeed *= speedfactor; if(GameInput::GetKey(playerindex, KSI_FIRE)) { if (!Chat::chatitem.IsChatting()) { flag |= PLAYER_SHOOT; } shootnotpushtimer = 0; } else { if (shootnotpushtimer < 0xff) { shootnotpushtimer++; } } if (shootpushtimer < _PLAYER_SHOOTPUSHOVER) { if (GameInput::GetKey(playerindex, KSI_FIRE)) { shootpushtimer++; } else { shootpushtimer = 0; } } else { if (!GameInput::GetKey(playerindex, KSI_FIRE)) { bCharge = false; flag &= ~PLAYER_CHARGE; shootpushtimer = 0; } else { if (!rechargedelaytimer) { flag &= ~PLAYER_SHOOT; bCharge = true; if (shootpushtimer >= _PLAYER_SHOOTPUSHOVER && !(flag & PLAYER_CHARGE)) { chargetimer = 0; flag |= PLAYER_CHARGE; shootpushtimer = 0xff; } } } } if (GameInput::GetKey(playerindex, KSI_DRAIN)) { bDrain = true; if (GameInput::GetKey(playerindex, KSI_DRAIN, DIKEY_DOWN)) { if (!(flag & PLAYER_DRAIN)) { draintimer = 0; SetDrainSpriteInfo(x, y, 0, 0); } } flag |= PLAYER_DRAIN; } else { bDrain = false; flag &= ~PLAYER_DRAIN; } if((GameInput::GetKey(playerindex, KSI_UP) ^ GameInput::GetKey(playerindex, KSI_DOWN)) && GameInput::GetKey(playerindex, KSI_LEFT) ^ GameInput::GetKey(playerindex, KSI_RIGHT)) nowspeed *= M_SQUARE_2; if(GameInput::GetKey(playerindex, KSI_UP)) y -= nowspeed; if(GameInput::GetKey(playerindex, KSI_DOWN)) y += nowspeed; if(GameInput::GetKey(playerindex, KSI_LEFT)) { updateFrame(PLAYER_FRAME_LEFTPRE); x -= nowspeed; } if(GameInput::GetKey(playerindex, KSI_RIGHT)) { if (!GameInput::GetKey(playerindex, KSI_LEFT)) { updateFrame(PLAYER_FRAME_RIGHTPRE); } else { updateFrame(PLAYER_FRAME_STAND); } x += nowspeed; } if (!GameInput::GetKey(playerindex, KSI_LEFT) && !GameInput::GetKey(playerindex, KSI_RIGHT)) { updateFrame(PLAYER_FRAME_STAND); } } if(GameInput::GetKey(playerindex, KSI_QUICK) && !(flag & PLAYER_MERGE)) { callBomb(); } if (!(flag & PLAYER_MERGE) || mergetimer >= 32) { if(x > PL_MOVABLE_RIGHT_(playerindex)) x = PL_MOVABLE_RIGHT_(playerindex); else if(x < PL_MOVABLE_LEFT_(playerindex)) x = PL_MOVABLE_LEFT_(playerindex); if(y > PL_MOVABLE_BOTTOM) y = PL_MOVABLE_BOTTOM; else if(y < PL_MOVABLE_TOP) y = PL_MOVABLE_TOP; } //AI GameAI::ai[playerindex].UpdateBasicInfo(x, y, speed*speedfactor, slowspeed*speedfactor, r, BResource::bres.playerdata[nowID].aidraintime); float aiaimx = _PL_MERGETOPOS_X_(playerindex); float aiaimy = _PL_MERGETOPOS_Y; bool tobelow = false; if (PlayerBullet::activelocked[playerindex] != PBLOCK_LOST) { aiaimx = Enemy::en[playerindex][PlayerBullet::activelocked[playerindex]].x; aiaimy = Enemy::en[playerindex][PlayerBullet::activelocked[playerindex]].y + 120; tobelow = true; } else if (PlayerBullet::locked[playerindex] != PBLOCK_LOST) { aiaimx = Enemy::en[playerindex][PlayerBullet::locked[playerindex]].x; aiaimy = Enemy::en[playerindex][PlayerBullet::locked[playerindex]].y; } GameAI::ai[playerindex].SetAim(aiaimx, aiaimy, tobelow); // // speedfactor = 1.0f; if (bInfi && timer % 8 < 4) { diffuse = 0xff99ff; } else diffuse = 0xffffff; esChange.action(); esShot.action(); esPoint.action(); effGraze.MoveTo(x, y); effGraze.action(); effCollapse.action(); effBorderOn.action(); effBorderOff.action(); if(!(flag & PLAYER_GRAZE)) effGraze.Stop(); for(int i=0;i<PLAYERGHOSTMAX;i++) { if (pg[i].exist) { pg[i].action(); } } } void Player::actionInSpellStop() { spellstoptimer++; Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERINSPELLSTOP, playerindex); } void Player::actionInStop() { // Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERINSTOP, playerindex); } bool Player::Merge() { mergetimer++; if(mergetimer == 1) { SetInfi(PLAYERINFI_MERGE, 60); if(GameInput::GetKey(playerindex, KSI_SLOW)) { flag |= PLAYER_SLOWCHANGE; slowtimer = 0; flag &= ~PLAYER_FASTCHANGE; } else { flag |= PLAYER_FASTCHANGE; fasttimer = 0; flag &= ~PLAYER_SLOWCHANGE; } } else if (mergetimer <= 24) { float interval = mergetimer / 24.0f; x = INTER(PL_MERGEPOS_X_(playerindex), _PL_MERGETOPOS_X_(playerindex), interval); y = INTER(PL_MERGEPOS_Y, _PL_MERGETOPOS_Y, interval); flag &= ~PLAYER_SHOOT; alpha = INTER(0, 0xff, interval); } else if(mergetimer < 60) { alpha = 0xff; } else if(mergetimer == 60) { mergetimer = 0; return true; } return false; } bool Player::Shot() { shottimer++; // TODO: if(bInfi) { shottimer = 0; return true; } if(shottimer == 1) { // Item::undrainAll(); SE::push(SE_PLAYER_SHOT, x); } else if(shottimer == shotdelay) { shottimer = 0; flag |= PLAYER_COSTLIFE; return true; } esShot.hscale = (shotdelay - shottimer) * 4.0f / shotdelay; Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSHOT, playerindex); return false; } bool Player::CostLife() { costlifetimer++; if (costlifetimer == 1) { AddLilyCount(-1500); if (nLife == 1) { nLife = 0; flag |= PLAYER_COLLAPSE; costlifetimer = 0; return true; } int nLifeCostNum = nLifeCost / 720 + 2; if (nLife > nLifeCostNum+1) { nLife -= nLifeCostNum; } else { FrontDisplay::fdisp.gameinfodisplay.lastlifecountdown[playerindex] = FDISP_COUNTDOWNTIME; SE::push(SE_PLAYER_ALERT, x); nLife = 1; } nLifeCost -= 1440; if (nLifeCost < 0) { nLifeCost = 0; } SetInfi(PLAYERINFI_COSTLIFE, 120); if (nLife == 1) { AddCharge(0, PLAYER_CHARGEMAX); } else { AddCharge(0, 130-nLife * 10); } nBounceAngle = randt(); } else if (costlifetimer == 50) { EventZone::Build(EVENTZONE_TYPE_BULLETFADEOUT|EVENTZONE_TYPE_ENEMYDAMAGE|EVENTZONE_TYPE_NOSEND|EVENTZONE_CHECKTYPE_CIRCLE, playerindex, x, y, 10, 0, 0, 10, EVENTZONE_EVENT_NULL, 15.6); } else if (costlifetimer == 60) { costlifetimer = 0; return true; } else { GameInput::SetKey(playerindex, KSI_UP, false); GameInput::SetKey(playerindex, KSI_DOWN, false); GameInput::SetKey(playerindex, KSI_LEFT, false); GameInput::SetKey(playerindex, KSI_RIGHT, false); // GameInput::SetKey(playerindex, KSI_FIRE, false); GameInput::SetKey(playerindex, KSI_QUICK, false); GameInput::SetKey(playerindex, KSI_SLOW, false); GameInput::SetKey(playerindex, KSI_DRAIN, false); x += cost(nBounceAngle) * ((60-costlifetimer) / 20.0f); y += sint(nBounceAngle) * ((60-costlifetimer) / 20.0f); } return false; } bool Player::Collapse() { collapsetimer++; if(collapsetimer == 1) { for (int i=0; i<M_PL_MATCHMAXPLAYER; i++) { EventZone::Build(EVENTZONE_TYPE_BULLETFADEOUT|EVENTZONE_TYPE_ENEMYDAMAGE|EVENTZONE_TYPE_NOSEND|EVENTZONE_CHECKTYPE_CIRCLE, i, p[i].x, p[i].y, 64, EVENTZONE_OVERZONE, 0, 1000, EVENTZONE_EVENT_NULL, 16); p[i].SetInfi(PLAYERINFI_COLLAPSE, 64); } esCollapse.x = x; esCollapse.y = y; SE::push(SE_PLAYER_DEAD, x); effCollapse.MoveTo(x, y , 0, true); effCollapse.Fire(); p[1-playerindex].winflag |= 1<<round; } else if(collapsetimer == 64) { x = PL_MERGEPOS_X_(playerindex); y = PL_MERGEPOS_Y; for(int i=0;i<PL_SAVELASTMAX;i++) { lastx[i] = x; lasty[i] = y; lastmx[i] = x; lastmy[i] = y; } timer = 0; collapsetimer = 0; vscale = 1.0f; flag |= PLAYER_MERGE; AddCharge(0, 130); // SetInfi(PLAYERINFI_COLLAPSE); exist = false; if(GameInput::GetKey(playerindex, KSI_SLOW)) { flag |= PLAYER_SLOWCHANGE; slowtimer = 0; flag &= ~PLAYER_FASTCHANGE; } else { flag |= PLAYER_FASTCHANGE; fasttimer = 0; flag &= ~PLAYER_SLOWCHANGE; } effCollapse.Stop(); return true; } esCollapse.hscale = collapsetimer / 1.5f; esCollapse.alpha = (BYTE)((WORD)(0xff * collapsetimer) / 0x3f); esCollapse.colorSet(0xff0000); alpha = (0xff - collapsetimer * 4); vscale = (float)(collapsetimer)/40.0f + 1.0f; return false; } bool Player::Shoot() { if(Chat::chatitem.IsChatting()) { shoottimer = 0; return true; } if (!(flag & PLAYER_SHOT) && !(flag & PLAYER_COSTLIFE)) { PlayerBullet::BuildShoot(playerindex, nowID, shoottimer); } shoottimer++; // if(shootnotpushtimer > _PLAYER_SHOOTNOTPUSHOVER) { shoottimer = 0; return true; } return false; } bool Player::Drain() { draintimer++; bDrain = true; Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERDRAIN, playerindex); return false; } bool Player::Bomb() { BYTE ncharge; BYTE nchargemax; GetNCharge(&ncharge, &nchargemax); if (nchargemax > 1) { BYTE nChargeLevel = shootCharge(nchargemax, true); if (nChargeLevel == nchargemax) { AddCharge(-PLAYER_CHARGEMAX, -PLAYER_CHARGEMAX); } else { AddCharge((nChargeLevel-nchargemax)*PLAYER_CHARGEONE, (nChargeLevel-nchargemax)*PLAYER_CHARGEONE); } } return true; } bool Player::SlowChange() { if(GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_DOWN)) slowtimer = 0; bSlow = true; slowtimer++; if(slowtimer == 1) { ResetPlayerGhost(); SE::push(SE_PLAYER_SLOWON, x); for(int i=0;i<PLAYERGHOSTMAX;i++) { pg[i].timer = 0; } } else if(slowtimer == 16) { esPoint.colorSet(0xffffffff); slowtimer = 0; return true; } esPoint.actionSet(0, 0, (24 - slowtimer) * 25); esPoint.colorSet(((slowtimer*16)<<24)+0xffffff); return false; } bool Player::FastChange() { if(GameInput::GetKey(playerindex, KSI_SLOW, DIKEY_UP)) fasttimer = 0; bSlow = false; fasttimer++; if(fasttimer == 1) { ResetPlayerGhost(); SE::push(SE_PLAYER_SLOWOFF, x); for(int i=0;i<PLAYERGHOSTMAX;i++) { pg[i].timer = 0; } } else if(fasttimer == 16) { esPoint.colorSet(0x00ffffff); fasttimer = 0; return true; } esPoint.colorSet(((0xff-fasttimer*16)<<24)+0xffffff); return false; } bool Player::Charge() { chargetimer++; if (chargetimer == 1) { SE::push(SE_PLAYER_CHARGEON, x); } BYTE nChargeLevel = AddCharge(chargespeed); if (!GameInput::GetKey(playerindex, KSI_FIRE)) { shootCharge(nChargeLevel); chargetimer = 0; fCharge = 0; if (nChargeLevel > 0) { rechargedelaytimer = rechargedelay; } return true; } bCharge = true; return false; } bool Player::PlayerChange() { if(GameInput::GetKey(playerindex, KSI_DRAIN, DIKEY_DOWN)) playerchangetimer = 0; playerchangetimer++; if(playerchangetimer == 1) { } else if(playerchangetimer == 16) { playerchangetimer = 0; return true; } esChange.colorSet(0x3030ff | (((16-playerchangetimer) * 16)<<16)); return false; } void Player::changePlayerID(WORD toID, bool moveghost/* =false */) { nowID = toID; ResetPlayerGhost(moveghost); UpdatePlayerData(); } bool Player::Graze() { effGraze.Fire(); SE::push(SE_PLAYER_GRAZE, x); return true; } void Player::DoEnemyCollapse(float x, float y, BYTE type) { float addcharge = nComboHitOri / 128.0f + 1.0f; if (addcharge > 2.0f) { addcharge = 2.0f; } AddComboHit(1, true); AddCharge(0, addcharge); enemyData * edata = &(BResource::bres.enemydata[type]); AddExPoint(edata->expoint, x, y); int addghostpoint; if (edata->ghostpoint < 0) { addghostpoint = nComboHitOri + 3; if (addghostpoint > 28) { addghostpoint = 28; } } else { addghostpoint = edata->ghostpoint; } AddGhostPoint(addghostpoint, x, y); int addbulletpoint; float _x = x + randtf(-4.0f, 4.0f); float _y = y + randtf(-4.0f, 4.0f); if (edata->bulletpoint < 0) { addbulletpoint = nComboHitOri * 3 + 27; if (addbulletpoint > 60) { addbulletpoint = 60; } } else { addbulletpoint = edata->bulletpoint; } AddBulletPoint(addbulletpoint, _x, _y); int addspellpoint; if (edata->spellpoint == -1) { if (nComboHitOri == 1) { addspellpoint = 20; } else { addspellpoint = nComboHitOri * 30 - 20; if (addspellpoint > 3000) { addspellpoint = 3000; } } } else if (edata->spellpoint == -2) { if (nComboHitOri == 1) { addspellpoint = 2000; } else { addspellpoint = (nComboHitOri + 4) * 200; if (addspellpoint > 11000) { addspellpoint = 11000; } } } else { addspellpoint = edata->spellpoint; } AddSpellPoint(addspellpoint); } void Player::DoGraze(float x, float y) { if(!(flag & (PLAYER_MERGE | PLAYER_SHOT | PLAYER_COLLAPSE))) { flag |= PLAYER_GRAZE; } } void Player::DoPlayerBulletHit(int hitonfactor) { if (hitonfactor < 0) { AddComboHit(-1, true); } } void Player::DoSendBullet(float x, float y, int sendbonus) { for (int i=0; i<sendbonus; i++) { AddComboHit(1, false); AddGhostPoint(2, x, y); AddBulletPoint(3, x, y); int addspellpoint = nComboHitOri * 9; if (addspellpoint > 1000) { addspellpoint = 1000; } AddSpellPoint(addspellpoint); } } void Player::DoShot() { if (!bInfi && !(flag & (PLAYER_SHOT | PLAYER_COLLAPSE))) { flag |= PLAYER_SHOT; AddComboHit(-1, true); AddSpellPoint(-1); } } void Player::DoItemGet(WORD itemtype, float _x, float _y) { switch (itemtype) { case ITEM_GAUGE: AddCharge(0, PLAYER_CHARGEMAX); break; case ITEM_BULLET: Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSENDITEMBULLET, playerindex); // Item::SendBullet(1-playerindex, _x, _y, EFFSPSET_SYSTEM_SENDITEMBULLET); break; case ITEM_EX: AddBulletPoint(1, _x, _y); AddExPoint(100, _x, _y); break; case ITEM_POINT: AddSpellPoint(70000+rank*7000); break; } } void Player::GetNCharge(BYTE * ncharge, BYTE * nchargemax) { if (ncharge) { *ncharge = (BYTE)(fCharge/PLAYER_CHARGEONE); } if (nchargemax) { *nchargemax = (BYTE)(fChargeMax/PLAYER_CHARGEONE); } } void Player::GetSpellClassAndLevel(BYTE * spellclass, BYTE * spelllevel, int _shootingchargeflag) { BYTE usingshootingchargeflag = shootingchargeflag; if (_shootingchargeflag > 0) { usingshootingchargeflag = _shootingchargeflag; } if (spellclass) { if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_4) { if ((usingshootingchargeflag & _PL_SHOOTINGCHARGE_3) || (usingshootingchargeflag & _PL_SHOOTINGCHARGE_2)) { *spellclass = 4; } else { *spellclass = 3; } } else if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_3) { *spellclass = 2; } else if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_2) { *spellclass = 1; } else { *spellclass = 0; } } if (spelllevel) { if (usingshootingchargeflag & _PL_SHOOTINGCHARGE_4) { *spelllevel = nowbosslevel; } else if(usingshootingchargeflag) { *spelllevel = nowcardlevel; } else { *spelllevel = 0; } } } void Player::ResetPlayerGhost(bool move /* = false */) { int tid = nowID; tid *= PLAYERGHOSTMAX * 2; if (bSlow) { tid += PLAYERGHOSTMAX; } for (int i=0; i<PLAYERGHOSTMAX; i++) { pg[i].valueSet(playerindex, tid+i, move); } } void Player::Render() { if (spdrain && bDrain) { SpriteItemManager::RenderSpriteEx(spdrain, drainx, drainy, ARC(drainheadangle), drainhscale, drainvscale); if (draincopyspriteangle) { SpriteItemManager::RenderSpriteEx(spdrain, drainx, drainy, ARC(drainheadangle+draincopyspriteangle), drainhscale, drainvscale); } } if (sprite) { sprite->SetColor(alpha<<24|diffuse); SpriteItemManager::RenderSpriteEx(sprite, x, y, 0, hscale, vscale); } } void Player::RenderEffect() { effGraze.Render(); for(int i=0;i<PLAYERGHOSTMAX;i++) { if (pg[i].exist) { pg[i].Render(); } } if(flag & PLAYER_PLAYERCHANGE) { esChange.Render(); } if(flag & PLAYER_SHOT) esShot.Render(); effBorderOff.Render(); if(bSlow || flag & PLAYER_FASTCHANGE) { esPoint.Render(); esPoint.headangle = -esPoint.headangle; esPoint.Render(); esPoint.headangle = -esPoint.headangle; } if(flag & PLAYER_COLLAPSE) esCollapse.Render(); effCollapse.Render(); } void Player::callCollapse() { if (flag & PLAYER_COLLAPSE) { return; } flag |= PLAYER_COLLAPSE; collapsetimer = 0; } bool Player::callBomb() { if (Chat::chatitem.IsChatting() || (flag & PLAYER_COLLAPSE)) { return false; } return Bomb(); } void Player::callSlowFastChange(bool toslow) { if (toslow) { GameInput::SetKey(playerindex, KSI_SLOW); } else { GameInput::SetKey(playerindex, KSI_SLOW, false); } } void Player::callPlayerChange() { flag |= PLAYER_PLAYERCHANGE; playerchangetimer = 0; } void Player::setShootingCharge(BYTE _shootingchargeflag) { if (!_shootingchargeflag) { shootingchargeflag = 0; } else { shootingchargeflag |= _shootingchargeflag; if (shootingchargeflag & _PL_SHOOTINGCHARGE_1) { shootchargetimer = BResource::bres.playerdata[nowID].shootchargetime; } if (_shootingchargeflag & ~_PL_SHOOTINGCHARGE_1) { nowshootingcharge = _shootingchargeflag; if (_shootingchargeflag & _PL_SHOOTINGCHARGE_4) { nowbosslevel = bosslevel; } else { nowcardlevel = cardlevel; } Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSHOOTCHARGE, playerindex); } } } BYTE Player::shootCharge(BYTE nChargeLevel, bool nodelete) { if (flag & PLAYER_COLLAPSE) { return 0; } if (!nChargeLevel) { return 0; } if (nChargeLevel > 3 && nChargeLevel < 7 && Enemy::bossindex[1-playerindex] != 0xff) { if (nChargeLevel == 4) { return shootCharge(3, nodelete); } else if (nChargeLevel == 6) { return shootCharge(7, nodelete); } return 0; } setShootingCharge(0); int chargezonemaxtime=1; float chargezoner=0; switch (nChargeLevel) { case 1: SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_1); setShootingCharge(_PL_SHOOTINGCHARGE_1); // AddCardBossLevel(1, 0); break; case 2: SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_2); if (!nodelete) { setShootingCharge(_PL_SHOOTINGCHARGE_1); } setShootingCharge(_PL_SHOOTINGCHARGE_2); AddCardBossLevel(1, 0); chargezonemaxtime = _PL_CHARGEZONE_MAXTIME_2; chargezoner = _PL_CHARGEZONE_R_2; break; case 3: SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_3); if (!nodelete) { setShootingCharge(_PL_SHOOTINGCHARGE_1); } setShootingCharge(_PL_SHOOTINGCHARGE_3); AddCardBossLevel(1, 0); chargezonemaxtime = _PL_CHARGEZONE_MAXTIME_3; chargezoner = _PL_CHARGEZONE_R_3; break; case 4: SetInfi(PLAYERINFI_SHOOTCHARGE, _PL_SHOOTCHARGEINFI_4); if (!nodelete) { setShootingCharge(_PL_SHOOTINGCHARGE_1); } setShootingCharge(_PL_SHOOTINGCHARGE_4); AddCardBossLevel(0, 1); chargezonemaxtime = _PL_CHARGEZONE_MAXTIME_4; chargezoner = _PL_CHARGEZONE_R_4; break; case 5: setShootingCharge(_PL_SHOOTINGCHARGE_4); AddCardBossLevel(0, 1); break; case 6: setShootingCharge(_PL_SHOOTINGCHARGE_3); setShootingCharge(_PL_SHOOTINGCHARGE_4); AddCardBossLevel(1, 1); break; case 7: setShootingCharge(_PL_SHOOTINGCHARGE_3); AddCardBossLevel(1, 0); break; } if (nChargeLevel > 1) { raisespellstopplayerindex = playerindex; spellstoptimer = 0; Process::mp.SetStop(FRAME_STOPFLAG_SPELLSET|FRAME_STOPFLAG_PLAYERINDEX_0|FRAME_STOPFLAG_PLAYERINDEX_1, PL_SHOOTINGCHARGE_STOPTIME); if (chargezoner) { EventZone::Build(EVENTZONE_TYPE_BULLETFADEOUT|EVENTZONE_TYPE_ENEMYDAMAGE|EVENTZONE_TYPE_NOSEND|EVENTZONE_CHECKTYPE_CIRCLE, playerindex, x, y, chargezonemaxtime, 0, 0, 10, EVENTZONE_EVENT_NULL, chargezoner/chargezonemaxtime, -2, SpriteItemManager::GetIndexByName(SI_PLAYER_CHARGEZONE), 400); } if (nChargeLevel < 5) { AddCharge(-PLAYER_CHARGEONE*(nChargeLevel-1), -PLAYER_CHARGEONE*(nChargeLevel-1)); } AddLilyCount(-500); FrontDisplay::fdisp.OnShootCharge(playerindex, nowshootingcharge); } return nChargeLevel; } void Player::SendEx(BYTE playerindex, float x, float y) { int _esindex = EffectSp::Build(EFFSPSET_SYSTEM_SENDEXATTACK, playerindex, EffectSp::senditemexsiid, x, y); if (_esindex >= 0) { Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSENDEX, playerindex); SE::push(SE_BULLET_SENDEX, x); } } void Player::AddExPoint(float expoint, float x, float y) { fExPoint += expoint; float fexsend = fExSendParaB + fExSendParaA * rank; if (fexsend < fExSendMax) { fexsend = fExSendMax; } if (fExPoint >= fexsend) { AddExPoint(-fexsend, x, y); SendEx(1-playerindex, x, y); } } void Player::AddGhostPoint(int ghostpoint, float x, float y) { nGhostPoint += ghostpoint; if (nGhostPoint >= 60-rank*1.5f) { if (nBulletPoint >= 10) { AddGhostPoint(-(60-rank*2), x, y); AddBulletPoint(-10, x, y); Enemy::SendGhost(1-playerindex, x, y, EFFSPSET_SYSTEM_SENDGHOST); } } } void Player::AddBulletPoint(int bulletpoint, float x, float y) { nBulletPoint += bulletpoint * 4 / 3; if (nBulletPoint >= 120-rank*4) { AddBulletPoint(-(120-rank*4), x, y); BYTE setID = EFFSPSET_SYSTEM_SENDBLUEBULLET; if (randt(0, 2) == 0) { setID = EFFSPSET_SYSTEM_SENDREDBULLET; } Bullet::SendBullet(1-playerindex, x, y, setID); } } void Player::AddSpellPoint(int spellpoint) { if (spellpoint < 0) { nSpellPoint = 0; return; } spellpoint = spellpoint * rank / 10 + spellpoint; int spellpointone = spellpoint % 10; if (spellpointone) { spellpoint += 10-spellpointone; } if (nSpellPoint < _PL_SPELLBONUS_BOSS_1 && nSpellPoint + spellpoint >= _PL_SPELLBONUS_BOSS_1 || nSpellPoint < _PL_SPELLBONUS_BOSS_2 && nSpellPoint + spellpoint >= _PL_SPELLBONUS_BOSS_2) { shootCharge(5); } else if (nSpellPoint < _PL_SPELLBONUS_BOSS_3 && nSpellPoint + spellpoint >= _PL_SPELLBONUS_BOSS_3) { shootCharge(6); } nSpellPoint += spellpoint; if (nSpellPoint > PLAYER_NSPELLPOINTMAX) { nSpellPoint = PLAYER_NSPELLPOINTMAX; } } void Player::AddComboHit(int combo, bool ori) { if (combo < 0) { nComboHit = 0; nComboHitOri = 0; return; } nComboHit += combo; if (nComboHit > PLAYER_NCOMBOHITMAX) { nComboHit = PLAYER_NCOMBOHITMAX; } if (ori) { nComboHitOri += combo; if (nComboHitOri > PLAYER_NCOMBOHITMAX) { nComboHitOri = PLAYER_NCOMBOHITMAX; } } if (nComboGage < 74) { nComboGage += 30; if (nComboGage < 74) { nComboGage = 74; } } else if (nComboGage < 94) { nComboGage += 5; } else { nComboGage += 2; } if (nComboGage > PLAYER_COMBOGAGEMAX) { nComboGage = PLAYER_COMBOGAGEMAX; } } BYTE Player::AddCharge(float addcharge, float addchargemax) { BYTE ncharge; BYTE nchargemax; GetNCharge(&ncharge, &nchargemax); float addchargemaxval = addchargemax; if (addchargemax > 0) { addchargemaxval = addchargemax * BResource::bres.playerdata[nowID].addchargerate; } fChargeMax += addchargemaxval; if (fChargeMax > PLAYER_CHARGEMAX) { fChargeMax = PLAYER_CHARGEMAX; } if (fChargeMax < 0) { fChargeMax = 0; } fCharge += addcharge; if (fCharge > fChargeMax) { fCharge = fChargeMax; } if (fCharge < 0) { fCharge = 0; } BYTE nchargenow; BYTE nchargemaxnow; GetNCharge(&nchargenow, &nchargemaxnow); if (nchargenow > ncharge) { SE::push(SE_PLAYER_CHARGEUP); } if (nchargemaxnow > nchargemax) { FrontDisplay::fdisp.gameinfodisplay.gaugefilledcountdown[playerindex] = FDISP_COUNTDOWNTIME; } return nchargenow; } void Player::AddLilyCount(int addval, bool bytime/* =false */) { if (bytime) { if (gametime < 5400) { AddLilyCount(gametime/1800+3); } else { AddLilyCount(7); } } lilycount += addval; if (lilycount > 10000) { Scripter::scr.Execute(SCR_EVENT, SCR_EVENT_PLAYERSENDLILY, rank); AddLilyCount(-10000); } else if (lilycount < 0) { lilycount = 0; } } void Player::AddCardBossLevel(int cardleveladd, int bossleveladd) { cardlevel += cardleveladd; bosslevel += bossleveladd; if (cardlevel > _CARDLEVEL_MAX) { cardlevel = _CARDLEVEL_MAX; } if (bosslevel > _BOSSLEVEL_MAX) { bosslevel = _BOSSLEVEL_MAX; } }
[ "CBE7F1F65@4a173d03-4959-223b-e14c-e2eaa5fc8a8b" ]
CBE7F1F65@4a173d03-4959-223b-e14c-e2eaa5fc8a8b
191657239974ecb19d11e21ccec214f536404e33
c53d20695965a467a68fd8c9383ef5e1d36659a1
/base/message_pump_uv.h
572c8cd3e667880e8636c81e4db67beb44ae8431
[ "BSD-3-Clause" ]
permissive
abhijeetk/chromium.src
ce9313444e905875ebfa045bb5777700157914a6
99faa1383d1fb0d745678484fd512b5d406da191
refs/heads/nw12
2021-09-30T21:57:06.633271
2016-03-15T15:01:49
2016-03-15T15:02:04
48,524,771
1
1
null
2015-12-24T04:29:46
2015-12-24T04:29:46
null
UTF-8
C++
false
false
1,163
h
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_MESSAGE_PUMP_UV_H_ #define BASE_MESSAGE_PUMP_UV_H_ #pragma once #include "base/message_loop/message_pump.h" #include "base/time/time.h" #include "base/base_export.h" #include <vector> //#include "third_party/node/deps/uv/include/uv.h" typedef struct uv_async_s uv_async_t; namespace base { class BASE_EXPORT MessagePumpUV : public MessagePump { public: MessagePumpUV(); // MessagePump methods: void Run(Delegate* delegate) override; void Quit() override; void ScheduleWork() override; void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override; private: ~MessagePumpUV() override; // This flag is set to false when Run should return. bool keep_running_; // Nested loop level. int nesting_level_; // Handle to wake up loop. std::vector<uv_async_t*> wakeup_events_; uv_async_t* wakeup_event_; TimeTicks delayed_work_time_; DISALLOW_COPY_AND_ASSIGN(MessagePumpUV); }; } // namespace base #endif // BASE_MESSAGE_PUMP_UV_H_
[ "wenrui@gmail.com" ]
wenrui@gmail.com
bba45e20d658a086c03d2709df0a7d8d4711a9e4
a081002197d091f1c387576894a160ececb69497
/activemq-cpp/src/main/decaf/security/cert/CertificateParsingException.cpp
08e1cde3bf079e4636c7f20c62d125538eef8ea5
[ "Apache-2.0" ]
permissive
greatyang/activemq-cpp
357fe087c839ed0d535ad7e3d987db2dc0badf1e
4f5d0847552d6a5e206cc54c4354ebd8b0bb8fe3
refs/heads/master
2021-03-03T09:53:20.887464
2020-03-09T05:34:59
2020-03-09T05:34:59
245,951,764
0
0
Apache-2.0
2020-03-09T05:31:25
2020-03-09T05:31:25
null
UTF-8
C++
false
false
2,723
cpp
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "CertificateParsingException.h" using namespace decaf; using namespace decaf::security; using namespace decaf::security::cert; //////////////////////////////////////////////////////////////////////////////// CertificateParsingException::CertificateParsingException() : CertificateException() { } //////////////////////////////////////////////////////////////////////////////// CertificateParsingException::CertificateParsingException(const Exception& ex) : CertificateException() { *(Exception*) this = ex; } //////////////////////////////////////////////////////////////////////////////// CertificateParsingException::CertificateParsingException(const CertificateParsingException& ex) : CertificateException() { *(Exception*) this = ex; } //////////////////////////////////////////////////////////////////////////////// CertificateParsingException::CertificateParsingException(const char* file, const int lineNumber, const std::exception* cause, const char* msg, ...) : CertificateException(cause) { va_list vargs; va_start(vargs, msg); buildMessage(msg, vargs); // Set the first mark for this exception. setMark(file, lineNumber); } //////////////////////////////////////////////////////////////////////////////// CertificateParsingException::CertificateParsingException(const std::exception* cause) : CertificateException(cause) { } //////////////////////////////////////////////////////////////////////////////// CertificateParsingException::CertificateParsingException(const char* file, const int lineNumber, const char* msg, ...) : CertificateException() { va_list vargs; va_start(vargs, msg); buildMessage(msg, vargs); // Set the first mark for this exception. setMark(file, lineNumber); } //////////////////////////////////////////////////////////////////////////////// CertificateParsingException::~CertificateParsingException() throw () { }
[ "tabish@apache.org" ]
tabish@apache.org
9b0ecbcb547d8306ec6de464d9e846a568031e27
f421bcf931dc3073e4c9b3e3e747f18f6fe617a2
/test/cts/reporter_test_cts.cc
f9294f4e5b534266302557dee05e7fe0528063c1
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
Evervolv/android_external_perfetto
9063868f2e8dd8446f079615b4427a4591603124
b4ea495f96c2aa70e49431dea2770403d27f23ca
refs/heads/t-13.1
2023-04-10T08:35:04.318754
2020-09-26T14:57:04
2022-12-08T01:39:15
145,198,818
0
1
Apache-2.0
2022-12-11T18:29:48
2018-08-18T07:13:50
C++
UTF-8
C++
false
false
4,074
cc
/* * Copyright (C) 2022 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 <sys/system_properties.h> #include <random> #include "test/gtest_and_gmock.h" #include "perfetto/ext/base/android_utils.h" #include "perfetto/ext/base/uuid.h" #include "perfetto/tracing/core/data_source_config.h" #include "src/base/test/test_task_runner.h" #include "test/android_test_utils.h" #include "test/test_helper.h" #include "protos/perfetto/config/test_config.gen.h" #include "protos/perfetto/trace/test_event.gen.h" #include "protos/perfetto/trace/trace.gen.h" #include "protos/perfetto/trace/trace_packet.gen.h" namespace perfetto { namespace { TEST(PerfettoReporterTest, TestEndToEndReport) { base::TestTaskRunner task_runner; TestHelper helper(&task_runner); helper.ConnectFakeProducer(); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(1024); trace_config.set_duration_ms(200); trace_config.set_allow_user_build_tracing(true); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.perfetto.FakeProducer"); ds_config->set_target_buffer(0); base::Uuid uuid = base::Uuidv4(); trace_config.set_trace_uuid_lsb(uuid.lsb()); trace_config.set_trace_uuid_msb(uuid.msb()); static constexpr uint32_t kRandomSeed = 42; static constexpr uint32_t kEventCount = 1; static constexpr uint32_t kMessageSizeBytes = 2; ds_config->mutable_for_testing()->set_seed(kRandomSeed); ds_config->mutable_for_testing()->set_message_count(kEventCount); ds_config->mutable_for_testing()->set_message_size(kMessageSizeBytes); ds_config->mutable_for_testing()->set_send_batch_on_register(true); auto* report_config = trace_config.mutable_android_report_config(); report_config->set_reporter_service_package("android.perfetto.cts.reporter"); report_config->set_reporter_service_class( "android.perfetto.cts.reporter.PerfettoReportService"); report_config->set_use_pipe_in_framework_for_testing(true); // We have to construct all the processes we want to fork before we start the // service with |StartServiceIfRequired()|. this is because it is unsafe // (could deadlock) to fork after we've spawned some threads which might // printf (and thus hold locks). auto perfetto_proc = Exec("perfetto", { "--upload", "-c", "-", }, trace_config.SerializeAsString()); std::string stderr_str; EXPECT_EQ(0, perfetto_proc.Run(&stderr_str)) << stderr_str; static constexpr char kPath[] = "/sdcard/Android/data/android.perfetto.cts.reporter/files/"; std::string path = kPath + uuid.ToPrettyString(); static constexpr uint32_t kIterationSleepMs = 500; static constexpr uint32_t kIterationCount = kDefaultTestTimeoutMs / kIterationSleepMs; for (size_t i = 0; i < kIterationCount; ++i) { if (!base::FileExists(path)) { base::SleepMicroseconds(kIterationSleepMs * 1000); continue; } std::string trace_str; ASSERT_TRUE(base::ReadFile(path, &trace_str)); protos::gen::Trace trace; ASSERT_TRUE(trace.ParseFromString(trace_str)); int for_testing = 0; for (const auto& packet : trace.packet()) { for_testing += packet.has_for_testing(); } ASSERT_EQ(for_testing, kEventCount); return; } FAIL() << "Timed out waiting for trace file"; } } // namespace } // namespace perfetto
[ "lalitm@google.com" ]
lalitm@google.com
e80e76e1d786272e8b603e2687fece8a0f409912
0bc95dbc9650afb1d8f6b194c447679553342e12
/model/DnaMetaData.h
cf9d1787eefbb3d81eaa186ad4102cd59468f9a2
[]
no_license
chanismile/Dna-project
f40e52aa8dd2546a257329550a2cd21a05833e4f
d02f1de75f9eeef746e151cfb8b2496e7ecb6f65
refs/heads/master
2020-04-15T14:08:17.495543
2019-02-07T09:39:45
2019-02-07T09:39:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
571
h
// // Created by cglick on 12/29/18. // #ifndef UNTITLED1_DNAMETADATA_H #define UNTITLED1_DNAMETADATA_H #include "DnaSequence.h" #include <glob.h> #include <string> enum Status{ Up_TO_DATE, MODIFIED, NEW }; class DnaMetaData { public: DnaMetaData(const std::string & seq, size_t id, const std::string & name); DnaMetaData(DnaSequence seq, size_t id, const std::string & name); IDna * getm_IDna(); std::string getm_name(); private: size_t m_id; std::string m_name; IDna * m_IDna; Status m_status; }; #endif //UNTITLED1_DNAMETADATA_H
[ "37192892+chanismile@users.noreply.github.com" ]
37192892+chanismile@users.noreply.github.com
04fdc302fca4e95894f708f9a89c247af15a47d4
d53f888b7720dc6fcb31016ba151931afb42a925
/shilibaohu_1.0/ESP8266.h
c194dc04304d6e9ca8402f60b49f92e041796966
[]
no_license
000562/-
9e019f2578cfd52c6aaabaeb7b92b7716b6365ac
d648a3a896b3e177eda3532574768e24b5e041d7
refs/heads/master
2020-04-12T15:48:26.993375
2018-12-20T15:37:55
2018-12-20T15:37:55
162,593,055
1
0
null
null
null
null
UTF-8
C++
false
false
24,347
h
/** @author Wu Pengfei<pengfei.wu@itead.cc> * @par Copyright: * Copyright (c) 2015 ITEAD Intelligent Systems Co., Ltd. \n\n * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. \n\n * 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 __ESP8266_H__ #define __ESP8266_H__ #include "Arduino.h" #define ESP8266_USE_SOFTWARE_SERIAL #ifdef ESP8266_USE_SOFTWARE_SERIAL #include "SoftwareSerial.h" #endif #define VERSION_18 0X18 #define VERSION_22 0X22 #define DEFAULT_PATTERN 3 /** * You can modify the macro to choose a different version */ #define USER_SEL_VERSION VERSION_18 /** * Provide an easy-to-use way to manipulate ESP8266. */ class ESP8266 { public: #ifdef ESP8266_USE_SOFTWARE_SERIAL /* * Constuctor. * * @param uart - an reference of SoftwareSerial object. * @param baud - the buad rate to communicate with ESP8266(default:9600). * * @warning parameter baud depends on the AT firmware. 9600 is an common value. */ #if (USER_SEL_VERSION == VERSION_22) ESP8266(SoftwareSerial &uart, uint32_t baud = 115200); #elif (USER_SEL_VERSION == VERSION_18) ESP8266(SoftwareSerial &uart, uint32_t baud = 9600); #endif /* #if(USER_SEL_VERSION==VERSION_22) */ #else /* HardwareSerial */ /* * Constuctor. * * @param uart - an reference of HardwareSerial object. * @param baud - the buad rate to communicate with ESP8266(default:9600). * * @warning parameter baud depends on the AT firmware. 9600 is an common value. */ #if (USER_SEL_VERSION == VERSION_22) ESP8266(HardwareSerial &uart, uint32_t baud = 115200); #elif (USER_SEL_VERSION == VERSION_18) ESP8266(HardwareSerial &uart, uint32_t baud = 9600); #endif /* #if(USER_SEL_VERSION == VERSION_22) */ #endif /* #ifdef ESP8266_USE_SOFTWARE_SERIAL */ /** * Verify ESP8266 whether live or not. * * Actually, this method will send command "AT" to ESP8266 and waiting for "OK". * * @retval true - alive. * @retval false - dead. */ bool kick(void); /** * Restart ESP8266 by "AT+RST". * * This method will take 3 seconds or more. * * @retval true - success. * @retval false - failure. */ bool restart(void); /** * Get the version of AT Command Set. * * @return the string of version. */ String getVersion(void); /** * Start function of deep sleep. * * @param time - the sleep time. * @retval true - success. * @retval false - failure. * @note the feature requires hardware support. */ bool deepSleep(uint32_t time); /** * Switch the echo function. * * @param mode - 1 start echo -0 stop echo * @retval true - success. * @retval false - failure. * */ bool setEcho(uint8_t mode); /** * Restore factory. * @retval true - success. * @retval false - failure. * @note The operation can lead to restart the machine. */ bool restore(void); /** * Set up a serial port configuration. * * @param pattern -1 send "AT+UART=", -2 send "AT+UART_CUR=", -3 send "AT+UART_DEF=". * @param baudrate - the uart baudrate. * @retval true - success. * @retval false - failure. * @note Only allows baud rate design, for the other parameters:databits- 8,stopbits -1,parity -0,flow control -0 . */ bool setUart(uint32_t baudrate,uint8_t pattern); /** * Set operation mode to station. * * @param pattern1 -1, send "AT+CWMODE_DEF?",-2,send "AT+CWMODE_CUR?",-3,send "AT+CWMODE?". * @param pattern2 -1, send "AT+CWMODE_DEF=",-2,send "AT+CWMODE_CUR=",-3,send "AT+CWMODE=". * @retval true - success. * @retval false - failure. * */ bool setOprToStation(uint8_t pattern1=DEFAULT_PATTERN,uint8_t pattern2=DEFAULT_PATTERN); /** * Get the model values list. * * @return the list of model. */ String getWifiModeList(void); /** * Set operation mode to softap. * @param pattern1 -1, send "AT+CWMODE_DEF?",-2,send "AT+CWMODE_CUR?",-3,send "AT+CWMODE?". * @param pattern2 -1, send "AT+CWMODE_DEF=",-2,send "AT+CWMODE_CUR=",-3,send "AT+CWMODE=". * * @retval true - success. * @retval false - failure. */ bool setOprToSoftAP(uint8_t pattern1=DEFAULT_PATTERN,uint8_t pattern2=DEFAULT_PATTERN); /** * Set operation mode to station + softap. * @param pattern1 -1, send "AT+CWMODE_DEF?",-2,send "AT+CWMODE_CUR?",-3,send "AT+CWMODE?". * @param pattern2 -1, send "AT+CWMODE_DEF=",-2,send "AT+CWMODE_CUR=",-3,send "AT+CWMODE=". * * @retval true - success. * @retval false - failure. */ bool setOprToStationSoftAP(uint8_t pattern1=DEFAULT_PATTERN,uint8_t pattern2=DEFAULT_PATTERN); /** * Get the operation mode. * @param pattern1 -1, send "AT+CWMODE_DEF?",-2,send "AT+CWMODE_CUR?",-3,send "AT+CWMODE?". * * @retval 0 - failure. * @retval 1 - mode Station. * @retval 2 - mode AP. * @retval 3 - mode AP + station. */ uint8_t getOprMode(uint8_t pattern1=DEFAULT_PATTERN); /** * Search available AP list and return it. * * @return the list of available APs. * @note This method will occupy a lot of memeory(hundreds of Bytes to a couple of KBytes). * Do not call this method unless you must and ensure that your board has enough memery left. */ String getAPList(void); /** * Search and returns the current connect AP. * * @param pattern -1, send "AT+CWJAP_DEF?",-2,send "AT+CWJAP_CUR?",-3,send "AT+CWJAP?". * @return the ssid of AP connected now. */ String getNowConecAp(uint8_t pattern=DEFAULT_PATTERN); /** * Join in AP. * * @param pattern -1 send "AT+CWJAP_DEF=" -2 send "AT+CWJAP_CUR=" -3 send "AT+CWJAP=". * @param ssid - SSID of AP to join in. * @param pwd - Password of AP to join in. * @retval true - success. * @retval false - failure. * @note This method will take a couple of seconds. */ bool joinAP(String ssid, String pwd,uint8_t pattern=DEFAULT_PATTERN); /** * Leave AP joined before. * * @retval true - success. * @retval false - failure. */ bool leaveAP(void); /** * Set SoftAP parameters. * * @param pattern -1 send "AT+CWSAP_DEF=" -2 send "AT+CWSAP_CUR=" -3 send "AT+CWSAP=". * @param ssid - SSID of SoftAP. * @param pwd - PASSWORD of SoftAP. * @param chl - the channel (1 - 13, default: 7). * @param ecn - the way of encrypstion (0 - OPEN, 1 - WEP, * 2 - WPA_PSK, 3 - WPA2_PSK, 4 - WPA_WPA2_PSK, default: 4). * @retval true - success. * @retval false - failure. * @note This method should not be called when station mode. */ bool setSoftAPParam(String ssid, String pwd, uint8_t chl = 7, uint8_t ecn = 4,uint8_t pattern=DEFAULT_PATTERN); /** * get SoftAP parameters. * * @param pattern -1 send "AT+CWSAP_DEF?" -2 send "AT+CWSAP_CUR?" -3 send "AT+CWSAP?". * @note This method should not be called when station mode. */ String getSoftAPParam(uint8_t pattern=DEFAULT_PATTERN); /** * Get the IP list of devices connected to SoftAP. * * @return the list of IP. * @note This method should not be called when station mode. */ String getJoinedDeviceIP(void); /** * Get the current state of DHCP. * * @param pattern -1 send "AT+CWDHCP_DEF?" -2 send "AT+CWDHCP_CUR?" -3 send "AT+CWDHCP?". * @return the state of DHCP. * */ String getDHCP(uint8_t pattern=DEFAULT_PATTERN); /** * Set the state of DHCP. * @param pattern -1 send "AT+CWDHCP_DEF=" -2 send "AT+CWDHCP_CUR=" -3 send "AT+CWDHCP=". * @param mode - set ap or set station or set ap + station. * @param en - 0 disable DHCP - 1 enable DHCP. * @retval true - success. * @retval false - failure. */ bool setDHCP(uint8_t mode, uint8_t en, uint8_t pattern=DEFAULT_PATTERN); /** * make boot automatically connected. * @param en -1 enable -0 disable. * @retval true - success. * @retval false - failure. */ bool setAutoConnect(uint8_t en); /** * Get the station's MAC address. * @param pattern -1 send "AT+CIPSTAMAC_DEF?=" -2 send "AT+CIPSTAMAC_CUR?" -3 send "AT+CIPSTAMAC?". * @return mac address. * @note This method should not be called when ap mode. */ String getStationMac(uint8_t pattern=DEFAULT_PATTERN); /** * Set the station's MAC address. * @param pattern -1 send "AT+CIPSTAMAC_DEF=" -2 send "AT+CIPSTAMAC_CUR=" -3 send "AT+CIPSTAMAC=". * @param mac - the mac address of station. * @retval true - success. * @retval false - failure. */ bool setStationMac(String mac,uint8_t pattern=DEFAULT_PATTERN); /** * Get the station's IP. * @param pattern -1 send "AT+CIPSTA_DEF?" -2 send "AT+CIPSTA_CUR?" -3 send "AT+CIPSTA?". * @return the station's IP. * @note This method should not be called when ap mode. */ String getStationIp(uint8_t pattern=DEFAULT_PATTERN); /** * Set the station's IP. * @param pattern -1 send "AT+CIPSTA_DEF=" -2 send "AT+CIPSTA_CUR=" -3 send "AT+CIPSTA=". * @param ip - the ip of station. * @param gateway -the gateway of station. * @param netmask -the netmask of station. * @retval true - success. * @retval false - failure. * @note This method should not be called when ap mode. */ bool setStationIp(String ip,String gateway,String netmask,uint8_t pattern=DEFAULT_PATTERN); /** * Get the AP's IP. * @param pattern -1 send "AT+CIPAP_DEF?" -2 send "AT+CIPAP_CUR?" -3 send "AT+CIPAP?". * @return ap's ip. * @note This method should not be called when station mode. * */ String getAPIp(uint8_t pattern=DEFAULT_PATTERN); /** * Set the AP IP. * @param pattern -1 send "AT+CIPAP_DEF=" -2 send "AT+CIPAP_CUR=" -3 send "AT+CIPAP=". * @param ip - the ip of AP. * @retval true - success. * @retval false - failure. * @note This method should not be called when station mode. */ bool setAPIp(String ip,uint8_t pattern=DEFAULT_PATTERN); /** * start smartconfig. * @param type -1:ESP_TOUCH -2:AirKiss. * @retval true - success. * @retval false - failure. */ bool startSmartConfig(uint8_t type); /** * stop smartconfig. * * @retval true - success. * @retval false - failure. */ bool stopSmartConfig(void); /** * Get the current status of connection(UDP and TCP). * * @return the status. */ String getIPStatus(void); /** * Get the IP address of ESP8266. * * @return the IP list. */ String getLocalIP(void); /** * Enable IP MUX(multiple connection mode). * * In multiple connection mode, a couple of TCP and UDP communication can be builded. * They can be distinguished by the identifier of TCP or UDP named mux_id. * * @retval true - success. * @retval false - failure. */ bool enableMUX(void); /** * Disable IP MUX(single connection mode). * * In single connection mode, only one TCP or UDP communication can be builded. * * @retval true - success. * @retval false - failure. */ bool disableMUX(void); /** * Create TCP connection in single mode. * * @param addr - the IP or domain name of the target host. * @param port - the port number of the target host. * @retval true - success. * @retval false - failure. */ bool createTCP(String addr, uint32_t port); /** * Release TCP connection in single mode. * * @retval true - success. * @retval false - failure. */ bool releaseTCP(void); /** * Register UDP port number in single mode. * * @param addr - the IP or domain name of the target host. * @param port - the port number of the target host. * @retval true - success. * @retval false - failure. */ bool registerUDP(String addr, uint32_t port); /** * Unregister UDP port number in single mode. * * @retval true - success. * @retval false - failure. */ bool unregisterUDP(void); /** * Create TCP connection in multiple mode. * * @param mux_id - the identifier of this TCP(available value: 0 - 4). * @param addr - the IP or domain name of the target host. * @param port - the port number of the target host. * @retval true - success. * @retval false - failure. */ bool createTCP(uint8_t mux_id, String addr, uint32_t port); /** * Release TCP connection in multiple mode. * * @param mux_id - the identifier of this TCP(available value: 0 - 4). * @retval true - success. * @retval false - failure. */ bool releaseTCP(uint8_t mux_id); /** * Register UDP port number in multiple mode. * * @param mux_id - the identifier of this TCP(available value: 0 - 4). * @param addr - the IP or domain name of the target host. * @param port - the port number of the target host. * @retval true - success. * @retval false - failure. */ bool registerUDP(uint8_t mux_id, String addr, uint32_t port); /** * Unregister UDP port number in multiple mode. * * @param mux_id - the identifier of this TCP(available value: 0 - 4). * @retval true - success. * @retval false - failure. */ bool unregisterUDP(uint8_t mux_id); /** * Set the timeout of TCP Server. * * @param timeout - the duration for timeout by second(0 ~ 28800, default:180). * @retval true - success. * @retval false - failure. */ bool setTCPServerTimeout(uint32_t timeout = 180); /** * Start TCP Server(Only in multiple mode). * * After started, user should call method: getIPStatus to know the status of TCP connections. * The methods of receiving data can be called for user's any purpose. After communication, * release the TCP connection is needed by calling method: releaseTCP with mux_id. * * @param port - the port number to listen(default: 333). * @retval true - success. * @retval false - failure. * * @see String getIPStatus(void); * @see uint32_t recv(uint8_t *coming_mux_id, uint8_t *buffer, uint32_t len, uint32_t timeout); * @see bool releaseTCP(uint8_t mux_id); */ bool startTCPServer(uint32_t port = 333); /** * Stop TCP Server(Only in multiple mode). * * @retval true - success. * @retval false - failure. */ bool stopTCPServer(void); /** *Set the module transfer mode * * @retval true - success. * @retval false - failure. */ bool setCIPMODE(uint8_t mode); /** * Start Server(Only in multiple mode). * * @param port - the port number to listen(default: 333). * @retval true - success. * @retval false - failure. * * @see String getIPStatus(void); * @see uint32_t recv(uint8_t *coming_mux_id, uint8_t *buffer, uint32_t len, uint32_t timeout); */ bool startServer(uint32_t port = 333); /** * Stop Server(Only in multiple mode). * * @retval true - success. * @retval false - failure. */ bool stopServer(void); /** * Save the passthrough links * * @retval true - success. * @retval false - failure. */ bool saveTransLink (uint8_t mode,String ip,uint32_t port); /** * PING COMMAND. * * @retval true - success. * @retval false - failure. */ bool setPing(String ip); /** * Send data based on TCP or UDP builded already in single mode. * * @param buffer - the buffer of data to send. * @param len - the length of data to send. * @retval true - success. * @retval false - failure. */ bool send(const uint8_t *buffer, uint32_t len); /** * Send data based on one of TCP or UDP builded already in multiple mode. * * @param mux_id - the identifier of this TCP(available value: 0 - 4). * @param buffer - the buffer of data to send. * @param len - the length of data to send. * @retval true - success. * @retval false - failure. */ bool send(uint8_t mux_id, const uint8_t *buffer, uint32_t len); /** * Send data based on TCP or UDP builded already in single mode. * * @param buffer - the buffer of data to send from flash memeory. * @param len - the length of data to send. * @retval true - success. * @retval false - failure. */ bool sendFromFlash(const uint8_t *buffer, uint32_t len); /** * Send data based on one of TCP or UDP builded already in multiple mode. * * @param mux_id - the identifier of this TCP(available value: 0 - 4). * @param buffer - the buffer of data to send from flash memeory. * @param len - the length of data to send. * @retval true - success. * @retval false - failure. */ bool sendFromFlash(uint8_t mux_id, const uint8_t *buffer, uint32_t len); /** * Receive data from TCP or UDP builded already in single mode. * * @param buffer - the buffer for storing data. * @param buffer_size - the length of the buffer. * @param timeout - the time waiting data. * @return the length of data received actually. */ uint32_t recv(uint8_t *buffer, uint32_t buffer_size, uint32_t timeout = 1000); /** * Receive data from one of TCP or UDP builded already in multiple mode. * * @param mux_id - the identifier of this TCP(available value: 0 - 4). * @param buffer - the buffer for storing data. * @param buffer_size - the length of the buffer. * @param timeout - the time waiting data. * @return the length of data received actually. */ uint32_t recv(uint8_t mux_id, uint8_t *buffer, uint32_t buffer_size, uint32_t timeout = 1000); /** * Receive data from all of TCP or UDP builded already in multiple mode. * * After return, coming_mux_id store the id of TCP or UDP from which data coming. * User should read the value of coming_mux_id and decide what next to do. * * @param coming_mux_id - the identifier of TCP or UDP. * @param buffer - the buffer for storing data. * @param buffer_size - the length of the buffer. * @param timeout - the time waiting data. * @return the length of data received actually. */ uint32_t recv(uint8_t *coming_mux_id, uint8_t *buffer, uint32_t buffer_size, uint32_t timeout = 1000); private: /* * Empty the buffer or UART RX. */ void rx_empty(void); /* * Recvive data from uart. Return all received data if target found or timeout. */ String recvString(String target, uint32_t timeout = 1000); /* * Recvive data from uart. Return all received data if one of target1 and target2 found or timeout. */ String recvString(String target1, String target2, uint32_t timeout = 1000); /* * Recvive data from uart. Return all received data if one of target1, target2 and target3 found or timeout. */ String recvString(String target1, String target2, String target3, uint32_t timeout = 1000); /* * Recvive data from uart and search first target. Return true if target found, false for timeout. */ bool recvFind(String target, uint32_t timeout = 1000); /* * Recvive data from uart and search first target and cut out the substring between begin and end(excluding begin and end self). * Return true if target found, false for timeout. */ bool recvFindAndFilter(String target, String begin, String end, String &data, uint32_t timeout = 1000); /* * Receive a package from uart. * * @param buffer - the buffer storing data. * @param buffer_size - guess what! * @param data_len - the length of data actually received(maybe more than buffer_size, the remained data will be abandoned). * @param timeout - the duration waitting data comming. * @param coming_mux_id - in single connection mode, should be NULL and not NULL in multiple. */ uint32_t recvPkg(uint8_t *buffer, uint32_t buffer_size, uint32_t *data_len, uint32_t timeout, uint8_t *coming_mux_id); bool eAT(void); bool eATRST(void); bool eATGMR(String &version); bool eATGSLP(uint32_t time); bool eATE(uint8_t mode); bool eATRESTORE(void); bool eATSETUART(uint32_t baudrate,uint8_t pattern); bool qATCWMODE(uint8_t *mode,uint8_t pattern=3); bool eATCWMODE(String &list) ; bool sATCWMODE(uint8_t mode,uint8_t pattern=3); bool qATCWJAP(String &ssid,uint8_t pattern=3) ; bool sATCWJAP(String ssid, String pwd,uint8_t pattern=3); bool eATCWLAP(String &list); bool eATCWQAP(void); bool qATCWSAP(String &List,uint8_t pattern=3); bool sATCWSAP(String ssid, String pwd, uint8_t chl, uint8_t ecn,uint8_t pattern=3); bool eATCWLIF(String &list); bool qATCWDHCP(String &List,uint8_t pattern=3); bool sATCWDHCP(uint8_t mode, uint8_t en, uint8_t pattern=3); bool eATCWAUTOCONN(uint8_t en); bool qATCIPSTAMAC(String &mac,uint8_t pattern=3); bool eATCIPSTAMAC(String mac,uint8_t pattern=3); bool qATCIPSTAIP(String &ip,uint8_t pattern=3); bool eATCIPSTAIP(String ip,String gateway,String netmask,uint8_t pattern=3); bool qATCIPAP(String &ip,uint8_t pattern=3); bool eATCIPAP(String ip,uint8_t pattern=3); bool eCWSTARTSMART(uint8_t type); bool eCWSTOPSMART(void); bool eATCIPSTATUS(String &list); bool sATCIPSTARTSingle(String type, String addr, uint32_t port); bool sATCIPSTARTMultiple(uint8_t mux_id, String type, String addr, uint32_t port); bool sATCIPSENDSingle(const uint8_t *buffer, uint32_t len); bool sATCIPSENDMultiple(uint8_t mux_id, const uint8_t *buffer, uint32_t len); bool sATCIPSENDSingleFromFlash(const uint8_t *buffer, uint32_t len); bool sATCIPSENDMultipleFromFlash(uint8_t mux_id, const uint8_t *buffer, uint32_t len); bool sATCIPCLOSEMulitple(uint8_t mux_id); bool eATCIPCLOSESingle(void); bool eATCIFSR(String &list); bool sATCIPMUX(uint8_t mode); bool sATCIPSERVER(uint8_t mode, uint32_t port = 333); bool sATCIPMODE(uint8_t mode); bool eATSAVETRANSLINK(uint8_t mode,String ip,uint32_t port); bool eATPING(String ip); bool sATCIPSTO(uint32_t timeout); /* * +IPD,len:data * +IPD,id,len:data */ #ifdef ESP8266_USE_SOFTWARE_SERIAL SoftwareSerial *m_puart; /* The UART to communicate with ESP8266 */ #else HardwareSerial *m_puart; /* The UART to communicate with ESP8266 */ #endif }; #endif /* #ifndef __ESP8266_H__ */
[ "970943222@qq.com" ]
970943222@qq.com
ed66f6e732c6046f0f5936255e53bb0ab483ec85
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-qt5-qhttpengine-server/generated/server/src/models/OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties.h
9d4d24bdaf5e2767a4af8ecf4ae12af946ba2599
[ "Apache-2.0", "MIT" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
1,713
h
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: opensource@shinesolutions.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ /* * OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties.h * * */ #ifndef OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties_H #define OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties_H #include <QJsonObject> #include "OAIConfigNodePropertyArray.h" #include "OAIObject.h" namespace OpenAPI { class OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties: public OAIObject { public: OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties(); OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties(QString json); ~OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties() override; void init(); QString asJson () const override; QJsonObject asJsonObject() const override; void fromJsonObject(QJsonObject json) override; void fromJson(QString jsonString) override; OAIConfigNodePropertyArray getHcTags() const; void setHcTags(const OAIConfigNodePropertyArray &hc_tags); virtual bool isSet() const override; private: OAIConfigNodePropertyArray hc_tags; bool m_hc_tags_isSet; }; } #endif // OAIComAdobeCqSecurityHcBundlesImplHtmlLibraryManagerConfigHealthChProperties_H
[ "cliffano@gmail.com" ]
cliffano@gmail.com
b23202a42e8ef90d059fb78b56b775fb6d8dc129
acd27324a6c44314cadbdeccdf04bda4ac13eef9
/src/main.cpp
8ef67afd9afcfe9a3aa41c0794dc69869bf7f8ab
[]
no_license
sumanthratna/vegetable-rush
8d4536bd27b0bb582159f2a1d128aceab400ea83
a760d95642c10ff6b558781ac2ce2aa1c0860e51
refs/heads/master
2020-04-29T09:44:28.941712
2019-03-31T01:39:19
2019-03-31T01:39:19
176,036,476
0
0
null
null
null
null
UTF-8
C++
false
false
652
cpp
#include <QApplication> #include <QMainWindow> #include <QSurfaceFormat> #include <QFontDatabase> #include "mainwindow.hpp" #include "file_settings.hpp" int main(int argc, char ** argv) { QApplication a(argc, argv); Settings::programPath = a.applicationDirPath().toStdString(); QSurfaceFormat format; format.setDepthBufferSize(24); format.setStencilBufferSize(8); QSurfaceFormat::setDefaultFormat(format); QFontDatabase::addApplicationFont(":/data/fonts/arcade.regular.ttf"); MainWindow mw; // a.setApplicationName("SUMANTH RATNA, ADITYA MENACHERY, STEVEN LI (Period 5)"); mw.show(); return a.exec(); }
[ "sumanthratna@gmail.com" ]
sumanthratna@gmail.com
5f6cfa93e3e8854f48c09d7e833360430a9e8530
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14443/function14443_schedule_36/function14443_schedule_36.cpp
89f65e4824854b3475f3002883257543c8271e41
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
765
cpp
#include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv){ tiramisu::init("function14443_schedule_36"); constant c0("c0", 64), c1("c1", 128), c2("c2", 128), c3("c3", 64); var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i3("i3", 0, c3), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06"); computation comp0("comp0", {i0, i1, i2, i3}, 8 * 3 * 8); comp0.tile(i0, i1, i2, 64, 32, 32, i01, i02, i03, i04, i05, i06); comp0.parallelize(i01); buffer buf0("buf0", {64, 128, 128, 64}, p_int32, a_output); comp0.store_in(&buf0); tiramisu::codegen({&buf0}, "../data/programs/function14443/function14443_schedule_36/function14443_schedule_36.o"); return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
b215f78f414fba84a03b2d58c81ebaee0ac79a7e
0f23651b08fd5a8ce21b9e78e39e61618996073b
/lib/CodeGen/MachineOutliner.cpp
b52d3ebfeff41d56f9a645a3ea801c472dac57e0
[ "NCSA" ]
permissive
arcosuc3m/clang-contracts
3983773f15872514f7b6ae72d7fea232864d7e3d
99446829e2cd96116e4dce9496f88cc7df1dbe80
refs/heads/master
2021-07-04T03:24:03.156444
2018-12-12T11:41:18
2018-12-12T12:56:08
118,155,058
31
1
null
null
null
null
UTF-8
C++
false
false
49,248
cpp
//===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// Replaces repeated sequences of instructions with function calls. /// /// This works by placing every instruction from every basic block in a /// suffix tree, and repeatedly querying that tree for repeated sequences of /// instructions. If a sequence of instructions appears often, then it ought /// to be beneficial to pull out into a function. /// /// The MachineOutliner communicates with a given target using hooks defined in /// TargetInstrInfo.h. The target supplies the outliner with information on how /// a specific sequence of instructions should be outlined. This information /// is used to deduce the number of instructions necessary to /// /// * Create an outlined function /// * Call that outlined function /// /// Targets must implement /// * getOutliningCandidateInfo /// * insertOutlinerEpilogue /// * insertOutlinedCall /// * insertOutlinerPrologue /// * isFunctionSafeToOutlineFrom /// /// in order to make use of the MachineOutliner. /// /// This was originally presented at the 2016 LLVM Developers' Meeting in the /// talk "Reducing Code Size Using Outlining". For a high-level overview of /// how this pass works, the talk is available on YouTube at /// /// https://www.youtube.com/watch?v=yorld-WSOeU /// /// The slides for the talk are available at /// /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf /// /// The talk provides an overview of how the outliner finds candidates and /// ultimately outlines them. It describes how the main data structure for this /// pass, the suffix tree, is queried and purged for candidates. It also gives /// a simplified suffix tree construction algorithm for suffix trees based off /// of the algorithm actually used here, Ukkonen's algorithm. /// /// For the original RFC for this pass, please see /// /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html /// /// For more information on the suffix tree data structure, please see /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf /// //===----------------------------------------------------------------------===// #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/Twine.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" #include "llvm/CodeGen/Passes.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetSubtargetInfo.h" #include <functional> #include <map> #include <sstream> #include <tuple> #include <vector> #define DEBUG_TYPE "machine-outliner" using namespace llvm; using namespace ore; STATISTIC(NumOutlined, "Number of candidates outlined"); STATISTIC(FunctionsCreated, "Number of functions created"); namespace { /// \brief An individual sequence of instructions to be replaced with a call to /// an outlined function. struct Candidate { /// Set to false if the candidate overlapped with another candidate. bool InCandidateList = true; /// The start index of this \p Candidate. unsigned StartIdx; /// The number of instructions in this \p Candidate. unsigned Len; /// The index of this \p Candidate's \p OutlinedFunction in the list of /// \p OutlinedFunctions. unsigned FunctionIdx; /// Contains all target-specific information for this \p Candidate. TargetInstrInfo::MachineOutlinerInfo MInfo; /// \brief The number of instructions that would be saved by outlining every /// candidate of this type. /// /// This is a fixed value which is not updated during the candidate pruning /// process. It is only used for deciding which candidate to keep if two /// candidates overlap. The true benefit is stored in the OutlinedFunction /// for some given candidate. unsigned Benefit = 0; Candidate(unsigned StartIdx, unsigned Len, unsigned FunctionIdx) : StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx) {} Candidate() {} /// \brief Used to ensure that \p Candidates are outlined in an order that /// preserves the start and end indices of other \p Candidates. bool operator<(const Candidate &RHS) const { return StartIdx > RHS.StartIdx; } }; /// \brief The information necessary to create an outlined function for some /// class of candidate. struct OutlinedFunction { /// The actual outlined function created. /// This is initialized after we go through and create the actual function. MachineFunction *MF = nullptr; /// A number assigned to this function which appears at the end of its name. unsigned Name; /// The number of candidates for this OutlinedFunction. unsigned OccurrenceCount = 0; /// \brief The sequence of integers corresponding to the instructions in this /// function. std::vector<unsigned> Sequence; /// Contains all target-specific information for this \p OutlinedFunction. TargetInstrInfo::MachineOutlinerInfo MInfo; /// \brief Return the number of instructions it would take to outline this /// function. unsigned getOutliningCost() { return (OccurrenceCount * MInfo.CallOverhead) + Sequence.size() + MInfo.FrameOverhead; } /// \brief Return the number of instructions that would be saved by outlining /// this function. unsigned getBenefit() { unsigned NotOutlinedCost = OccurrenceCount * Sequence.size(); unsigned OutlinedCost = getOutliningCost(); return (NotOutlinedCost < OutlinedCost) ? 0 : NotOutlinedCost - OutlinedCost; } OutlinedFunction(unsigned Name, unsigned OccurrenceCount, const std::vector<unsigned> &Sequence, TargetInstrInfo::MachineOutlinerInfo &MInfo) : Name(Name), OccurrenceCount(OccurrenceCount), Sequence(Sequence), MInfo(MInfo) {} }; /// Represents an undefined index in the suffix tree. const unsigned EmptyIdx = -1; /// A node in a suffix tree which represents a substring or suffix. /// /// Each node has either no children or at least two children, with the root /// being a exception in the empty tree. /// /// Children are represented as a map between unsigned integers and nodes. If /// a node N has a child M on unsigned integer k, then the mapping represented /// by N is a proper prefix of the mapping represented by M. Note that this, /// although similar to a trie is somewhat different: each node stores a full /// substring of the full mapping rather than a single character state. /// /// Each internal node contains a pointer to the internal node representing /// the same string, but with the first character chopped off. This is stored /// in \p Link. Each leaf node stores the start index of its respective /// suffix in \p SuffixIdx. struct SuffixTreeNode { /// The children of this node. /// /// A child existing on an unsigned integer implies that from the mapping /// represented by the current node, there is a way to reach another /// mapping by tacking that character on the end of the current string. DenseMap<unsigned, SuffixTreeNode *> Children; /// A flag set to false if the node has been pruned from the tree. bool IsInTree = true; /// The start index of this node's substring in the main string. unsigned StartIdx = EmptyIdx; /// The end index of this node's substring in the main string. /// /// Every leaf node must have its \p EndIdx incremented at the end of every /// step in the construction algorithm. To avoid having to update O(N) /// nodes individually at the end of every step, the end index is stored /// as a pointer. unsigned *EndIdx = nullptr; /// For leaves, the start index of the suffix represented by this node. /// /// For all other nodes, this is ignored. unsigned SuffixIdx = EmptyIdx; /// \brief For internal nodes, a pointer to the internal node representing /// the same sequence with the first character chopped off. /// /// This acts as a shortcut in Ukkonen's algorithm. One of the things that /// Ukkonen's algorithm does to achieve linear-time construction is /// keep track of which node the next insert should be at. This makes each /// insert O(1), and there are a total of O(N) inserts. The suffix link /// helps with inserting children of internal nodes. /// /// Say we add a child to an internal node with associated mapping S. The /// next insertion must be at the node representing S - its first character. /// This is given by the way that we iteratively build the tree in Ukkonen's /// algorithm. The main idea is to look at the suffixes of each prefix in the /// string, starting with the longest suffix of the prefix, and ending with /// the shortest. Therefore, if we keep pointers between such nodes, we can /// move to the next insertion point in O(1) time. If we don't, then we'd /// have to query from the root, which takes O(N) time. This would make the /// construction algorithm O(N^2) rather than O(N). SuffixTreeNode *Link = nullptr; /// The parent of this node. Every node except for the root has a parent. SuffixTreeNode *Parent = nullptr; /// The number of times this node's string appears in the tree. /// /// This is equal to the number of leaf children of the string. It represents /// the number of suffixes that the node's string is a prefix of. unsigned OccurrenceCount = 0; /// The length of the string formed by concatenating the edge labels from the /// root to this node. unsigned ConcatLen = 0; /// Returns true if this node is a leaf. bool isLeaf() const { return SuffixIdx != EmptyIdx; } /// Returns true if this node is the root of its owning \p SuffixTree. bool isRoot() const { return StartIdx == EmptyIdx; } /// Return the number of elements in the substring associated with this node. size_t size() const { // Is it the root? If so, it's the empty string so return 0. if (isRoot()) return 0; assert(*EndIdx != EmptyIdx && "EndIdx is undefined!"); // Size = the number of elements in the string. // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1. return *EndIdx - StartIdx + 1; } SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link, SuffixTreeNode *Parent) : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {} SuffixTreeNode() {} }; /// A data structure for fast substring queries. /// /// Suffix trees represent the suffixes of their input strings in their leaves. /// A suffix tree is a type of compressed trie structure where each node /// represents an entire substring rather than a single character. Each leaf /// of the tree is a suffix. /// /// A suffix tree can be seen as a type of state machine where each state is a /// substring of the full string. The tree is structured so that, for a string /// of length N, there are exactly N leaves in the tree. This structure allows /// us to quickly find repeated substrings of the input string. /// /// In this implementation, a "string" is a vector of unsigned integers. /// These integers may result from hashing some data type. A suffix tree can /// contain 1 or many strings, which can then be queried as one large string. /// /// The suffix tree is implemented using Ukkonen's algorithm for linear-time /// suffix tree construction. Ukkonen's algorithm is explained in more detail /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The /// paper is available at /// /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf class SuffixTree { public: /// Stores each leaf node in the tree. /// /// This is used for finding outlining candidates. std::vector<SuffixTreeNode *> LeafVector; /// Each element is an integer representing an instruction in the module. ArrayRef<unsigned> Str; private: /// Maintains each node in the tree. SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator; /// The root of the suffix tree. /// /// The root represents the empty string. It is maintained by the /// \p NodeAllocator like every other node in the tree. SuffixTreeNode *Root = nullptr; /// Maintains the end indices of the internal nodes in the tree. /// /// Each internal node is guaranteed to never have its end index change /// during the construction algorithm; however, leaves must be updated at /// every step. Therefore, we need to store leaf end indices by reference /// to avoid updating O(N) leaves at every step of construction. Thus, /// every internal node must be allocated its own end index. BumpPtrAllocator InternalEndIdxAllocator; /// The end index of each leaf in the tree. unsigned LeafEndIdx = -1; /// \brief Helper struct which keeps track of the next insertion point in /// Ukkonen's algorithm. struct ActiveState { /// The next node to insert at. SuffixTreeNode *Node; /// The index of the first character in the substring currently being added. unsigned Idx = EmptyIdx; /// The length of the substring we have to add at the current step. unsigned Len = 0; }; /// \brief The point the next insertion will take place at in the /// construction algorithm. ActiveState Active; /// Allocate a leaf node and add it to the tree. /// /// \param Parent The parent of this node. /// \param StartIdx The start index of this node's associated string. /// \param Edge The label on the edge leaving \p Parent to this node. /// /// \returns A pointer to the allocated leaf node. SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx, unsigned Edge) { assert(StartIdx <= LeafEndIdx && "String can't start after it ends!"); SuffixTreeNode *N = new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent); Parent.Children[Edge] = N; return N; } /// Allocate an internal node and add it to the tree. /// /// \param Parent The parent of this node. Only null when allocating the root. /// \param StartIdx The start index of this node's associated string. /// \param EndIdx The end index of this node's associated string. /// \param Edge The label on the edge leaving \p Parent to this node. /// /// \returns A pointer to the allocated internal node. SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx, unsigned EndIdx, unsigned Edge) { assert(StartIdx <= EndIdx && "String can't start after it ends!"); assert(!(!Parent && StartIdx != EmptyIdx) && "Non-root internal nodes must have parents!"); unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx); SuffixTreeNode *N = new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx, E, Root, Parent); if (Parent) Parent->Children[Edge] = N; return N; } /// \brief Set the suffix indices of the leaves to the start indices of their /// respective suffixes. Also stores each leaf in \p LeafVector at its /// respective suffix index. /// /// \param[in] CurrNode The node currently being visited. /// \param CurrIdx The current index of the string being visited. void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) { bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot(); // Store the length of the concatenation of all strings from the root to // this node. if (!CurrNode.isRoot()) { if (CurrNode.ConcatLen == 0) CurrNode.ConcatLen = CurrNode.size(); if (CurrNode.Parent) CurrNode.ConcatLen += CurrNode.Parent->ConcatLen; } // Traverse the tree depth-first. for (auto &ChildPair : CurrNode.Children) { assert(ChildPair.second && "Node had a null child!"); setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size()); } // Is this node a leaf? if (IsLeaf) { // If yes, give it a suffix index and bump its parent's occurrence count. CurrNode.SuffixIdx = Str.size() - CurrIdx; assert(CurrNode.Parent && "CurrNode had no parent!"); CurrNode.Parent->OccurrenceCount++; // Store the leaf in the leaf vector for pruning later. LeafVector[CurrNode.SuffixIdx] = &CurrNode; } } /// \brief Construct the suffix tree for the prefix of the input ending at /// \p EndIdx. /// /// Used to construct the full suffix tree iteratively. At the end of each /// step, the constructed suffix tree is either a valid suffix tree, or a /// suffix tree with implicit suffixes. At the end of the final step, the /// suffix tree is a valid tree. /// /// \param EndIdx The end index of the current prefix in the main string. /// \param SuffixesToAdd The number of suffixes that must be added /// to complete the suffix tree at the current phase. /// /// \returns The number of suffixes that have not been added at the end of /// this step. unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) { SuffixTreeNode *NeedsLink = nullptr; while (SuffixesToAdd > 0) { // Are we waiting to add anything other than just the last character? if (Active.Len == 0) { // If not, then say the active index is the end index. Active.Idx = EndIdx; } assert(Active.Idx <= EndIdx && "Start index can't be after end index!"); // The first character in the current substring we're looking at. unsigned FirstChar = Str[Active.Idx]; // Have we inserted anything starting with FirstChar at the current node? if (Active.Node->Children.count(FirstChar) == 0) { // If not, then we can just insert a leaf and move too the next step. insertLeaf(*Active.Node, EndIdx, FirstChar); // The active node is an internal node, and we visited it, so it must // need a link if it doesn't have one. if (NeedsLink) { NeedsLink->Link = Active.Node; NeedsLink = nullptr; } } else { // There's a match with FirstChar, so look for the point in the tree to // insert a new node. SuffixTreeNode *NextNode = Active.Node->Children[FirstChar]; unsigned SubstringLen = NextNode->size(); // Is the current suffix we're trying to insert longer than the size of // the child we want to move to? if (Active.Len >= SubstringLen) { // If yes, then consume the characters we've seen and move to the next // node. Active.Idx += SubstringLen; Active.Len -= SubstringLen; Active.Node = NextNode; continue; } // Otherwise, the suffix we're trying to insert must be contained in the // next node we want to move to. unsigned LastChar = Str[EndIdx]; // Is the string we're trying to insert a substring of the next node? if (Str[NextNode->StartIdx + Active.Len] == LastChar) { // If yes, then we're done for this step. Remember our insertion point // and move to the next end index. At this point, we have an implicit // suffix tree. if (NeedsLink && !Active.Node->isRoot()) { NeedsLink->Link = Active.Node; NeedsLink = nullptr; } Active.Len++; break; } // The string we're trying to insert isn't a substring of the next node, // but matches up to a point. Split the node. // // For example, say we ended our search at a node n and we're trying to // insert ABD. Then we'll create a new node s for AB, reduce n to just // representing C, and insert a new leaf node l to represent d. This // allows us to ensure that if n was a leaf, it remains a leaf. // // | ABC ---split---> | AB // n s // C / \ D // n l // The node s from the diagram SuffixTreeNode *SplitNode = insertInternalNode(Active.Node, NextNode->StartIdx, NextNode->StartIdx + Active.Len - 1, FirstChar); // Insert the new node representing the new substring into the tree as // a child of the split node. This is the node l from the diagram. insertLeaf(*SplitNode, EndIdx, LastChar); // Make the old node a child of the split node and update its start // index. This is the node n from the diagram. NextNode->StartIdx += Active.Len; NextNode->Parent = SplitNode; SplitNode->Children[Str[NextNode->StartIdx]] = NextNode; // SplitNode is an internal node, update the suffix link. if (NeedsLink) NeedsLink->Link = SplitNode; NeedsLink = SplitNode; } // We've added something new to the tree, so there's one less suffix to // add. SuffixesToAdd--; if (Active.Node->isRoot()) { if (Active.Len > 0) { Active.Len--; Active.Idx = EndIdx - SuffixesToAdd + 1; } } else { // Start the next phase at the next smallest suffix. Active.Node = Active.Node->Link; } } return SuffixesToAdd; } public: /// Construct a suffix tree from a sequence of unsigned integers. /// /// \param Str The string to construct the suffix tree for. SuffixTree(const std::vector<unsigned> &Str) : Str(Str) { Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0); Root->IsInTree = true; Active.Node = Root; LeafVector = std::vector<SuffixTreeNode *>(Str.size()); // Keep track of the number of suffixes we have to add of the current // prefix. unsigned SuffixesToAdd = 0; Active.Node = Root; // Construct the suffix tree iteratively on each prefix of the string. // PfxEndIdx is the end index of the current prefix. // End is one past the last element in the string. for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End; PfxEndIdx++) { SuffixesToAdd++; LeafEndIdx = PfxEndIdx; // Extend each of the leaves. SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd); } // Set the suffix indices of each leaf. assert(Root && "Root node can't be nullptr!"); setSuffixIndices(*Root, 0); } }; /// \brief Maps \p MachineInstrs to unsigned integers and stores the mappings. struct InstructionMapper { /// \brief The next available integer to assign to a \p MachineInstr that /// cannot be outlined. /// /// Set to -3 for compatability with \p DenseMapInfo<unsigned>. unsigned IllegalInstrNumber = -3; /// \brief The next available integer to assign to a \p MachineInstr that can /// be outlined. unsigned LegalInstrNumber = 0; /// Correspondence from \p MachineInstrs to unsigned integers. DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait> InstructionIntegerMap; /// Corresponcence from unsigned integers to \p MachineInstrs. /// Inverse of \p InstructionIntegerMap. DenseMap<unsigned, MachineInstr *> IntegerInstructionMap; /// The vector of unsigned integers that the module is mapped to. std::vector<unsigned> UnsignedVec; /// \brief Stores the location of the instruction associated with the integer /// at index i in \p UnsignedVec for each index i. std::vector<MachineBasicBlock::iterator> InstrList; /// \brief Maps \p *It to a legal integer. /// /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap, /// \p IntegerInstructionMap, and \p LegalInstrNumber. /// /// \returns The integer that \p *It was mapped to. unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) { // Get the integer for this instruction or give it the current // LegalInstrNumber. InstrList.push_back(It); MachineInstr &MI = *It; bool WasInserted; DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator ResultIt; std::tie(ResultIt, WasInserted) = InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber)); unsigned MINumber = ResultIt->second; // There was an insertion. if (WasInserted) { LegalInstrNumber++; IntegerInstructionMap.insert(std::make_pair(MINumber, &MI)); } UnsignedVec.push_back(MINumber); // Make sure we don't overflow or use any integers reserved by the DenseMap. if (LegalInstrNumber >= IllegalInstrNumber) report_fatal_error("Instruction mapping overflow!"); assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() && "Tried to assign DenseMap tombstone or empty key to instruction."); assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() && "Tried to assign DenseMap tombstone or empty key to instruction."); return MINumber; } /// Maps \p *It to an illegal integer. /// /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber. /// /// \returns The integer that \p *It was mapped to. unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) { unsigned MINumber = IllegalInstrNumber; InstrList.push_back(It); UnsignedVec.push_back(IllegalInstrNumber); IllegalInstrNumber--; assert(LegalInstrNumber < IllegalInstrNumber && "Instruction mapping overflow!"); assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() && "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() && "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); return MINumber; } /// \brief Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds /// and appends it to \p UnsignedVec and \p InstrList. /// /// Two instructions are assigned the same integer if they are identical. /// If an instruction is deemed unsafe to outline, then it will be assigned an /// unique integer. The resulting mapping is placed into a suffix tree and /// queried for candidates. /// /// \param MBB The \p MachineBasicBlock to be translated into integers. /// \param TRI \p TargetRegisterInfo for the module. /// \param TII \p TargetInstrInfo for the module. void convertToUnsignedVec(MachineBasicBlock &MBB, const TargetRegisterInfo &TRI, const TargetInstrInfo &TII) { for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et; It++) { // Keep track of where this instruction is in the module. switch (TII.getOutliningType(*It)) { case TargetInstrInfo::MachineOutlinerInstrType::Illegal: mapToIllegalUnsigned(It); break; case TargetInstrInfo::MachineOutlinerInstrType::Legal: mapToLegalUnsigned(It); break; case TargetInstrInfo::MachineOutlinerInstrType::Invisible: break; } } // After we're done every insertion, uniquely terminate this part of the // "string". This makes sure we won't match across basic block or function // boundaries since the "end" is encoded uniquely and thus appears in no // repeated substring. InstrList.push_back(MBB.end()); UnsignedVec.push_back(IllegalInstrNumber); IllegalInstrNumber--; } InstructionMapper() { // Make sure that the implementation of DenseMapInfo<unsigned> hasn't // changed. assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 && "DenseMapInfo<unsigned>'s empty key isn't -1!"); assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 && "DenseMapInfo<unsigned>'s tombstone key isn't -2!"); } }; /// \brief An interprocedural pass which finds repeated sequences of /// instructions and replaces them with calls to functions. /// /// Each instruction is mapped to an unsigned integer and placed in a string. /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree /// is then repeatedly queried for repeated sequences of instructions. Each /// non-overlapping repeated sequence is then placed in its own /// \p MachineFunction and each instance is then replaced with a call to that /// function. struct MachineOutliner : public ModulePass { static char ID; StringRef getPassName() const override { return "Machine Outliner"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<MachineModuleInfo>(); AU.addPreserved<MachineModuleInfo>(); AU.setPreservesAll(); ModulePass::getAnalysisUsage(AU); } MachineOutliner() : ModulePass(ID) { initializeMachineOutlinerPass(*PassRegistry::getPassRegistry()); } /// Find all repeated substrings that satisfy the outlining cost model. /// /// If a substring appears at least twice, then it must be represented by /// an internal node which appears in at least two suffixes. Each suffix is /// represented by a leaf node. To do this, we visit each internal node in /// the tree, using the leaf children of each internal node. If an internal /// node represents a beneficial substring, then we use each of its leaf /// children to find the locations of its substring. /// /// \param ST A suffix tree to query. /// \param TII TargetInstrInfo for the target. /// \param Mapper Contains outlining mapping information. /// \param[out] CandidateList Filled with candidates representing each /// beneficial substring. /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each /// type of candidate. /// /// \returns The length of the longest candidate found. unsigned findCandidates(SuffixTree &ST, const TargetInstrInfo &TII, InstructionMapper &Mapper, std::vector<Candidate> &CandidateList, std::vector<OutlinedFunction> &FunctionList); /// \brief Replace the sequences of instructions represented by the /// \p Candidates in \p CandidateList with calls to \p MachineFunctions /// described in \p FunctionList. /// /// \param M The module we are outlining from. /// \param CandidateList A list of candidates to be outlined. /// \param FunctionList A list of functions to be inserted into the module. /// \param Mapper Contains the instruction mappings for the module. bool outline(Module &M, const ArrayRef<Candidate> &CandidateList, std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper); /// Creates a function for \p OF and inserts it into the module. MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF, InstructionMapper &Mapper); /// Find potential outlining candidates and store them in \p CandidateList. /// /// For each type of potential candidate, also build an \p OutlinedFunction /// struct containing the information to build the function for that /// candidate. /// /// \param[out] CandidateList Filled with outlining candidates for the module. /// \param[out] FunctionList Filled with functions corresponding to each type /// of \p Candidate. /// \param ST The suffix tree for the module. /// \param TII TargetInstrInfo for the module. /// /// \returns The length of the longest candidate found. 0 if there are none. unsigned buildCandidateList(std::vector<Candidate> &CandidateList, std::vector<OutlinedFunction> &FunctionList, SuffixTree &ST, InstructionMapper &Mapper, const TargetInstrInfo &TII); /// \brief Remove any overlapping candidates that weren't handled by the /// suffix tree's pruning method. /// /// Pruning from the suffix tree doesn't necessarily remove all overlaps. /// If a short candidate is chosen for outlining, then a longer candidate /// which has that short candidate as a suffix is chosen, the tree's pruning /// method will not find it. Thus, we need to prune before outlining as well. /// /// \param[in,out] CandidateList A list of outlining candidates. /// \param[in,out] FunctionList A list of functions to be outlined. /// \param Mapper Contains instruction mapping info for outlining. /// \param MaxCandidateLen The length of the longest candidate. /// \param TII TargetInstrInfo for the module. void pruneOverlaps(std::vector<Candidate> &CandidateList, std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper, unsigned MaxCandidateLen, const TargetInstrInfo &TII); /// Construct a suffix tree on the instructions in \p M and outline repeated /// strings from that tree. bool runOnModule(Module &M) override; }; } // Anonymous namespace. char MachineOutliner::ID = 0; namespace llvm { ModulePass *createMachineOutlinerPass() { return new MachineOutliner(); } } // namespace llvm INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false, false) unsigned MachineOutliner::findCandidates(SuffixTree &ST, const TargetInstrInfo &TII, InstructionMapper &Mapper, std::vector<Candidate> &CandidateList, std::vector<OutlinedFunction> &FunctionList) { CandidateList.clear(); FunctionList.clear(); unsigned MaxLen = 0; // FIXME: Visit internal nodes instead of leaves. for (SuffixTreeNode *Leaf : ST.LeafVector) { assert(Leaf && "Leaves in LeafVector cannot be null!"); if (!Leaf->IsInTree) continue; assert(Leaf->Parent && "All leaves must have parents!"); SuffixTreeNode &Parent = *(Leaf->Parent); // If it doesn't appear enough, or we already outlined from it, skip it. if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree) continue; // Figure out if this candidate is beneficial. unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size(); // Too short to be beneficial; skip it. // FIXME: This isn't necessarily true for, say, X86. If we factor in // instruction lengths we need more information than this. if (StringLen < 2) continue; // If this is a beneficial class of candidate, then every one is stored in // this vector. std::vector<Candidate> CandidatesForRepeatedSeq; // Describes the start and end point of each candidate. This allows the // target to infer some information about each occurrence of each repeated // sequence. // FIXME: CandidatesForRepeatedSeq and this should be combined. std::vector< std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>> RepeatedSequenceLocs; // Figure out the call overhead for each instance of the sequence. for (auto &ChildPair : Parent.Children) { SuffixTreeNode *M = ChildPair.second; if (M && M->IsInTree && M->isLeaf()) { // Each sequence is over [StartIt, EndIt]. MachineBasicBlock::iterator StartIt = Mapper.InstrList[M->SuffixIdx]; MachineBasicBlock::iterator EndIt = Mapper.InstrList[M->SuffixIdx + StringLen - 1]; CandidatesForRepeatedSeq.emplace_back(M->SuffixIdx, StringLen, FunctionList.size()); RepeatedSequenceLocs.emplace_back(std::make_pair(StartIt, EndIt)); // Never visit this leaf again. M->IsInTree = false; } } // We've found something we might want to outline. // Create an OutlinedFunction to store it and check if it'd be beneficial // to outline. TargetInstrInfo::MachineOutlinerInfo MInfo = TII.getOutlininingCandidateInfo(RepeatedSequenceLocs); std::vector<unsigned> Seq; for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++) Seq.push_back(ST.Str[i]); OutlinedFunction OF(FunctionList.size(), Parent.OccurrenceCount, Seq, MInfo); unsigned Benefit = OF.getBenefit(); // Is it better to outline this candidate than not? if (Benefit < 1) { // Outlining this candidate would take more instructions than not // outlining. // Emit a remark explaining why we didn't outline this candidate. std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator> C = RepeatedSequenceLocs[0]; MachineOptimizationRemarkEmitter MORE( *(C.first->getParent()->getParent()), nullptr); MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper", C.first->getDebugLoc(), C.first->getParent()); R << "Did not outline " << NV("Length", StringLen) << " instructions" << " from " << NV("NumOccurrences", RepeatedSequenceLocs.size()) << " locations." << " Instructions from outlining all occurrences (" << NV("OutliningCost", OF.getOutliningCost()) << ")" << " >= Unoutlined instruction count (" << NV("NotOutliningCost", StringLen * OF.OccurrenceCount) << ")" << " (Also found at: "; // Tell the user the other places the candidate was found. for (unsigned i = 1, e = RepeatedSequenceLocs.size(); i < e; i++) { R << NV((Twine("OtherStartLoc") + Twine(i)).str(), RepeatedSequenceLocs[i].first->getDebugLoc()); if (i != e - 1) R << ", "; } R << ")"; MORE.emit(R); // Move to the next candidate. continue; } if (StringLen > MaxLen) MaxLen = StringLen; // At this point, the candidate class is seen as beneficial. Set their // benefit values and save them in the candidate list. for (Candidate &C : CandidatesForRepeatedSeq) { C.Benefit = Benefit; C.MInfo = MInfo; CandidateList.push_back(C); } FunctionList.push_back(OF); // Move to the next function. Parent.IsInTree = false; } return MaxLen; } void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList, std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper, unsigned MaxCandidateLen, const TargetInstrInfo &TII) { // Return true if this candidate became unbeneficial for outlining in a // previous step. auto ShouldSkipCandidate = [&FunctionList](Candidate &C) { // Check if the candidate was removed in a previous step. if (!C.InCandidateList) return true; // Check if C's associated function is still beneficial after previous // pruning steps. OutlinedFunction &F = FunctionList[C.FunctionIdx]; if (F.OccurrenceCount < 2 || F.getBenefit() < 1) { assert(F.OccurrenceCount > 0 && "Can't remove OutlinedFunction with no occurrences!"); F.OccurrenceCount--; C.InCandidateList = false; return true; } // C is in the list, and F is still beneficial. return false; }; // Remove C from the candidate space, and update its OutlinedFunction. auto Prune = [&FunctionList](Candidate &C) { // Get the OutlinedFunction associated with this Candidate. OutlinedFunction &F = FunctionList[C.FunctionIdx]; // Update C's associated function's occurrence count. assert(F.OccurrenceCount > 0 && "Can't remove OutlinedFunction with no occurrences!"); F.OccurrenceCount--; // Remove C from the CandidateList. C.InCandidateList = false; DEBUG(dbgs() << "- Removed a Candidate \n"; dbgs() << "--- Num fns left for candidate: " << F.OccurrenceCount << "\n"; dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit() << "\n";); }; // TODO: Experiment with interval trees or other interval-checking structures // to lower the time complexity of this function. // TODO: Can we do better than the simple greedy choice? // Check for overlaps in the range. // This is O(MaxCandidateLen * CandidateList.size()). for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et; It++) { Candidate &C1 = *It; // If C1 was already pruned, or its function is no longer beneficial for // outlining, move to the next candidate. if (ShouldSkipCandidate(C1)) continue; // The minimum start index of any candidate that could overlap with this // one. unsigned FarthestPossibleIdx = 0; // Either the index is 0, or it's at most MaxCandidateLen indices away. if (C1.StartIdx > MaxCandidateLen) FarthestPossibleIdx = C1.StartIdx - MaxCandidateLen; // Compare against the candidates in the list that start at at most // FarthestPossibleIdx indices away from C1. There are at most // MaxCandidateLen of these. for (auto Sit = It + 1; Sit != Et; Sit++) { Candidate &C2 = *Sit; // Is this candidate too far away to overlap? if (C2.StartIdx < FarthestPossibleIdx) break; // If C2 was already pruned, or its function is no longer beneficial for // outlining, move to the next candidate. if (ShouldSkipCandidate(C2)) continue; unsigned C2End = C2.StartIdx + C2.Len - 1; // Do C1 and C2 overlap? // // Not overlapping: // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices // // We sorted our candidate list so C2Start <= C1Start. We know that // C2End > C2Start since each candidate has length >= 2. Therefore, all we // have to check is C2End < C2Start to see if we overlap. if (C2End < C1.StartIdx) continue; // C1 and C2 overlap. // We need to choose the better of the two. // // Approximate this by picking the one which would have saved us the // most instructions before any pruning. if (C1.Benefit >= C2.Benefit) { Prune(C2); } else { Prune(C1); // C1 is out, so we don't have to compare it against anyone else. break; } } } } unsigned MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList, std::vector<OutlinedFunction> &FunctionList, SuffixTree &ST, InstructionMapper &Mapper, const TargetInstrInfo &TII) { std::vector<unsigned> CandidateSequence; // Current outlining candidate. unsigned MaxCandidateLen = 0; // Length of the longest candidate. MaxCandidateLen = findCandidates(ST, TII, Mapper, CandidateList, FunctionList); // Sort the candidates in decending order. This will simplify the outlining // process when we have to remove the candidates from the mapping by // allowing us to cut them out without keeping track of an offset. std::stable_sort(CandidateList.begin(), CandidateList.end()); return MaxCandidateLen; } MachineFunction * MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF, InstructionMapper &Mapper) { // Create the function name. This should be unique. For now, just hash the // module name and include it in the function name plus the number of this // function. std::ostringstream NameStream; NameStream << "OUTLINED_FUNCTION_" << OF.Name; // Create the function using an IR-level function. LLVMContext &C = M.getContext(); Function *F = dyn_cast<Function>( M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C))); assert(F && "Function was null!"); // NOTE: If this is linkonceodr, then we can take advantage of linker deduping // which gives us better results when we outline from linkonceodr functions. F->setLinkage(GlobalValue::PrivateLinkage); F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F); IRBuilder<> Builder(EntryBB); Builder.CreateRetVoid(); MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>(); MachineFunction &MF = MMI.getOrCreateMachineFunction(*F); MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock(); const TargetSubtargetInfo &STI = MF.getSubtarget(); const TargetInstrInfo &TII = *STI.getInstrInfo(); // Insert the new function into the module. MF.insert(MF.begin(), &MBB); TII.insertOutlinerPrologue(MBB, MF, OF.MInfo); // Copy over the instructions for the function using the integer mappings in // its sequence. for (unsigned Str : OF.Sequence) { MachineInstr *NewMI = MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second); NewMI->dropMemRefs(); // Don't keep debug information for outlined instructions. // FIXME: This means outlined functions are currently undebuggable. NewMI->setDebugLoc(DebugLoc()); MBB.insert(MBB.end(), NewMI); } TII.insertOutlinerEpilogue(MBB, MF, OF.MInfo); return &MF; } bool MachineOutliner::outline(Module &M, const ArrayRef<Candidate> &CandidateList, std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper) { bool OutlinedSomething = false; // Replace the candidates with calls to their respective outlined functions. for (const Candidate &C : CandidateList) { // Was the candidate removed during pruneOverlaps? if (!C.InCandidateList) continue; // If not, then look at its OutlinedFunction. OutlinedFunction &OF = FunctionList[C.FunctionIdx]; // Was its OutlinedFunction made unbeneficial during pruneOverlaps? if (OF.OccurrenceCount < 2 || OF.getBenefit() < 1) continue; // If not, then outline it. assert(C.StartIdx < Mapper.InstrList.size() && "Candidate out of bounds!"); MachineBasicBlock *MBB = (*Mapper.InstrList[C.StartIdx]).getParent(); MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.StartIdx]; unsigned EndIdx = C.StartIdx + C.Len - 1; assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!"); MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx]; assert(EndIt != MBB->end() && "EndIt out of bounds!"); EndIt++; // Erase needs one past the end index. // Does this candidate have a function yet? if (!OF.MF) { OF.MF = createOutlinedFunction(M, OF, Mapper); FunctionsCreated++; } MachineFunction *MF = OF.MF; const TargetSubtargetInfo &STI = MF->getSubtarget(); const TargetInstrInfo &TII = *STI.getInstrInfo(); // Insert a call to the new function and erase the old sequence. TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.MInfo); StartIt = Mapper.InstrList[C.StartIdx]; MBB->erase(StartIt, EndIt); OutlinedSomething = true; // Statistics. NumOutlined++; } DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";); return OutlinedSomething; } bool MachineOutliner::runOnModule(Module &M) { // Is there anything in the module at all? if (M.empty()) return false; MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>(); const TargetSubtargetInfo &STI = MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget(); const TargetRegisterInfo *TRI = STI.getRegisterInfo(); const TargetInstrInfo *TII = STI.getInstrInfo(); InstructionMapper Mapper; // Build instruction mappings for each function in the module. for (Function &F : M) { MachineFunction &MF = MMI.getOrCreateMachineFunction(F); // Is the function empty? Safe to outline from? if (F.empty() || !TII->isFunctionSafeToOutlineFrom(MF)) continue; // If it is, look at each MachineBasicBlock in the function. for (MachineBasicBlock &MBB : MF) { // Is there anything in MBB? if (MBB.empty()) continue; // If yes, map it. Mapper.convertToUnsignedVec(MBB, *TRI, *TII); } } // Construct a suffix tree, use it to find candidates, and then outline them. SuffixTree ST(Mapper.UnsignedVec); std::vector<Candidate> CandidateList; std::vector<OutlinedFunction> FunctionList; // Find all of the outlining candidates. unsigned MaxCandidateLen = buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII); // Remove candidates that overlap with other candidates. pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII); // Outline each of the candidates and return true if something was outlined. return outline(M, CandidateList, FunctionList, Mapper); }
[ "courbet@91177308-0d34-0410-b5e6-96231b3b80d8" ]
courbet@91177308-0d34-0410-b5e6-96231b3b80d8
22c7104a287830a94bda85d8159ab52bd06210dc
279238a61d78e867f971902ca1e60e4f559dc266
/ex00/Parser.hpp
dfe584b61ab36493625f5194cb869c4f415ce475
[]
no_license
jferrier34/cpp_d16_2018
3fd914ef540438be81f0ad7cd400a1f67ad24dc5
f0632bab50a69a6ae02f87654868bdda550afd32
refs/heads/master
2023-08-11T22:11:03.563707
2019-01-18T08:06:24
2019-01-18T08:06:24
407,254,421
0
0
null
null
null
null
UTF-8
C++
false
false
344
hpp
/* ** EPITECH PROJECT, 2019 ** Parser.hpp ** File description: ** ex00 */ #ifndef PARSER_H #define PARSER_H #include <stack> #include <string> class Parser { std::stack<char> _operators; std::stack<int> _operands; public: Parser(); ~Parser(); void feed(std::string const&); int result() const; void reset(); }; #endif
[ "jferrier@localhost.localdomain" ]
jferrier@localhost.localdomain
21497800dba0b90df14830c6f591c708a27de31f
ed71c7bc5e116282084713b0ec36b1370780f99e
/icu/source/test/intltest/tfsmalls.h
f62e590a36f731d36c74407a098c6cd8af31bb43
[ "ICU", "LicenseRef-scancode-unicode" ]
permissive
alexswider/dropup.brigade
12e6a12f82a44e568f39b98bb0dbafee78c0c3f7
13fa5308c30786b5bba98564a0959b3c05343502
refs/heads/master
2021-01-18T22:20:51.901107
2016-04-25T18:46:27
2016-04-25T18:46:27
47,217,645
0
0
null
null
null
null
UTF-8
C++
false
false
869
h
/******************************************************************** * COPYRIGHT: * Copyright (c) 1997-2001, International Business Machines Corporation and * others. All Rights Reserved. ********************************************************************/ #ifndef TESTFORMATSMALLCLASSES_H #define TESTFORMATSMALLCLASSES_H #include "intltest.h" /** * tests 3 smaller classes in the format library **/ class TestFormatSmallClasses: public IntlTest { /** * runs tests in 4 local routines, * performs test for API and funtionalty of 3 smaller format classes: * ParsePosition in test_ParsePosition(), * FieldPosition in test_FieldPosition(), * Formattable in test_Formattable(). **/ void runIndexedTest( int32_t index, UBool exec, const char* &name, char* par = NULL ); }; #endif
[ "marcinkozakk@gmail.com" ]
marcinkozakk@gmail.com
2932e7c98d7dc83d5d62d889b33fe6a8292003e6
12b8d53b486019224d3cafbdf8d69e8dd4251a52
/gcpp/classes/oCSSProperty.cpp
29b7087dd866df7f41f1115d4739d09aae5f8868
[ "ISC" ]
permissive
wol22/MotleyTools
468bea011a6621480420952094fe23fb31b5475a
221640737061d91e01d8bf769ce79e131bd79a60
refs/heads/master
2021-01-16T17:42:19.822564
2013-08-02T14:51:53
2013-08-02T14:51:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,771
cpp
/*====================================================================* * * oCSSProperty.cpp - definition of the oCSSProperty class. * * symbol table containing CSS property names; * *. Motley Tools by Charles Maier *: Published 1982-2005 by Charles Maier for personal use *; Licensed under the Internet Software Consortium License * *--------------------------------------------------------------------*/ #ifndef oCSSPROPERTY_SOURCE #define oCSSPROPERTY_SOURCE /*====================================================================* * custom header files; *--------------------------------------------------------------------*/ #include "../classes/oCSSProperty.hpp" /*====================================================================* * * oCSSProperty (); * * *--------------------------------------------------------------------*/ oCSSProperty::oCSSProperty () { static char const * table [] = { "azimuth", "background", "background-attachment", "background-color", "background-image", "background-position", "background-repeat", "border", "border-bottom", "border-bottom-color", "border-bottom-style", "border-bottom-width", "border-collapse", "border-color", "border-left", "border-left-color", "border-left-style", "border-left-width", "border-right", "border-right-color", "border-right-style", "border-right-width", "border-spacing", "border-style", "border-top", "border-top-color", "border-top-style", "border-top-width", "border-width", "bottom", "caption-side", "clear", "clip", "color", "content", "counter-increment", "counter-reset", "cue", "cue-after", "cue-before", "cursor", "direction", "display", "elevation", "empty-cells", "float", "font", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "height", "left", "letter-spacing", "line-height", "list-style", "list-style-image", "list-style-position", "list-style-type", "margin", "margin-bottom", "margin-left", "margin-right", "margin-top", "marker-offset", "marks", "max-height", "max-width", "min-height", "min-width", "orphans", "outline", "outline-color", "outline-style", "outline-width", "overflow", "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", "page", "page-break-after", "page-break-before", "page-break-inside", "pause", "pause-after", "pause-before", "pitch", "pitch-range", "play-during", "position", "quotes", "richness", "right", "size", "speak", "speak-header", "speak-numeral", "speak-punctuation", "speech-rate", "stress", "table-layout", "text-align", "text-decoration", "text-indent", "text-shadow", "text-transform", "top", "unicode-bidi", "vertical-align", "visibility", "voice-family", "volume", "white-space", "widows", "width", "word-spacing", "z-index", (char const *)(0) }; okeywords::mtitle = "CSSProperty"; okeywords::mcount = sizeof (table) / sizeof (char const *) - 1; okeywords::mtable = table; okeywords::mcheck (); return; } /*====================================================================* * * ~oCSSProperty (); * *. Motley Tools by Charles Maier *: Published 1982-2005 by Charles Maier for personal use *; Licensed under the Internet Software Consortium License * *--------------------------------------------------------------------*/ oCSSProperty::~oCSSProperty () { return; } /*====================================================================* * end definition; *--------------------------------------------------------------------*/ #endif
[ "charlesmaier@localhost" ]
charlesmaier@localhost
99022096b56dedc0d40c695934faf466c0df6e80
4a65b0e5b77d57a6dde55e2bf001c415f148ef21
/Src/EditableStringView.cpp
9e89d173e341a15f4d0e8af9df98f728792b6e46
[ "MIT" ]
permissive
thinkpractice/bme
99829da10f79b224cececb996ba1480d11dab2d1
8f55457fa2900e41ff112188b8683b4312e99d73
refs/heads/master
2021-06-01T22:26:05.779520
2016-11-19T17:24:40
2016-11-19T17:24:40
56,915,046
1
0
null
null
null
null
UTF-8
C++
false
false
3,578
cpp
/***************************************************************** * Copyright (c) 2005 Tim de Jong * * * * All rights reserved. * * Distributed under the terms of the MIT License. * *****************************************************************/ #ifndef EDITABLE_STRING_VIEW #include "EditableStringView.h" #endif #include <be/app/Messenger.h> #include <be/interface/Window.h> #include <iostream> EditableStringView::EditableStringView(BRect frame, const char *name, const char *text, BMessage *message, const char* label, uint32 resizingMode, uint32 flags) : BControl(frame, name, label, message, resizingMode, flags), m_editing(false) { //construct label view m_labelView = new BStringView(Bounds(), name, text, resizingMode, flags); m_labelView->AddFilter(new MouseDownFilter(this)); AddChild(m_labelView); //construct edit view BRect textRect = Bounds(); m_editView = new BTextView(Bounds(),"editView", textRect, B_FOLLOW_ALL_SIDES, B_WILL_DRAW); m_editView->AddFilter(new KeyFilter(this)); m_editScroll = new BScrollView("editScroll",m_editView); AddChild(m_editScroll); m_editScroll->Hide(); } EditableStringView::~EditableStringView() { } void EditableStringView::MessageReceived(BMessage *message) { switch(message->what) { case K_CHANGE_VIEW_MSG: { m_editing = !m_editing; if (m_editing) { //start the editing process m_editScroll->Show(); m_editView->MakeFocus(true); m_editView->SelectAll(); m_labelView->Hide(); } else { //end editing m_editScroll->Hide(); m_labelView->Show(); m_labelView->SetText(m_editView->Text()); //notify user that the label has been changed Invoke(); } } break; default: BView::MessageReceived(message); break; } } void EditableStringView::SetFont(const BFont *font, uint32 properties) { m_labelView->SetFont(font, properties); m_editView->SetFont(font, properties); BView::SetFont(font, properties); } void EditableStringView::SetText(const char *string) { m_labelView->SetText(string); m_editView->SetText(string); } const char* EditableStringView::Text() const { return m_editView->Text(); } //======================================MouseDownFilter==================================================== MouseDownFilter::MouseDownFilter(BView *owner) : BMessageFilter(B_ANY_DELIVERY,B_ANY_SOURCE), m_owner(owner) { } MouseDownFilter::~MouseDownFilter() { } filter_result MouseDownFilter::Filter(BMessage *message, BHandler **target) { filter_result result = B_DISPATCH_MESSAGE; switch (message->what) { case B_MOUSE_DOWN: { //send message to owner BMessenger owner(m_owner); owner.SendMessage(new BMessage(K_CHANGE_VIEW_MSG)); result = B_SKIP_MESSAGE; } break; } return result; } //=====================================KeyFilter=========================================================== KeyFilter::KeyFilter(BView *owner) : BMessageFilter(B_ANY_DELIVERY,B_ANY_SOURCE), m_owner(owner) { } KeyFilter::~KeyFilter() { } filter_result KeyFilter::Filter(BMessage *message, BHandler **target) { filter_result result = B_DISPATCH_MESSAGE; switch (message->what) { case B_KEY_DOWN: { int8 byte; if (message->FindInt8("byte", &byte) == B_OK) { if (byte == B_ENTER) { //send message to owner BMessenger owner(m_owner); owner.SendMessage(new BMessage(K_CHANGE_VIEW_MSG)); result = B_SKIP_MESSAGE; } } } break; } return result; }
[ "opensource@thinkpractice.nl" ]
opensource@thinkpractice.nl
f136d6cfad26054247607d98ac7fa0b5818e3d2d
9d2c5d766a9bc46bb9c2e8c2981147c7b8a61edb
/server.cpp
f7e1d9a46f595cc86039436da85e13e7c09d6b4c
[]
no_license
anamika25/TFTP-Server
6202b4fe9b73f1e2db7f07c4652e6356de642c7c
4c508fe8a5ceddfc5f372a1620b5be1cb8d47c7a
refs/heads/master
2021-09-05T18:07:13.753509
2018-01-30T05:11:12
2018-01-30T05:11:12
119,483,050
0
0
null
null
null
null
UTF-8
C++
false
false
11,063
cpp
#include <stdio.h> #include <cstdio> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/time.h> #include <time.h> #include <iostream> #include <string> #include <set> #include <map> #include <sstream> using namespace std; // port to listen #define PORT "9048" // get sockaddr, IPv4/IPv6 void *get_in_addr(struct sockaddr *socket_addr) { if (socket_addr->sa_family == AF_INET) { return &(((struct sockaddr_in*)socket_addr)->sin_addr); } return &(((struct sockaddr_in6*)socket_addr)->sin6_addr); } struct tftp_packet { int16_t opcode; int16_t blockno; int16_t errcode; char filename[30]; }; struct client_info { struct sockaddr_in client_addr; char filename[30]; struct timeval time_start, time_end; int last_ack; FILE *fp; FILE *fp_end; int16_t block_num; int block_size = false; //bool retran ; }; void packi16 (char *buf, unsigned short int i) { i = htons(i); memcpy(buf,&i,2); } unsigned short int unpacki16(char *buf) { unsigned short int i; memcpy(&i,buf,2); i = ntohs(i); return i; } int main(int argc, char* argv[]) { if(argc!=3) { cout<<"please enter server, server_ip_address, server_port \n"<<endl; } fd_set master; // master file descriptor list fd_set read_fds; // temp file descriptor list for select() /*struct SBCP_packet packet_recv, packet_send; //set<string> user_list; char user_name[16]; char message[512]; char reason[32]; int client_count = 0; string msg="";*/ map<int,client_info*> list_of_clients; struct client_info *client; int fdmax; // maximum file descriptor number int listener; // listening socket descriptor int newfd; // newly accept()ed socket descriptor struct sockaddr_in serveraddr, clientaddr; // client address socklen_t addrlen, templen; char buf[700]; // buffer for incoming data //char buf_send[700]; //buffer for outgoing data //int nbytes; char remoteIP[INET6_ADDRSTRLEN]; //int yes=1; // for setsockopt() SO_REUSEADDR, below int i, j, rv; struct addrinfo hints, *ai, *p; FD_ZERO(&master); // clear the master and temp sets FD_ZERO(&read_fds); // get us a socket and bind it memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE; if ((rv = getaddrinfo(argv[1], argv[2], &hints, &ai)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); exit(1); } for(p = ai; p != NULL; p = p->ai_next) { listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (listener < 0) { perror("socket error"); continue; } // lose the pesky "address already in use" error message //setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) { close(listener); perror("bind error"); continue; } break; } // if we got here, it means we didn't get bound if (p == NULL) { fprintf(stderr, "selectserver: failed to bind\n"); exit(2); } freeaddrinfo(ai); // all done with this /* listen if (listen(listener, 100) == -1) { perror("listen"); exit(3); }*/ // add the listener to the master set FD_SET(listener, &master); // keep track of the biggest file descriptor fdmax = listener; // so far, it's this one // main loop for(;;) { //cout<<"entering main loop"<<endl; read_fds = master; // copy it if (select(fdmax+1, &read_fds, NULL, NULL,NULL) == -1) { perror("select"); exit(4); } //cout<<"listener:"<<listener<<endl; //put check for timeout for (auto it = list_of_clients.begin(); it != list_of_clients.end(); it++) { gettimeofday(&(it->second->time_end), NULL); double interval = it->second->time_end.tv_usec - it->second->time_start.tv_usec; if (interval >= 100000) { cout << "timeout for filename " << it->second->filename << endl; //it->second->retran = true; fseek(it->second->fp, -it->second->block_size, SEEK_CUR); uint16_t opcode = htons(3); uint16_t block_num = htons(it->second->block_num); char buf_send[600] = { 0 }; memcpy(buf_send, &opcode, 2); memcpy(buf_send + 2, &block_num, 2); int size = ftell(it->second->fp_end) - ftell(it->second->fp); if (size >= 512) size = 512; else it->second->last_ack = 1; fread(buf_send + 4, 1, size, it->second->fp); sendto(i, buf_send, size + 4, 0, (struct sockaddr *)&(it->second->client_addr), addrlen); cout << "retransmitting block num= " << it->second->block_num << endl; } } // run through the existing connections looking for data to read for(i = 0; i <= fdmax; i++) { if (FD_ISSET(i, &read_fds)) // we have a client { if(i==listener) //new client { addrlen = sizeof(clientaddr); if(recvfrom(listener, buf, 512,0, (struct sockaddr *)&clientaddr ,(socklen_t*)&addrlen)==-1) { perror("recvfrom"); return -1; } //read packet struct tftp_packet *received; received = (struct tftp_packet *)malloc(sizeof(struct tftp_packet)); received->opcode = unpacki16(buf); //action according to opcode if(received->opcode==1) //RRQ { char temp[30]; int index=2, temp_index=0; while(buf[index]!='\0') { temp[temp_index++] = buf[index++]; } temp[temp_index]='\0'; //received->filename = (char *)malloc(strlen(temp)*sizeof(char)); strcpy(received->filename,temp); newfd = socket(AF_INET, SOCK_DGRAM, 0); //create new socket cout<<"Received RRQ for file "<<received->filename<<" on socket "<<newfd<<endl; if (newfd<0) { perror("accept"); return -1; } FD_SET(newfd, &master); if (newfd > fdmax) fdmax = newfd; srand(time(NULL)); short int client_port = rand() % 1001 + 3000; memset(&serveraddr, 0, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(client_port); serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(newfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))<0) { perror("bind"); return 1; } //fill the client information client = new client_info; strcpy(client->filename, received->filename); client->last_ack = 0; client->client_addr = clientaddr; list_of_clients[newfd] = client; list_of_clients[newfd]->fp = fopen(received->filename, "r"); if (list_of_clients[newfd]->fp == NULL) //failed to open the file { uint16_t opcode = htons(5); uint16_t err_code = htons(1); char buf_send[100] = {0}; memcpy(buf_send, &opcode, 2); memcpy(buf_send+2, &err_code, 2); memcpy(buf_send+4, "File not found", strlen("File not found")); addrlen = sizeof(struct sockaddr_in); if (sendto(newfd, buf_send, 100, 0, (struct sockaddr *)&list_of_clients[newfd]->client_addr, addrlen)!=-1) { cout << "Error Message sent: failed to open file"<<endl; } else { cout << "Error Message failed to send"<<endl; } map<int, client_info *>::iterator it = list_of_clients.find(newfd); list_of_clients.erase(it); close(newfd); cout<<"connection closed due to error"<<endl; FD_CLR(newfd, &master); } else { uint16_t opcode = htons(3); uint16_t block_num = htons(1); char buf_send[600] = { 0 }; memcpy(buf_send, &opcode, 2); memcpy(buf_send + 2, &block_num, 2); list_of_clients[newfd]->fp_end = list_of_clients[newfd]->fp; fseek(list_of_clients[newfd]->fp_end, 0, SEEK_END); list_of_clients[newfd]->fp = fopen(received->filename, "r"); //fseek(list_of_clients[newfd]->fp, 0, SEEK_SET); //rewind(list_of_clients[newfd]->fp); int size = ftell(list_of_clients[newfd]->fp_end) - ftell(list_of_clients[newfd]->fp); //cout<<"size="<<size<<endl; if (size >= 512) size = 512; else list_of_clients[newfd]->last_ack = 1; list_of_clients[newfd]->block_size = size; list_of_clients[newfd]->block_num = 1; gettimeofday(&(list_of_clients[newfd]->time_start), NULL); fread(buf_send + 4, 1, size, list_of_clients[newfd]->fp); /* if ( fgets (buf_send , 50 , list_of_clients[newfd]->fp) != NULL ) puts (buf_send); else cout<<"size="<<size; cout<<endl;*/ sendto(newfd, buf_send, size + 4, 0, (struct sockaddr *)&list_of_clients[newfd]->client_addr, addrlen); cout << "sent block num= " << list_of_clients[newfd]->block_num << endl; } } delete(received); } else //old client { addrlen = sizeof(clientaddr); if(recvfrom(i, buf, 512,0, (struct sockaddr *)&clientaddr ,(socklen_t*)&addrlen)==-1) { perror("recvfrom"); return -1; } //read packet struct tftp_packet *received; received = (struct tftp_packet *)malloc(sizeof(struct tftp_packet)); received->opcode = unpacki16(buf); if ((received->opcode == 4)) { if (list_of_clients[i]->last_ack) //connection close as the ACK is for the last block { fclose(list_of_clients[i]->fp); auto it = list_of_clients.find(i); list_of_clients.erase(it); cout<<"file transfer completed"<<endl; break; } received->blockno = unpacki16(buf + 2); if (list_of_clients[i]->block_num == received->blockno) //send the next block with block_num+1 { //fseek(list_of_clients[i]->fp, -list_of_clients[i]->block_size, SEEK_CUR); cout<<"Received ACK for file "<<list_of_clients[i]->filename<<" on socket "<<newfd<<" for block "<<received->blockno<<endl; uint16_t opcode = htons(3); uint16_t block_num = htons(received->blockno + 1); char buf_send[600] = { 0 }; memcpy(buf_send, &opcode, 2); memcpy(buf_send + 2, &block_num, 2); //list_of_clients[i]->fp_end = list_of_clients[newfd]->fp; //fseek(list_of_clients[i]->fp_end, 0, SEEK_END); int size = ftell(list_of_clients[i]->fp_end) - ftell(list_of_clients[i]->fp); //cout<<"size="<<size<<endl; if (size >= 512) size = 512; else list_of_clients[i]->last_ack = 1; list_of_clients[i]->block_size = size; list_of_clients[i]->block_num++; gettimeofday(&(list_of_clients[i]->time_start), NULL); fread(buf_send + 4, 1, size, list_of_clients[i]->fp); sendto(i, buf_send, size + 4, 0, (struct sockaddr *)&list_of_clients[i]->client_addr, addrlen); cout << "sent block num= " <<list_of_clients[i]->block_num << endl; } } delete(received); } } } } return 0; }
[ "{ID?}-{username}@users.noreply.github.com" ]
{ID?}-{username}@users.noreply.github.com
b1456f6643b119c8326967ee3067a4ab2015f2e7
d4b733f2e00b5d0ab103ea0df6341648d95c993b
/src/c-cpp/lib/sst/private/guts/generic_socket_poll_set/consolidate-windows.cpp
367a21b1df5b02bef84b9003cad75c3c9cd4ab1e
[ "MIT" ]
permissive
stealthsoftwareinc/sst
ad6117a3d5daf97d947862674336e6938c0bc699
f828f77db0ab27048b3204e10153ee8cfc1b2081
refs/heads/master
2023-04-06T15:21:14.371804
2023-03-24T08:30:48
2023-03-24T08:30:48
302,539,309
1
0
null
null
null
null
UTF-8
C++
false
false
1,949
cpp
// // Copyright (C) 2012-2023 Stealth Software Technologies, Inc. // // 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 (including // the next paragraph) 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. // // SPDX-License-Identifier: MIT // // Include first to test independence. #include <sst/private/guts/generic_socket_poll_set.hpp> // Include twice to test idempotence. #include <sst/private/guts/generic_socket_poll_set.hpp> // #include <sst/catalog/SST_WITH_WINDOWS_WS2_32.h> #if SST_WITH_WINDOWS_WS2_32 #include <sst/catalog/windows_socket.hpp> #include <sst/catalog/windows_socket_poll_set_entry.hpp> #include <sst/private/guts/generic_socket_poll_set/pfd_t-windows.hpp> namespace sst { namespace guts { template<> void generic_socket_poll_set< sst::windows_socket, sst::windows_socket_poll_set_entry>::consolidate() { this->template consolidate_helper<pfd_t>(); } } // namespace guts } // namespace sst #endif // #if SST_WITH_WINDOWS_WS2_32
[ "sst@stealthsoftwareinc.com" ]
sst@stealthsoftwareinc.com
1a053157bbfa0c84e5df398342732dd2b173bb81
c42aa20328948971e0f28fc29d3547b6f3bab693
/player/common.cpp
136bc6b4f1c1a16619ece901be4fb70cd9acf219
[]
no_license
JarrettBillingsley/DecompilingSonic1
9d3cca3b68c0af48675a41b2a95d6d18301980f9
3238a55ac642cf8f8b0e26b61727c295290173af
refs/heads/master
2020-03-29T09:57:05.815554
2015-11-11T22:49:14
2015-11-11T22:49:14
42,833,717
6
3
null
2020-02-14T17:26:34
2015-09-20T23:29:45
C++
UTF-8
C++
false
false
3,607
cpp
bool Player_IsFlipped () { return Obj_IsFlipped(v_player); } bool Player_IsInAir () { return Obj_IsInAir(v_player); } bool Player_IsRolling () { return Obj_IsRolling(v_player); } bool Player_IsStanding () { return Obj_IsStanding(v_player); } bool Player_IsJumping () { return Obj_IsJumping(v_player); } bool Player_IsPushing () { return Obj_IsPushing(v_player); } bool Player_IsUnderwater() { return Obj_IsUnderwater(v_player); } void Player_SetFlipped (bool val = true) { Obj_SetFlipped (v_player, val); } void Player_SetInAir (bool val = true) { Obj_SetInAir (v_player, val); } void Player_SetRolling (bool val = true) { Obj_SetRolling (v_player, val); } void Player_SetStanding (bool val = true) { Obj_SetStanding (v_player, val); } void Player_SetJumping (bool val = true) { Obj_SetJumping (v_player, val); } void Player_SetPushing (bool val = true) { Obj_SetPushing (v_player, val); } void Player_SetUnderwater(bool val = true) { Obj_SetUnderwater(v_player, val); } void Player_SetNotFlipped() { Obj_SetNotFlipped(v_player); } void Player_SetNotInAir() { Obj_SetNotInAir(v_player); } void Player_SetNotRolling() { Obj_SetNotRolling(v_player); } void Player_SetNotStanding() { Obj_SetNotStanding(v_player); } void Player_SetNotJumping() { Obj_SetNotJumping(v_player); } void Player_SetNotPushing() { Obj_SetNotPushing(v_player); } void Player_SetNotUnderwater() { Obj_SetNotUnderwater(v_player); } bool Player_IsDead() { return v_player->routine >= PlayerRoutine_Dead; } bool Player_IsControllable() { return v_player->routine < PlayerRoutine_Hurt; } void Player_SetHurt() { v_player->routine = PlayerRoutine_Hurt; } void Player_SetDead() { v_player->routine = PlayerRoutine_Dead; } void Player_SetAnimFloat() { v_player->anim = 0xF; } void Player_SetAnimDrowning() { v_player->anim = 0x17; } void Player_SetAnimSlide() { v_player->anim = 0x1F; } // a0 a2 void Player_Hurt(Object* player, Object* obj) { // If he has no shield.. if(!v_shield) { // if he has rings, make the rings spill out if(v_rings) { if(auto ringLoss = FindFreeObj()) { ringLoss->id = ID_RingLoss; ringLoss->x = player->x; ringLoss->y = player->y; } } else if(!f_debugmode) // otherwise, kill him (if debug mode isn't on) { Player_Kill(player, obj); return; } } // Hurt sonic v_shield = 0; Player_SetHurt(); Player_ResetOnFloor(player); Player_SetInAir(); // Bounce him away if(Player_IsUnderwater()) { player->velY = -0x200; player->velX = -0x100; } else { player->velY = -0x400; player->velX = -0x200; } // Make him bounce right if he's to the right of the object if(player->x > obj->x) player->velX = -player->velX; player->inertia = 0; player->anim = Anim::Hurt; VAR_W(player, Player_InvincibilityW) = 120; // 2 seconds of invincibility; // Bwah if(obj->id == ID_Spikes || obj->id == ID_Harpoon) PlaySound_Special(SFX_HitSpikes); else PlaySound_Special(SFX_Death); } // a0 a2 void Player_Kill(Object* player, Object* killer) { if(v_debuguse) return; // Set him up to do the death bounce v_invinc = 0; Player_SetDead(); Player_ResetOnFloor(player); Player_SetInAir(); player->velY = -0x700; player->velX = 0; player->inertia = 0; VAR_W(player, Player_DeathOrigYW) = player->y; player->anim = Anim::Death; BSET(player->gfx, 0x80); // Bwah if(killer->id == ID_Spikes) PlaySound_Special(SFX_HitSpikes); else PlaySound_Special(SFX_Death); }
[ "jarrett.billingsley@gmail.com" ]
jarrett.billingsley@gmail.com
2cb322bc8a90873b2ceb33986989428105b29638
befaf0dfc5880d18f42e1fa7e39e27f8d2f8dde9
/SDK/SCUM_Event_1H_N9_Black_classes.hpp
13aa8cb779d7f6fbda9437758eb6250763fcb567
[]
no_license
cpkt9762/SCUM-SDK
0b59c99748a9e131eb37e5e3d3b95ebc893d7024
c0dbd67e10a288086120cde4f44d60eb12e12273
refs/heads/master
2020-03-28T00:04:48.016948
2018-09-04T13:32:38
2018-09-04T13:32:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
936
hpp
#pragma once // SCUM (0.1.17.8320) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SCUM_Event_1H_N9_Black_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Event_1H_N9_Black.Event_1H_N9_Black_C // 0x0008 (0x07D8 - 0x07D0) class AEvent_1H_N9_Black_C : public AWeaponItem { public: class UMeleeAttackCollisionCapsule* MeleeAttackCollisionCapsule; // 0x07D0(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_InstancedReference, CPF_IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("BlueprintGeneratedClass Event_1H_N9_Black.Event_1H_N9_Black_C"); return ptr; } void UserConstructionScript(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
8ee17980724818e501b03634ca1d051ebcc3bcc6
170957e55bba18bf1c2d44195329b25e3305323c
/Arduino/led_control/led_control.ino
5b61e1285fa1498f1801f300e0cc04ec405138c7
[]
no_license
nikolaevis/Arduino-ultrasonic-sensor-control
7278af2e002a4d641baa4fcfe687d1b53b21499c
11e40ef48577dc046ecc7ee94878853e9aefffad
refs/heads/master
2021-01-01T18:46:30.665629
2018-06-06T11:42:45
2018-06-06T11:42:45
98,433,628
0
0
null
null
null
null
UTF-8
C++
false
false
1,837
ino
/* Simple LED sketch */ int led1 = 3;// Pin 3 int led2 = 4;// Pin 4 int led3 = 5;// Pin 5 void setup() { pinMode(led1, OUTPUT); // Set pin 3 as digital out pinMode(led2, OUTPUT); // Set pin 4 as digital out pinMode(led3, OUTPUT); // Set pin 5 as digital out // Start up serial connection Serial.begin(9600); // baud rate Serial.flush(); } void loop() { String input = ""; // Read any serial input while (Serial.available() > 0) { input += (char) Serial.read(); // Read in one char at a time delay(5); // Delay for 5 ms so the next char has time to be received } //handshake if (input == "<Hello Arduino>"){ Serial.println("<Hello there>"); digitalWrite(led1, HIGH); digitalWrite(led2, HIGH); digitalWrite(led3, HIGH); delay(100); digitalWrite(led1, LOW); digitalWrite(led2, LOW); digitalWrite(led3, LOW); } if (input == "on1") { digitalWrite(led1, HIGH); // on } else if (input == "off1") { digitalWrite(led1, LOW); // off } else if (input == "on2") { digitalWrite(led2, HIGH); // on } else if (input == "off2") { digitalWrite(led2, LOW); // off } else if (input == "on3") { digitalWrite(led3, HIGH); // on } else if (input == "off3") { digitalWrite(led3, LOW); // off } else if (input == "on_all") { digitalWrite(led1, HIGH); // on digitalWrite(led2, HIGH); // on digitalWrite(led3, HIGH); // on } else if (input == "off_all") { digitalWrite(led1, LOW); // on digitalWrite(led2, LOW); // on digitalWrite(led3, LOW); // off } }
[ "igor_nikolaev@cz.ibm.com" ]
igor_nikolaev@cz.ibm.com
dd6d645e31a92c36f75c359761b9bc42bc0b8405
2bbca1dd862b65b9a1aa5bd4fc5402a557e4036f
/qspotifyutil.h
c56aedc11ae6982cac76be970b9314987d8c4512
[]
no_license
juiceme/libQtSpotify
5bb5397d37a7e3a9110dfc8385dbd7fbe639660b
9cf1ef4752522552370c426e2861cdedde6c20da
refs/heads/master
2020-03-21T10:44:51.612525
2018-03-22T14:35:29
2018-03-22T14:35:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
274
h
#ifndef QSPOTIFYUTIL_H #define QSPOTIFYUTIL_H #include <functional> class QString; struct sp_link; class QSpotifyUtil { public: QSpotifyUtil(); static void spLinkToQString(sp_link *link, std::function<void(const QString&)> consumer); }; #endif // QSPOTIFYUTIL_H
[ "lukedirtwalker@gmail.com" ]
lukedirtwalker@gmail.com
5641674050dc7e13bc0bb8f371f545a6d4a5253e
515a28f08f58aaab7e277c90c7902c21bc8f4125
/src/lipservice/PLOTR/Card5/Xstep.hpp
b6140e4907664e0f8df6a964df71224a59b30030
[ "BSD-2-Clause" ]
permissive
njoy/lipservice
e3bf4c8c07d79a46c13a88976f22ee07e416f4a6
1efa5e9452384a7bfc278fde57979c4d91e312c0
refs/heads/master
2023-08-04T11:01:04.411539
2021-01-20T22:24:17
2021-01-20T22:24:17
146,359,436
0
2
NOASSERTION
2023-07-25T19:41:10
2018-08-27T22:05:50
C++
UTF-8
C++
false
false
840
hpp
struct Xstep { using Value_t = std::optional< double >; static std::string name(){ return "xstep"; } static std::string description(){ return "The xstep argument specifies the spacing for tics on the energy (x)\n" "axis.\n\n" "The default behavior is automatic scaling. If the default is used,\n" "the default should be used for el and eh as well.\n\n" "The value is ignored if log scaling is used."; } static Value_t defaultValue(){ // const Value_t el ){ // if( el != std::nullopt ){ // Log::info( "When using a default value in PLOTR::Card5, all values\n" // "should use their default value.\n" ); // std::exception e; // throw e; // } return std::nullopt; } static bool verify( const Value_t v ){ //, const Value_t ){ return *v > 0.0; } };
[ "jlconlin@lanl.gov" ]
jlconlin@lanl.gov
94a2b17e4bba50dfe045637151cfa7817290276e
d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3
/Modules/Filtering/BiasCorrection/include/itkMRASlabIdentifier.hxx
bed513de391080321896176bce89ee1ab83e3b4f
[ "SMLNJ", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "NTP", "IJG", "GPL-1.0-or-later", "libtiff", "BSD-4.3TAHOE", "Zlib", "MIT", "LicenseRef-scancode-proprietary-license", "Spencer-86", "Apache-2.0", "FSFUL", "LicenseRef-scancode-public-domain", "Libpng", "BSD-2-Clause" ]
permissive
nalinimsingh/ITK_4D
18e8929672df64df58a6446f047e6ec04d3c2616
95a2eacaeaffe572889832ef0894239f89e3f303
refs/heads/master
2020-03-17T18:58:50.953317
2018-10-01T20:46:43
2018-10-01T21:21:01
133,841,430
0
0
Apache-2.0
2018-05-17T16:34:54
2018-05-17T16:34:53
null
UTF-8
C++
false
false
5,556
hxx
/*========================================================================= * * 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 itkMRASlabIdentifier_hxx #define itkMRASlabIdentifier_hxx #include <algorithm> #include <vector> #include <queue> #include "itkMRASlabIdentifier.h" #include "itkImageRegionIterator.h" #include "itkMath.h" namespace itk { template< typename TInputImage > MRASlabIdentifier< TInputImage > ::MRASlabIdentifier() { m_Image = ITK_NULLPTR; m_NumberOfSamples = 10; m_BackgroundMinimumThreshold = NumericTraits< ImagePixelType >::min(); m_Tolerance = 0.0; // default slicing axis is z m_SlicingDirection = 2; } template< typename TInputImage > void MRASlabIdentifier< TInputImage > ::GenerateSlabRegions(void) { // this method only works with 3D MRI image if ( ImageType::ImageDimension != 3 ) { itkExceptionMacro("ERROR: This algorithm only works with 3D images."); } ImageSizeType size; ImageRegionType region; ImageIndexType index; region = m_Image->GetLargestPossibleRegion(); size = region.GetSize(); index = region.GetIndex(); IndexValueType firstSlice = index[m_SlicingDirection]; IndexValueType lastSlice = firstSlice + size[m_SlicingDirection]; SizeValueType totalSlices = size[m_SlicingDirection]; double sum; std::vector< double > avgMin(totalSlices); // calculate minimum intensities for each slice ImagePixelType pixel; for ( int i = 0; i < 3; i++ ) { if ( i != m_SlicingDirection ) { index[i] = 0; } } size[m_SlicingDirection] = 1; region.SetSize(size); SizeValueType count = 0; IndexValueType currentSlice = firstSlice; while ( currentSlice < lastSlice ) { index[m_SlicingDirection] = currentSlice; region.SetIndex(index); ImageRegionConstIterator< TInputImage > iter(m_Image, region); iter.GoToBegin(); std::priority_queue< ImagePixelType > mins; for ( unsigned int i = 0; i < m_NumberOfSamples; ++i ) { mins.push( NumericTraits< ImagePixelType >::max() ); } while ( !iter.IsAtEnd() ) { pixel = iter.Get(); if ( pixel > m_BackgroundMinimumThreshold ) { if ( mins.top() > pixel ) { mins.pop(); mins.push(pixel); } } ++iter; } sum = 0.0; while ( !mins.empty() ) { sum += mins.top(); mins.pop(); } avgMin[count] = sum / (double)m_NumberOfSamples; ++count; ++currentSlice; } // calculate overall average sum = 0.0; std::vector< double >::iterator am_iter = avgMin.begin(); while ( am_iter != avgMin.end() ) { sum += *am_iter; ++am_iter; } double average = sum / (double)totalSlices; // determine slabs am_iter = avgMin.begin(); double prevSign = *am_iter - average; double avgMinValue; ImageIndexType slabIndex; ImageRegionType slabRegion; ImageSizeType slabSize; SizeValueType slabLength = 0; IndexValueType slabBegin = firstSlice; slabSize = size; slabIndex = index; while ( am_iter != avgMin.end() ) { avgMinValue = *am_iter; double sign = avgMinValue - average; if ( ( sign * prevSign < 0 ) && ( itk::Math::abs(sign) > m_Tolerance ) ) { slabIndex[m_SlicingDirection] = slabBegin; slabSize[m_SlicingDirection] = slabLength; slabRegion.SetSize(slabSize); slabRegion.SetIndex(slabIndex); m_Slabs.push_back(slabRegion); prevSign = sign; slabBegin += slabLength; slabLength = 0; } am_iter++; slabLength++; } slabIndex[m_SlicingDirection] = slabBegin; slabSize[m_SlicingDirection] = slabLength; slabRegion.SetIndex(slabIndex); slabRegion.SetSize(slabSize); m_Slabs.push_back(slabRegion); } template< typename TInputImage > typename MRASlabIdentifier< TInputImage >::SlabRegionVectorType MRASlabIdentifier< TInputImage > ::GetSlabRegionVector(void) { return m_Slabs; } template< typename TInputImage > void MRASlabIdentifier< TInputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); if ( m_Image ) { os << indent << "Image: " << m_Image << std::endl; } else { os << indent << "Image: " << "(None)" << std::endl; } os << indent << "NumberOfSamples: " << m_NumberOfSamples << std::endl; os << indent << "SlicingDirection: " << m_SlicingDirection << std::endl; os << indent << "Background Pixel Minimum Intensity Threshold: " << m_BackgroundMinimumThreshold << std::endl; os << indent << "Tolerance: " << m_Tolerance << std::endl; } } // end namespace itk #endif /* itkMRASlabIdentifier_hxx */
[ "ruizhi@csail.mit.edu" ]
ruizhi@csail.mit.edu
c3fc7ad56d655dd15cecf126d2ab982269fa55a2
bac1c0c112e93e0838e622246d2a5be6c2c00219
/server/Server.hpp
404ba084d8a64b36a04d3834720a872bca7f8a10
[]
no_license
ThoSe1990/cppDatabase
bc1135dd83ff93b216a5135f0d2fc9295e8e81aa
6a65aaaa4a49623892a9fa965b322bbd10ea0f57
refs/heads/master
2023-05-06T13:07:39.408098
2021-05-27T10:49:16
2021-05-27T10:49:16
370,110,951
0
0
null
null
null
null
UTF-8
C++
false
false
2,111
hpp
#ifndef _SERVER_SERVER_HPP_ #define _SERVER_SERVER_HPP_ #include <iostream> #include <boost/asio.hpp> #include "DatabaseServerApi.hpp" using boost::asio::ip::tcp; class Session : public std::enable_shared_from_this<Session> { public: Session(tcp::socket Socket) : socket(std::move(Socket)){ } void Run() { std::cout << "session created" << std::endl; waitForRequest(); } private: tcp::socket socket; boost::asio::streambuf buffer; const std::string end_of_stream{"<EOF>"}; void waitForRequest() { auto self(shared_from_this()); boost::asio::async_read_until(socket, buffer, end_of_stream, [this, self](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) { std::string serializedData { buffers_begin(buffer.data()), buffers_end(buffer.data()) - end_of_stream.length() }; buffer.consume(buffer.size()); DatabaseServerApi::HandleRequest(std::move(serializedData), socket); DatabaseServerApi::Update(); waitForRequest(); } else std::cout << "error: " << ec << std::endl;; }); } }; class Server { public: Server(boost::asio::io_context& io_context, short port) : acceptor(io_context, tcp::endpoint(tcp::v4(), port)) { do_accept(); } private: tcp::acceptor acceptor; void do_accept() { acceptor.async_accept( [this](boost::system::error_code ec, tcp::socket socket) { if (!ec) { std::cout << "creating session on: " << socket.remote_endpoint().address().to_string() << ":" << socket.remote_endpoint().port() << std::endl; std::make_shared<Session>(std::move(socket))->Run(); } else std::cout << "error: " << ec.message() << std::endl; do_accept(); }); } }; #endif
[ "thomas.sedlmair@googlemail.com" ]
thomas.sedlmair@googlemail.com
ead4b7016944910f54b573bc743b730c7a91aacd
313269781178b4aa9d585a6c7f7a8f63b07df439
/etu-impala-cdh1.0.1/src/debug/impala-1.0.1-SNAPSHOT/be/generated-sources/gen-cpp/Frontend_types.cpp
d32232f586685b4574ecb52918161e38ba46a46a
[]
no_license
stephenchinqlz/pkgs
06f8823cd8a646527a3eae787c5dd7f6c8da81f4
796bf57f1034ac54c3b3788c9c3fa907b4fc1ab7
refs/heads/master
2021-01-24T05:15:16.299619
2013-07-06T17:23:01
2013-07-06T17:23:01
null
0
0
null
null
null
null
UTF-8
C++
false
true
134,047
cpp
/** * Autogenerated by Thrift Compiler (0.9.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "Frontend_types.h" #include <algorithm> namespace impala { int _kTFileFormatValues[] = { TFileFormat::PARQUETFILE, TFileFormat::RCFILE, TFileFormat::SEQUENCEFILE, TFileFormat::TEXTFILE }; const char* _kTFileFormatNames[] = { "PARQUETFILE", "RCFILE", "SEQUENCEFILE", "TEXTFILE" }; const std::map<int, const char*> _TFileFormat_VALUES_TO_NAMES(::apache::thrift::TEnumIterator(4, _kTFileFormatValues, _kTFileFormatNames), ::apache::thrift::TEnumIterator(-1, NULL, NULL)); int _kTAlterTableTypeValues[] = { TAlterTableType::ADD_REPLACE_COLUMNS, TAlterTableType::ADD_PARTITION, TAlterTableType::CHANGE_COLUMN, TAlterTableType::DROP_COLUMN, TAlterTableType::DROP_PARTITION, TAlterTableType::RENAME_TABLE, TAlterTableType::SET_FILE_FORMAT, TAlterTableType::SET_LOCATION }; const char* _kTAlterTableTypeNames[] = { "ADD_REPLACE_COLUMNS", "ADD_PARTITION", "CHANGE_COLUMN", "DROP_COLUMN", "DROP_PARTITION", "RENAME_TABLE", "SET_FILE_FORMAT", "SET_LOCATION" }; const std::map<int, const char*> _TAlterTableType_VALUES_TO_NAMES(::apache::thrift::TEnumIterator(8, _kTAlterTableTypeValues, _kTAlterTableTypeNames), ::apache::thrift::TEnumIterator(-1, NULL, NULL)); int _kTDdlTypeValues[] = { TDdlType::SHOW_TABLES, TDdlType::SHOW_DBS, TDdlType::USE, TDdlType::DESCRIBE, TDdlType::ALTER_TABLE, TDdlType::CREATE_DATABASE, TDdlType::CREATE_TABLE, TDdlType::CREATE_TABLE_LIKE, TDdlType::DROP_DATABASE, TDdlType::DROP_TABLE }; const char* _kTDdlTypeNames[] = { "SHOW_TABLES", "SHOW_DBS", "USE", "DESCRIBE", "ALTER_TABLE", "CREATE_DATABASE", "CREATE_TABLE", "CREATE_TABLE_LIKE", "DROP_DATABASE", "DROP_TABLE" }; const std::map<int, const char*> _TDdlType_VALUES_TO_NAMES(::apache::thrift::TEnumIterator(10, _kTDdlTypeValues, _kTDdlTypeNames), ::apache::thrift::TEnumIterator(-1, NULL, NULL)); int _kTMetadataOpcodeValues[] = { TMetadataOpcode::GET_TYPE_INFO, TMetadataOpcode::GET_CATALOGS, TMetadataOpcode::GET_SCHEMAS, TMetadataOpcode::GET_TABLES, TMetadataOpcode::GET_TABLE_TYPES, TMetadataOpcode::GET_COLUMNS, TMetadataOpcode::GET_FUNCTIONS }; const char* _kTMetadataOpcodeNames[] = { "GET_TYPE_INFO", "GET_CATALOGS", "GET_SCHEMAS", "GET_TABLES", "GET_TABLE_TYPES", "GET_COLUMNS", "GET_FUNCTIONS" }; const std::map<int, const char*> _TMetadataOpcode_VALUES_TO_NAMES(::apache::thrift::TEnumIterator(7, _kTMetadataOpcodeValues, _kTMetadataOpcodeNames), ::apache::thrift::TEnumIterator(-1, NULL, NULL)); const char* TGetTablesParams::ascii_fingerprint = "D0297FC5011701BD87898CC36146A565"; const uint8_t TGetTablesParams::binary_fingerprint[16] = {0xD0,0x29,0x7F,0xC5,0x01,0x17,0x01,0xBD,0x87,0x89,0x8C,0xC3,0x61,0x46,0xA5,0x65}; uint32_t TGetTablesParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->db); this->__isset.db = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->pattern); this->__isset.pattern = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t TGetTablesParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TGetTablesParams"); if (this->__isset.db) { ++fcnt; xfer += oprot->writeFieldBegin("db", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->db); xfer += oprot->writeFieldEnd(); } if (this->__isset.pattern) { ++fcnt; xfer += oprot->writeFieldBegin("pattern", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->pattern); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TGetTablesParams &a, TGetTablesParams &b) { using ::std::swap; swap(a.db, b.db); swap(a.pattern, b.pattern); swap(a.__isset, b.__isset); } const char* TGetTablesResult::ascii_fingerprint = "ACE4F644F0FDD289DDC4EE5B83BC13C0"; const uint8_t TGetTablesResult::binary_fingerprint[16] = {0xAC,0xE4,0xF6,0x44,0xF0,0xFD,0xD2,0x89,0xDD,0xC4,0xEE,0x5B,0x83,0xBC,0x13,0xC0}; uint32_t TGetTablesResult::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->tables.clear(); uint32_t _size0; ::apache::thrift::protocol::TType _etype3; xfer += iprot->readListBegin(_etype3, _size0); this->tables.resize(_size0); uint32_t _i4; for (_i4 = 0; _i4 < _size0; ++_i4) { xfer += iprot->readString(this->tables[_i4]); } xfer += iprot->readListEnd(); } this->__isset.tables = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t TGetTablesResult::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TGetTablesResult"); ++fcnt; xfer += oprot->writeFieldBegin("tables", ::apache::thrift::protocol::T_LIST, 1); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->tables.size())); std::vector<std::string> ::const_iterator _iter5; for (_iter5 = this->tables.begin(); _iter5 != this->tables.end(); ++_iter5) { xfer += oprot->writeString((*_iter5)); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TGetTablesResult &a, TGetTablesResult &b) { using ::std::swap; swap(a.tables, b.tables); swap(a.__isset, b.__isset); } const char* TGetDbsParams::ascii_fingerprint = "66E694018C17E5B65A59AE8F55CCA3CD"; const uint8_t TGetDbsParams::binary_fingerprint[16] = {0x66,0xE6,0x94,0x01,0x8C,0x17,0xE5,0xB6,0x5A,0x59,0xAE,0x8F,0x55,0xCC,0xA3,0xCD}; uint32_t TGetDbsParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->pattern); this->__isset.pattern = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t TGetDbsParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TGetDbsParams"); if (this->__isset.pattern) { ++fcnt; xfer += oprot->writeFieldBegin("pattern", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->pattern); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TGetDbsParams &a, TGetDbsParams &b) { using ::std::swap; swap(a.pattern, b.pattern); swap(a.__isset, b.__isset); } const char* TGetDbsResult::ascii_fingerprint = "ACE4F644F0FDD289DDC4EE5B83BC13C0"; const uint8_t TGetDbsResult::binary_fingerprint[16] = {0xAC,0xE4,0xF6,0x44,0xF0,0xFD,0xD2,0x89,0xDD,0xC4,0xEE,0x5B,0x83,0xBC,0x13,0xC0}; uint32_t TGetDbsResult::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->dbs.clear(); uint32_t _size6; ::apache::thrift::protocol::TType _etype9; xfer += iprot->readListBegin(_etype9, _size6); this->dbs.resize(_size6); uint32_t _i10; for (_i10 = 0; _i10 < _size6; ++_i10) { xfer += iprot->readString(this->dbs[_i10]); } xfer += iprot->readListEnd(); } this->__isset.dbs = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t TGetDbsResult::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TGetDbsResult"); ++fcnt; xfer += oprot->writeFieldBegin("dbs", ::apache::thrift::protocol::T_LIST, 1); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->dbs.size())); std::vector<std::string> ::const_iterator _iter11; for (_iter11 = this->dbs.begin(); _iter11 != this->dbs.end(); ++_iter11) { xfer += oprot->writeString((*_iter11)); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TGetDbsResult &a, TGetDbsResult &b) { using ::std::swap; swap(a.dbs, b.dbs); swap(a.__isset, b.__isset); } const char* TColumnDesc::ascii_fingerprint = "D6FD826D949221396F4FFC3ECCD3D192"; const uint8_t TColumnDesc::binary_fingerprint[16] = {0xD6,0xFD,0x82,0x6D,0x94,0x92,0x21,0x39,0x6F,0x4F,0xFC,0x3E,0xCC,0xD3,0xD1,0x92}; uint32_t TColumnDesc::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_columnName = false; bool isset_columnType = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->columnName); isset_columnName = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast12; xfer += iprot->readI32(ecast12); this->columnType = ( ::impala::TPrimitiveType::type)ecast12; isset_columnType = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_columnName) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_columnType) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TColumnDesc::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TColumnDesc"); ++fcnt; xfer += oprot->writeFieldBegin("columnName", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->columnName); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("columnType", ::apache::thrift::protocol::T_I32, 2); xfer += oprot->writeI32((int32_t)this->columnType); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TColumnDesc &a, TColumnDesc &b) { using ::std::swap; swap(a.columnName, b.columnName); swap(a.columnType, b.columnType); } const char* TColumnDef::ascii_fingerprint = "1A466928A838FDE756589DF00F1277D0"; const uint8_t TColumnDef::binary_fingerprint[16] = {0x1A,0x46,0x69,0x28,0xA8,0x38,0xFD,0xE7,0x56,0x58,0x9D,0xF0,0x0F,0x12,0x77,0xD0}; uint32_t TColumnDef::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_columnDesc = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->columnDesc.read(iprot); isset_columnDesc = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->comment); this->__isset.comment = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_columnDesc) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TColumnDef::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TColumnDef"); ++fcnt; xfer += oprot->writeFieldBegin("columnDesc", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->columnDesc.write(oprot); xfer += oprot->writeFieldEnd(); if (this->__isset.comment) { ++fcnt; xfer += oprot->writeFieldBegin("comment", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->comment); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TColumnDef &a, TColumnDef &b) { using ::std::swap; swap(a.columnDesc, b.columnDesc); swap(a.comment, b.comment); swap(a.__isset, b.__isset); } const char* TDescribeTableParams::ascii_fingerprint = "383E55F0D02199A3E52B9227E13A83A2"; const uint8_t TDescribeTableParams::binary_fingerprint[16] = {0x38,0x3E,0x55,0xF0,0xD0,0x21,0x99,0xA3,0xE5,0x2B,0x92,0x27,0xE1,0x3A,0x83,0xA2}; uint32_t TDescribeTableParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_table_name = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->db); this->__isset.db = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->table_name); isset_table_name = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_table_name) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TDescribeTableParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TDescribeTableParams"); if (this->__isset.db) { ++fcnt; xfer += oprot->writeFieldBegin("db", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->db); xfer += oprot->writeFieldEnd(); } ++fcnt; xfer += oprot->writeFieldBegin("table_name", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->table_name); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TDescribeTableParams &a, TDescribeTableParams &b) { using ::std::swap; swap(a.db, b.db); swap(a.table_name, b.table_name); swap(a.__isset, b.__isset); } const char* TDescribeTableResult::ascii_fingerprint = "310594E5EEC07991F491FF2D8123E958"; const uint8_t TDescribeTableResult::binary_fingerprint[16] = {0x31,0x05,0x94,0xE5,0xEE,0xC0,0x79,0x91,0xF4,0x91,0xFF,0x2D,0x81,0x23,0xE9,0x58}; uint32_t TDescribeTableResult::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_columns = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->columns.clear(); uint32_t _size13; ::apache::thrift::protocol::TType _etype16; xfer += iprot->readListBegin(_etype16, _size13); this->columns.resize(_size13); uint32_t _i17; for (_i17 = 0; _i17 < _size13; ++_i17) { xfer += this->columns[_i17].read(iprot); } xfer += iprot->readListEnd(); } isset_columns = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_columns) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TDescribeTableResult::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TDescribeTableResult"); ++fcnt; xfer += oprot->writeFieldBegin("columns", ::apache::thrift::protocol::T_LIST, 1); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->columns.size())); std::vector<TColumnDef> ::const_iterator _iter18; for (_iter18 = this->columns.begin(); _iter18 != this->columns.end(); ++_iter18) { xfer += (*_iter18).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TDescribeTableResult &a, TDescribeTableResult &b) { using ::std::swap; swap(a.columns, b.columns); } const char* TCreateDbParams::ascii_fingerprint = "CAD4F97378DF2EFF77F23A193511C552"; const uint8_t TCreateDbParams::binary_fingerprint[16] = {0xCA,0xD4,0xF9,0x73,0x78,0xDF,0x2E,0xFF,0x77,0xF2,0x3A,0x19,0x35,0x11,0xC5,0x52}; uint32_t TCreateDbParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_db = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->db); isset_db = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->comment); this->__isset.comment = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->location); this->__isset.location = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->if_not_exists); this->__isset.if_not_exists = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_db) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TCreateDbParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TCreateDbParams"); ++fcnt; xfer += oprot->writeFieldBegin("db", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->db); xfer += oprot->writeFieldEnd(); if (this->__isset.comment) { ++fcnt; xfer += oprot->writeFieldBegin("comment", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->comment); xfer += oprot->writeFieldEnd(); } if (this->__isset.location) { ++fcnt; xfer += oprot->writeFieldBegin("location", ::apache::thrift::protocol::T_STRING, 3); xfer += oprot->writeString(this->location); xfer += oprot->writeFieldEnd(); } if (this->__isset.if_not_exists) { ++fcnt; xfer += oprot->writeFieldBegin("if_not_exists", ::apache::thrift::protocol::T_BOOL, 4); xfer += oprot->writeBool(this->if_not_exists); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TCreateDbParams &a, TCreateDbParams &b) { using ::std::swap; swap(a.db, b.db); swap(a.comment, b.comment); swap(a.location, b.location); swap(a.if_not_exists, b.if_not_exists); swap(a.__isset, b.__isset); } const char* TTableName::ascii_fingerprint = "07A9615F837F7D0A952B595DD3020972"; const uint8_t TTableName::binary_fingerprint[16] = {0x07,0xA9,0x61,0x5F,0x83,0x7F,0x7D,0x0A,0x95,0x2B,0x59,0x5D,0xD3,0x02,0x09,0x72}; uint32_t TTableName::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_db_name = false; bool isset_table_name = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->db_name); isset_db_name = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->table_name); isset_table_name = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_db_name) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_table_name) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TTableName::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TTableName"); ++fcnt; xfer += oprot->writeFieldBegin("db_name", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->db_name); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("table_name", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->table_name); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TTableName &a, TTableName &b) { using ::std::swap; swap(a.db_name, b.db_name); swap(a.table_name, b.table_name); } const char* TTableRowFormat::ascii_fingerprint = "B2C950B9C25B62CA02C2A8C700FEE26F"; const uint8_t TTableRowFormat::binary_fingerprint[16] = {0xB2,0xC9,0x50,0xB9,0xC2,0x5B,0x62,0xCA,0x02,0xC2,0xA8,0xC7,0x00,0xFE,0xE2,0x6F}; uint32_t TTableRowFormat::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->field_terminator); this->__isset.field_terminator = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->line_terminator); this->__isset.line_terminator = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->escaped_by); this->__isset.escaped_by = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t TTableRowFormat::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TTableRowFormat"); if (this->__isset.field_terminator) { ++fcnt; xfer += oprot->writeFieldBegin("field_terminator", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->field_terminator); xfer += oprot->writeFieldEnd(); } if (this->__isset.line_terminator) { ++fcnt; xfer += oprot->writeFieldBegin("line_terminator", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->line_terminator); xfer += oprot->writeFieldEnd(); } if (this->__isset.escaped_by) { ++fcnt; xfer += oprot->writeFieldBegin("escaped_by", ::apache::thrift::protocol::T_STRING, 3); xfer += oprot->writeString(this->escaped_by); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TTableRowFormat &a, TTableRowFormat &b) { using ::std::swap; swap(a.field_terminator, b.field_terminator); swap(a.line_terminator, b.line_terminator); swap(a.escaped_by, b.escaped_by); swap(a.__isset, b.__isset); } const char* TPartitionKeyValue::ascii_fingerprint = "07A9615F837F7D0A952B595DD3020972"; const uint8_t TPartitionKeyValue::binary_fingerprint[16] = {0x07,0xA9,0x61,0x5F,0x83,0x7F,0x7D,0x0A,0x95,0x2B,0x59,0x5D,0xD3,0x02,0x09,0x72}; uint32_t TPartitionKeyValue::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_name = false; bool isset_value = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->name); isset_name = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->value); isset_value = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_name) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_value) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TPartitionKeyValue::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TPartitionKeyValue"); ++fcnt; xfer += oprot->writeFieldBegin("name", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->name); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("value", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->value); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TPartitionKeyValue &a, TPartitionKeyValue &b) { using ::std::swap; swap(a.name, b.name); swap(a.value, b.value); } const char* TAlterTableRenameParams::ascii_fingerprint = "A756D3DBE614FB13F70BF7F7B6EB3D73"; const uint8_t TAlterTableRenameParams::binary_fingerprint[16] = {0xA7,0x56,0xD3,0xDB,0xE6,0x14,0xFB,0x13,0xF7,0x0B,0xF7,0xF7,0xB6,0xEB,0x3D,0x73}; uint32_t TAlterTableRenameParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_new_table_name = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->new_table_name.read(iprot); isset_new_table_name = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_new_table_name) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TAlterTableRenameParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TAlterTableRenameParams"); ++fcnt; xfer += oprot->writeFieldBegin("new_table_name", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->new_table_name.write(oprot); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TAlterTableRenameParams &a, TAlterTableRenameParams &b) { using ::std::swap; swap(a.new_table_name, b.new_table_name); } const char* TAlterTableAddReplaceColsParams::ascii_fingerprint = "8A062F846D2647E1DF73D40439FB8C26"; const uint8_t TAlterTableAddReplaceColsParams::binary_fingerprint[16] = {0x8A,0x06,0x2F,0x84,0x6D,0x26,0x47,0xE1,0xDF,0x73,0xD4,0x04,0x39,0xFB,0x8C,0x26}; uint32_t TAlterTableAddReplaceColsParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_columns = false; bool isset_replace_existing_cols = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->columns.clear(); uint32_t _size19; ::apache::thrift::protocol::TType _etype22; xfer += iprot->readListBegin(_etype22, _size19); this->columns.resize(_size19); uint32_t _i23; for (_i23 = 0; _i23 < _size19; ++_i23) { xfer += this->columns[_i23].read(iprot); } xfer += iprot->readListEnd(); } isset_columns = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->replace_existing_cols); isset_replace_existing_cols = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_columns) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_replace_existing_cols) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TAlterTableAddReplaceColsParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TAlterTableAddReplaceColsParams"); ++fcnt; xfer += oprot->writeFieldBegin("columns", ::apache::thrift::protocol::T_LIST, 1); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->columns.size())); std::vector<TColumnDef> ::const_iterator _iter24; for (_iter24 = this->columns.begin(); _iter24 != this->columns.end(); ++_iter24) { xfer += (*_iter24).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("replace_existing_cols", ::apache::thrift::protocol::T_BOOL, 2); xfer += oprot->writeBool(this->replace_existing_cols); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TAlterTableAddReplaceColsParams &a, TAlterTableAddReplaceColsParams &b) { using ::std::swap; swap(a.columns, b.columns); swap(a.replace_existing_cols, b.replace_existing_cols); } const char* TAlterTableAddPartitionParams::ascii_fingerprint = "DDBF94C5C0804BF720FBDF685968F8B2"; const uint8_t TAlterTableAddPartitionParams::binary_fingerprint[16] = {0xDD,0xBF,0x94,0xC5,0xC0,0x80,0x4B,0xF7,0x20,0xFB,0xDF,0x68,0x59,0x68,0xF8,0xB2}; uint32_t TAlterTableAddPartitionParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_partition_spec = false; bool isset_if_not_exists = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->partition_spec.clear(); uint32_t _size25; ::apache::thrift::protocol::TType _etype28; xfer += iprot->readListBegin(_etype28, _size25); this->partition_spec.resize(_size25); uint32_t _i29; for (_i29 = 0; _i29 < _size25; ++_i29) { xfer += this->partition_spec[_i29].read(iprot); } xfer += iprot->readListEnd(); } isset_partition_spec = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->if_not_exists); isset_if_not_exists = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->location); this->__isset.location = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_partition_spec) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_if_not_exists) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TAlterTableAddPartitionParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TAlterTableAddPartitionParams"); ++fcnt; xfer += oprot->writeFieldBegin("partition_spec", ::apache::thrift::protocol::T_LIST, 1); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->partition_spec.size())); std::vector<TPartitionKeyValue> ::const_iterator _iter30; for (_iter30 = this->partition_spec.begin(); _iter30 != this->partition_spec.end(); ++_iter30) { xfer += (*_iter30).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); if (this->__isset.location) { ++fcnt; xfer += oprot->writeFieldBegin("location", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->location); xfer += oprot->writeFieldEnd(); } ++fcnt; xfer += oprot->writeFieldBegin("if_not_exists", ::apache::thrift::protocol::T_BOOL, 3); xfer += oprot->writeBool(this->if_not_exists); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TAlterTableAddPartitionParams &a, TAlterTableAddPartitionParams &b) { using ::std::swap; swap(a.partition_spec, b.partition_spec); swap(a.if_not_exists, b.if_not_exists); swap(a.location, b.location); swap(a.__isset, b.__isset); } const char* TAlterTableDropColParams::ascii_fingerprint = "EFB929595D312AC8F305D5A794CFEDA1"; const uint8_t TAlterTableDropColParams::binary_fingerprint[16] = {0xEF,0xB9,0x29,0x59,0x5D,0x31,0x2A,0xC8,0xF3,0x05,0xD5,0xA7,0x94,0xCF,0xED,0xA1}; uint32_t TAlterTableDropColParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_col_name = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->col_name); isset_col_name = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_col_name) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TAlterTableDropColParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TAlterTableDropColParams"); ++fcnt; xfer += oprot->writeFieldBegin("col_name", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->col_name); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TAlterTableDropColParams &a, TAlterTableDropColParams &b) { using ::std::swap; swap(a.col_name, b.col_name); } const char* TAlterTableDropPartitionParams::ascii_fingerprint = "6F92A0A7B206615BE32209BF2E6A7ED1"; const uint8_t TAlterTableDropPartitionParams::binary_fingerprint[16] = {0x6F,0x92,0xA0,0xA7,0xB2,0x06,0x61,0x5B,0xE3,0x22,0x09,0xBF,0x2E,0x6A,0x7E,0xD1}; uint32_t TAlterTableDropPartitionParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_partition_spec = false; bool isset_if_exists = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->partition_spec.clear(); uint32_t _size31; ::apache::thrift::protocol::TType _etype34; xfer += iprot->readListBegin(_etype34, _size31); this->partition_spec.resize(_size31); uint32_t _i35; for (_i35 = 0; _i35 < _size31; ++_i35) { xfer += this->partition_spec[_i35].read(iprot); } xfer += iprot->readListEnd(); } isset_partition_spec = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->if_exists); isset_if_exists = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_partition_spec) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_if_exists) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TAlterTableDropPartitionParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TAlterTableDropPartitionParams"); ++fcnt; xfer += oprot->writeFieldBegin("partition_spec", ::apache::thrift::protocol::T_LIST, 1); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->partition_spec.size())); std::vector<TPartitionKeyValue> ::const_iterator _iter36; for (_iter36 = this->partition_spec.begin(); _iter36 != this->partition_spec.end(); ++_iter36) { xfer += (*_iter36).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("if_exists", ::apache::thrift::protocol::T_BOOL, 2); xfer += oprot->writeBool(this->if_exists); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TAlterTableDropPartitionParams &a, TAlterTableDropPartitionParams &b) { using ::std::swap; swap(a.partition_spec, b.partition_spec); swap(a.if_exists, b.if_exists); } const char* TAlterTableChangeColParams::ascii_fingerprint = "50D38FCE9C274638E6D49F7975E2CE6C"; const uint8_t TAlterTableChangeColParams::binary_fingerprint[16] = {0x50,0xD3,0x8F,0xCE,0x9C,0x27,0x46,0x38,0xE6,0xD4,0x9F,0x79,0x75,0xE2,0xCE,0x6C}; uint32_t TAlterTableChangeColParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_col_name = false; bool isset_new_col_def = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->col_name); isset_col_name = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->new_col_def.read(iprot); isset_new_col_def = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_col_name) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_new_col_def) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TAlterTableChangeColParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TAlterTableChangeColParams"); ++fcnt; xfer += oprot->writeFieldBegin("col_name", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->col_name); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("new_col_def", ::apache::thrift::protocol::T_STRUCT, 2); xfer += this->new_col_def.write(oprot); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TAlterTableChangeColParams &a, TAlterTableChangeColParams &b) { using ::std::swap; swap(a.col_name, b.col_name); swap(a.new_col_def, b.new_col_def); } const char* TAlterTableSetFileFormatParams::ascii_fingerprint = "101E22EEE714785E462FCF6056B14937"; const uint8_t TAlterTableSetFileFormatParams::binary_fingerprint[16] = {0x10,0x1E,0x22,0xEE,0xE7,0x14,0x78,0x5E,0x46,0x2F,0xCF,0x60,0x56,0xB1,0x49,0x37}; uint32_t TAlterTableSetFileFormatParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_file_format = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast37; xfer += iprot->readI32(ecast37); this->file_format = (TFileFormat::type)ecast37; isset_file_format = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->partition_spec.clear(); uint32_t _size38; ::apache::thrift::protocol::TType _etype41; xfer += iprot->readListBegin(_etype41, _size38); this->partition_spec.resize(_size38); uint32_t _i42; for (_i42 = 0; _i42 < _size38; ++_i42) { xfer += this->partition_spec[_i42].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.partition_spec = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_file_format) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TAlterTableSetFileFormatParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TAlterTableSetFileFormatParams"); ++fcnt; xfer += oprot->writeFieldBegin("file_format", ::apache::thrift::protocol::T_I32, 1); xfer += oprot->writeI32((int32_t)this->file_format); xfer += oprot->writeFieldEnd(); if (this->__isset.partition_spec) { ++fcnt; xfer += oprot->writeFieldBegin("partition_spec", ::apache::thrift::protocol::T_LIST, 2); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->partition_spec.size())); std::vector<TPartitionKeyValue> ::const_iterator _iter43; for (_iter43 = this->partition_spec.begin(); _iter43 != this->partition_spec.end(); ++_iter43) { xfer += (*_iter43).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TAlterTableSetFileFormatParams &a, TAlterTableSetFileFormatParams &b) { using ::std::swap; swap(a.file_format, b.file_format); swap(a.partition_spec, b.partition_spec); swap(a.__isset, b.__isset); } const char* TAlterTableSetLocationParams::ascii_fingerprint = "620BD7B2710FAEABD876BE1FA48F69F0"; const uint8_t TAlterTableSetLocationParams::binary_fingerprint[16] = {0x62,0x0B,0xD7,0xB2,0x71,0x0F,0xAE,0xAB,0xD8,0x76,0xBE,0x1F,0xA4,0x8F,0x69,0xF0}; uint32_t TAlterTableSetLocationParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_location = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->location); isset_location = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->partition_spec.clear(); uint32_t _size44; ::apache::thrift::protocol::TType _etype47; xfer += iprot->readListBegin(_etype47, _size44); this->partition_spec.resize(_size44); uint32_t _i48; for (_i48 = 0; _i48 < _size44; ++_i48) { xfer += this->partition_spec[_i48].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.partition_spec = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_location) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TAlterTableSetLocationParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TAlterTableSetLocationParams"); ++fcnt; xfer += oprot->writeFieldBegin("location", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->location); xfer += oprot->writeFieldEnd(); if (this->__isset.partition_spec) { ++fcnt; xfer += oprot->writeFieldBegin("partition_spec", ::apache::thrift::protocol::T_LIST, 2); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->partition_spec.size())); std::vector<TPartitionKeyValue> ::const_iterator _iter49; for (_iter49 = this->partition_spec.begin(); _iter49 != this->partition_spec.end(); ++_iter49) { xfer += (*_iter49).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TAlterTableSetLocationParams &a, TAlterTableSetLocationParams &b) { using ::std::swap; swap(a.location, b.location); swap(a.partition_spec, b.partition_spec); swap(a.__isset, b.__isset); } const char* TAlterTableParams::ascii_fingerprint = "8F534EA99B58367B90C40A9C386F9A64"; const uint8_t TAlterTableParams::binary_fingerprint[16] = {0x8F,0x53,0x4E,0xA9,0x9B,0x58,0x36,0x7B,0x90,0xC4,0x0A,0x9C,0x38,0x6F,0x9A,0x64}; uint32_t TAlterTableParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_alter_type = false; bool isset_table_name = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast50; xfer += iprot->readI32(ecast50); this->alter_type = (TAlterTableType::type)ecast50; isset_alter_type = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->table_name.read(iprot); isset_table_name = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->rename_params.read(iprot); this->__isset.rename_params = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->add_replace_cols_params.read(iprot); this->__isset.add_replace_cols_params = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->add_partition_params.read(iprot); this->__isset.add_partition_params = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->change_col_params.read(iprot); this->__isset.change_col_params = true; } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->drop_col_params.read(iprot); this->__isset.drop_col_params = true; } else { xfer += iprot->skip(ftype); } break; case 8: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->drop_partition_params.read(iprot); this->__isset.drop_partition_params = true; } else { xfer += iprot->skip(ftype); } break; case 9: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->set_file_format_params.read(iprot); this->__isset.set_file_format_params = true; } else { xfer += iprot->skip(ftype); } break; case 10: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->set_location_params.read(iprot); this->__isset.set_location_params = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_alter_type) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_table_name) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TAlterTableParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TAlterTableParams"); ++fcnt; xfer += oprot->writeFieldBegin("alter_type", ::apache::thrift::protocol::T_I32, 1); xfer += oprot->writeI32((int32_t)this->alter_type); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("table_name", ::apache::thrift::protocol::T_STRUCT, 2); xfer += this->table_name.write(oprot); xfer += oprot->writeFieldEnd(); if (this->__isset.rename_params) { ++fcnt; xfer += oprot->writeFieldBegin("rename_params", ::apache::thrift::protocol::T_STRUCT, 3); xfer += this->rename_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.add_replace_cols_params) { ++fcnt; xfer += oprot->writeFieldBegin("add_replace_cols_params", ::apache::thrift::protocol::T_STRUCT, 4); xfer += this->add_replace_cols_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.add_partition_params) { ++fcnt; xfer += oprot->writeFieldBegin("add_partition_params", ::apache::thrift::protocol::T_STRUCT, 5); xfer += this->add_partition_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.change_col_params) { ++fcnt; xfer += oprot->writeFieldBegin("change_col_params", ::apache::thrift::protocol::T_STRUCT, 6); xfer += this->change_col_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.drop_col_params) { ++fcnt; xfer += oprot->writeFieldBegin("drop_col_params", ::apache::thrift::protocol::T_STRUCT, 7); xfer += this->drop_col_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.drop_partition_params) { ++fcnt; xfer += oprot->writeFieldBegin("drop_partition_params", ::apache::thrift::protocol::T_STRUCT, 8); xfer += this->drop_partition_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.set_file_format_params) { ++fcnt; xfer += oprot->writeFieldBegin("set_file_format_params", ::apache::thrift::protocol::T_STRUCT, 9); xfer += this->set_file_format_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.set_location_params) { ++fcnt; xfer += oprot->writeFieldBegin("set_location_params", ::apache::thrift::protocol::T_STRUCT, 10); xfer += this->set_location_params.write(oprot); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TAlterTableParams &a, TAlterTableParams &b) { using ::std::swap; swap(a.alter_type, b.alter_type); swap(a.table_name, b.table_name); swap(a.rename_params, b.rename_params); swap(a.add_replace_cols_params, b.add_replace_cols_params); swap(a.add_partition_params, b.add_partition_params); swap(a.change_col_params, b.change_col_params); swap(a.drop_col_params, b.drop_col_params); swap(a.drop_partition_params, b.drop_partition_params); swap(a.set_file_format_params, b.set_file_format_params); swap(a.set_location_params, b.set_location_params); swap(a.__isset, b.__isset); } const char* TCreateTableLikeParams::ascii_fingerprint = "7BEC16F01713BB030792212D7EDE7C30"; const uint8_t TCreateTableLikeParams::binary_fingerprint[16] = {0x7B,0xEC,0x16,0xF0,0x17,0x13,0xBB,0x03,0x07,0x92,0x21,0x2D,0x7E,0xDE,0x7C,0x30}; uint32_t TCreateTableLikeParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_table_name = false; bool isset_src_table_name = false; bool isset_is_external = false; bool isset_if_not_exists = false; bool isset_owner = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->table_name.read(iprot); isset_table_name = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->src_table_name.read(iprot); isset_src_table_name = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->is_external); isset_is_external = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->if_not_exists); isset_if_not_exists = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->owner); isset_owner = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast51; xfer += iprot->readI32(ecast51); this->file_format = (TFileFormat::type)ecast51; this->__isset.file_format = true; } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->comment); this->__isset.comment = true; } else { xfer += iprot->skip(ftype); } break; case 8: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->location); this->__isset.location = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_table_name) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_src_table_name) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_is_external) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_if_not_exists) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_owner) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TCreateTableLikeParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TCreateTableLikeParams"); ++fcnt; xfer += oprot->writeFieldBegin("table_name", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->table_name.write(oprot); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("src_table_name", ::apache::thrift::protocol::T_STRUCT, 2); xfer += this->src_table_name.write(oprot); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("is_external", ::apache::thrift::protocol::T_BOOL, 3); xfer += oprot->writeBool(this->is_external); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("if_not_exists", ::apache::thrift::protocol::T_BOOL, 4); xfer += oprot->writeBool(this->if_not_exists); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("owner", ::apache::thrift::protocol::T_STRING, 5); xfer += oprot->writeString(this->owner); xfer += oprot->writeFieldEnd(); if (this->__isset.file_format) { ++fcnt; xfer += oprot->writeFieldBegin("file_format", ::apache::thrift::protocol::T_I32, 6); xfer += oprot->writeI32((int32_t)this->file_format); xfer += oprot->writeFieldEnd(); } if (this->__isset.comment) { ++fcnt; xfer += oprot->writeFieldBegin("comment", ::apache::thrift::protocol::T_STRING, 7); xfer += oprot->writeString(this->comment); xfer += oprot->writeFieldEnd(); } if (this->__isset.location) { ++fcnt; xfer += oprot->writeFieldBegin("location", ::apache::thrift::protocol::T_STRING, 8); xfer += oprot->writeString(this->location); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TCreateTableLikeParams &a, TCreateTableLikeParams &b) { using ::std::swap; swap(a.table_name, b.table_name); swap(a.src_table_name, b.src_table_name); swap(a.is_external, b.is_external); swap(a.if_not_exists, b.if_not_exists); swap(a.owner, b.owner); swap(a.file_format, b.file_format); swap(a.comment, b.comment); swap(a.location, b.location); swap(a.__isset, b.__isset); } const char* TCreateTableParams::ascii_fingerprint = "A806D16923885311424912DE4D07024D"; const uint8_t TCreateTableParams::binary_fingerprint[16] = {0xA8,0x06,0xD1,0x69,0x23,0x88,0x53,0x11,0x42,0x49,0x12,0xDE,0x4D,0x07,0x02,0x4D}; uint32_t TCreateTableParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_table_name = false; bool isset_columns = false; bool isset_file_format = false; bool isset_is_external = false; bool isset_if_not_exists = false; bool isset_owner = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->table_name.read(iprot); isset_table_name = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->columns.clear(); uint32_t _size52; ::apache::thrift::protocol::TType _etype55; xfer += iprot->readListBegin(_etype55, _size52); this->columns.resize(_size52); uint32_t _i56; for (_i56 = 0; _i56 < _size52; ++_i56) { xfer += this->columns[_i56].read(iprot); } xfer += iprot->readListEnd(); } isset_columns = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->partition_columns.clear(); uint32_t _size57; ::apache::thrift::protocol::TType _etype60; xfer += iprot->readListBegin(_etype60, _size57); this->partition_columns.resize(_size57); uint32_t _i61; for (_i61 = 0; _i61 < _size57; ++_i61) { xfer += this->partition_columns[_i61].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.partition_columns = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast62; xfer += iprot->readI32(ecast62); this->file_format = (TFileFormat::type)ecast62; isset_file_format = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->is_external); isset_is_external = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->if_not_exists); isset_if_not_exists = true; } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->owner); isset_owner = true; } else { xfer += iprot->skip(ftype); } break; case 8: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->row_format.read(iprot); this->__isset.row_format = true; } else { xfer += iprot->skip(ftype); } break; case 9: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->comment); this->__isset.comment = true; } else { xfer += iprot->skip(ftype); } break; case 10: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->location); this->__isset.location = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_table_name) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_columns) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_file_format) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_is_external) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_if_not_exists) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_owner) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TCreateTableParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TCreateTableParams"); ++fcnt; xfer += oprot->writeFieldBegin("table_name", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->table_name.write(oprot); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("columns", ::apache::thrift::protocol::T_LIST, 2); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->columns.size())); std::vector<TColumnDef> ::const_iterator _iter63; for (_iter63 = this->columns.begin(); _iter63 != this->columns.end(); ++_iter63) { xfer += (*_iter63).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); if (this->__isset.partition_columns) { ++fcnt; xfer += oprot->writeFieldBegin("partition_columns", ::apache::thrift::protocol::T_LIST, 3); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->partition_columns.size())); std::vector<TColumnDef> ::const_iterator _iter64; for (_iter64 = this->partition_columns.begin(); _iter64 != this->partition_columns.end(); ++_iter64) { xfer += (*_iter64).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } ++fcnt; xfer += oprot->writeFieldBegin("file_format", ::apache::thrift::protocol::T_I32, 4); xfer += oprot->writeI32((int32_t)this->file_format); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("is_external", ::apache::thrift::protocol::T_BOOL, 5); xfer += oprot->writeBool(this->is_external); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("if_not_exists", ::apache::thrift::protocol::T_BOOL, 6); xfer += oprot->writeBool(this->if_not_exists); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("owner", ::apache::thrift::protocol::T_STRING, 7); xfer += oprot->writeString(this->owner); xfer += oprot->writeFieldEnd(); if (this->__isset.row_format) { ++fcnt; xfer += oprot->writeFieldBegin("row_format", ::apache::thrift::protocol::T_STRUCT, 8); xfer += this->row_format.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.comment) { ++fcnt; xfer += oprot->writeFieldBegin("comment", ::apache::thrift::protocol::T_STRING, 9); xfer += oprot->writeString(this->comment); xfer += oprot->writeFieldEnd(); } if (this->__isset.location) { ++fcnt; xfer += oprot->writeFieldBegin("location", ::apache::thrift::protocol::T_STRING, 10); xfer += oprot->writeString(this->location); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TCreateTableParams &a, TCreateTableParams &b) { using ::std::swap; swap(a.table_name, b.table_name); swap(a.columns, b.columns); swap(a.partition_columns, b.partition_columns); swap(a.file_format, b.file_format); swap(a.is_external, b.is_external); swap(a.if_not_exists, b.if_not_exists); swap(a.owner, b.owner); swap(a.row_format, b.row_format); swap(a.comment, b.comment); swap(a.location, b.location); swap(a.__isset, b.__isset); } const char* TDropDbParams::ascii_fingerprint = "7D61C9AA00102AB4D8F72A1DA58297DC"; const uint8_t TDropDbParams::binary_fingerprint[16] = {0x7D,0x61,0xC9,0xAA,0x00,0x10,0x2A,0xB4,0xD8,0xF7,0x2A,0x1D,0xA5,0x82,0x97,0xDC}; uint32_t TDropDbParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_db = false; bool isset_if_exists = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->db); isset_db = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->if_exists); isset_if_exists = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_db) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_if_exists) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TDropDbParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TDropDbParams"); ++fcnt; xfer += oprot->writeFieldBegin("db", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->db); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("if_exists", ::apache::thrift::protocol::T_BOOL, 2); xfer += oprot->writeBool(this->if_exists); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TDropDbParams &a, TDropDbParams &b) { using ::std::swap; swap(a.db, b.db); swap(a.if_exists, b.if_exists); } const char* TDropTableParams::ascii_fingerprint = "790158CF902C527D004C99E60A2E4B2E"; const uint8_t TDropTableParams::binary_fingerprint[16] = {0x79,0x01,0x58,0xCF,0x90,0x2C,0x52,0x7D,0x00,0x4C,0x99,0xE6,0x0A,0x2E,0x4B,0x2E}; uint32_t TDropTableParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_table_name = false; bool isset_if_exists = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->table_name.read(iprot); isset_table_name = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->if_exists); isset_if_exists = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_table_name) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_if_exists) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TDropTableParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TDropTableParams"); ++fcnt; xfer += oprot->writeFieldBegin("table_name", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->table_name.write(oprot); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("if_exists", ::apache::thrift::protocol::T_BOOL, 2); xfer += oprot->writeBool(this->if_exists); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TDropTableParams &a, TDropTableParams &b) { using ::std::swap; swap(a.table_name, b.table_name); swap(a.if_exists, b.if_exists); } const char* TSessionState::ascii_fingerprint = "07A9615F837F7D0A952B595DD3020972"; const uint8_t TSessionState::binary_fingerprint[16] = {0x07,0xA9,0x61,0x5F,0x83,0x7F,0x7D,0x0A,0x95,0x2B,0x59,0x5D,0xD3,0x02,0x09,0x72}; uint32_t TSessionState::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_database = false; bool isset_user = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->database); isset_database = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->user); isset_user = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_database) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_user) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TSessionState::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TSessionState"); ++fcnt; xfer += oprot->writeFieldBegin("database", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->database); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("user", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->user); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TSessionState &a, TSessionState &b) { using ::std::swap; swap(a.database, b.database); swap(a.user, b.user); } const char* TClientRequest::ascii_fingerprint = "AEEBB37EB85D30D8B07D47726C1C3058"; const uint8_t TClientRequest::binary_fingerprint[16] = {0xAE,0xEB,0xB3,0x7E,0xB8,0x5D,0x30,0xD8,0xB0,0x7D,0x47,0x72,0x6C,0x1C,0x30,0x58}; uint32_t TClientRequest::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_stmt = false; bool isset_queryOptions = false; bool isset_sessionState = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->stmt); isset_stmt = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->queryOptions.read(iprot); isset_queryOptions = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->sessionState.read(iprot); isset_sessionState = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_stmt) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_queryOptions) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_sessionState) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TClientRequest::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TClientRequest"); ++fcnt; xfer += oprot->writeFieldBegin("stmt", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->stmt); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("queryOptions", ::apache::thrift::protocol::T_STRUCT, 2); xfer += this->queryOptions.write(oprot); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("sessionState", ::apache::thrift::protocol::T_STRUCT, 3); xfer += this->sessionState.write(oprot); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TClientRequest &a, TClientRequest &b) { using ::std::swap; swap(a.stmt, b.stmt); swap(a.queryOptions, b.queryOptions); swap(a.sessionState, b.sessionState); } const char* TShowDbsParams::ascii_fingerprint = "66E694018C17E5B65A59AE8F55CCA3CD"; const uint8_t TShowDbsParams::binary_fingerprint[16] = {0x66,0xE6,0x94,0x01,0x8C,0x17,0xE5,0xB6,0x5A,0x59,0xAE,0x8F,0x55,0xCC,0xA3,0xCD}; uint32_t TShowDbsParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->show_pattern); this->__isset.show_pattern = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t TShowDbsParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TShowDbsParams"); if (this->__isset.show_pattern) { ++fcnt; xfer += oprot->writeFieldBegin("show_pattern", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->show_pattern); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TShowDbsParams &a, TShowDbsParams &b) { using ::std::swap; swap(a.show_pattern, b.show_pattern); swap(a.__isset, b.__isset); } const char* TShowTablesParams::ascii_fingerprint = "D0297FC5011701BD87898CC36146A565"; const uint8_t TShowTablesParams::binary_fingerprint[16] = {0xD0,0x29,0x7F,0xC5,0x01,0x17,0x01,0xBD,0x87,0x89,0x8C,0xC3,0x61,0x46,0xA5,0x65}; uint32_t TShowTablesParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->db); this->__isset.db = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->show_pattern); this->__isset.show_pattern = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t TShowTablesParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TShowTablesParams"); if (this->__isset.db) { ++fcnt; xfer += oprot->writeFieldBegin("db", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->db); xfer += oprot->writeFieldEnd(); } if (this->__isset.show_pattern) { ++fcnt; xfer += oprot->writeFieldBegin("show_pattern", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->show_pattern); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TShowTablesParams &a, TShowTablesParams &b) { using ::std::swap; swap(a.db, b.db); swap(a.show_pattern, b.show_pattern); swap(a.__isset, b.__isset); } const char* TUseDbParams::ascii_fingerprint = "EFB929595D312AC8F305D5A794CFEDA1"; const uint8_t TUseDbParams::binary_fingerprint[16] = {0xEF,0xB9,0x29,0x59,0x5D,0x31,0x2A,0xC8,0xF3,0x05,0xD5,0xA7,0x94,0xCF,0xED,0xA1}; uint32_t TUseDbParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_db = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->db); isset_db = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_db) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TUseDbParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TUseDbParams"); ++fcnt; xfer += oprot->writeFieldBegin("db", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->db); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TUseDbParams &a, TUseDbParams &b) { using ::std::swap; swap(a.db, b.db); } const char* TExplainResult::ascii_fingerprint = "33B1AC796556B5D176326D0D2FCA5450"; const uint8_t TExplainResult::binary_fingerprint[16] = {0x33,0xB1,0xAC,0x79,0x65,0x56,0xB5,0xD1,0x76,0x32,0x6D,0x0D,0x2F,0xCA,0x54,0x50}; uint32_t TExplainResult::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_results = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->results.clear(); uint32_t _size65; ::apache::thrift::protocol::TType _etype68; xfer += iprot->readListBegin(_etype68, _size65); this->results.resize(_size65); uint32_t _i69; for (_i69 = 0; _i69 < _size65; ++_i69) { xfer += this->results[_i69].read(iprot); } xfer += iprot->readListEnd(); } isset_results = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_results) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TExplainResult::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TExplainResult"); ++fcnt; xfer += oprot->writeFieldBegin("results", ::apache::thrift::protocol::T_LIST, 1); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->results.size())); std::vector< ::impala::TResultRow> ::const_iterator _iter70; for (_iter70 = this->results.begin(); _iter70 != this->results.end(); ++_iter70) { xfer += (*_iter70).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TExplainResult &a, TExplainResult &b) { using ::std::swap; swap(a.results, b.results); } const char* TResultSetMetadata::ascii_fingerprint = "D50C2F9EC7D3B85649634752C0F64DC3"; const uint8_t TResultSetMetadata::binary_fingerprint[16] = {0xD5,0x0C,0x2F,0x9E,0xC7,0xD3,0xB8,0x56,0x49,0x63,0x47,0x52,0xC0,0xF6,0x4D,0xC3}; uint32_t TResultSetMetadata::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_columnDescs = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->columnDescs.clear(); uint32_t _size71; ::apache::thrift::protocol::TType _etype74; xfer += iprot->readListBegin(_etype74, _size71); this->columnDescs.resize(_size71); uint32_t _i75; for (_i75 = 0; _i75 < _size71; ++_i75) { xfer += this->columnDescs[_i75].read(iprot); } xfer += iprot->readListEnd(); } isset_columnDescs = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_columnDescs) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TResultSetMetadata::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TResultSetMetadata"); ++fcnt; xfer += oprot->writeFieldBegin("columnDescs", ::apache::thrift::protocol::T_LIST, 1); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->columnDescs.size())); std::vector<TColumnDesc> ::const_iterator _iter76; for (_iter76 = this->columnDescs.begin(); _iter76 != this->columnDescs.end(); ++_iter76) { xfer += (*_iter76).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TResultSetMetadata &a, TResultSetMetadata &b) { using ::std::swap; swap(a.columnDescs, b.columnDescs); } const char* TCatalogUpdate::ascii_fingerprint = "845BD8C082A6EDFE58B66C91C7C24C6E"; const uint8_t TCatalogUpdate::binary_fingerprint[16] = {0x84,0x5B,0xD8,0xC0,0x82,0xA6,0xED,0xFE,0x58,0xB6,0x6C,0x91,0xC7,0xC2,0x4C,0x6E}; uint32_t TCatalogUpdate::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_target_table = false; bool isset_db_name = false; bool isset_created_partitions = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->target_table); isset_target_table = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->db_name); isset_db_name = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_SET) { { this->created_partitions.clear(); uint32_t _size77; ::apache::thrift::protocol::TType _etype80; xfer += iprot->readSetBegin(_etype80, _size77); uint32_t _i81; for (_i81 = 0; _i81 < _size77; ++_i81) { std::string _elem82; xfer += iprot->readString(_elem82); this->created_partitions.insert(_elem82); } xfer += iprot->readSetEnd(); } isset_created_partitions = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_target_table) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_db_name) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_created_partitions) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TCatalogUpdate::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TCatalogUpdate"); ++fcnt; xfer += oprot->writeFieldBegin("target_table", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->target_table); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("db_name", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->db_name); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("created_partitions", ::apache::thrift::protocol::T_SET, 3); { xfer += oprot->writeSetBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->created_partitions.size())); std::set<std::string> ::const_iterator _iter83; for (_iter83 = this->created_partitions.begin(); _iter83 != this->created_partitions.end(); ++_iter83) { xfer += oprot->writeString((*_iter83)); } xfer += oprot->writeSetEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TCatalogUpdate &a, TCatalogUpdate &b) { using ::std::swap; swap(a.target_table, b.target_table); swap(a.db_name, b.db_name); swap(a.created_partitions, b.created_partitions); } const char* TFinalizeParams::ascii_fingerprint = "B7080D97FBE64A05254F705FB1FADA7F"; const uint8_t TFinalizeParams::binary_fingerprint[16] = {0xB7,0x08,0x0D,0x97,0xFB,0xE6,0x4A,0x05,0x25,0x4F,0x70,0x5F,0xB1,0xFA,0xDA,0x7F}; uint32_t TFinalizeParams::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_is_overwrite = false; bool isset_hdfs_base_dir = false; bool isset_table_name = false; bool isset_table_db = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->is_overwrite); isset_is_overwrite = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->hdfs_base_dir); isset_hdfs_base_dir = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->table_name); isset_table_name = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->table_db); isset_table_db = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_is_overwrite) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_hdfs_base_dir) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_table_name) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_table_db) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TFinalizeParams::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TFinalizeParams"); ++fcnt; xfer += oprot->writeFieldBegin("is_overwrite", ::apache::thrift::protocol::T_BOOL, 1); xfer += oprot->writeBool(this->is_overwrite); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("hdfs_base_dir", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->hdfs_base_dir); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("table_name", ::apache::thrift::protocol::T_STRING, 3); xfer += oprot->writeString(this->table_name); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("table_db", ::apache::thrift::protocol::T_STRING, 4); xfer += oprot->writeString(this->table_db); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TFinalizeParams &a, TFinalizeParams &b) { using ::std::swap; swap(a.is_overwrite, b.is_overwrite); swap(a.hdfs_base_dir, b.hdfs_base_dir); swap(a.table_name, b.table_name); swap(a.table_db, b.table_db); } const char* TQueryExecRequest::ascii_fingerprint = "1D4C017A9088C19C6BE21EB79C551FB1"; const uint8_t TQueryExecRequest::binary_fingerprint[16] = {0x1D,0x4C,0x01,0x7A,0x90,0x88,0xC1,0x9C,0x6B,0xE2,0x1E,0xB7,0x9C,0x55,0x1F,0xB1}; uint32_t TQueryExecRequest::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_fragments = false; bool isset_query_globals = false; bool isset_stmt_type = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->desc_tbl.read(iprot); this->__isset.desc_tbl = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->fragments.clear(); uint32_t _size84; ::apache::thrift::protocol::TType _etype87; xfer += iprot->readListBegin(_etype87, _size84); this->fragments.resize(_size84); uint32_t _i88; for (_i88 = 0; _i88 < _size84; ++_i88) { xfer += this->fragments[_i88].read(iprot); } xfer += iprot->readListEnd(); } isset_fragments = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->dest_fragment_idx.clear(); uint32_t _size89; ::apache::thrift::protocol::TType _etype92; xfer += iprot->readListBegin(_etype92, _size89); this->dest_fragment_idx.resize(_size89); uint32_t _i93; for (_i93 = 0; _i93 < _size89; ++_i93) { xfer += iprot->readI32(this->dest_fragment_idx[_i93]); } xfer += iprot->readListEnd(); } this->__isset.dest_fragment_idx = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_MAP) { { this->per_node_scan_ranges.clear(); uint32_t _size94; ::apache::thrift::protocol::TType _ktype95; ::apache::thrift::protocol::TType _vtype96; xfer += iprot->readMapBegin(_ktype95, _vtype96, _size94); uint32_t _i98; for (_i98 = 0; _i98 < _size94; ++_i98) { ::impala::TPlanNodeId _key99; xfer += iprot->readI32(_key99); std::vector< ::impala::TScanRangeLocations> & _val100 = this->per_node_scan_ranges[_key99]; { _val100.clear(); uint32_t _size101; ::apache::thrift::protocol::TType _etype104; xfer += iprot->readListBegin(_etype104, _size101); _val100.resize(_size101); uint32_t _i105; for (_i105 = 0; _i105 < _size101; ++_i105) { xfer += _val100[_i105].read(iprot); } xfer += iprot->readListEnd(); } } xfer += iprot->readMapEnd(); } this->__isset.per_node_scan_ranges = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->result_set_metadata.read(iprot); this->__isset.result_set_metadata = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->finalize_params.read(iprot); this->__isset.finalize_params = true; } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->query_globals.read(iprot); isset_query_globals = true; } else { xfer += iprot->skip(ftype); } break; case 8: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->query_plan); this->__isset.query_plan = true; } else { xfer += iprot->skip(ftype); } break; case 9: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast106; xfer += iprot->readI32(ecast106); this->stmt_type = ( ::impala::TStmtType::type)ecast106; isset_stmt_type = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_fragments) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_query_globals) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_stmt_type) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TQueryExecRequest::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TQueryExecRequest"); if (this->__isset.desc_tbl) { ++fcnt; xfer += oprot->writeFieldBegin("desc_tbl", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->desc_tbl.write(oprot); xfer += oprot->writeFieldEnd(); } ++fcnt; xfer += oprot->writeFieldBegin("fragments", ::apache::thrift::protocol::T_LIST, 2); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->fragments.size())); std::vector< ::impala::TPlanFragment> ::const_iterator _iter107; for (_iter107 = this->fragments.begin(); _iter107 != this->fragments.end(); ++_iter107) { xfer += (*_iter107).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); if (this->__isset.dest_fragment_idx) { ++fcnt; xfer += oprot->writeFieldBegin("dest_fragment_idx", ::apache::thrift::protocol::T_LIST, 3); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_I32, static_cast<uint32_t>(this->dest_fragment_idx.size())); std::vector<int32_t> ::const_iterator _iter108; for (_iter108 = this->dest_fragment_idx.begin(); _iter108 != this->dest_fragment_idx.end(); ++_iter108) { xfer += oprot->writeI32((*_iter108)); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } if (this->__isset.per_node_scan_ranges) { ++fcnt; xfer += oprot->writeFieldBegin("per_node_scan_ranges", ::apache::thrift::protocol::T_MAP, 4); { xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_I32, ::apache::thrift::protocol::T_LIST, static_cast<uint32_t>(this->per_node_scan_ranges.size())); std::map< ::impala::TPlanNodeId, std::vector< ::impala::TScanRangeLocations> > ::const_iterator _iter109; for (_iter109 = this->per_node_scan_ranges.begin(); _iter109 != this->per_node_scan_ranges.end(); ++_iter109) { xfer += oprot->writeI32(_iter109->first); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(_iter109->second.size())); std::vector< ::impala::TScanRangeLocations> ::const_iterator _iter110; for (_iter110 = _iter109->second.begin(); _iter110 != _iter109->second.end(); ++_iter110) { xfer += (*_iter110).write(oprot); } xfer += oprot->writeListEnd(); } } xfer += oprot->writeMapEnd(); } xfer += oprot->writeFieldEnd(); } if (this->__isset.result_set_metadata) { ++fcnt; xfer += oprot->writeFieldBegin("result_set_metadata", ::apache::thrift::protocol::T_STRUCT, 5); xfer += this->result_set_metadata.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.finalize_params) { ++fcnt; xfer += oprot->writeFieldBegin("finalize_params", ::apache::thrift::protocol::T_STRUCT, 6); xfer += this->finalize_params.write(oprot); xfer += oprot->writeFieldEnd(); } ++fcnt; xfer += oprot->writeFieldBegin("query_globals", ::apache::thrift::protocol::T_STRUCT, 7); xfer += this->query_globals.write(oprot); xfer += oprot->writeFieldEnd(); if (this->__isset.query_plan) { ++fcnt; xfer += oprot->writeFieldBegin("query_plan", ::apache::thrift::protocol::T_STRING, 8); xfer += oprot->writeString(this->query_plan); xfer += oprot->writeFieldEnd(); } ++fcnt; xfer += oprot->writeFieldBegin("stmt_type", ::apache::thrift::protocol::T_I32, 9); xfer += oprot->writeI32((int32_t)this->stmt_type); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TQueryExecRequest &a, TQueryExecRequest &b) { using ::std::swap; swap(a.desc_tbl, b.desc_tbl); swap(a.fragments, b.fragments); swap(a.dest_fragment_idx, b.dest_fragment_idx); swap(a.per_node_scan_ranges, b.per_node_scan_ranges); swap(a.result_set_metadata, b.result_set_metadata); swap(a.finalize_params, b.finalize_params); swap(a.query_globals, b.query_globals); swap(a.query_plan, b.query_plan); swap(a.stmt_type, b.stmt_type); swap(a.__isset, b.__isset); } const char* TDdlExecRequest::ascii_fingerprint = "0CD54BC026F4A54FCCF01B6B6F3FADA6"; const uint8_t TDdlExecRequest::binary_fingerprint[16] = {0x0C,0xD5,0x4B,0xC0,0x26,0xF4,0xA5,0x4F,0xCC,0xF0,0x1B,0x6B,0x6F,0x3F,0xAD,0xA6}; uint32_t TDdlExecRequest::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_ddl_type = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast111; xfer += iprot->readI32(ecast111); this->ddl_type = (TDdlType::type)ecast111; isset_ddl_type = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->use_db_params.read(iprot); this->__isset.use_db_params = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->describe_table_params.read(iprot); this->__isset.describe_table_params = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->show_dbs_params.read(iprot); this->__isset.show_dbs_params = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->show_tables_params.read(iprot); this->__isset.show_tables_params = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->alter_table_params.read(iprot); this->__isset.alter_table_params = true; } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->create_db_params.read(iprot); this->__isset.create_db_params = true; } else { xfer += iprot->skip(ftype); } break; case 8: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->create_table_params.read(iprot); this->__isset.create_table_params = true; } else { xfer += iprot->skip(ftype); } break; case 9: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->create_table_like_params.read(iprot); this->__isset.create_table_like_params = true; } else { xfer += iprot->skip(ftype); } break; case 10: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->drop_db_params.read(iprot); this->__isset.drop_db_params = true; } else { xfer += iprot->skip(ftype); } break; case 11: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->drop_table_params.read(iprot); this->__isset.drop_table_params = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_ddl_type) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TDdlExecRequest::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TDdlExecRequest"); ++fcnt; xfer += oprot->writeFieldBegin("ddl_type", ::apache::thrift::protocol::T_I32, 1); xfer += oprot->writeI32((int32_t)this->ddl_type); xfer += oprot->writeFieldEnd(); if (this->__isset.use_db_params) { ++fcnt; xfer += oprot->writeFieldBegin("use_db_params", ::apache::thrift::protocol::T_STRUCT, 2); xfer += this->use_db_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.describe_table_params) { ++fcnt; xfer += oprot->writeFieldBegin("describe_table_params", ::apache::thrift::protocol::T_STRUCT, 3); xfer += this->describe_table_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.show_dbs_params) { ++fcnt; xfer += oprot->writeFieldBegin("show_dbs_params", ::apache::thrift::protocol::T_STRUCT, 4); xfer += this->show_dbs_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.show_tables_params) { ++fcnt; xfer += oprot->writeFieldBegin("show_tables_params", ::apache::thrift::protocol::T_STRUCT, 5); xfer += this->show_tables_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.alter_table_params) { ++fcnt; xfer += oprot->writeFieldBegin("alter_table_params", ::apache::thrift::protocol::T_STRUCT, 6); xfer += this->alter_table_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.create_db_params) { ++fcnt; xfer += oprot->writeFieldBegin("create_db_params", ::apache::thrift::protocol::T_STRUCT, 7); xfer += this->create_db_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.create_table_params) { ++fcnt; xfer += oprot->writeFieldBegin("create_table_params", ::apache::thrift::protocol::T_STRUCT, 8); xfer += this->create_table_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.create_table_like_params) { ++fcnt; xfer += oprot->writeFieldBegin("create_table_like_params", ::apache::thrift::protocol::T_STRUCT, 9); xfer += this->create_table_like_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.drop_db_params) { ++fcnt; xfer += oprot->writeFieldBegin("drop_db_params", ::apache::thrift::protocol::T_STRUCT, 10); xfer += this->drop_db_params.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.drop_table_params) { ++fcnt; xfer += oprot->writeFieldBegin("drop_table_params", ::apache::thrift::protocol::T_STRUCT, 11); xfer += this->drop_table_params.write(oprot); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TDdlExecRequest &a, TDdlExecRequest &b) { using ::std::swap; swap(a.ddl_type, b.ddl_type); swap(a.use_db_params, b.use_db_params); swap(a.describe_table_params, b.describe_table_params); swap(a.show_dbs_params, b.show_dbs_params); swap(a.show_tables_params, b.show_tables_params); swap(a.alter_table_params, b.alter_table_params); swap(a.create_db_params, b.create_db_params); swap(a.create_table_params, b.create_table_params); swap(a.create_table_like_params, b.create_table_like_params); swap(a.drop_db_params, b.drop_db_params); swap(a.drop_table_params, b.drop_table_params); swap(a.__isset, b.__isset); } const char* TMetadataOpRequest::ascii_fingerprint = "4F3B3DA03A312B25CD984C98432A660A"; const uint8_t TMetadataOpRequest::binary_fingerprint[16] = {0x4F,0x3B,0x3D,0xA0,0x3A,0x31,0x2B,0x25,0xCD,0x98,0x4C,0x98,0x43,0x2A,0x66,0x0A}; uint32_t TMetadataOpRequest::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_opcode = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast112; xfer += iprot->readI32(ecast112); this->opcode = (TMetadataOpcode::type)ecast112; isset_opcode = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->get_info_req.read(iprot); this->__isset.get_info_req = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->get_type_info_req.read(iprot); this->__isset.get_type_info_req = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->get_catalogs_req.read(iprot); this->__isset.get_catalogs_req = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->get_schemas_req.read(iprot); this->__isset.get_schemas_req = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->get_tables_req.read(iprot); this->__isset.get_tables_req = true; } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->get_table_types_req.read(iprot); this->__isset.get_table_types_req = true; } else { xfer += iprot->skip(ftype); } break; case 8: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->get_columns_req.read(iprot); this->__isset.get_columns_req = true; } else { xfer += iprot->skip(ftype); } break; case 9: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->get_functions_req.read(iprot); this->__isset.get_functions_req = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_opcode) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TMetadataOpRequest::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TMetadataOpRequest"); ++fcnt; xfer += oprot->writeFieldBegin("opcode", ::apache::thrift::protocol::T_I32, 1); xfer += oprot->writeI32((int32_t)this->opcode); xfer += oprot->writeFieldEnd(); if (this->__isset.get_info_req) { ++fcnt; xfer += oprot->writeFieldBegin("get_info_req", ::apache::thrift::protocol::T_STRUCT, 2); xfer += this->get_info_req.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.get_type_info_req) { ++fcnt; xfer += oprot->writeFieldBegin("get_type_info_req", ::apache::thrift::protocol::T_STRUCT, 3); xfer += this->get_type_info_req.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.get_catalogs_req) { ++fcnt; xfer += oprot->writeFieldBegin("get_catalogs_req", ::apache::thrift::protocol::T_STRUCT, 4); xfer += this->get_catalogs_req.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.get_schemas_req) { ++fcnt; xfer += oprot->writeFieldBegin("get_schemas_req", ::apache::thrift::protocol::T_STRUCT, 5); xfer += this->get_schemas_req.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.get_tables_req) { ++fcnt; xfer += oprot->writeFieldBegin("get_tables_req", ::apache::thrift::protocol::T_STRUCT, 6); xfer += this->get_tables_req.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.get_table_types_req) { ++fcnt; xfer += oprot->writeFieldBegin("get_table_types_req", ::apache::thrift::protocol::T_STRUCT, 7); xfer += this->get_table_types_req.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.get_columns_req) { ++fcnt; xfer += oprot->writeFieldBegin("get_columns_req", ::apache::thrift::protocol::T_STRUCT, 8); xfer += this->get_columns_req.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.get_functions_req) { ++fcnt; xfer += oprot->writeFieldBegin("get_functions_req", ::apache::thrift::protocol::T_STRUCT, 9); xfer += this->get_functions_req.write(oprot); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TMetadataOpRequest &a, TMetadataOpRequest &b) { using ::std::swap; swap(a.opcode, b.opcode); swap(a.get_info_req, b.get_info_req); swap(a.get_type_info_req, b.get_type_info_req); swap(a.get_catalogs_req, b.get_catalogs_req); swap(a.get_schemas_req, b.get_schemas_req); swap(a.get_tables_req, b.get_tables_req); swap(a.get_table_types_req, b.get_table_types_req); swap(a.get_columns_req, b.get_columns_req); swap(a.get_functions_req, b.get_functions_req); swap(a.__isset, b.__isset); } const char* TMetadataOpResponse::ascii_fingerprint = "AA4955CB4C4B7C6D8052EE00C6221E71"; const uint8_t TMetadataOpResponse::binary_fingerprint[16] = {0xAA,0x49,0x55,0xCB,0x4C,0x4B,0x7C,0x6D,0x80,0x52,0xEE,0x00,0xC6,0x22,0x1E,0x71}; uint32_t TMetadataOpResponse::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_result_set_metadata = false; bool isset_results = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->result_set_metadata.read(iprot); isset_result_set_metadata = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->results.clear(); uint32_t _size113; ::apache::thrift::protocol::TType _etype116; xfer += iprot->readListBegin(_etype116, _size113); this->results.resize(_size113); uint32_t _i117; for (_i117 = 0; _i117 < _size113; ++_i117) { xfer += this->results[_i117].read(iprot); } xfer += iprot->readListEnd(); } isset_results = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_result_set_metadata) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_results) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TMetadataOpResponse::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TMetadataOpResponse"); ++fcnt; xfer += oprot->writeFieldBegin("result_set_metadata", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->result_set_metadata.write(oprot); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("results", ::apache::thrift::protocol::T_LIST, 2); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->results.size())); std::vector< ::impala::TResultRow> ::const_iterator _iter118; for (_iter118 = this->results.begin(); _iter118 != this->results.end(); ++_iter118) { xfer += (*_iter118).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TMetadataOpResponse &a, TMetadataOpResponse &b) { using ::std::swap; swap(a.result_set_metadata, b.result_set_metadata); swap(a.results, b.results); } const char* TExecRequest::ascii_fingerprint = "1C016EECD0A86E8488A03ED102679100"; const uint8_t TExecRequest::binary_fingerprint[16] = {0x1C,0x01,0x6E,0xEC,0xD0,0xA8,0x6E,0x84,0x88,0xA0,0x3E,0xD1,0x02,0x67,0x91,0x00}; uint32_t TExecRequest::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_stmt_type = false; bool isset_query_options = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast119; xfer += iprot->readI32(ecast119); this->stmt_type = ( ::impala::TStmtType::type)ecast119; isset_stmt_type = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->query_options.read(iprot); isset_query_options = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->query_exec_request.read(iprot); this->__isset.query_exec_request = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->ddl_exec_request.read(iprot); this->__isset.ddl_exec_request = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->result_set_metadata.read(iprot); this->__isset.result_set_metadata = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->explain_result.read(iprot); this->__isset.explain_result = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_stmt_type) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_query_options) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t TExecRequest::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; uint32_t fcnt = 0; xfer += oprot->writeStructBegin("TExecRequest"); ++fcnt; xfer += oprot->writeFieldBegin("stmt_type", ::apache::thrift::protocol::T_I32, 1); xfer += oprot->writeI32((int32_t)this->stmt_type); xfer += oprot->writeFieldEnd(); ++fcnt; xfer += oprot->writeFieldBegin("query_options", ::apache::thrift::protocol::T_STRUCT, 2); xfer += this->query_options.write(oprot); xfer += oprot->writeFieldEnd(); if (this->__isset.query_exec_request) { ++fcnt; xfer += oprot->writeFieldBegin("query_exec_request", ::apache::thrift::protocol::T_STRUCT, 3); xfer += this->query_exec_request.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.ddl_exec_request) { ++fcnt; xfer += oprot->writeFieldBegin("ddl_exec_request", ::apache::thrift::protocol::T_STRUCT, 4); xfer += this->ddl_exec_request.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.result_set_metadata) { ++fcnt; xfer += oprot->writeFieldBegin("result_set_metadata", ::apache::thrift::protocol::T_STRUCT, 5); xfer += this->result_set_metadata.write(oprot); xfer += oprot->writeFieldEnd(); } if (this->__isset.explain_result) { ++fcnt; xfer += oprot->writeFieldBegin("explain_result", ::apache::thrift::protocol::T_STRUCT, 6); xfer += this->explain_result.write(oprot); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(TExecRequest &a, TExecRequest &b) { using ::std::swap; swap(a.stmt_type, b.stmt_type); swap(a.query_options, b.query_options); swap(a.query_exec_request, b.query_exec_request); swap(a.ddl_exec_request, b.ddl_exec_request); swap(a.result_set_metadata, b.result_set_metadata); swap(a.explain_result, b.explain_result); swap(a.__isset, b.__isset); } } // namespace
[ "hlshih@gmail.com" ]
hlshih@gmail.com
bed83d44393ca4b1c55f7f9dd1320dd097c7b371
24893618660f768d9c411c0723ccbe822a628913
/Mammoth/TSE/CDesignTable.cpp
f1dc9c37aba899117bbe92e9857d7ca3ea73e53d
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
kronosaur/TranscendenceDev
da4940b77dd1e2846f8d1bfa83e349b1277e506d
a53798ed0f23cbbafa69b85dc1b9ec26b1d5bdda
refs/heads/master
2023-07-09T11:17:37.539313
2023-07-01T05:05:49
2023-07-01T05:05:49
164,558,909
31
14
NOASSERTION
2022-05-12T21:06:30
2019-01-08T04:15:34
C++
UTF-8
C++
false
false
5,722
cpp
// CDesignTable.cpp // // CDesignTable class #include "PreComp.h" ALERROR CDesignTable::AddEntry (CDesignType *pEntry) // AddEntry // // Adds an entry to the table. Returns ERR_OUTOFROOM if we already have an // entry with that UNID. { if (!pEntry) throw CException(ERR_FAIL); bool bNew; m_Table.SetAt(pEntry->GetUNID(), pEntry, &bNew); if (!bNew) return ERR_OUTOFROOM; return NOERROR; } ALERROR CDesignTable::AddOrReplaceEntry (CDesignType *pEntry, CDesignType **retpOldEntry) // AddOrReplaceEntry // // Adds or replaces an entry { bool bAdded; CDesignType **pSlot = m_Table.SetAt(pEntry->GetUNID(), &bAdded); if (retpOldEntry) *retpOldEntry = (!bAdded ? *pSlot : NULL); *pSlot = pEntry; return NOERROR; } void CDesignTable::Delete (DWORD dwUNID) // Delete // // Delete by UNID { int iIndex; if (m_Table.FindPos(dwUNID, &iIndex)) { if (m_bFreeTypes) m_Table[iIndex]->Delete(); m_Table.Delete(iIndex); } } void CDesignTable::DeleteAll (void) // DeleteAll // // Removes all entries and deletes the object that they point to { int i; if (m_bFreeTypes) { for (i = 0; i < GetCount(); i++) GetEntry(i)->Delete(); } m_Table.DeleteAll(); } CDesignType *CDesignTable::FindByUNID (DWORD dwUNID) const // FindByUNID // // Returns a pointer to the given entry or NULL { CDesignType * const *pObj = m_Table.GetAt(dwUNID); return (pObj ? *pObj : NULL); } ALERROR CDesignTable::Merge (const CDynamicDesignTable &Source, CDesignList *ioOverride) // Merge // // Merge the given table into ours. { DEBUG_TRY int i; for (i = 0; i < Source.GetCount(); i++) { CDesignType *pNewType = Source.GetType(i); // If this is an override then we put it on a different table and // leave the type alone. if (pNewType->IsModification()) { if (ioOverride) ioOverride->AddEntry(pNewType); } // Otherwise, add or replace else AddOrReplaceEntry(pNewType); } return NOERROR; DEBUG_CATCH } ALERROR CDesignTable::Merge (const CDesignTable &Source, CDesignList &Override, const TArray<DWORD> &ExtensionsIncluded, const TSortMap<DWORD, bool> &TypesUsed, DWORD dwAPIVersion) // Merge // // Merge the given table into ours. Entries in Table override our entries // if they have the same UNID. { int i; TArray<CDesignType *> Replaced; // We move through both tables in order and handle when we get an // addition or overlap. int iSrcPos = 0; int iDestPos = 0; // Merge while (iSrcPos < Source.GetCount()) { CDesignType *pNewType = Source.m_Table.GetValue(iSrcPos); // If this is an optional type then we need to figure out whether we're // going to include it or not. bool bMustExist = false; bool bExcluded = false; if (pNewType->IsOptional()) { bMustExist = (TypesUsed.GetCount() > 0 && TypesUsed.Find(pNewType->GetUNID())); bExcluded = !pNewType->IsIncluded(dwAPIVersion, ExtensionsIncluded); } // If this is an override type, then we add to a special table. // // NOTE: It is OK if we add multiple types of the same UNID. As long // as we add them in order, we're OK. if (pNewType->IsModification()) { // Modifications always rely on some underlying type, so if we're // excluding this modification, we can skip it, even if the type // itself is required by the save file. if (!bExcluded) Override.AddEntry(pNewType); iSrcPos++; } // If we're at the end of the destination then just insert else if (iDestPos == m_Table.GetCount()) { // Do not add excluded type, unless required by the save file. // The latter can happen if we make a type optional after a save // file has been created. if (!bExcluded || bMustExist) { m_Table.InsertSorted(pNewType->GetUNID(), pNewType); iDestPos++; } // Advance iSrcPos++; } // Otherwise, see if we need to insert or replace else { int iCompare = AscendingSort * KeyCompare(pNewType->GetUNID(), m_Table.GetKey(iDestPos)); // If the same key then we replace if (iCompare == 0) { // We found the UNID in the destination table, so we don't have // to worry about the type existing--it does. if (!bExcluded) { // If we have to free our originals, then remember them here. if (m_bFreeTypes) { CDesignType *pOriginalType = m_Table.GetValue(iDestPos); Replaced.Insert(pOriginalType); } // If the new type is different than the original, then warn // LATER: This should probably be an error. if (m_Table.GetValue(iDestPos)->GetType() != pNewType->GetType()) ::kernelDebugLogPattern("WARNING: Override of %08x is changing the type.", pNewType->GetUNID()); // Replace m_Table.GetValue(iDestPos) = pNewType; // Advance iDestPos++; } iSrcPos++; } // If the source is less than dest then we insert at this // position. else if (iCompare == 1) { if (!bExcluded || bMustExist) { m_Table.InsertSorted(pNewType->GetUNID(), pNewType, iDestPos); iDestPos++; } // Advance iSrcPos++; } // Otherwise, go to the next destination slot else // LATER: We could optimize this case by skipping ahead in an // inner loop. Otherwise we're recalculating pNewType and all // its state (particularly for optional types). iDestPos++; } } // Delete replaced entries for (i = 0; i < Replaced.GetCount(); i++) Replaced[i]->Delete(); return NOERROR; } void CDesignTable::SetHierarchyResolved (bool bValue) // SetHierarchyResolved // // Sets the hierarchy resolved flag. { for (int i = 0; i < m_Table.GetCount(); i++) m_Table[i]->SetHierarchyResolved(bValue); }
[ "public@neurohack.com" ]
public@neurohack.com
4044d70d1203a0c918ed9628b793b6c3ec5db78b
4bea57e631734f8cb1c230f521fd523a63c1ff23
/projects/openfoam/rarefied-flows/impingment/sims/test/nozzle1/5.28/uniform/time
d9cf1386a521bbe82bce01c30bc277698868fd52
[]
no_license
andytorrestb/cfal
76217f77dd43474f6b0a7eb430887e8775b78d7f
730fb66a3070ccb3e0c52c03417e3b09140f3605
refs/heads/master
2023-07-04T01:22:01.990628
2021-08-01T15:36:17
2021-08-01T15:36:17
294,183,829
1
0
null
null
null
null
UTF-8
C++
false
false
997
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1912 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "5.28/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 5.2800000000010332; name "5.28"; index 52800; deltaT 0.0001; deltaT0 0.0001; // ************************************************************************* //
[ "andytorrestb@gmail.com" ]
andytorrestb@gmail.com
51dd7a27279752184dd0959baf25ba191aa51454
1b904895aa5ba33e0137a962c33cc86a94308c73
/src/game/Game.h
4ed2a7a81f927be65b1bc0ad1b45ed241d26c52b
[ "MIT" ]
permissive
len-m/zombievival
b7105c4fd1eeeab01598eb0df80bb88666e6f561
8894c79bd57e98348e77c2208d593293da2225cd
refs/heads/master
2023-02-12T21:20:12.449988
2021-01-07T19:40:39
2021-01-07T19:40:39
323,917,435
0
0
null
null
null
null
UTF-8
C++
false
false
4,604
h
#ifndef GAME_H #define GAME_H #include <SFML/Graphics.hpp> #include <math.h> #include "Player.h" #include "Enemy.h" #include "Bullet.h" #include <vector> #include <stdlib.h> //srand, rand #include "Collision.h" #include "Chunk.h" #include "UpgradeMenu.h" #include "ItemDrop.h" #include "Trap.h" #include "Inventory.h" #include "../ResourceManager.h" #include <algorithm> class Game { public: Game(sf::RenderWindow *window); void update(const float &deltaTime); void render(); bool getIsActive(); void setIsActive(const bool &newIsActive); bool getIsDead(); bool getIsPaused(); void setIsPaused(const bool &isPaused); private: //general stuff Collision m_collision; int generateRandomNumber(const int &range); float getVectorLength(const sf::Vector2f &vector, const sf::Vector2f &offset); sf::RenderWindow *m_window; sf::View m_view; bool m_isActive; sf::Clock m_gametime; sf::RectangleShape m_field; sf::RectangleShape m_borderLeft; sf::RectangleShape m_borderTop; sf::RectangleShape m_borderRight; sf::RectangleShape m_borderBottom; ResourceManager resourceManager; float m_score; sf::Text m_scoreText; sf::Text m_gameOverText; bool m_isPaused; sf::Text m_isPausedText; //cursor sf::Vector2f m_cursorWorldPosition; sf::Sprite m_cursor; //bullet std::vector<std::shared_ptr<Bullet>> m_bulletVector; sf::Clock m_bulletCooldownClock; float m_bulletSpeed; float m_bulletLifetime; float m_bulletCooldown; bool m_onBulletCooldown; float m_bulletDamage; bool m_playerFiredLastFrame; float m_bulletSpawnAmountRest; //player void move(const sf::Vector2f &movement, const float &deltaTime); void moveOutOfBorder(const float &deltaTime); void shoot(); void takeTrap(); void placeTrap(); std::shared_ptr<Player> m_player; float m_playerMaxLife; float m_movementSpeed; float m_knockbackMovementSpeed; sf::Vector2f m_knockbackStartingPosition; float m_knockbackLength; bool m_dead; //enemy std::vector<std::shared_ptr<Enemy>> m_enemyVector; sf::Clock m_enemySpawnClock; float m_enemySpawnRate; float m_enemySpawnCountDifference; float m_enemySpawnRadius; int m_maxAllowedAliveEnemies; float m_enemyMoveFactor; float m_enemyMaxDistanceFromPlayer; int m_wave; int m_enemiesTotalToBeSpawnedInWave; int m_enemiesSpawnedCount; sf::Text m_waveText; sf::Clock m_waveCooldownClock; bool m_onWaveCooldown; bool m_drawWaveText; float m_waveCooldownLength; std::vector<float> m_enemyTrappedClock; float m_trappedTime; //enemyType float m_enemyNormalDamage; float m_enemyNormalMovementSpeed; float m_enemyNormalMaxLife; float m_enemyTankDamage; float m_enemyTankMovementSpeed; float m_enemyTankMaxLife; //item drops std::vector<std::shared_ptr<ItemDrop>> m_itemDropHeartVector; std::vector<std::shared_ptr<ItemDrop>> m_itemDropCoinVector; std::vector<std::shared_ptr<ItemDrop>> m_itemDropTrapVector; float m_heartLifeRefill; int m_itemDropSpawnRate; int m_coinAmount; //trap bool m_hasTrap; std::vector<std::shared_ptr<Trap>> m_trapVector; float m_trapUseDamage; //damage the trap gets if an enemy steps inside //chunk void canSpawnChunk(bool *canSpawn, sf::Vector2f chunkToBeCheckedForOccupation, sf::Vector2f postion); void spawnChunk(bool canSpawn, sf::Vector2f position); void chunkSpawning(const int &i, const sf::Vector2f &chunkPosition1, const sf::Vector2f &chunkPosition2, const sf::Vector2f &chunkPosition3); std::vector<std::shared_ptr<Chunk>> m_chunkVector; float m_chunkLength; int m_numberOfTilesPerChunk; std::vector<sf::Texture> m_backgroundTextures; //upgrade Menu void upgrade(float *upgradeType, const bool &multiply, const float &amount, const int &i); std::shared_ptr<UpgradeMenu> m_upgradeMenu; //inventory std::shared_ptr<Inventory> m_inventory; //sounds sf::Sound shootSound; sf::Sound enemyHit; sf::Sound playerHit; }; #endif
[ "l.michalke@tu-bs.de" ]
l.michalke@tu-bs.de
c6893b0263737cf2aa782cb2f1b86bb7f4bce8e7
6d64c36b9e0c158829ca11e275fe8759e2bc0eff
/src/qt/addressbookpage.cpp
519ff3652baac8ffc4249be61cddd9877ab7db75
[ "MIT" ]
permissive
thehomosapien/dutcoin
65e4ae372f7622b96df4d80a87706d609c4e56f0
43a2a3e42713260eec7dac62145c991e59bb3287
refs/heads/master
2020-07-01T03:36:21.234004
2019-08-07T13:01:27
2019-08-07T13:01:27
200,853,776
0
0
null
null
null
null
UTF-8
C++
false
false
10,127
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/dutcoin-config.h" #endif #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "bitcoingui.h" #include "csvmodelwriter.h" #include "editaddressdialog.h" #include "guiutil.h" #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget* parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); #endif switch (mode) { case ForSelection: switch (tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch (tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch (tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your DUT addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your DUT addresses for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); break; } // Context menu actions QAction* copyAddressAction = new QAction(tr("&Copy Address"), this); QAction* copyLabelAction = new QAction(tr("Copy &Label"), this); QAction* editAction = new QAction(tr("&Edit"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if (tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel* model) { this->model = model; if (!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch (tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(selectNewAddress(QModelIndex, int, int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if (!model) return; if (!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if (indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if (!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if (dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView* table = ui->tableView; if (!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if (!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView* table = ui->tableView; if (!table->selectionModel()) return; if (table->selectionModel()->hasSelection()) { switch (tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView* table = ui->tableView; if (!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if (returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if (!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1. Please try again.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint& point) { QModelIndex index = ui->tableView->indexAt(point); if (index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex& parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if (idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
[ "rishabhshukla@opulasoft.com" ]
rishabhshukla@opulasoft.com
354dc3d9c57b2446e0e9ae5def6e8427b3edb031
05e1f94ae1a5513a222d38dfe4c3c6737cb84251
/Mulberry/branches/users/kenneth_porter/FromTrunk/Linux/Sources/Application/Calendar/Component_Editing/CNewToDoTiming.h
02252f938942a3162d77b9679bf250c44edd45c7
[ "Apache-2.0" ]
permissive
eskilblomfeldt/mulberry-svn
16ca9d4d6ec05cbbbd18045c7b59943b0aca9335
7ed26b61244e47d4d4d50a1c7cc2d31efa548ad7
refs/heads/master
2020-05-20T12:35:42.340160
2014-12-24T18:03:50
2014-12-24T18:03:50
29,127,476
0
0
null
null
null
null
UTF-8
C++
false
false
2,132
h
/* Copyright (c) 2007 Cyrus Daboo. All rights reserved. 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. */ #ifndef H_CNewToDoTiming #define H_CNewToDoTiming #include "CNewTimingPanel.h" class CDateTimeZoneSelect; class CDurationSelect; class JXRadioGroup; class JXTextCheckbox; class JXTextRadioButton; // =========================================================================== // CNewToDoTiming class CNewToDoTiming : public CNewTimingPanel { public: CNewToDoTiming(JXContainer* enclosure, const HSizingOption hSizing, const VSizingOption vSizing, const JCoordinate x, const JCoordinate y, const JCoordinate w, const JCoordinate h) : CNewTimingPanel(enclosure, hSizing, vSizing, x, y, w, h) {} virtual ~CNewToDoTiming() {} virtual void OnCreate(); virtual bool GetAllDay() const; virtual void GetTimezone(iCal::CICalendarTimezone& tz) const; virtual void SetToDo(const iCal::CICalendarVToDo& vtodo); virtual void GetToDo(iCal::CICalendarVToDo& vtodo); virtual void SetReadOnly(bool read_only); protected: enum { eDue_NoDue = 1, eDue_DueBy, eDue_Start }; // UI Objects // begin JXLayout1 JXTextCheckbox* mAllDay; JXRadioGroup* mDueGroup; JXTextRadioButton* mNoDue; JXTextRadioButton* mDueBy; CDateTimeZoneSelect* mDueDateTimeZone; JXTextRadioButton* mStarts; CDateTimeZoneSelect* mStartDateTimeZone; CDurationSelect* mDuration; // end JXLayout1 virtual void Receive(JBroadcaster* sender, const Message& message); void DoAllDay(bool set); void DoDueGroup(JIndex group); }; #endif
[ "svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132" ]
svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132
169f289295df40ddb74b44def83b3c31f2e18b0f
fb3c1e036f18193d6ffe59f443dad8323cb6e371
/src/flash/AVMSWF/api/flash/media/AS3AudioDecoder.h
da858ed910c9eb1a4bddd1eaf752aa696e293c9e
[]
no_license
playbar/nstest
a61aed443af816fdc6e7beab65e935824dcd07b2
d56141912bc2b0e22d1652aa7aff182e05142005
refs/heads/master
2021-06-03T21:56:17.779018
2016-08-01T03:17:39
2016-08-01T03:17:39
64,627,195
3
1
null
null
null
null
UTF-8
C++
false
false
2,197
h
#ifndef _AS3AudioDecoder_ #define _AS3AudioDecoder_ namespace avmplus { namespace NativeID { class AudioDecoderClassSlots { friend class SlotOffsetsAndAsserts; public://Declare your STATIC AS3 slots here!!! // DOLBY_DIGITAL:String = "DolbyDigital" // DOLBY_DIGITAL_PLUS:String = "DolbyDigitalPlus" // DTS:String = "DTS" // DTS_EXPRESS:String = "DTSExpress" // DTS_HD_HIGH_RESOLUTION_AUDIO:String = "DTSHDHighResolutionAudio" // DTS_HD_MASTER_AUDIO:String = "DTSHDMasterAudio" Stringp DOLBY_DIGITAL; Stringp DOLBY_DIGITAL_PLUS; Stringp DTS; Stringp DTS_EXPRESS; Stringp DTS_HD_HIGH_RESOLUTION_AUDIO; Stringp DTS_HD_MASTER_AUDIO; private: }; class AudioDecoderObjectSlots { friend class SlotOffsetsAndAsserts; public: //Declare your MEMBER AS3 slots here!!! private: }; } } namespace avmshell{ class AudioDecoderClass : public ClassClosure//EventClass { public: AudioDecoderClass(VTable *vtable); ScriptObject *createInstance(VTable *ivtable, ScriptObject *delegate); inline Stringp getSlotDOLBY_DIGITAL(){return m_slots_AudioDecoderClass.DOLBY_DIGITAL;} inline Stringp getSlotDOLBY_DIGITAL_PLUS(){return m_slots_AudioDecoderClass.DOLBY_DIGITAL_PLUS;} inline Stringp getSlotDTS(){return m_slots_AudioDecoderClass.DTS;} inline Stringp getSlotDTS_EXPRESS(){return m_slots_AudioDecoderClass.DTS_EXPRESS;} inline Stringp getSlotDTS_HD_HIGH_RESOLUTION_AUDIO(){return m_slots_AudioDecoderClass.DTS_HD_HIGH_RESOLUTION_AUDIO;} inline Stringp getSlotDTS_HD_MASTER_AUDIO(){return m_slots_AudioDecoderClass.DTS_HD_MASTER_AUDIO;} public: private: #ifdef _SYMBIAN public: #endif friend class avmplus::NativeID::SlotOffsetsAndAsserts; avmplus::NativeID::AudioDecoderClassSlots m_slots_AudioDecoderClass; }; class AudioDecoderObject : public ScriptObject { public: AudioDecoderObject(VTable* _vtable, ScriptObject* _delegate, int capacity); private: #ifdef _SYMBIAN public: #endif friend class avmplus::NativeID::SlotOffsetsAndAsserts; avmplus::NativeID::AudioDecoderObjectSlots m_slots_AudioDecoderObject; }; } #endif
[ "hgl868@126.com" ]
hgl868@126.com
b14054b753e8ada3ecf9cbc49f1b24499d942887
5d01a2a16078b78fbb7380a6ee548fc87a80e333
/ETS/Components/MM/EtsMmQuotesCV/MmQvExpAtom.h
015c31481c0c1cbbc1821d6d69e734e4df30173d
[]
no_license
WilliamQf-AI/IVRMstandard
2fd66ae6e81976d39705614cfab3dbfb4e8553c5
761bbdd0343012e7367ea111869bb6a9d8f043c0
refs/heads/master
2023-04-04T22:06:48.237586
2013-04-17T13:56:40
2013-04-17T13:56:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,603
h
// MmQvExpAtom.h : Declaration of the CMmQvExpAtom #ifndef __MMQVEXPATOM_H__ #define __MMQVEXPATOM_H__ #pragma once #include "resource.h" // main symbols #include "EtsMmQuotes.h" #include "MmQvStrikeColl.h" _COM_SMARTPTR_TYPEDEF(IMmQvExpAtom, IID_IMmQvExpAtom); struct __MmQvExpAtom { DATE m_dtExpiryMonth; DATE m_dtExpiry; DOUBLE m_dRate; DOUBLE m_dRateCust; VARIANT_BOOL m_bVisible; IMmQvStrikeCollPtr m_spStrike; IMmQvStrikeAtomPtr m_spAtmStrike; _bstr_t m_bstrRootNames; DOUBLE m_dHTBRate; DATE m_dtExpiryOV; DATE m_dtTradingClose; __MmQvExpAtom() : m_dtExpiryMonth(0.), m_dtExpiry(0.), m_dRate(0.), m_dRateCust(0.), m_bVisible(VARIANT_FALSE), m_dHTBRate(BAD_DOUBLE_VALUE), m_dtExpiryOV(0), m_dtTradingClose(0) { } }; // CMmQvExpAtom class ATL_NO_VTABLE CMmQvExpAtom : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CMmQvExpAtom, &CLSID_MmQvExpAtom>, public ISupportErrorInfoImpl<&IID_IMmQvExpAtom>, public IDispatchImpl<IMmQvExpAtom, &IID_IMmQvExpAtom, &LIBID_EtsMmQuotesLib, /*wMajor =*/ 1, /*wMinor =*/ 0>, public __MmQvExpAtom { typedef std::set<_bstr_t> CRootNamesCollection; public: CMmQvExpAtom() :m_pStrike(NULL) { m_pUnkMarshaler = NULL; } DECLARE_REGISTRY_RESOURCEID(IDR_MMQVEXPATOM) BEGIN_COM_MAP(CMmQvExpAtom) COM_INTERFACE_ENTRY(IMmQvExpAtom) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY_AGGREGATE(IID_IMarshal, m_pUnkMarshaler.p) END_COM_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() DECLARE_GET_CONTROLLING_UNKNOWN() HRESULT FinalConstruct() { HRESULT hr = S_OK; try { _CHK(CComObject<CMmQvStrikeColl>::CreateInstance(&m_pStrike), _T("Fail to create strikes.")); m_spStrike.Attach(m_pStrike, TRUE); hr = CoCreateFreeThreadedMarshaler( GetControllingUnknown(), &m_pUnkMarshaler.p); } catch(const _com_error& e) { hr = Error((PTCHAR)CComErrorWrapper::ErrorDescription(e), IID_IMmQvExpAtom, e.Error()); } return hr; } void FinalRelease() { m_spStrike = NULL; m_spAtmStrike = NULL; m_pUnkMarshaler.Release(); } bool AddRoot(_bstr_t& bsRootName) { CRootNamesCollection::iterator itrFind = m_Roots.find(bsRootName); if(itrFind != m_Roots.end()) { if(m_Roots.empty()) m_bstrRootNames = bsRootName; else m_bstrRootNames += _bstr_t(L",") + bsRootName; m_Roots.insert(bsRootName); return true; } return false; } public: CComObject<CMmQvStrikeColl>* m_pStrike; private: CRootNamesCollection m_Roots; CComPtr<IUnknown> m_pUnkMarshaler; public: IMPLEMENT_SIMPLE_PROPERTY(DATE, ExpiryMonth, m_dtExpiryMonth) IMPLEMENT_SIMPLE_PROPERTY(DATE, Expiry, m_dtExpiry) IMPLEMENT_SIMPLE_PROPERTY(DOUBLE, Rate, m_dRate) IMPLEMENT_SIMPLE_PROPERTY(DOUBLE, HTBRate, m_dHTBRate) IMPLEMENT_SIMPLE_PROPERTY(DOUBLE, RateCust, m_dRateCust) IMPLEMENT_SIMPLE_PROPERTY(VARIANT_BOOL, Visible, m_bVisible) IMPLEMENT_OBJECTREADONLY_PROPERTY(IMmQvStrikeColl*, Strike, m_spStrike) IMPLEMENT_OBJECT_PROPERTY(IMmQvStrikeAtom*, NearAtmStrike, m_spAtmStrike) IMPLEMENT_BSTRT_PROPERTY(RootNames, m_bstrRootNames) STDMETHOD(get_NearAtmVola)(DOUBLE* pVal); STDMETHOD(FindAtmStrike)(DOUBLE UnderlyingSpot); IMPLEMENT_SIMPLE_PROPERTY(DATE, ExpiryOV, m_dtExpiryOV) IMPLEMENT_SIMPLE_PROPERTY(DATE, TradingClose, m_dtTradingClose) }; OBJECT_ENTRY_AUTO(__uuidof(MmQvExpAtom), CMmQvExpAtom) #endif //__MMQVEXPATOM_H__
[ "chuchev@egartech.com" ]
chuchev@egartech.com
162bed304530afad15b3e0fadf0f95f071f1da24
8eb53dd4d630f370f9d878274e445a5806410c23
/addition/CellConnection.h
bca478cc7b7c93350e841e50d33a6300ef33af20
[]
no_license
XCodeMegic/CellView
d2f3e6f986b81084879c69b6dd0b2dbfa27b5481
b37cf54c34fc40eb7895c3bcfc84f3776f64b889
refs/heads/master
2021-01-13T15:37:49.510772
2016-12-20T03:06:39
2016-12-20T03:06:39
76,914,052
0
0
null
null
null
null
UTF-8
C++
false
false
545
h
#pragma once #include "extdefined.h" #include "x_motion.h" #include "connectionlistener.h" class CCellConnection : public gloox::ConnectionListener { public: CCellConnection(gloox::Client *client); virtual ~CCellConnection(); protected: //ConnectionListener virtual void onConnect(); virtual void onDisconnect(gloox::ConnectionError e); virtual bool onTLSConnect(const gloox::CertInfo& info); private: XMotion *m_motion; gloox::Client *m_client; public: void SetMotion(XMotion *mt) { m_motion = mt; } };
[ "xzq_@xxxx.x" ]
xzq_@xxxx.x
e7784c07f88a05496ed700b341a85f7f95b2656e
6616e8cab837f20e2cc41585609a2e6d2c053de7
/handTracker/src-gen/HandTrackerCompdef/HandTracker.h
009f985d3bc53f80c62b0c187f9d6790aa38341b
[]
no_license
EkaterinaKapanzha/PapPercComp
792c643b8466edf331cf77eb82cc071117ef9b71
fa454bd7747fc980d77447aadb6ffa6b188c0802
refs/heads/master
2022-10-06T22:58:27.262434
2020-06-08T11:33:02
2020-06-08T11:33:02
270,269,240
0
0
null
2020-06-07T10:22:55
2020-06-07T10:22:54
null
UTF-8
C++
false
false
1,748
h
// -------------------------------------------------------- // Code generated by Papyrus C++ // -------------------------------------------------------- #ifndef HANDTRACKERCOMPDEF_HANDTRACKER_H #define HANDTRACKERCOMPDEF_HANDTRACKER_H /************************************************************ HandTracker class header ************************************************************/ #include "HandTrackerCompdef/Pkg_HandTrackerCompdef.h" #include "rclcpp_lifecycle/lifecycle_node.hpp" #include "sensor_msgs/msg/image.hpp" #include "std_msgs/msg/float32multi_array.hpp" // Include from Include stereotype (header) #include <rclcpp/rclcpp.hpp> // End of Include stereotype (header) namespace ros2Library { namespace rclcpp { class NodeOptions; } } namespace ros2Library { namespace rclcpp { class Subscription; } } namespace HandTrackerCompdef { /************************************************************/ /** * */ class HandTracker: public rclcpp_lifecycle::LifecycleNode { public: /** * */ rclcpp::Subscription<sensor_msgs::msg::Image>::SharedPtr image_S_sub_; /** * */ rclcpp_lifecycle::LifecyclePublisher<std_msgs::msg::Float32MultiArray>::SharedPtr points_P_pub_; /** * * @param options */ HandTracker(rclcpp::NodeOptions /*in*/options); }; /************************************************************/ /* External declarations (package visibility) */ /************************************************************/ /* Inline functions */ } // of namespace HandTrackerCompdef /************************************************************ End of HandTracker class header ************************************************************/ #endif
[ "ekaterina.kapanzha@gmail.com" ]
ekaterina.kapanzha@gmail.com
2f03c1cc6bee6559b5af9d0098a185e781dd40d7
8e3e4a8aa16934a32ad6882225cbae405ae511f5
/synth_02/89_midi_util.ino
dddf29c6bf9842c9d3f1ad6c251267bdc5a86330
[]
no_license
apiel/sequencer
da5db792ef0ae796f9dbefbfbad362222c3712e0
8eac658bdc17ecf2ff9f8b9a5ce44845c2e81a9c
refs/heads/main
2023-03-19T23:35:37.046268
2021-03-10T17:27:45
2021-03-10T17:27:45
326,249,794
0
0
null
null
null
null
UTF-8
C++
false
false
1,390
ino
#define KNOB_MAX_VALUE 127 #define KNOB_INIT_VALUE 200 byte knobValues[KNOB_COUNT] = { KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE, KNOB_INIT_VALUE}; int getKnobDirection(byte knob, byte val) { int direction = 0; if (knobValues[knob] == KNOB_INIT_VALUE) { knobValues[knob] = val; } else if (val == 0) { direction = -1; knobValues[knob] = 0; } else if (val == KNOB_MAX_VALUE) { direction = 1; knobValues[knob] = KNOB_MAX_VALUE; } else { direction = val - knobValues[knob]; knobValues[knob] = between(knobValues[knob] + direction, 0, KNOB_MAX_VALUE); } return direction; } // used for first row from x touch mini to know which item // number is it, e.g. which tone selected byte getItemKey(byte key) { if (getItemKeyA(key) < 255) { return getItemKeyA(key); } return getItemKeyB(key); } byte getItemKeyA(byte key) { if (key >= 8 && key <= 15) { return key - 8; } return 255; } byte getItemKeyB(byte key) { if (key >= 32 && key <= 39) { return key - 32; } return 255; }
[ "alexandre.piel@gmail.com" ]
alexandre.piel@gmail.com
dc3b4d286d2af100e2c7e55548fcd0956f33c551
92b52435650d53c956187a85af2705652232fee7
/include/Analysis/token.h
7a9684453a95444629a274f12a4cb817448e73f2
[]
no_license
LarichevVitaly/Compiler
f91ee8083bc08c6a45fa07f2effe641b13c98fa5
d92f9dbb93641b762926353f1d3de46d939fa2fb
refs/heads/master
2021-01-18T12:15:41.456341
2016-02-24T18:27:02
2016-02-24T18:27:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
398
h
#ifndef COMPILER_TOKEN_H #define COMPILER_TOKEN_H #include <iostream> #include "Const.h" #include "Console/Console.h" class Token { public: Token(); ~Token(); void Set(std::string value,TokenType type); const char * GetStringType(); const char * GetValue(); private: std::string value; TokenType type; }; #endif //COMPILER_TOKEN_H
[ "dikiigr@gmail.com" ]
dikiigr@gmail.com
2d35bb480ddec10ab2765bc45683b6ab5b4d90f9
7e7a3cd90fdeb556dd3459eb5e6a8f68a0718d1d
/Support/util/file.cpp
6add6896d5695331c9691013da78494145115f5b
[ "Apache-2.0" ]
permissive
robojan/EmuAll
7d3c792fce79db4b10613b93f0a0a7c23f42a530
0a589136df9fefbfa142e605e1d3a0c94f726bad
refs/heads/master
2021-01-21T04:50:46.603365
2016-07-22T10:44:18
2016-07-22T10:44:18
44,864,341
1
0
null
null
null
null
UTF-8
C++
false
false
9,830
cpp
#include <emuall/util/file.h> #include <cerrno> #include <vector> class File::Prvt { public: std::shared_ptr<FILE> _file; std::string _filename; fileOpenMode _mode; errno_t _lastErrno; }; File::File(const char *filename, fileOpenMode mode) { _prvt = new Prvt; _prvt->_filename = filename; _prvt->_mode = mode; _prvt->_lastErrno = 0; _prvt->_file = nullptr; Open(); } File::File() { _prvt = new Prvt; _prvt->_mode = openReadOnly; _prvt->_lastErrno = 0; _prvt->_file = nullptr; } File::File(File &other) { _prvt = other._prvt; other._prvt = new Prvt; _prvt->_mode = openReadOnly; _prvt->_lastErrno = 0; _prvt->_file = nullptr; } File::~File() { Close(); delete _prvt; } bool File::Seek(long offset, File::seekOrigins origin) { if (_prvt->_file.get() == NULL) { _prvt->_lastErrno = errno = ENOSR; return false; } size_t pos = ftell(_prvt->_file.get()); if ((origin == File::seekBeginning && offset == pos) || (origin == File::seekCurrent && offset == 0)) return true; if (fseek(_prvt->_file.get(), offset, origin) != 0) { _prvt->_lastErrno = errno; throw FileException(_prvt->_lastErrno, "File seek failed: %s", strerror(_prvt->_lastErrno)); } return true; } long int File::GetPosition() { if (_prvt->_file.get() == NULL) { _prvt->_lastErrno = errno = ENOSR; throw FileException(_prvt->_lastErrno, "File not opened: %s", strerror(_prvt->_lastErrno)); return -1L; } return ftell(_prvt->_file.get()); } long int File::GetSize() { if (_prvt->_file.get() == NULL) { _prvt->_lastErrno = errno = ENOSR; throw FileException(_prvt->_lastErrno, "File not opened: %s", strerror(_prvt->_lastErrno)); } long int currentPos = ftell(_prvt->_file.get()); bool success = Seek(0, seekEnd); long int endPos = ftell(_prvt->_file.get()); success &= Seek(currentPos, seekBeginning); if (success) { return endPos; } _prvt->_lastErrno = errno; throw FileException(_prvt->_lastErrno, "Getting file size failed: %s", strerror(_prvt->_lastErrno)); } bool File::IsEOF() const { return _prvt->_file.get() == NULL || feof(_prvt->_file.get()) != 0; } bool File::Open() { if (_prvt->_filename.empty() || _prvt->_mode == 0) { _prvt->_lastErrno = errno = EINVAL; throw FileException(_prvt->_lastErrno, "No filename or mode was given"); } if (_prvt->_file.get() != NULL) { FILE *tmp = freopen(_prvt->_filename.c_str(), GetOpenModeString(_prvt->_mode), _prvt->_file.get()); _prvt->_file = std::shared_ptr<FILE>(tmp, std::fclose); } else { FILE *tmp = fopen(_prvt->_filename.c_str(), GetOpenModeString(_prvt->_mode)); _prvt->_file = std::shared_ptr<FILE>(tmp, std::fclose); } if (_prvt->_file.get() == NULL) { _prvt->_lastErrno = errno; throw FileException(_prvt->_lastErrno, "Could not open file: %s", strerror(_prvt->_lastErrno)); } return true; } bool File::Open(fileOpenMode mode) { _prvt->_mode = mode; if (_prvt->_file.get() != NULL) { if (freopen(_prvt->_filename.c_str(), GetOpenModeString(_prvt->_mode), _prvt->_file.get()) == NULL) { _prvt->_lastErrno = errno; throw FileException(_prvt->_lastErrno, "Could not open file: %s", strerror(_prvt->_lastErrno)); } return true; } else { return Open(); } } bool File::IsOpen() const { return _prvt->_file.get() != NULL; } bool File::Close() { _prvt->_file.reset(); return true; } size_t File::Read(void *ptr, size_t size) { if (_prvt->_file.get() == NULL) { _prvt->_lastErrno = errno = ENOSR; throw FileException(_prvt->_lastErrno, "File not opened: %s", strerror(_prvt->_lastErrno)); } size_t result = fread(ptr, 1, size, _prvt->_file.get()); if (result != size) { if (IsEOF()) { throw EndOfFileException(); } _prvt->_lastErrno = errno; throw FileException(_prvt->_lastErrno, "File reading failed: %s", strerror(_prvt->_lastErrno)); } return result; } size_t File::Write(const void *ptr, size_t size) { if (_prvt->_file.get() == NULL) { _prvt->_lastErrno = errno = ENOSR; throw FileException(_prvt->_lastErrno, "File not opened: %s", strerror(_prvt->_lastErrno)); } size_t result = fwrite(ptr, 1, size, _prvt->_file.get()); if (result != size) { _prvt->_lastErrno = errno; throw FileException(_prvt->_lastErrno, "File writing failed: %s", strerror(_prvt->_lastErrno)); } return result; } int File::GetC() { if (_prvt->_file.get() == NULL) { _prvt->_lastErrno = errno = ENOSR; throw FileException(_prvt->_lastErrno, "File not opened: %s", strerror(_prvt->_lastErrno)); } int result = fgetc(_prvt->_file.get()); if (IsEOF()) { throw EndOfFileException(); } return result; } bool File::GetC(unsigned char *c) { int result; if (c == NULL) { _prvt->_lastErrno = errno = EINVAL; throw FileException(_prvt->_lastErrno, "File not opened: %s", strerror(_prvt->_lastErrno)); } if ((result = GetC()) == EOF) { if (IsEOF()) { throw EndOfFileException(); } _prvt->_lastErrno = errno; throw FileException(_prvt->_lastErrno, "File reading failed: %s", strerror(_prvt->_lastErrno)); } *c = (unsigned char)result; return true; } bool File::GetC(char *c) { int result; if (c == NULL) { _prvt->_lastErrno = errno = EINVAL; throw FileException(_prvt->_lastErrno, "File not opened: %s", strerror(_prvt->_lastErrno)); } if ((result = GetC()) == EOF) { if (IsEOF()) { throw EndOfFileException(); } _prvt->_lastErrno = errno; throw FileException(_prvt->_lastErrno, "File reading failed: %s", strerror(_prvt->_lastErrno)); } *c = (char) result; return true; } bool File::PutC(unsigned char c) { if (_prvt->_file.get() == NULL) { _prvt->_lastErrno = errno = ENOSR; throw FileException(_prvt->_lastErrno, "File not opened: %s", strerror(_prvt->_lastErrno)); } if (fputc(c, _prvt->_file.get()) != c) { _prvt->_lastErrno = errno; throw FileException(_prvt->_lastErrno, "File writing failed: %s", strerror(_prvt->_lastErrno)); } return true; } bool File::PutC(char c) { if (_prvt->_file.get() == NULL) { _prvt->_lastErrno = errno = ENOSR; throw FileException(_prvt->_lastErrno, "File not opened: %s", strerror(_prvt->_lastErrno)); } if (fputc(c, _prvt->_file.get()) != c) { _prvt->_lastErrno = errno; throw FileException(_prvt->_lastErrno, "File writing failed: %s", strerror(_prvt->_lastErrno)); } return true; } const char *File::GetOpenModeString(fileOpenMode mode) { switch (mode) { case openReadOnly: return "r"; case openWriteOnly: return "w"; case openAppend: return "a"; case openRW: return "r+"; case openRWCreate: return "w+"; case openAppendRead: return "a+"; case openWriteOnlyFail: return "wx"; case openRWCreateFail: return "w+x"; // Keep raw and text mode seperated case openRawReadOnly: return "rb"; case openRawWriteOnly: return "wb"; case openRawAppend: return "ab"; case openRawRW: return "rb+"; case openRawRWCreate: return "wb+"; case openRawAppendRead: return "ab+"; case openRawWriteOnlyFail: return "wbx"; case openRawRWCreateFail: return "wb+x"; default: return "rb"; } } errno_t File::GetLastErrno() const { return _prvt->_lastErrno; } void File::ClearErrno() { _prvt->_lastErrno = 0; } File & File::operator=(File &other) { _prvt = other._prvt; other._prvt = new Prvt; return *this; } RawFile::RawFile(const char *filepath, fileOpenMode mode, bool littleEndian) : File(filepath, mode), _conv(!littleEndian) { } RawFile::RawFile(bool littleEndian) : File(), _conv(!littleEndian) { } RawFile::RawFile(RawFile &other) : File(other), _conv(other._conv) { } RawFile::~RawFile() { } RawFile & RawFile::operator=(RawFile &other) { File::operator=(other); _conv = other._conv; return *this; } uint8_t RawFile::GetU8() { uint8_t x; Read(&x, sizeof(x)); return x; } int8_t RawFile::GetI8() { int8_t x; Read(&x, sizeof(x)); return x; } uint16_t RawFile::GetU16() { uint16_t x; Read(&x, sizeof(x)); return _conv.convu16(x); } int16_t RawFile::GetI16() { int16_t x; Read(&x, sizeof(x)); return _conv.convi16(x); } uint32_t RawFile::GetU24() { uint32_t x = 0; GetC(((uint8_t *) &x) + 0); GetC(((uint8_t *) &x) + 1); GetC(((uint8_t *) &x) + 2); return _conv.convu32(x); } int32_t RawFile::GetI24() { int32_t x; GetC(((uint8_t *) &x) + 0); GetC(((uint8_t *) &x) + 1); GetC(((uint8_t *) &x) + 2); return _conv.convi32(x); } uint32_t RawFile::GetU32() { uint32_t x; Read(&x, sizeof(x)); return _conv.convu32(x); } int32_t RawFile::GetI32() { int32_t x; Read(&x, sizeof(x)); return _conv.convi32(x); } uint64_t RawFile::GetU64() { uint64_t x; Read(&x, sizeof(x)); return _conv.convu64(x); } int64_t RawFile::GetI64() { int64_t x; Read(&x, sizeof(x)); return _conv.convi64(x); } float RawFile::GetFloat() { float x; Read(&x, sizeof(x)); return _conv.convf(x); } double RawFile::GetDouble() { double x; Read(&x, sizeof(x)); return _conv.convd(x); } void RawFile::PutU8(uint8_t x) { Write(&x, sizeof(x)); } void RawFile::PutI8(int8_t x) { Write(&x, sizeof(x)); } void RawFile::PutU16(uint16_t x) { uint16_t t = _conv.convu16(x); Write(&t, sizeof(t)); } void RawFile::PutI16(int16_t x) { int16_t t = _conv.convi16(x); Write(&t, sizeof(t)); } void RawFile::PutU24(uint32_t x) { uint32_t t = _conv.convu32(x); Write(&t, 3); } void RawFile::PutI24(int32_t x) { int32_t t = _conv.convi32(x); Write(&t, 3); } void RawFile::PutU32(uint32_t x) { uint32_t t = _conv.convu32(x); Write(&t, sizeof(t)); } void RawFile::PutI32(int32_t x) { int32_t t = _conv.convi32(x); Write(&t, sizeof(t)); } void RawFile::PutU64(uint64_t x) { uint64_t t = _conv.convu64(x); Write(&t, sizeof(t)); } void RawFile::PutI64(int64_t x) { int64_t t = _conv.convi64(x); Write(&t, sizeof(t)); } void RawFile::PutFloat(float x) { float t = _conv.convf(x); Write(&t, sizeof(t)); } void RawFile::PutDouble(double x) { double t = _conv.convd(x); Write(&t, sizeof(t)); }
[ "robojan1@hotmail.com" ]
robojan1@hotmail.com
6d478e5f2c0bf884cd63153dbca54e975746a619
7e9a3bea88da528fc8e201a018612d6e552a238a
/TopicExtraction/ArticleHandler.cpp
ad60f9ecbc15b05e357aef78d98db1c0593086de
[ "BSD-3-Clause" ]
permissive
fusiyuan2010/cs634
0eb4ccb5c3d6fec225b86bd4a8c89de7bf731a44
846c9c36e88ac0a10f98c2b6dffc6dfd87b1f4f4
refs/heads/master
2016-09-03T06:32:11.472042
2014-05-03T22:42:03
2014-05-03T22:42:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,913
cpp
#include "ArticleHandler.h" #include <cstdio> #include <cmath> #include <cstring> #include <utility> void SimpleArticleHandler::AddArticle(const std::vector<std::string> &title, const std::vector<std::string> &article, time_t timestamp) { printf("Article %ld:\nTitle:", timestamp); for(const std::string &s : title) { printf("%s ", s.c_str()); } printf("\nContent:"); int acount = 0; for(const std::string &s : article) { printf("%s ", s.c_str()); if (++acount == 20) break; } printf("\n"); } void TFIDFArticleHandler::AddArticle(const std::vector<std::string> &title, const std::vector<std::string> &article, time_t timestamp) { /* currently title is not used */ /* skip too short useless articles */ double avg_len = 0; for(const auto &t : article) { avg_len += t.size(); } avg_len /= (double)article.size(); if (article.size() < 10 || avg_len <= 4.5) return; articles_.emplace_back(Article(title, article, timestamp)); int i = rand() % articles_.size(); /* reorder */ std::swap(articles_[i], articles_[articles_.size() - 1]); } void TFIDFArticleHandler::GetTFIDF() { for(auto &d : articles_) { int max_term_freq = 0; for(auto &t: d.terms_) { if (++d.term_freq_[t] > max_term_freq) max_term_freq = d.term_freq_[t]; } for(const auto &t: d.term_freq_) { df_[t.first]++; if (tfidf_fomula_ == 1) d.term_weight_[t.first] = t.second; else if (tfidf_fomula_ == 2) d.term_weight_[t.first] = 0.5 + 0.5 * t.second / max_term_freq; else d.term_weight_[t.first] = 1; d.freq_terms_.insert(make_pair(t.second, t.first)); } } for(auto &d : articles_) { for(auto &t : d.term_weight_) { if (tfidf_fomula_ != 3) { if (df_[t.first] < 3) continue; t.second *= log(articles_.size() / df_[t.first]); } d.tfidf_terms_.insert(make_pair(t.second, t.first)); } } } void TFIDFArticleHandler::ShowResult(FILE *f) { for(auto &d : articles_) { int i = 0; fprintf(f, "==========================\nTime stamp: %ld\n", d.timestamp_); fprintf(f, "Title: "); for(const auto &s : d.title_) fprintf(f, "%s ", s.c_str()); fprintf(f, "\n"); for(std::map<double, std::string>::const_reverse_iterator it = d.tfidf_terms_.rbegin(); it != d.tfidf_terms_.rend(); ++it) { if (++i <= 20) fprintf(f, "%s : %lf\n", it->second.c_str(), it->first); } } }
[ "fusiyuan2010@gmail.com" ]
fusiyuan2010@gmail.com
5140067ed69b9740dab3d1d695da532b8010f542
eaa12bb5236314fccc27241efbc642b0eb1ab1dd
/Source/vendor/glm/ext/scalar_ulp.inl
bb767758a854e05d383ed7588332436f5c649b8c
[]
no_license
AdhavanT/OpenGL_Practice
30b70f9a468ad6e136d4beaad4682d14aff424df
a8b1022edc2b711255eefd332c6db1d77ee78e26
refs/heads/master
2022-12-10T12:28:44.164774
2020-08-22T14:07:55
2020-08-22T14:07:55
243,744,550
0
0
null
null
null
null
UTF-8
C++
false
false
7,161
inl
/// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. /// /// Developed at SunPro, a Sun Microsystems, Inc. business. /// Permission to use, copy, modify, and distribute this /// software is freely granted, provided that this notice /// is preserved. #include "../detail/type_float.hpp" #include "../ext/scalar_constants.hpp" #include <cmath> #include <cfloat> #if(GLM_COMPILER & GLM_COMPILER_VC) # pragma warning(push) # pragma warning(disable : 4127) #endif typedef union { float value; /* FIXME: Assumes 32 bit int. */ unsigned int word; } ieee_float_shape_type; typedef union { double value; struct { int lsw; int msw; } parts; } ieee_double_shape_type; #define GLM_EXTRACT_WORDS(ix0,ix1,d) \ do { \ ieee_double_shape_type ew_u; \ ew_u.value = (d); \ (ix0) = ew_u.parts.msw; \ (ix1) = ew_u.parts.lsw; \ } while (0) #define GLM_GET_FLOAT_WORD(i,d) \ do { \ ieee_float_shape_type gf_u; \ gf_u.value = (d); \ (i) = gf_u.word; \ } while (0) #define GLM_SET_FLOAT_WORD(d,i) \ do { \ ieee_float_shape_type sf_u; \ sf_u.word = (i); \ (d) = sf_u.value; \ } while (0) #define GLM_INSERT_WORDS(d,ix0,ix1) \ do { \ ieee_double_shape_type iw_u; \ iw_u.parts.msw = (ix0); \ iw_u.parts.lsw = (ix1); \ (d) = iw_u.value; \ } while (0) namespace glm { namespace detail { GLM_FUNC_QUALIFIER float nextafterf(float x, float y) { volatile float t; int hx, hy, ix, iy; GLM_GET_FLOAT_WORD(hx, x); GLM_GET_FLOAT_WORD(hy, y); ix = hx & 0x7fffffff; // |x| iy = hy & 0x7fffffff; // |y| if ((ix > 0x7f800000) || // x is nan (iy > 0x7f800000)) // y is nan return x + y; if (abs(y - x) <= epsilon<float>()) return y; // x=y, return y if (ix == 0) { // x == 0 GLM_SET_FLOAT_WORD(x, (hy & 0x80000000) | 1);// return +-minsubnormal t = x * x; if (abs(t - x) <= epsilon<float>()) return t; else return x; // raise underflow flag } if (hx >= 0) { // x > 0 if (hx > hy) // x > y, x -= ulp hx -= 1; else // x < y, x += ulp hx += 1; } else { // x < 0 if (hy >= 0 || hx > hy) // x < y, x -= ulp hx -= 1; else // x > y, x += ulp hx += 1; } hy = hx & 0x7f800000; if (hy >= 0x7f800000) return x + x; // overflow if (hy < 0x00800000) // underflow { t = x * x; if (abs(t - x) > epsilon<float>()) { // raise underflow flag GLM_SET_FLOAT_WORD(y, hx); return y; } } GLM_SET_FLOAT_WORD(x, hx); return x; } GLM_FUNC_QUALIFIER double nextafter(double x, double y) { volatile double t; int hx, hy, ix, iy; unsigned int lx, ly; GLM_EXTRACT_WORDS(hx, lx, x); GLM_EXTRACT_WORDS(hy, ly, y); ix = hx & 0x7fffffff; // |x| iy = hy & 0x7fffffff; // |y| if (((ix >= 0x7ff00000) && ((ix - 0x7ff00000) | lx) != 0) || // x is nan ((iy >= 0x7ff00000) && ((iy - 0x7ff00000) | ly) != 0)) // y is nan return x + y; if (abs(y - x) <= epsilon<double>()) return y; // x=y, return y if ((ix | lx) == 0) { // x == 0 GLM_INSERT_WORDS(x, hy & 0x80000000, 1); // return +-minsubnormal t = x * x; if (abs(t - x) <= epsilon<double>()) return t; else return x; // raise underflow flag } if (hx >= 0) { // x > 0 if (hx > hy || ((hx == hy) && (lx > ly))) { // x > y, x -= ulp if (lx == 0) hx -= 1; lx -= 1; } else { // x < y, x += ulp lx += 1; if (lx == 0) hx += 1; } } else { // x < 0 if (hy >= 0 || hx > hy || ((hx == hy) && (lx > ly))) {// x < y, x -= ulp if (lx == 0) hx -= 1; lx -= 1; } else { // x > y, x += ulp lx += 1; if (lx == 0) hx += 1; } } hy = hx & 0x7ff00000; if (hy >= 0x7ff00000) return x + x; // overflow if (hy < 0x00100000) { // underflow t = x * x; if (abs(t - x) > epsilon<double>()) { // raise underflow flag GLM_INSERT_WORDS(y, hx, lx); return y; } } GLM_INSERT_WORDS(x, hx, lx); return x; } }//namespace detail }//namespace glm #if(GLM_COMPILER & GLM_COMPILER_VC) # pragma warning(pop) #endif namespace glm { template<> GLM_FUNC_QUALIFIER float nextFloat(float x) { # if GLM_HAS_CXX11_STL return std::nextafter(x, std::numeric_limits<float>::max()); # elif((GLM_COMPILER & GLM_COMPILER_VC) || ((GLM_COMPILER & GLM_COMPILER_INTEL) && (GLM_PLATFORM & GLM_PLATFORM_WINDOWS))) return detail::nextafterf(x, FLT_MAX); # elif(GLM_PLATFORM & GLM_PLATFORM_ANDROID) return __builtin_nextafterf(x, FLT_MAX); # else return nextafterf(x, FLT_MAX); # endif } template<> GLM_FUNC_QUALIFIER double nextFloat(double x) { # if GLM_HAS_CXX11_STL return std::nextafter(x, std::numeric_limits<double>::max()); # elif((GLM_COMPILER & GLM_COMPILER_VC) || ((GLM_COMPILER & GLM_COMPILER_INTEL) && (GLM_PLATFORM & GLM_PLATFORM_WINDOWS))) return detail::nextafter(x, std::numeric_limits<double>::max()); # elif(GLM_PLATFORM & GLM_PLATFORM_ANDROID) return __builtin_nextafter(x, DBL_MAX); # else return nextafter(x, DBL_MAX); # endif } template<typename T> GLM_FUNC_QUALIFIER T nextFloat(T x, int ULPs) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'next_float' only accept floating-point input"); assert(ULPs >= 0); T temp = x; for (int i = 0; i < ULPs; ++i) temp = nextFloat(temp); return temp; } GLM_FUNC_QUALIFIER float prevFloat(float x) { # if GLM_HAS_CXX11_STL return std::nextafter(x, std::numeric_limits<float>::min()); # elif((GLM_COMPILER & GLM_COMPILER_VC) || ((GLM_COMPILER & GLM_COMPILER_INTEL) && (GLM_PLATFORM & GLM_PLATFORM_WINDOWS))) return detail::nextafterf(x, FLT_MIN); # elif(GLM_PLATFORM & GLM_PLATFORM_ANDROID) return __builtin_nextafterf(x, FLT_MIN); # else return nextafterf(x, FLT_MIN); # endif } GLM_FUNC_QUALIFIER double prevFloat(double x) { # if GLM_HAS_CXX11_STL return std::nextafter(x, std::numeric_limits<double>::min()); # elif((GLM_COMPILER & GLM_COMPILER_VC) || ((GLM_COMPILER & GLM_COMPILER_INTEL) && (GLM_PLATFORM & GLM_PLATFORM_WINDOWS))) return _nextafter(x, DBL_MIN); # elif(GLM_PLATFORM & GLM_PLATFORM_ANDROID) return __builtin_nextafter(x, DBL_MIN); # else return nextafter(x, DBL_MIN); # endif } template<typename T> GLM_FUNC_QUALIFIER T prevFloat(T x, int ULPs) { GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'prev_float' only accept floating-point input"); assert(ULPs >= 0); T temp = x; for (int i = 0; i < ULPs; ++i) temp = prevFloat(temp); return temp; } GLM_FUNC_QUALIFIER int floatDistance(float x, float y) { detail::float_t<float> const a(x); detail::float_t<float> const b(y); return abs(a.i - b.i); } GLM_FUNC_QUALIFIER int64 floatDistance(double x, double y) { detail::float_t<double> const a(x); detail::float_t<double> const b(y); return abs(a.i - b.i); } }//namespace glm
[ "adhavthiru@gmail.com" ]
adhavthiru@gmail.com
9aacec50263e2cfcd8e4f5e94ae15220915c54a9
7f62f204ffde7fed9c1cb69e2bd44de9203f14c8
/NtlLib/Server/NtlSystem/NtlMemoryPool.h
f0be3595b948606f02d0dc7e36238bcec12a8af1
[]
no_license
4l3dx/DBOGLOBAL
9853c49f19882d3de10b5ca849ba53b44ab81a0c
c5828b24e99c649ae6a2953471ae57a653395ca2
refs/heads/master
2022-05-28T08:57:10.293378
2020-05-01T00:41:08
2020-05-01T00:41:08
259,094,679
3
3
null
2020-04-29T17:06:22
2020-04-26T17:43:08
null
UHC
C++
false
false
12,367
h
//*********************************************************************************** // // File : NtlMemoryPool.h // // Begin : 2005-12-13 // // Copyright : ⓒ NTL-Inc Co., Ltd // // Author : Hyun Woo, Koo ( zeroera@ntl-inc.com ) // // Desc : NTL 객체 메모리 풀 ( static 및 dynamic ) // //*********************************************************************************** #pragma once //----------------------------------------------------------------------------------- // class CNtlMemoryPool_Dynamic //----------------------------------------------------------------------------------- #define __DONOT_USE_MEMORYPOOL__ #include <deque> #include "NtlMutex.h" template<class TYPE> class CNtlMemoryPool_Dynamic { public: CNtlMemoryPool_Dynamic(int nReserved = 0); virtual ~CNtlMemoryPool_Dynamic() { Destroy(); } public: // void Destroy(); // TYPE* Alloc(); // void Free(TYPE * t); // 전체 메모리 생성 개수 int GetTotalCount() { return m_nTotalCount; } // 할당 가능한 공간 반환(리스트에 있는 여분의 공간의 개수) int GetAvailableCount() { return store.size(); } // 처음 생성시 예약한 개수 int GetReservedCount() { return m_nReserved; } // 클라이언트에 메모리를 할당해준 개수 int GetAllocatedCount() { return GetTotalCount() - GetAvailableCount(); } private: void Init(); bool Reserve(int nCount); private: typedef std::deque<TYPE*> LIST; typedef typename LIST::iterator LISTIST; LIST m_store; int m_nTotalCount; // 메모리 생성 개수 int m_nReserved; // 예약한 개수 }; //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- template <class TYPE> inline CNtlMemoryPool_Dynamic<TYPE>::CNtlMemoryPool_Dynamic(int nReserved) : m_nReserved( nReserved ), m_nTotalCount( 0 ) { if( nReserved > 0 ) { Reserve( m_nReserved ); } } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- template <class TYPE> inline void CNtlMemoryPool_Dynamic<TYPE>::Destroy() { LISTIST it = m_store.begin(); while( it != m_store.end() ) { free( *it ); it = m_store.erase(it); m_nTotalCount--; } } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- template <class TYPE> inline bool CNtlMemoryPool_Dynamic<TYPE>::Reserve(int nCount) { for( int i = 0; i < nCount; i++ ) { TYPE * pObject = (TYPE*) malloc( sizeof(TYPE) ); if ( NULL == pObject ) { Destroy(); return false; } m_store.push_back( pObject ); m_nTotalCount++; } return true; } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- template <class TYPE> inline TYPE* CNtlMemoryPool_Dynamic<TYPE>::Alloc() { TYPE * pObject = NULL; if( true == m_store.empty() ) { pObject = (TYPE*) malloc( sizeof(TYPE) ); if ( NULL == pObject ) { return NULL; } m_nTotalCount++; } else { pObject = *m_store.begin(); m_store.pop_front(); } return pObject; } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- template <class TYPE> inline void CNtlMemoryPool_Dynamic<TYPE>::Free(TYPE * t) { m_store.push_front(t); } //----------------------------------------------------------------------------------- // DYNAMIC MEMORY POOL MACRO //----------------------------------------------------------------------------------- #define DECLARE_DYNAMIC_MEMORYPOOL(classname) \ public: \ void * operator new( size_t stAllocationBlock ); \ void operator delete( void * pMem ); \ private: \ static CNtlMemoryPool_Dynamic<classname> __m_memoryPool__; #define DEFINE_DYNAMIC_MEMORYPOOL(classname, reserve) \ CNtlMemoryPool_Dynamic<classname> classname::__m_memoryPool__(reserve); \ void * classname::operator new( size_t stAllocationBlock ) \ { \ (void) stAllocationBlock; \ classname * pMem = __m_memoryPool__.Alloc(); \ return pMem; \ } \ \ void classname::operator delete( void * pMem ) \ { \ __m_memoryPool__.Free((classname*)pMem); \ } #ifdef __DONOT_USE_MEMORYPOOL__ #undef DECLARE_DYNAMIC_MEMORYPOOL #define DECLARE_DYNAMIC_MEMORYPOOL(classname) #undef DEFINE_DYNAMIC_MEMORYPOOL #define DEFINE_DYNAMIC_MEMORYPOOL(classname, reserve) #endif //----------------------------------------------------------------------------------- // DYNAMIC MEMORY POOL MACRO ( THREAD SAFE ) //----------------------------------------------------------------------------------- #define DECLARE_DYNAMIC_MEMORYPOOL_THREADSAFE(classname) \ public: \ void * operator new( size_t stAllocationBlock ); \ void operator delete( void * pMem ); \ private: \ static CNtlMutex __m_poolMutex__; \ static CNtlMemoryPool_Dynamic<classname> __m_memoryPool__; #define DEFINE_DYNAMIC_MEMORYPOOL_THREADSAFE(classname, reserve) \ CNtlMutex classname::__m_poolMutex__; \ CNtlMemoryPool_Dynamic<classname> classname::__m_memoryPool__(reserve); \ void * classname::operator new( size_t stAllocationBlock ) \ { \ (void) stAllocationBlock; \ __m_poolMutex__.Lock(); \ classname * pMem = __m_memoryPool__.Alloc(); \ __m_poolMutex__.Unlock(); \ return pMem; \ } \ \ void classname::operator delete( void * pMem ) \ { \ __m_poolMutex__.Lock(); \ __m_memoryPool__.Free((classname*)pMem); \ __m_poolMutex__.Unlock(); \ } #ifdef __DONOT_USE_MEMORYPOOL__ #undef DECLARE_DYNAMIC_MEMORYPOOL_THREADSAFE #define DECLARE_DYNAMIC_MEMORYPOOL_THREADSAFE(classname) #undef DEFINE_DYNAMIC_MEMORYPOOL_THREADSAFE #define DEFINE_DYNAMIC_MEMORYPOOL_THREADSAFE(classname, reserve) #endif ///////////////////////////////////////////////////////////////////////////////////// // // class CNtlMemoryPool_Static // ///////////////////////////////////////////////////////////////////////////////////// template <class TYPE> class CNtlMemoryPool_Static { public: CNtlMemoryPool_Static(int nSize = 0); virtual ~CNtlMemoryPool_Static() { Destroy(); } public: bool Create(int nSize); bool Destroy(); TYPE * Alloc(); void Free(TYPE * t); protected: int m_nPoolSize; int m_nAllocPos; TYPE * m_pTypeStore; TYPE ** m_ppTypePtrStore; }; //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- template <class TYPE> inline CNtlMemoryPool_Static<TYPE>::CNtlMemoryPool_Static(int nSize) : m_nPoolSize( nSize ), m_nAllocPos( 0 ), m_pTypeStore( 0 ), m_ppTypePtrStore( 0 ) { if( nSize ) { Create( nSize ); } } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- template <class TYPE> inline bool CNtlMemoryPool_Static<TYPE>::Create(int nSize) { if( nSize <= 0 ) { return false; } m_nPoolSize = nSize; m_pTypeStore = (TYPE*) malloc( sizeof(TYPE) * m_nPoolSize ); if( NULL == m_pTypeStore ) { return false; } m_ppTypePtrStore = (TYPE**) malloc( sizeof(TYPE*) * m_nPoolSize ); if( NULL == m_ppTypePtrStore ) { return false; } for(int i = 0; i < nSize; i++) { m_ppTypePtrStore[i] = &m_pTypeStore[i]; } m_nAllocPos = 0; return true; } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- template <class TYPE> inline bool CNtlMemoryPool_Static<TYPE>::Destroy() { if( !m_nPoolSize ) return false; if( m_pTypeStore ) { free( m_pTypeStore ); m_pTypeStore = NULL; } if( m_ppTypePtrStore) { free( m_ppTypePtrStore ); m_ppTypePtrStore = NULL; } m_nPoolSize = 0; m_nAllocPos = 0; return true; } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- template <class TYPE> inline TYPE * CNtlMemoryPool_Static<TYPE>::Alloc() { if( m_nAllocPos >= m_nPoolSize ) { return (TYPE*) 0; printf("alloc fail \n"); } printf("alloc success \n"); return m_ppTypePtrStore[ m_nAllocPos++ ]; } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- template <class TYPE> inline void CNtlMemoryPool_Static<TYPE>::Free(TYPE * t) { if( m_nAllocPos <= 0 ) return; m_ppTypePtrStore[--m_nAllocPos] = t; } //----------------------------------------------------------------------------------- // STATIC MEMORY POOL DECLARE MACRO //----------------------------------------------------------------------------------- #define DECLARE_STATIC_MEMORYPOOL(classname) \ public: \ void * operator new( size_t stAllocationBlock ); \ void operator delete( void * pMem ); \ private: \ static CNtlMemoryPool_Static<classname> __m_memoryPool__; #define DEFINE_STATIC_MEMORYPOOL(classname, reserve) \ CNtlMemoryPool_Static<classname> classname::__m_memoryPool__(reserve); \ void * classname::operator new( size_t stAllocationBlock ) \ { \ (void) stAllocationBlock; \ classname * pMem = __m_memoryPool__.Alloc(); \ return pMem; \ } \ \ void classname::operator delete( void * pMem ) \ { \ __m_memoryPool__.Free((classname*)pMem); \ } #ifdef __DONOT_USE_MEMORYPOOL__ #undef DECLARE_STATIC_MEMORYPOOL #define DECLARE_STATIC_MEMORYPOOL(classname) #undef DEFINE_STATIC_MEMORYPOOL #define DEFINE_STATIC_MEMORYPOOL(classname, reserve) #endif //----------------------------------------------------------------------------------- // STATIC MEMORY POOL DECLARE MACRO ( THREAD SAFE ) //----------------------------------------------------------------------------------- #define DECLARE_STATIC_MEMORYPOOL_THREADSAFE(classname) \ public: \ void * operator new( size_t stAllocationBlock ); \ void operator delete( void * pMem ); \ private: \ static CNtlMutex __m_poolMutex__; \ static CNtlMemoryPool_Static<classname> __m_memoryPool__; \ #define DEFINE_STATIC_MEMORYPOOL_THREADSAFE(classname, reserve) \ CNtlMutex classname::__m_poolMutex__; \ CNtlMemoryPool_Static<classname> classname::__m_memoryPool__(reserve); \ void * classname::operator new( size_t stAllocationBlock ) \ { \ (void) stAllocationBlock; \ __m_poolMutex__.Lock(); \ classname * pMem = __m_memoryPool__.Alloc(); \ __m_poolMutex__.Unlock(); \ return pMem; \ } \ \ void classname::operator delete( void * pMem ) \ { \ __m_poolMutex__.Lock(); \ __m_memoryPool__.Free((classname*)pMem); \ __m_poolMutex__.Unlock(); \ } #ifdef __DONOT_USE_MEMORYPOOL__ #undef DECLARE_STATIC_MEMORYPOOL_THREADSAFE #define DECLARE_STATIC_MEMORYPOOL_THREADSAFE(classname) #undef DEFINE_STATIC_MEMORYPOOL_THREADSAFE #define DEFINE_STATIC_MEMORYPOOL_THREADSAFE(classname, reserve) #endif
[ "64261665+dboguser@users.noreply.github.com" ]
64261665+dboguser@users.noreply.github.com
00b10a5d6370b17fbf729657f00aef08cfe26827
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/xgboost/xgboost-gumtree/dmlc_xgboost_old_new_new_log_622.cpp
71f6a1cbdf6243ac1564b6687e30815d786bfbf6
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
87
cpp
utils::Assert(index >= start_ && index < end_,"The query index out of sampling bound");
[ "993273596@qq.com" ]
993273596@qq.com
39c1c8c324c3e64b5febdbf599d114641baf14a6
f175bcab3c2f0aad7378c94ac220256982ab2027
/Temp/il2cppOutput/il2cppOutput/Facebook_Unity_Facebook_Unity_Editor_EditorFacebookG63110230.h
a2e9b4a711b77da2e6c19eed2d320ff70ffafdd8
[]
no_license
al2css/erpkunity
6618387e9a5b44378e70ccb859d3b33a7837268c
c618dc989963bcd7b7ec9fa9b17c39fff88bb89b
refs/heads/master
2020-07-22T04:59:49.139202
2017-06-23T16:33:13
2017-06-23T16:33:13
94,344,128
0
0
null
null
null
null
UTF-8
C++
false
false
585
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "Facebook_Unity_Facebook_Unity_FacebookGameObject2922570967.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Facebook.Unity.Editor.EditorFacebookGameObject struct EditorFacebookGameObject_t63110230 : public FacebookGameObject_t2922570967 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "alecsdulgheru@gmail.com" ]
alecsdulgheru@gmail.com
3ab55f74b81e9cf44071d5ee247ee642102bca70
d9034557db7da3a94a68b982c708df056d37dcc3
/Libs/Bill/BillRepository.cpp
511bde7e111ceb469aff108441cb8efecc385ef4
[]
no_license
KhoiHoang2410/CoffeeManagement
143febc11500a0b5ede80602fc7f6ff8e1396df0
052eb37dc7241a250e7010063e1be795e1d85936
refs/heads/main
2023-05-01T09:03:54.375712
2021-05-23T08:44:18
2021-05-23T08:44:18
365,730,599
0
0
null
null
null
null
UTF-8
C++
false
false
2,678
cpp
// // BillRepository.cpp // CoffeeManagement // // Created by Khoi Hoang on 21/05/2021. // #include "../../Include/Bill/BillRepository.hpp" #include "../../Include/Helper.hpp" #include <tuple> #include <fstream> #include <iostream> using namespace std; void BillRepository::CreateBill(string employeeName) { billRepository.push_back(Bill(employeeName)); } void BillRepository::AddBill(string employeeName, vector<string> productName, vector<double> price, vector<int> amount) { billRepository.push_back(Bill(employeeName, productName, price, amount)); } void BillRepository::AddItemToBill(string productName, int price) { billRepository.back().AddProduct(productName, price); } void BillRepository::RemoveAnItemFromBill(int id) { billRepository.back().RemoveProduct(id); } void BillRepository::ExportPriceLastBill() const { billRepository.back().Total(); } void BillRepository::ExportLastBill() const { billRepository.back().ExportData(); } bool BillRepository::ExportAllData() const { for (int i=0; i<billRepository.size(); ++i) { billRepository[i].ExportData(); cout << endl; } return 1; } int BillRepository::Size() { return billRepository.size(); } tuple<vector<string>, vector<vector<string> >, vector<vector<int> >, vector<vector<double> > > BillRepository::ImportDataFromFile(string fileName) { ifstream cin(fileName); if (!cin.is_open()) { PutError("BillRepository::ImportDataFromFile", "File not Found", 1); } vector<vector<string> > productNames; vector<vector<int> > amounts; vector<vector<double> > prices; vector<string> employeeNames; int n, m, amount; double price; string employee, productName; cin >> n; OutPut("BillRepository::ImportDataFromFile", fileName + " " + to_string(n)); for(int i=0; i < n; i++) { getline(cin, employee); getline(cin, employee); cin >> m; employeeNames.push_back(employee); productNames.push_back(vector<string>()); amounts.push_back(vector<int>()); prices.push_back(vector<double>()); for (int j=0; j < m; ++j) { getline(cin, productName); getline(cin, productName); cin >> amount >> price; productNames.back().push_back(productName); prices.back().push_back(price); amounts.back().push_back(amount); } } cin.close(); OutPut("BillRepository::ImportDataFromFile", "Import success"); return make_tuple(employeeNames, productNames, amounts, prices); } void BillRepository::AddBill(Bill bill) { billRepository.push_back(bill); }
[ "khoi.hoang@kaligo.com" ]
khoi.hoang@kaligo.com
ab411f812b135a409ee67ffa038461895dad3d77
65a6f59dd89d02eb66a0a758ae5da44b9007a4e9
/mde/DiesteinMDE/SendEMail.cpp
a8b4c8f64525295c8b44433a34f12c776fc6c4a1
[ "Unlicense" ]
permissive
hjgode/mde6
9b15c80e6f03269357a164a5d613373ccfac1ae6
d40e93f101b7bcb14dd16e2c83535348cf62d61f
refs/heads/master
2020-05-25T12:57:45.366421
2019-05-21T10:19:31
2019-05-21T10:19:31
187,810,000
0
0
null
null
null
null
ISO-8859-1
C++
false
false
11,775
cpp
// SendEMail.cpp : Definiert die Initialisierungsroutinen für die DLL. // #include "stdafx.h" #include "cstools4.h" #include "SendEMail.h" #include "afxwin.h" #ifdef _DEBUG #define new DEBUG_NEW #endif //********************************************************************************* //********************************************************************************* //********************************************************************************* //********************************************************************************* //********************************************************************************* // Einsprungpunkt //--------------------------------------------------------------------------------------------- BOOL EMAIL_Send( const TCHAR *strFrom, const TCHAR *strTo, const TCHAR *strBcc, // kann NULL oder "" sein const TCHAR *strCc, // kann NULL oder "" sein const TCHAR *strSubject, // kann NULL oder "" sein const TCHAR *strMessage, // kann NULL oder "" sein const TCHAR *strAttachment,// kann NULL oder "" sein const TCHAR *strHostName, UINT nHostPort, // kann 0 sein const TCHAR *strUserName, // kann NULL oder "" sein const TCHAR *strPassword, // kann NULL oder "" sein BOOL bAuthenticate, TCHAR *strError) // Receive String { if (!MimeInitialize(_T("DKHLQKCTJOHBMVNF"), NULL) || !SmtpInitialize(_T("DKHLQKCTJOHBMVNF"), NULL)) //CSTOOLS4_LICENSE_KEY { _tcscpy(strError,_T("Falscher Lizenzkey")); return FALSE; } CSendEMail myEmail(strFrom,strTo,strBcc,strCc,strSubject,strMessage,strAttachment, strHostName,nHostPort,strUserName,strPassword,bAuthenticate); myEmail.Send(); _tcscpy(strError,myEmail.m_strError); MimeUninitialize(); SmtpUninitialize(); if(myEmail.m_strError.IsEmpty()) return TRUE; return FALSE; } //--------------------------------------------------------------------------------------------- CSendEMail::CSendEMail( const TCHAR *strFrom, const TCHAR *strTo, const TCHAR *strBcc, const TCHAR *strCc, const TCHAR *strSubject, const TCHAR *strMessage, const TCHAR *strAttachment, const TCHAR *strHostName, UINT nHostPort, const TCHAR *strUserName, const TCHAR *strPassword, BOOL bAuthenticate) { m_strFrom = strFrom; m_strTo = strTo; if(strBcc) m_strBcc = strBcc; // kann NULL sein if(strCc) m_strCc = strCc; if(strSubject) m_strSubject = strSubject; if(strMessage) m_strMessage = strMessage; if(strAttachment) m_strAttachment = strAttachment; m_strHostName = strHostName; m_nHostPort = nHostPort; if(!nHostPort) m_nHostPort = SMTP_PORT_DEFAULT; if(strUserName) m_strUserName = strUserName; if(strPassword) m_strPassword = strPassword; m_bAuthenticate = bAuthenticate; m_hClient = INVALID_CLIENT; m_hMessage = INVALID_MESSAGE; m_bCanceled = FALSE; } //----------------------------------------------------------------------------------- CSendEMail::~CSendEMail() { if(m_hClient != INVALID_CLIENT) { SmtpDisconnect(m_hClient); m_hClient = INVALID_CLIENT; } if(m_hMessage != INVALID_MESSAGE) { MimeDeleteMessage(m_hMessage); m_hMessage = INVALID_MESSAGE; } } //------------------------------------------------------------------------------- void CSendEMail::ShowError(DWORD dwError) { TCHAR szError[128]; *(szError) = 0; if(dwError == 0) dwError = GetLastError(); // Because the error codes all shared between all of the // SocketTools libraries, the descriptions are the same, // regardless of what function actually generated the error if((MimeGetErrorString(dwError,szError,126)) == 0) m_strError.Format(_T("Unknown SocketTools error 0x%08lX"),dwError); else m_strError = szError; m_strError = _T("Errortest"); //AfxMessageBox(m_strError,MB_OK|MB_ICONEXCLAMATION); } // This event handler function is called as the message is being // submitted to the mail server //void CALLBACK CSendMailDlg::EventHandler(HCLIENT hClient, UINT nEventId, DWORD dwError, DWORD dwParam) //{ // CSendMailDlg *pThis = (CSendMailDlg *)dwParam; // // if (pThis == NULL) // return; // // SMTPTRANSFERSTATUS smtpStatus; // INT nResult = SmtpGetTransferStatus(hClient, &smtpStatus); // // if (nResult != SMTP_ERROR && smtpStatus.dwBytesTotal > 0) // { // INT nPercent = (INT)((DOUBLE)(100.0 * (DOUBLE)smtpStatus.dwBytesCopied / (DOUBLE)smtpStatus.dwBytesTotal)); // if (nPercent > 100) // nPercent = 100; // // pThis->m_ctlProgress.SetPos(nPercent); // pThis->m_ctlProgress.RedrawWindow(); // } // // TCHAR szStatus[256]; // // wsprintf(szStatus, _T("Submitting message to server %lu/%lu"), // smtpStatus.dwBytesCopied, smtpStatus.dwBytesTotal); // // pThis->m_ctlStatus.SetWindowText(szStatus); // pThis->m_ctlStatus.RedrawWindow(); //} void CSendEMail::Send() { BOOL bResult; int nResult; // Compose the message based on the input provided by the user m_hMessage = MimeComposeMessage( m_strFrom, m_strTo, m_strCc, m_strSubject, m_strMessage, NULL, MIME_CHARSET_ISOLATIN1, MIME_ENCODING_8BIT ); if(m_hMessage == INVALID_MESSAGE) { ShowError(); return; } // If a file attachment was specified, then attach it to the // message that was created CStringArray strArr; int start = 0; CString str = m_strAttachment.Tokenize(_T(";,"),start); while(!str.IsEmpty()) { str.Trim(); strArr.Add(str); str = m_strAttachment.Tokenize(_T(";,"),start); } for(int i = 0; i < strArr.GetCount(); i++) { if(strArr.GetAt(i).GetLength() > 0) { bResult = MimeAttachFile(m_hMessage,strArr.GetAt(i),MIME_ATTACH_BASE64); if(!bResult) { ShowError(); return; } } } // Get the contents of the complete message, including the headers, // main message body and optional file attachment data; it will be // returned a global memory handle HGLOBAL hgblMessage = NULL; DWORD dwMessageSize = 0; bResult = MimeExportMessageEx( m_hMessage, MIME_EXPORT_HGLOBAL, MIME_OPTION_DEFAULT, &hgblMessage, &dwMessageSize); if(!bResult) { ShowError(); return; } // Parse the sender email address to make sure that we only have // the actual address, not their name, etc. TCHAR szSender[256]; MimeParseAddress(m_strFrom, NULL, szSender, 256); // Create a list of all of the recipient addresses; we will use // this when submitting the message to the SMTP server LPTSTR lpszRecipients = NULL; DWORD cchRecipients = 0; INT nRecipients = 0; // Determine the number of characters that should be allocated to store // all of the addresses in the current message nRecipients = MimeEnumMessageRecipients( m_hMessage, m_strBcc, NULL, &cchRecipients); // Allocate the memory for the string buffer that will contain all // of the recipient addresses and call MimeEnumMessageRecipients // again to store those addresses in the buffer if((nRecipients > 0) && (cchRecipients > 0)) { lpszRecipients = (LPTSTR)LocalAlloc(LPTR,cchRecipients*sizeof(TCHAR)); if(lpszRecipients == NULL) return; // Virtual memory exhausted nRecipients = MimeEnumMessageRecipients( m_hMessage, m_strBcc, lpszRecipients, &cchRecipients); } if(nRecipients == 0) { AfxMessageBox(_T("kein Empfänger"), MB_ICONEXCLAMATION); return; } else { TCHAR *lpszAddress = lpszRecipients; int cchAddress; while(lpszAddress != NULL) { if((cchAddress = (int)_tcslen(lpszAddress)) == 0) break; // Change the null characters which separate each address // into commas, creating a comma-separated list of addresses if (*(lpszAddress + cchAddress + 1) != '\0') *(lpszAddress + cchAddress) = ','; lpszAddress += cchAddress + 1; } } // Connect to the SMTP server that was specified by the user m_hClient = SmtpConnect( m_strHostName, m_nHostPort, 10,//SMTP_TIMEOUT, SMTP_OPTION_EXTENDED, NULL, NULL); if(m_hClient == INVALID_CLIENT) { ShowError(); return; } // If the user has checked the 'requires authentication' checkbox, // then authenticate the client session with the server if(m_bAuthenticate) { BOOL bExtended; DWORD dwOptions; INT nResult; // Determine if this server really does support extended // options, and if it does, what they are bExtended = SmtpGetExtendedOptions(m_hClient, &dwOptions); if(bExtended && (dwOptions & SMTP_EXTOPT_AUTHLOGIN)) { nResult = SmtpAuthenticate( m_hClient, SMTP_AUTH_DEFAULT, m_strUserName, m_strPassword); if(nResult == SMTP_ERROR) { // Display a friendly error message here if the user could // not be authenticated; some SMTP servers can return rather // cryptic messages m_strError = _T("Falscher Authorisierungskode"); return; } } else { // This server doesn't support authentication; the user needs // to clear the checkbox and try again m_strError = _T("Kein Authorisierungskode"); return; } } // Register a handler for the SMTP_EVENT_PROGRESS event so that // we can update the progress bar control; note that since the // event handler is static, we pass the 'this' pointer as the // optional parameter and then use that in the handler //nResult = SmtpRegisterEvent( // m_hClient, // SMTP_EVENT_PROGRESS, // EventHandler, // (DWORD)this); // //if(nResult == SMTP_ERROR) // { // ShowError(); // return; // } nResult = SmtpSendMessage( m_hClient, szSender, lpszRecipients, hgblMessage, dwMessageSize, SMTP_MESSAGE_HGLOBAL); // Free memory allocated for the message GlobalFree(hgblMessage); if(nResult == SMTP_ERROR) { DWORD dwError = SmtpGetLastError(); if(dwError != ST_ERROR_NO_VALID_RECIPIENTS) ShowError(); else { // If the error is ST_ERROR_NO_VALID_RECIPIENTS the server is // probably rejecting the message because its being asked to // relay a message to a user outside of its domain, and the client // session has not been authenticated. // Display a helpful error message, disconnect from the server // and allow the user to try again, rather than closing the // dialog m_strError = _T("Ungültiger Empfänger"); SmtpDisconnect(m_hClient); m_hClient = INVALID_CLIENT; MimeDeleteMessage(m_hMessage); m_hMessage = INVALID_MESSAGE; return; } } else { // AfxMessageBox(_T("Email-Versand erfolgreich"),MB_ICONINFORMATION); } }
[ "hjgode@gmail.com" ]
hjgode@gmail.com
e20446854aa385c3e2e3254f93be9431c11dd62e
05de431b4040d8ff839895f2233512ee66d2a1c4
/Calculator/main.cpp
f7664a25905584214b5b8101d211ddaf9faac9fd
[]
no_license
chavychaze/Calculator
08b7e632861ea45c37137a1c420d5f9cd01fca53
0622334cd686880d5520a58f80382d9d15f1c810
refs/heads/master
2021-06-17T19:13:17.724840
2017-06-20T13:58:12
2017-06-20T13:58:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,880
cpp
// The desk calulator // reads from standard input or command line // uses namespaces and no exceptions #include <map> #include<iostream> #include<cctype> #include<string> using namespace std; namespace Error { struct Zero_divide { }; struct Syntax_error { const char* p; Syntax_error(const char* q) { p = q; } }; } namespace Lexer { enum Token_value { NAME, NUMBER, END, PLUS = '+', MINUS = '-', MUL = '*', DIV = '/', PRINT = ';', ASSIGN = '=', LP = '(', RP = ')' }; Token_value curr_tok; double number_value; string string_value; Token_value get_token(); } namespace Parser { double prim(bool get); // handle primaries double term(bool get); // multiply and divide double expr(bool get); // and subtract using namespace Lexer; using namespace Error; } namespace Symbol_table { map<string, double> table; } namespace Driver { int no_of_errors; std::istream* input; void skip(); } Lexer::Token_value Lexer::get_token() { char ch; do { // skip whitespace except '\n' if (!Driver::input->get(ch)) return curr_tok = END; } while (ch != '\n' && isspace(ch)); switch (ch) { case 0: return END; case ';': case '\n': return curr_tok = PRINT; case '*': case '/': case '+': case '-': case '(': case ')': case '=': return curr_tok = Token_value(ch); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': Driver::input->putback(ch); *Driver::input >> number_value; return curr_tok = NUMBER; default: // NAME, NAME =, or error if (isalpha(ch)) { string_value = ch; while (Driver::input->get(ch) && isalnum(ch)) string_value += ch; // string_value.push_back(ch); // to work around library bug Driver::input->putback(ch); return curr_tok = NAME; } throw Error::Syntax_error("bad token"); } } double Parser::prim(bool get) // handle primaries { if (get) get_token(); switch (curr_tok) { case Lexer::NUMBER: // floating point constant get_token(); return number_value; case Lexer::NAME: { double& v = Symbol_table::table[string_value]; if (get_token() == ASSIGN) v = expr(1); return v; } case Lexer::MINUS: // unary minus return -prim(1); case Lexer::LP: { double e = expr(1); if (curr_tok != RP) throw Error::Syntax_error("`)' expected"); get_token(); // eat ')' return e; } case Lexer::END: return 1; default: throw Error::Syntax_error("primary expected"); } } double Parser::term(bool get) // multiply and divide { double left = prim(get); for (;;) // ``forever'' switch (curr_tok) { case Lexer::MUL: left *= prim(true); break; case Lexer::DIV: if (double d = prim(true)) { left /= d; break; } throw Error::Zero_divide(); default: return left; } } double Parser::expr(bool get) // add and subtract { double left = term(get); for (;;) // ``forever'' switch (curr_tok) { case Lexer::PLUS: left += term(true); break; case Lexer::MINUS: left -= term(true); break; default: return left; } } void Driver::skip() { no_of_errors++; while (*input) { // discard characters until newline or semicolon char ch; input->get(ch); switch (ch) { case '\n': case ';': return; } } } int fib(int n) //fibonacci formula { // Declare an array to store Fibonacci numbers. int f[1000]; //can't inpute [n+1] int i; // 0th and 1st number of the series are 0 and 1 f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { // Add the previous 2 numbers in the series and store it f[i] = f[i - 1] + f[i - 2]; } return f[n]; } #include <vector> #include <algorithm> int median(int iArray[]) { vector<int> mArray(iArray, iArray + 14); //set this number to match the number of items in your int array vector<int>::iterator it; sort(mArray.begin(), mArray.end()); // Find the median. float median, middle, middleh; float middlel; vector<int>::iterator z; switch (mArray.size() % 2) { case(0): // even z = mArray.begin(); middlel = mArray.size() / 2; z += middlel; middleh = (*z + *(--z)) / 2; cout << "Median is: " << middleh << endl; break; case(1): // odd z = mArray.begin(); middle = mArray.size() / 2; cout << "Median is : " << *(z += middle) << endl; break; } // display the sorted array. for (it = mArray.begin(); it != mArray.end(); it++) { cout << *it << " "; } return *it; } #include <fstream> void load_data() { string load; getline(cin, load); if (load == "load") { //to load saved file ifstream loadFile; loadFile.open("Save.txt", ifstream::in); cout << "The file contained: "; while (loadFile.good()) { cout << (char)loadFile.get(); } cout << " " << endl; loadFile.close(); } } #include <strstream> int main(int argc, char* argv[]) { using namespace Driver; switch (argc) { case 1: // read from standard input input = &cin; break; case 2: // read argument string input = new istrstream(argv[1], strlen(argv[1])); break; default: cerr << "too many arguments\n"; return 1; } // insert pre-defined names: Symbol_table::table["pi"] = 3.1415926535897932385; Symbol_table::table["e"] = 2.7182818284590452354; while (*input) { cout << "new expression:\n"; try { Lexer::get_token(); if (Lexer::curr_tok == Lexer::END) break; if (Lexer::curr_tok == Lexer::PRINT) continue; cout << Parser::expr(false) << '\n'; string textToSave; //block to save all inpute getline(cin, textToSave); ofstream saveFile("Save.txt"); saveFile << textToSave; saveFile.close(); } catch (Error::Zero_divide) { cerr << "attempt to divide by zero\n"; skip(); } catch (Error::Syntax_error e) { cerr << "syntax error:" << e.p << "\n"; skip(); } } string ld = "load"; if (cin >> ld) load_data(); if (input != &std::cin) delete input; return no_of_errors; }
[ "inAsobolrip1@gmail.com" ]
inAsobolrip1@gmail.com
edaebe49a7dbe4d9738bb163bad025db97481e4f
33eaafc0b1b10e1ae97a67981fe740234bc5d592
/tests/RandomSAT/z3-master/src/muz/pdr/pdr_reachable_cache.cpp
85100c19f4508cfba05598f8d290848573202d1c
[ "MIT" ]
permissive
akinanop/mvl-solver
6c21bec03422bb2366f146cb02e6bf916eea6dd0
bfcc5b243e43bddcc34aba9c34e67d820fc708c8
refs/heads/master
2021-01-16T23:30:46.413902
2021-01-10T16:53:23
2021-01-10T16:53:23
48,694,935
6
2
null
2016-08-30T10:47:25
2015-12-28T13:55:32
C++
UTF-8
C++
false
false
3,230
cpp
/*++ Copyright (c) 2011 Microsoft Corporation Module Name: reachable_cache.cpp Abstract: Object for caching of reachable states. Author: Krystof Hoder (t-khoder) 2011-9-14. Revision History: --*/ #include "pdr_reachable_cache.h" namespace pdr { reachable_cache::reachable_cache(pdr::manager & pm, datalog::PDR_CACHE_MODE cm) : m(pm.get_manager()), m_pm(pm), m_ctx(0), m_ref_holder(m), m_disj_connector(m), m_cache_mode(cm) { if (m_cache_mode == datalog::CONSTRAINT_CACHE) { m_ctx = pm.mk_fresh(); m_ctx->assert_expr(m_pm.get_background()); } } void reachable_cache::add_disjuncted_formula(expr * f) { app_ref new_connector(m.mk_fresh_const("disj_conn", m.mk_bool_sort()), m); app_ref neg_new_connector(m.mk_not(new_connector), m); app_ref extended_form(m); if(m_disj_connector) { extended_form = m.mk_or(m_disj_connector, neg_new_connector, f); } else { extended_form = m.mk_or(neg_new_connector, f); } if (m_ctx) { m_ctx->assert_expr(extended_form); } m_disj_connector = new_connector; } void reachable_cache::add_reachable(expr * cube) { switch (m_cache_mode) { case datalog::NO_CACHE: break; case datalog::HASH_CACHE: m_stats.m_inserts++; m_cache.insert(cube); m_ref_holder.push_back(cube); break; case datalog::CONSTRAINT_CACHE: m_stats.m_inserts++; TRACE("pdr", tout << mk_pp(cube, m) << "\n";); add_disjuncted_formula(cube); break; default: UNREACHABLE(); } } bool reachable_cache::is_reachable(expr * cube) { bool found = false; switch (m_cache_mode) { case datalog::NO_CACHE: return false; case datalog::HASH_CACHE: found = m_cache.contains(cube); break; case datalog::CONSTRAINT_CACHE: { if(!m_disj_connector) { found = false; break; } expr * connector = m_disj_connector.get(); expr_ref_vector assms(m); assms.push_back(connector); m_ctx->push(); m_ctx->assert_expr(cube); lbool res = m_ctx->check(assms); m_ctx->pop(); TRACE("pdr", tout << "is_reachable: " << res << " " << mk_pp(cube, m) << "\n";); found = res == l_true; break; } default: UNREACHABLE(); break; } if (found) m_stats.m_hits++; m_stats.m_miss++; return found; } void reachable_cache::collect_statistics(statistics& st) const { st.update("cache inserts", m_stats.m_inserts); st.update("cache miss", m_stats.m_miss); st.update("cache hits", m_stats.m_hits); } void reachable_cache::reset_statistics() { m_stats.reset(); } }
[ "nikaponens@gmail.com" ]
nikaponens@gmail.com
df4f6474cc7722b5672ae2135e097e3131c5a3c8
a1e63481e515b2c41bc8cbda4daa9671d44b5ca0
/1557.frankr.cpp
b5e405cd2afd43faf5efe7328105b12d705e0c55
[]
no_license
frarteaga/cojSolutions
b05134ed793b7f36f2dbcc74f61d55b3e5c6a825
b93b53e092e417670584ec240cfa5010d33b55cf
refs/heads/master
2020-04-15T15:01:24.156176
2019-12-30T14:32:48
2019-12-30T14:32:48
55,257,183
3
2
null
null
null
null
UTF-8
C++
false
false
2,349
cpp
//1557 - Assignments //dp + bitmask memo //frankr@coj #include <iostream> #include <cstring> using namespace std; typedef long long LL; const int MAXN = 20; int c, n; int P[MAXN][MAXN]; int T[MAXN + 1][MAXN + 1]; LL fact[MAXN + 1]; bool calc[1 << MAXN]; LL dp[1 << MAXN]; LL f(int S){ if (!calc[S]){ LL r = 0; int Ce = __builtin_popcount(S); //if (Ce == 1) // r = P[__builtin_ctz(S)][0]; //else for (int i = 0 ; i < n ; i++) if (((1 << i) & S) && (P[i][Ce - 1])) r += f(S ^ (1 << i)); calc[S] = true; dp[S] = r; } return dp[S]; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); fact[0] = 1; for (int i = 1 ; i <= MAXN ; i++) fact[i] = fact[i - 1] * i; cin >> c; //cout << __builtin_ctz(c); while (c--){ cin >> n; for (int i = 0 ; i < n ; i++) for (int j = 0 ; j < n ; j++){ cin >> P[i][j]; T[i + 1][j + 1] = P[i][j] + T[i][j + 1] + T[i + 1][j] - T[i][j]; if (i == j && T[i + 1][i + 1] == (i + 1) * (i + 1)){ calc[(1 << i) - 1] = true; dp[(1 << i) - 1] = fact[i + 1]; } } for (int i = 0 ; i < (1 << n) ; i++) calc[i] = false; for (int i = 0 ; i < n ; i++){ calc[1 << i] = true; dp[1 << i] = P[i][0]; } cout << f((1 << n) - 1) << '\n'; } return 0; } /* 20 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 */
[ "farteaga@ipvce.lt.rimed.cu" ]
farteaga@ipvce.lt.rimed.cu
39e5fcff79ebb8905e55e066802e975f95e506c7
46d93bce5be0405c33bfd9efc8ec46341a345282
/rvalue_references/MyInt.hpp
30f23331bc2989cde3dd3e95e3add2b06b07d7b2
[]
no_license
yashpatel007/Function-wrapper
47de9051cf6ec7a5df911549b088d1831cfdfd37
a721617ac18decbfc34d8ffa807bf28d0b9d8dd9
refs/heads/master
2021-04-21T03:10:04.542239
2019-12-11T18:48:42
2019-12-11T18:48:42
249,744,347
1
0
null
null
null
null
UTF-8
C++
false
false
417
hpp
#ifndef MY_INT_HPP #define MY_INT_HPP #include <iostream> class MyInt { friend std::ostream &operator<<(std::ostream &os, const MyInt &mi) { return os << mi.i; } public: MyInt() { count++; } MyInt(const MyInt &mi) : i(mi.i) { count++; } MyInt(int i) : i(i) { count++; } private: int i; public: static std::size_t count; }; #endif
[ "hqin4@binghamton.edu" ]
hqin4@binghamton.edu
678f238f01c31e5d8ada3c37cd6b05492c651cdf
768371d8c4db95ad629da1bf2023b89f05f53953
/applayerpluginsandutils/httpprotocolplugins/httpclient/chttpconnectfilter.cpp
e3673e15fd3a874e067a966bbfc2fe0dcb89b486
[]
no_license
SymbianSource/oss.FCL.sf.mw.netprotocols
5eae982437f5b25dcf3d7a21aae917f5c7c0a5bd
cc43765893d358f20903b5635a2a125134a2ede8
refs/heads/master
2021-01-13T08:23:16.214294
2010-10-03T21:53:08
2010-10-03T21:53:08
71,899,655
2
0
null
null
null
null
UTF-8
C++
false
false
12,767
cpp
// Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // #include "chttpconnectfilter.h" #include <httpstringconstants.h> #include <httperr.h> #include <http/rhttpheaders.h> _LIT8(KUAProfile, "x-wap-profile"); // 'this' used in base member initializer list, The 'this' pointer being used is a base class pointer. #pragma warning( disable : 4355 ) CHttpConnectFilter* CHttpConnectFilter::NewL(RHTTPSession aSession) { CHttpConnectFilter* self = new (ELeave) CHttpConnectFilter(aSession); CleanupStack::PushL(self); self->ConstructL(); CleanupStack::Pop(self); return self; } CHttpConnectFilter::~CHttpConnectFilter() { iConnectTransactions.Close(); iPendingTransactions.Close(); // If this object has been destroyed from the cleanup stack during creation // of the object, it might still be loaded - check. Normally the delete is // initiated by the 'delete this' in MHFUnload. if( iLoadCount ) { // As already in a destructor, MHFUnload must not delete this again. iLoadCount = -1; RStringF filterName = iStringPool.StringF(HTTP::EHttpConnectFilter, iStringTable); iSession.FilterCollection().RemoveFilter(filterName); } } CHttpConnectFilter::CHttpConnectFilter(RHTTPSession aSession) : CBase(), iSession(aSession), iStringTable(RHTTPSession::GetTable()), iStringPool(aSession.StringPool()), iCallback(*this) { } void CHttpConnectFilter::ConstructL() { // Register the filter. RStringF filterName = iStringPool.StringF(HTTP::EHttpConnectFilter, iStringTable); iSession.FilterCollection().AddFilterL( *this, THTTPEvent::ENeedTunnel, MHTTPFilter::EProtocolHandler +20, filterName ); iSession.FilterCollection().AddFilterL( *this, THTTPEvent::ECancel, MHTTPFilter::EProtocolHandler +20, filterName ); } TInt CHttpConnectFilter::FindConnectRequest(RStringF aTunnelHost, RStringF aProxy) { TInt id = KErrNotFound; TInt index = iConnectTransactions.Count(); RStringF tunnelName = iStringPool.StringF(HTTP::ETunnel, iStringTable); while( index > 0 && id == KErrNotFound ) { --index; RHTTPTransaction trans = iConnectTransactions[index]; THTTPHdrVal tunnelVal; #ifdef _DEBUG TBool found = #endif trans.PropertySet().Property(tunnelName, tunnelVal); __ASSERT_DEBUG( found, User::Invariant() ); if( aTunnelHost == tunnelVal.StrF() ) { // Ok the tunnel matches - check to see if a specific proxy is being // used. THTTPHdrVal proxyVal = RStringF(); trans.PropertySet().Property(iStringPool.StringF(HTTP::EProxyAddress, iStringTable), proxyVal); if( proxyVal.StrF() == aProxy ) { // There already is a CONNECT request for this tunnel - no need to // create another. id = trans.Id(); } } } return id; } TInt CHttpConnectFilter::CreateConnectTransactionL(RStringF aTunnelHost, RStringF aProxy, RStringF aUserAgent, RStringF aProfile) { // The Request-URI for the CONNECT request is in the 'authority' form, as // described in RFC2616, section 5.1.2, but need to pass the request uri as // a TUriC8... _LIT8(KSchemeString, "https://%S"); // uses more code to use RString EHTTPS than we save by adding the 5 bytes here TUriParser8 connectUri; HBufC8* uri = HBufC8::NewLC(aTunnelHost.DesC().Length()+8); uri->Des().AppendFormat(KSchemeString(), &aTunnelHost.DesC()); connectUri.Parse(*uri); // Open a CONNECT transaction... RStringF connectMethod = iStringPool.StringF(HTTP::ECONNECT, iStringTable); iNewConnectTransaction = iSession.OpenTransactionL( connectUri, iCallback, connectMethod ); CleanupStack::PopAndDestroy(uri); // As the CONNECT transaction is prepared, submitted and stored, it is // possible to orphan this transaction - it will need to be closed if a // leave occurs. iCloseConnectTransaction = ETrue; // Set aTunnelHost as the ETunnel property in the transaction. RStringF tunnelName = iStringPool.StringF(HTTP::ETunnel, iStringTable); THTTPHdrVal tunnelVal(aTunnelHost); iNewConnectTransaction.PropertySet().SetPropertyL(tunnelName, tunnelVal); if( aProxy.DesC().Length() > 0 ) { // ok need to use a specific proxy - set the appropriate properties in // the transaction. RHTTPPropertySet properties = iNewConnectTransaction.PropertySet(); properties.SetPropertyL( iStringPool.StringF(HTTP::EProxyUsage, iStringTable), iStringPool.StringF(HTTP::EUseProxy, iStringTable) ); properties.SetPropertyL( iStringPool.StringF(HTTP::EProxyAddress, iStringTable), aProxy ); } // get new transaction headers RHTTPHeaders hdr = iNewConnectTransaction.Request().GetHeaderCollection(); if(aUserAgent.DesC().Length() > 0) { // add the User-agent header hdr.SetFieldL( iStringPool.StringF(HTTP::EUserAgent, iStringTable), THTTPHdrVal(aUserAgent) ); } if(aProfile.DesC().Length() > 0) { // add the User Agent profile header //Note: if mmp file defines SRCDBG the next 4 lines cause a compiler bug in thumb udeb builds // can workaround compiler bug by removing local variable & using this line instead: // hdr.SetFieldL(iStringPool.OpenFStringL(KUAProfile), THTTPHdrVal(aProfile)); // but its not leave safe, but could be used for debugging if SRCDBG is really needed RStringF profileHeader = iStringPool.OpenFStringL(KUAProfile); CleanupClosePushL(profileHeader); hdr.SetFieldL(profileHeader, THTTPHdrVal(aProfile)); CleanupStack::PopAndDestroy(&profileHeader); } // Submit the CONNECT request... iNewConnectTransaction.SubmitL(); // Store CONNECT transaction... User::LeaveIfError(iConnectTransactions.Append(iNewConnectTransaction)); return iNewConnectTransaction.Id(); } void CHttpConnectFilter::CloseConnectTransaction(TInt aConnectId) { // Run through connect transaction array, remove and close the one with // this id. const TInt count = iConnectTransactions.Count(); for( TInt index = 0; index < count; ++index ) { RHTTPTransaction trans = iConnectTransactions[index]; if( trans.Id() == aConnectId ) { trans.Close(); iConnectTransactions.Remove(index); return; } } // If no CONNECT transaction found with that id - something has gone wrong. User::Invariant(); } /* * Methods from MHTTPFilterBase */ void CHttpConnectFilter::MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent) { switch( aEvent.iStatus ) { case THTTPEvent::ENeedTunnel: { // Transaction needs a tunnel - need to see if a CONNECT request has // been made for this origin server via the same proxy. aTransaction.Cancel(); // The transaction must have the ETunnel property - this contains the // host/port of where the tunnel needs to lead to. RHTTPPropertySet properties = aTransaction.PropertySet(); THTTPHdrVal tunnelVal; #ifdef _DEBUG TBool found = #endif properties.Property(iStringPool.StringF(HTTP::ETunnel, iStringTable), tunnelVal); __ASSERT_DEBUG( found, User::Invariant() ); __ASSERT_DEBUG( tunnelVal.Type() == THTTPHdrVal::KStrFVal, User::Invariant() ); // Also, check to see if the transaction has a specific proxy to use. // NOTE - no need to check HTTP::EUseProxy, only need to see if // the HTTP::EProxyAddress is set/ THTTPHdrVal proxyVal = RStringF(); properties.Property(iStringPool.StringF(HTTP::EProxyAddress, iStringTable), proxyVal); // See if there already is CONNECT transaction for this tunnel host/port. TInt connectId = FindConnectRequest(tunnelVal.StrF(), proxyVal.StrF()); if( connectId == KErrNotFound ) { // get request headers RHTTPHeaders hdr = aTransaction.Request().GetHeaderCollection(); // extract user-agent header THTTPHdrVal userAgent = RStringF(); hdr.GetField(iStringPool.StringF(HTTP::EUserAgent, iStringTable), 0, userAgent); // extract UA profile header RStringF profileHeader = iStringPool.OpenFStringL(KUAProfile); THTTPHdrVal profile = RStringF(); hdr.GetField(profileHeader, 0, profile); profileHeader.Close(); // Create a CONNECT transaction for the host/port. connectId = CreateConnectTransactionL(tunnelVal.StrF(), proxyVal.StrF(), userAgent.StrF(), profile.StrF()); } // Associate this transaction with the CONNECT transaction. TPendingTransaction pending = TPendingTransaction(aTransaction, connectId); User::LeaveIfError(iPendingTransactions.Append(pending)); // If a new CONNECT request was created, it is now safe. iCloseConnectTransaction = EFalse; } break; case THTTPEvent::ECancel: { // Check if this transaction is in the pending queue TBool found = EFalse; TInt index = iPendingTransactions.Count(); while( index > 0 && !found ) { --index; TPendingTransaction pending = iPendingTransactions[index]; if( pending.iPendingTransaction == aTransaction ) { // This transaction was waiting for a tunnel - remove it from the // queue. Let the CONNECT transaction for the tunnel continue as // there could be other pending transactions waiting for that // same tunnel. iPendingTransactions.Remove(index); found = ETrue; } } } break; default: break; } } void CHttpConnectFilter::MHFSessionRunL(const THTTPSessionEvent& /*aEvent*/) { } TInt CHttpConnectFilter::MHFRunError(TInt aError, RHTTPTransaction aTransaction, const THTTPEvent& /*aEvent*/) { // Something has gone a bit wrong - does the connect transaction need to be // closed? if( iCloseConnectTransaction ) { // Yep, this means that leave occured after the new connect transaction // was opened. iNewConnectTransaction.Close(); } // Send the error to the client if(aTransaction.SendEvent(aError, THTTPEvent::EIncoming, THTTPFilterHandle(THTTPFilterHandle::ECurrentFilter)) != KErrNone ) { aTransaction.Fail(); } return KErrNone; } TInt CHttpConnectFilter::MHFSessionRunError(TInt aError, const THTTPSessionEvent& /*aEvent*/) { return aError; } /* * Methods from MHTTPFilter */ void CHttpConnectFilter::MHFLoad(RHTTPSession, THTTPFilterHandle) { ++iLoadCount; } void CHttpConnectFilter::MHFUnload(RHTTPSession /*aSession*/, THTTPFilterHandle) { if( --iLoadCount > 0 ) return; delete this; } /* * Methods from MHttpConnectObserver */ void CHttpConnectFilter::ConnectCompleteL(TInt aConnectId) { // Close this CONNECT transaction CloseConnectTransaction(aConnectId); // Locate the pending transactions that were waiting for this tunnel. TInt index = iPendingTransactions.Count(); while( index > 0 ) { --index; TPendingTransaction pending = iPendingTransactions[index]; if( pending.iConnectId == aConnectId ) { // This transaction was waiting for the tunnel - re-submit it. pending.iPendingTransaction.SubmitL(); // Remove this entry. iPendingTransactions.Remove(index); } } } void CHttpConnectFilter::ConnectErrorL(TInt aConnectId) { // Close this CONNECT transaction CloseConnectTransaction(aConnectId); // Locate the pending transactions that were waiting for this tunnel. TInt index = iPendingTransactions.Count(); while( index > 0 ) { --index; TPendingTransaction pending = iPendingTransactions[index]; if( pending.iConnectId == aConnectId ) { // This transaction was waiting for the tunnel - send error. Pretend // that the error came from the protocol handler. This ensures all // filters are notified. pending.iPendingTransaction.SendEventL( KErrHttpCannotEstablishTunnel, THTTPEvent::EIncoming, THTTPFilterHandle(THTTPFilterHandle::EProtocolHandler) ); // Remove this entry. iPendingTransactions.Remove(index); } } } void CHttpConnectFilter::FailPendingTransactions(TInt aConnectId) { // No need to close the CONNECT transaction - would have closed already. // Locate the pending transactions that were waiting for this tunnel. TInt index = iPendingTransactions.Count(); while( index > 0 ) { --index; TPendingTransaction pending = iPendingTransactions[index]; if( pending.iConnectId == aConnectId ) { // This transaction was waiting for the tunnel - fail it! pending.iPendingTransaction.Fail(); // Remove this entry. iPendingTransactions.Remove(index); } } }
[ "kirill.dremov@nokia.com" ]
kirill.dremov@nokia.com
546748a0d2af4968d91fa79594a7dcc893f46c77
202771bbbc2afc7027b74993e7000f3ea39255b4
/src/Jugador.h
81f74268421146b43f68106dc15e180770aa4423
[]
no_license
Gonan98/sfml-dungeon-game
f563b433bdf244a7212db000e63e9ae959b8e087
acf321cffdef1d0367709ffca535f34c94a1ee1b
refs/heads/master
2021-05-26T00:46:25.591376
2020-07-09T23:14:12
2020-07-09T23:14:12
254,148,855
1
0
null
2020-06-24T19:20:27
2020-04-08T16:57:20
C++
UTF-8
C++
false
false
562
h
#ifndef _JUGADOR_H_ #define _JUGADOR_H_ #include "Entidad.h" #include <string> class Jugador : public Entidad{ private: int vidas; int puntaje; std::string nombre; public: Jugador(); Jugador(Texture& t, Animacion* animacion, std::string nombre, float x, float y, float dx, float dy); ~Jugador(); int getVidas(); int getPuntaje(); std::string getNombre(); void setVidas(int); void setPuntaje(int); void setNombre(std::string); void dibujar(sf::RenderWindow &w); void mover(Direccion dir); void hurt(int damage); bool interactuar(); }; #endif
[ "andreg-16@hotmail.com" ]
andreg-16@hotmail.com
9f78062d4af7a32ff6c2265c3d12614eb89c23f4
a7d39b83bee548cc4d280d05434ba80bd4f08e36
/gefranseven_moudle_thread.cpp
9aa9a793fa1b677852d9994ffc7920db73a4d78a
[]
no_license
kimbakcho/QCserver2
5cf1b8cbf28e9b04e2c2eddf0a3e5acb74903f9e
f78db7ed417074fad874ab14aab03eaf285ea970
refs/heads/master
2020-12-25T09:57:14.469564
2016-07-20T00:15:06
2016-07-20T00:15:06
62,351,198
0
0
null
null
null
null
UTF-8
C++
false
false
533
cpp
#include "gefranseven_moudle_thread.h" #include "gefranseven_base_logic.h" gefranseven_moudle_thread::gefranseven_moudle_thread(QObject *parent) { playflag = true; this->parent = parent; } void gefranseven_moudle_thread::run(){ gefranseven_base_logic *parent_logic = (gefranseven_base_logic *)this->parent; while(playflag){ parent_logic->mutex.lock(); parent_logic->waitcondition.wait(&(parent_logic->mutex)); parent_logic->url_gefranbaseloop(); parent_logic->mutex.unlock(); } }
[ "vngkgk624@naver.com" ]
vngkgk624@naver.com
de78026d1cbe39a402f61600249758e5e2122f98
42aee3f10fd1bf1ff3073d68cb75c82628dbf324
/psql_mongo_replication/include/psql_mongo_replication/psql_mongo_replication.hpp
a020109f0409f161d42944099fe984478ea098fc
[]
no_license
FriendOrYes/psql_mongo_replication
5ad9450a84619e11a27b87f3179edf4cdaec1e63
7b9d8a388134081b37c64c2eb9f9c000a99cb0e4
refs/heads/master
2022-11-01T18:02:16.986739
2020-06-11T13:43:51
2020-06-11T13:43:51
268,163,010
0
0
null
null
null
null
UTF-8
C++
false
false
1,123
hpp
#pragma once #include <memory> #include <thread> #include <mutex> #include <vector> struct pg_recvlogical_connection_settings_t; namespace psql_mongo_replication { class mongo_replication; class psql_to_mongo { private: std::vector<std::unique_ptr<mongo_replication>> _mongo_replications_db; static unsigned char on_changes_static(const void* context, const char* changes, unsigned size); psql_mongo_replication::mongo_replication* get_db_instance(int id); std::unique_ptr<std::thread> _replication_thread; std::mutex _mutex; public: psql_to_mongo(); ~psql_to_mongo(); void on_changes(const char* changes, unsigned size); void connect_to_mongo_db(const pg_recvlogical_connection_settings_t& connection); void reconnect(int id); void unconnect_from_mongo_db(); void connect_to_mongo_dbs(const pg_recvlogical_connection_settings_t* connection, unsigned count); void start_replication(const pg_recvlogical_connection_settings_t& host_connection); }; }
[ "a.chaban@infomir.com" ]
a.chaban@infomir.com
67e8df65e35771455e3b1ce337a6cc1544e1cadd
8889c4dd54494a7d6ee63b69922331154ffd6ba4
/app/kubeDimension/dependencies/osrm-backend/extractor/extractor.cpp
029c47c0a3c5a5a2f7ced2214a54f863ca849989
[ "BSD-2-Clause" ]
permissive
hello-web/kubeDimension
27d5e95f7b2d5c5b3743a0a53c6ac2b55c7bc509
a52277e0622676ff65e9d210386aac018e3b43fa
refs/heads/master
2021-05-30T02:19:22.596418
2015-11-30T02:46:21
2015-11-30T02:46:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,723
cpp
/* Copyright (c) 2015, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "extractor.hpp" #include "extraction_containers.hpp" #include "extraction_node.hpp" #include "extraction_way.hpp" #include "extractor_callbacks.hpp" #include "restriction_parser.hpp" #include "scripting_environment.hpp" #include "../data_structures/raster_source.hpp" #include "../util/make_unique.hpp" #include "../util/simple_logger.hpp" #include "../util/timing_util.hpp" #include "../util/lua_util.hpp" #include "../util/graph_loader.hpp" #include "../typedefs.h" #include "../data_structures/static_graph.hpp" #include "../data_structures/static_rtree.hpp" #include "../data_structures/restriction_map.hpp" #include "../data_structures/compressed_edge_container.hpp" #include "../algorithms/tarjan_scc.hpp" #include "../algorithms/crc32_processor.hpp" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/optional/optional.hpp> #include <luabind/luabind.hpp> #include <osmium/io/any_input.hpp> #include <tbb/parallel_for.h> #include <tbb/task_scheduler_init.h> #include <cstdlib> #include <algorithm> #include <atomic> #include <chrono> #include <fstream> #include <iostream> #include <thread> #include <unordered_map> #include <vector> /** * TODO: Refactor this function into smaller functions for better readability. * * This function is the entry point for the whole extraction process. The goal of the extraction * step is to filter and convert the OSM geometry to something more fitting for routing. * That includes: * - extracting turn restrictions * - splitting ways into (directional!) edge segments * - checking if nodes are barriers or traffic signal * - discarding all tag information: All relevant type information for nodes/ways * is extracted at this point. * * The result of this process are the following files: * .names : Names of all streets, stored as long consecutive string with prefix sum based index * .osrm : Nodes and edges in a intermediate format that easy to digest for osrm-prepare * .restrictions : Turn restrictions that are used my osrm-prepare to construct the edge-expanded graph * */ int extractor::run() { try { LogPolicy::GetInstance().Unmute(); TIMER_START(extracting); const unsigned recommended_num_threads = tbb::task_scheduler_init::default_num_threads(); const auto number_of_threads = std::min(recommended_num_threads, config.requested_num_threads); tbb::task_scheduler_init init(number_of_threads); SimpleLogger().Write() << "Input file: " << config.input_path.filename().string(); SimpleLogger().Write() << "Profile: " << config.profile_path.filename().string(); SimpleLogger().Write() << "Threads: " << number_of_threads; // setup scripting environment ScriptingEnvironment scripting_environment(config.profile_path.string().c_str()); ExtractionContainers extraction_containers; auto extractor_callbacks = osrm::make_unique<ExtractorCallbacks>(extraction_containers); const osmium::io::File input_file(config.input_path.string()); osmium::io::Reader reader(input_file); const osmium::io::Header header = reader.header(); std::atomic<unsigned> number_of_nodes{0}; std::atomic<unsigned> number_of_ways{0}; std::atomic<unsigned> number_of_relations{0}; std::atomic<unsigned> number_of_others{0}; SimpleLogger().Write() << "Parsing in progress.."; TIMER_START(parsing); lua_State *segment_state = scripting_environment.get_lua_state(); if (lua_function_exists(segment_state, "source_function")) { // bind a single instance of SourceContainer class to relevant lua state SourceContainer sources; luabind::globals(segment_state)["sources"] = sources; luabind::call_function<void>(segment_state, "source_function"); } std::string generator = header.get("generator"); if (generator.empty()) { generator = "unknown tool"; } SimpleLogger().Write() << "input file generated by " << generator; // write .timestamp data file std::string timestamp = header.get("osmosis_replication_timestamp"); if (timestamp.empty()) { timestamp = "n/a"; } SimpleLogger().Write() << "timestamp: " << timestamp; boost::filesystem::ofstream timestamp_out(config.timestamp_file_name); timestamp_out.write(timestamp.c_str(), timestamp.length()); timestamp_out.close(); // initialize vectors holding parsed objects tbb::concurrent_vector<std::pair<std::size_t, ExtractionNode>> resulting_nodes; tbb::concurrent_vector<std::pair<std::size_t, ExtractionWay>> resulting_ways; tbb::concurrent_vector<boost::optional<InputRestrictionContainer>> resulting_restrictions; // setup restriction parser const RestrictionParser restriction_parser(scripting_environment.get_lua_state()); while (const osmium::memory::Buffer buffer = reader.read()) { // create a vector of iterators into the buffer std::vector<osmium::memory::Buffer::const_iterator> osm_elements; for (auto iter = std::begin(buffer), end = std::end(buffer); iter != end; ++iter) { osm_elements.push_back(iter); } // clear resulting vectors resulting_nodes.clear(); resulting_ways.clear(); resulting_restrictions.clear(); // parse OSM entities in parallel, store in resulting vectors tbb::parallel_for( tbb::blocked_range<std::size_t>(0, osm_elements.size()), [&](const tbb::blocked_range<std::size_t> &range) { ExtractionNode result_node; ExtractionWay result_way; lua_State *local_state = scripting_environment.get_lua_state(); for (auto x = range.begin(), end = range.end(); x != end; ++x) { const auto entity = osm_elements[x]; switch (entity->type()) { case osmium::item_type::node: result_node.clear(); ++number_of_nodes; luabind::call_function<void>( local_state, "node_function", boost::cref(static_cast<const osmium::Node &>(*entity)), boost::ref(result_node)); resulting_nodes.push_back(std::make_pair(x, result_node)); break; case osmium::item_type::way: result_way.clear(); ++number_of_ways; luabind::call_function<void>( local_state, "way_function", boost::cref(static_cast<const osmium::Way &>(*entity)), boost::ref(result_way)); resulting_ways.push_back(std::make_pair(x, result_way)); break; case osmium::item_type::relation: ++number_of_relations; resulting_restrictions.push_back(restriction_parser.TryParse( static_cast<const osmium::Relation &>(*entity))); break; default: ++number_of_others; break; } } }); // put parsed objects thru extractor callbacks for (const auto &result : resulting_nodes) { extractor_callbacks->ProcessNode( static_cast<const osmium::Node &>(*(osm_elements[result.first])), result.second); } for (const auto &result : resulting_ways) { extractor_callbacks->ProcessWay( static_cast<const osmium::Way &>(*(osm_elements[result.first])), result.second); } for (const auto &result : resulting_restrictions) { extractor_callbacks->ProcessRestriction(result); } } TIMER_STOP(parsing); SimpleLogger().Write() << "Parsing finished after " << TIMER_SEC(parsing) << " seconds"; SimpleLogger().Write() << "Raw input contains " << number_of_nodes.load() << " nodes, " << number_of_ways.load() << " ways, and " << number_of_relations.load() << " relations, and " << number_of_others.load() << " unknown entities"; extractor_callbacks.reset(); if (extraction_containers.all_edges_list.empty()) { SimpleLogger().Write(logWARNING) << "The input data is empty, exiting."; return 1; } extraction_containers.PrepareData(config.output_file_name, config.restriction_file_name, config.names_file_name, segment_state); TIMER_STOP(extracting); SimpleLogger().Write() << "extraction finished after " << TIMER_SEC(extracting) << "s"; } catch (const std::exception &e) { SimpleLogger().Write(logWARNING) << e.what(); return 1; } try { // Transform the node-based graph that OSM is based on into an edge-based graph // that is better for routing. Every edge becomes a node, and every valid // movement (e.g. turn from A->B, and B->A) becomes an edge // // // // Create a new lua state SimpleLogger().Write() << "Generating edge-expanded graph representation"; TIMER_START(expansion); std::vector<EdgeBasedNode> node_based_edge_list; DeallocatingVector<EdgeBasedEdge> edge_based_edge_list; std::vector<QueryNode> internal_to_external_node_map; auto graph_size = BuildEdgeExpandedGraph(internal_to_external_node_map, node_based_edge_list, edge_based_edge_list); auto number_of_node_based_nodes = graph_size.first; auto max_edge_id = graph_size.second; TIMER_STOP(expansion); SimpleLogger().Write() << "building r-tree ..."; TIMER_START(rtree); FindComponents(max_edge_id, edge_based_edge_list, node_based_edge_list); BuildRTree(node_based_edge_list, internal_to_external_node_map); TIMER_STOP(rtree); SimpleLogger().Write() << "writing node map ..."; WriteNodeMapping(internal_to_external_node_map); WriteEdgeBasedGraph(config.edge_graph_output_path, max_edge_id, edge_based_edge_list); SimpleLogger().Write() << "Expansion : " << (number_of_node_based_nodes / TIMER_SEC(expansion)) << " nodes/sec and " << ((max_edge_id + 1) / TIMER_SEC(expansion)) << " edges/sec"; SimpleLogger().Write() << "To prepare the data for routing, run: " << "./osrm-prepare " << config.output_file_name << std::endl; } catch (const std::exception &e) { SimpleLogger().Write(logWARNING) << e.what(); return 1; } return 0; } /** \brief Setups scripting environment (lua-scripting) Also initializes speed profile. */ void extractor::SetupScriptingEnvironment(lua_State *lua_state, SpeedProfileProperties &speed_profile) { // open utility libraries string library; luaL_openlibs(lua_state); // adjust lua load path luaAddScriptFolderToLoadPath(lua_state, config.profile_path.string().c_str()); // Now call our function in a lua script if (0 != luaL_dofile(lua_state, config.profile_path.string().c_str())) { std::stringstream msg; msg << lua_tostring(lua_state, -1) << " occured in scripting block"; throw osrm::exception(msg.str()); } if (0 != luaL_dostring(lua_state, "return traffic_signal_penalty\n")) { std::stringstream msg; msg << lua_tostring(lua_state, -1) << " occured in scripting block"; throw osrm::exception(msg.str()); } speed_profile.traffic_signal_penalty = 10 * lua_tointeger(lua_state, -1); SimpleLogger().Write(logDEBUG) << "traffic_signal_penalty: " << speed_profile.traffic_signal_penalty; if (0 != luaL_dostring(lua_state, "return u_turn_penalty\n")) { std::stringstream msg; msg << lua_tostring(lua_state, -1) << " occured in scripting block"; throw osrm::exception(msg.str()); } speed_profile.u_turn_penalty = 10 * lua_tointeger(lua_state, -1); speed_profile.has_turn_penalty_function = lua_function_exists(lua_state, "turn_function"); } void extractor::FindComponents(unsigned max_edge_id, const DeallocatingVector<EdgeBasedEdge> &input_edge_list, std::vector<EdgeBasedNode> &input_nodes) const { struct UncontractedEdgeData { }; struct InputEdge { unsigned source; unsigned target; UncontractedEdgeData data; bool operator<(const InputEdge &rhs) const { return source < rhs.source || (source == rhs.source && target < rhs.target); } bool operator==(const InputEdge &rhs) const { return source == rhs.source && target == rhs.target; } }; using UncontractedGraph = StaticGraph<UncontractedEdgeData>; std::vector<InputEdge> edges; edges.reserve(input_edge_list.size() * 2); for (const auto &edge : input_edge_list) { BOOST_ASSERT_MSG(static_cast<unsigned int>(std::max(edge.weight, 1)) > 0, "edge distance < 1"); if (edge.forward) { edges.push_back({edge.source, edge.target, {}}); } if (edge.backward) { edges.push_back({edge.target, edge.source, {}}); } } // connect forward and backward nodes of each edge for (const auto &node : input_nodes) { if (node.reverse_edge_based_node_id != SPECIAL_NODEID) { edges.push_back({node.forward_edge_based_node_id, node.reverse_edge_based_node_id, {}}); edges.push_back({node.reverse_edge_based_node_id, node.forward_edge_based_node_id, {}}); } } tbb::parallel_sort(edges.begin(), edges.end()); auto new_end = std::unique(edges.begin(), edges.end()); edges.resize(new_end - edges.begin()); auto uncontractor_graph = std::make_shared<UncontractedGraph>(max_edge_id + 1, edges); TarjanSCC<UncontractedGraph> component_search( std::const_pointer_cast<const UncontractedGraph>(uncontractor_graph)); component_search.run(); for (auto &node : input_nodes) { auto forward_component = component_search.get_component_id(node.forward_edge_based_node_id); BOOST_ASSERT(node.reverse_edge_based_node_id == SPECIAL_EDGEID || forward_component == component_search.get_component_id(node.reverse_edge_based_node_id)); const unsigned component_size = component_search.get_component_size(forward_component); const bool is_tiny_component = component_size < 1000; node.component_id = is_tiny_component ? (1 + forward_component) : 0; } } /** \brief Build load restrictions from .restriction file */ std::shared_ptr<RestrictionMap> extractor::LoadRestrictionMap() { boost::filesystem::ifstream input_stream(config.restriction_file_name, std::ios::in | std::ios::binary); std::vector<TurnRestriction> restriction_list; loadRestrictionsFromFile(input_stream, restriction_list); SimpleLogger().Write() << " - " << restriction_list.size() << " restrictions."; return std::make_shared<RestrictionMap>(restriction_list); } /** \brief Load node based graph from .osrm file */ std::shared_ptr<NodeBasedDynamicGraph> extractor::LoadNodeBasedGraph(std::unordered_set<NodeID> &barrier_nodes, std::unordered_set<NodeID> &traffic_lights, std::vector<QueryNode> &internal_to_external_node_map) { std::vector<NodeBasedEdge> edge_list; boost::filesystem::ifstream input_stream(config.output_file_name, std::ios::in | std::ios::binary); std::vector<NodeID> barrier_list; std::vector<NodeID> traffic_light_list; NodeID number_of_node_based_nodes = loadNodesFromFile( input_stream, barrier_list, traffic_light_list, internal_to_external_node_map); SimpleLogger().Write() << " - " << barrier_list.size() << " bollard nodes, " << traffic_light_list.size() << " traffic lights"; // insert into unordered sets for fast lookup barrier_nodes.insert(barrier_list.begin(), barrier_list.end()); traffic_lights.insert(traffic_light_list.begin(), traffic_light_list.end()); barrier_list.clear(); barrier_list.shrink_to_fit(); traffic_light_list.clear(); traffic_light_list.shrink_to_fit(); loadEdgesFromFile(input_stream, edge_list); if (edge_list.empty()) { SimpleLogger().Write(logWARNING) << "The input data is empty, exiting."; return std::shared_ptr<NodeBasedDynamicGraph>(); } return NodeBasedDynamicGraphFromEdges(number_of_node_based_nodes, edge_list); } /** \brief Building an edge-expanded graph from node-based input and turn restrictions */ std::pair<std::size_t, std::size_t> extractor::BuildEdgeExpandedGraph(std::vector<QueryNode> &internal_to_external_node_map, std::vector<EdgeBasedNode> &node_based_edge_list, DeallocatingVector<EdgeBasedEdge> &edge_based_edge_list) { lua_State *lua_state = luaL_newstate(); luabind::open(lua_state); SpeedProfileProperties speed_profile; SetupScriptingEnvironment(lua_state, speed_profile); std::unordered_set<NodeID> barrier_nodes; std::unordered_set<NodeID> traffic_lights; auto restriction_map = LoadRestrictionMap(); auto node_based_graph = LoadNodeBasedGraph(barrier_nodes, traffic_lights, internal_to_external_node_map); CompressedEdgeContainer compressed_edge_container; GraphCompressor graph_compressor(speed_profile); graph_compressor.Compress(barrier_nodes, traffic_lights, *restriction_map, *node_based_graph, compressed_edge_container); EdgeBasedGraphFactory edge_based_graph_factory( node_based_graph, compressed_edge_container, barrier_nodes, traffic_lights, std::const_pointer_cast<RestrictionMap const>(restriction_map), internal_to_external_node_map, speed_profile); compressed_edge_container.SerializeInternalVector(config.geometry_output_path); edge_based_graph_factory.Run(config.edge_output_path, lua_state, config.edge_segment_lookup_path, config.edge_penalty_path, config.generate_edge_lookup #ifdef DEBUG_GEOMETRY , config.debug_turns_path #endif ); lua_close(lua_state); edge_based_graph_factory.GetEdgeBasedEdges(edge_based_edge_list); edge_based_graph_factory.GetEdgeBasedNodes(node_based_edge_list); auto max_edge_id = edge_based_graph_factory.GetHighestEdgeID(); const std::size_t number_of_node_based_nodes = node_based_graph->GetNumberOfNodes(); return std::make_pair(number_of_node_based_nodes, max_edge_id); } /** \brief Writing info on original (node-based) nodes */ void extractor::WriteNodeMapping(const std::vector<QueryNode> & internal_to_external_node_map) { boost::filesystem::ofstream node_stream(config.node_output_path, std::ios::binary); const unsigned size_of_mapping = internal_to_external_node_map.size(); node_stream.write((char *)&size_of_mapping, sizeof(unsigned)); if (size_of_mapping > 0) { node_stream.write((char *)internal_to_external_node_map.data(), size_of_mapping * sizeof(QueryNode)); } node_stream.close(); } /** \brief Building rtree-based nearest-neighbor data structure Saves tree into '.ramIndex' and leaves into '.fileIndex'. */ void extractor::BuildRTree(const std::vector<EdgeBasedNode> &node_based_edge_list, const std::vector<QueryNode> &internal_to_external_node_map) { StaticRTree<EdgeBasedNode>(node_based_edge_list, config.rtree_nodes_output_path.c_str(), config.rtree_leafs_output_path.c_str(), internal_to_external_node_map); } void extractor::WriteEdgeBasedGraph(std::string const &output_file_filename, size_t const max_edge_id, DeallocatingVector<EdgeBasedEdge> const & edge_based_edge_list) { std::ofstream file_out_stream; file_out_stream.open(output_file_filename.c_str(), std::ios::binary); const FingerPrint fingerprint = FingerPrint::GetValid(); file_out_stream.write((char *)&fingerprint, sizeof(FingerPrint)); std::cout << "[extractor] Writing edge-based-graph egdes ... " << std::flush; TIMER_START(write_edges); size_t number_of_used_edges = edge_based_edge_list.size(); file_out_stream.write((char *)&number_of_used_edges, sizeof(size_t)); file_out_stream.write((char *)&max_edge_id, sizeof(size_t)); for (const auto& edge : edge_based_edge_list) { file_out_stream.write((char *) &edge, sizeof(EdgeBasedEdge)); } TIMER_STOP(write_edges); std::cout << "ok, after " << TIMER_SEC(write_edges) << "s" << std::endl; SimpleLogger().Write() << "Processed " << number_of_used_edges << " edges"; file_out_stream.close(); }
[ "luc@blippar.com" ]
luc@blippar.com
071d9c3301858fecb3e1e406c86c970bb874b952
c6b738445a406886733f4ee39ae71b18b31e22d2
/test/overload/include_pass.cpp
708fc67d84c1eb3a1133520979410808f20a3938
[]
no_license
viboes/tags
4a79810cc48a7a83abefa0e1cfe1ee24d708c510
6285ffa0472da8c6b2f1b7a6d8bbffb800bb9558
refs/heads/master
2021-01-19T01:32:46.758433
2018-04-02T16:26:53
2018-04-02T16:26:53
26,433,487
13
2
null
null
null
null
UTF-8
C++
false
false
14,796
cpp
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Vicente J. Botet Escriba 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // ////////////////////////////////////////////////////////////////////////////// #include <yafpl/v1/functional/overload.hpp> #include <iostream> #include <string> #include <vector> #include <cassert> #include <boost/detail/lightweight_test.hpp> struct X { X& f(char) { std::cout << "X::f" << std::endl; return *this; } int g(char) { return 33; } bool operator==(X const&) { return true; } }; struct Y { }; struct final_function_object_const final { void operator ()(int arg) const { } }; struct final_function_object_non_const final { void operator ()(int arg) { } }; struct function_with_state { void operator ()(int arg) { invoked = true; } bool invoked = false; }; struct function_without_state { constexpr void operator ()(int arg) const noexcept { } }; struct function_without_state_x { constexpr void operator ()(float arg) const noexcept { } }; struct convertible_to_function_object { operator function_without_state() const { return function_without_state{}; } }; struct function_without_state_throw { void operator ()(int arg) const { throw 1;} }; struct function_without_state2 { constexpr int operator ()(int arg) const noexcept { return arg;} }; struct function_without_state3 { int operator ()(int arg) const noexcept { return arg;} }; struct function_with_rvalue_ref_q { int operator ()(int arg) && { return 1; } int operator ()(int arg) const && { return 2; } int operator ()(int arg) & { return 3;} int operator ()(int arg) const & { return 4;} }; struct final_function_with_rvalue_ref_q final { int operator ()(int arg) && { return 1; } int operator ()(int arg) const && { return 2; } int operator ()(int arg) & { return 3;} int operator ()(int arg) const & { return 4;} }; struct function_with_lvalue_ref_q { void operator ()(int arg) & { } }; struct function_with_no_ref_q { void operator ()(int arg) { } }; struct function_with_ref_q { int operator ()(int arg) & { return 1; } int operator ()(int arg) && { return 2; } }; struct function_with_cv_q { int operator ()(int arg) { return 0; } int operator ()(int arg) const { return 1; } int operator ()(int arg) volatile { return 2; } int operator ()(int arg) const volatile { return 3; } }; int nonMember( float ) { std::cout << "int(float)" << std::endl; return 42; } int nonMember_throw( float ) { throw 1;; } namespace cppljevans { //Purpose: // See if can multi-inherit classes // with member function with same // name but different signature. // //Result: // Works. // //=========== template<int I> struct udt_i /**@brief * User Defined Type. */ { friend std::ostream& operator<< ( std::ostream& os , udt_i const& ) { return os<<"udt_i<"<<I<<">"; } }; template<int I> struct functor_i /**@brief * User Defined Functor. */ { using arg_t=udt_i<I>; void operator()(arg_t const&a) { std::cout<<"functor_i<"<<I<<">::operator()("<<a<<" const&).\n"; } }; template<typename Functor> struct forwarder /**@brief * this->operator() forwards to Functor::operator() */ { Functor functor_v; forwarder(Functor const& functor_a) : functor_v(functor_a) {} using arg_t=typename Functor::arg_t; void operator()(arg_t const&arg_v) { functor_v(arg_v); } }; #ifdef __clang__ template<typename... Functors> struct overloader /**@brief * "Mixin" all the Functors::operator()'s * into this class. */ : public forwarder<Functors>... { overloader(Functors&&... functors_a) : forwarder<Functors>(functors_a)... {} }; #else template<typename... Functors> struct overloader /**@brief * "Mixin" all the Functors::operator()'s * into this class. */ ; template<> struct overloader<> { void operator()() { } }; template<typename Functor0, typename... Functors> struct overloader<Functor0, Functors...> : public forwarder<Functor0>, overloader<Functors...> { overloader(Functor0&& functor0, Functors&&... functors_a) : forwarder<Functor0>(std::forward<Functor0>(functor0)) , overloader<Functors...>(std::forward<Functors>(functors_a)...) {} using forwarder<Functor0>::operator(); using overloader<Functors...>::operator(); }; #endif } int main() { { using namespace cppljevans; overloader < functor_i<0> , functor_i<1> , functor_i<2> > ovldr ( functor_i<0>{} , functor_i<1>{} , functor_i<2>{} ) ; ovldr(udt_i<0>{}); ovldr(udt_i<1>{}); ovldr(udt_i<2>{}); } using namespace yafpl; // { // auto f = overload( // [](int i, double d) {}, // [](std::string str, int i) { // }, // [](double d, int i) { // BOOST_TEST(false); // } // ); // f(1,1); // ambiguous call compile fails // } { final_function_object_const foo; auto f = overload(foo); f(1); } { final_function_object_non_const foo; auto f = overload(foo, // foo should be copied [](std::string str) { BOOST_TEST(false); return 1; } ); f(1); } { final_function_object_const foo; auto f = overload<int>(foo); f(1); } { final_function_object_non_const foo; auto f = overload<int>(foo, // foo should be copied [](std::string str) { BOOST_TEST(false); return 1; } ); f(1); } { final_function_object_non_const foo; overload<int>(foo, [](std::string str) { BOOST_TEST(false); return 1; } )(1); } #if 0 //../include/yafpl/v1/functional/overload.hpp:29:18: error: no member named 'operator()' in 'convertible_to_function_object' // using F::operator(); ~~~^ { convertible_to_function_object foo; auto f = overload<int>(foo); f(1); } #endif { function_without_state foo; auto f = overload<int>(foo, // foo should be copied [](std::string str) { BOOST_TEST(false); return 1; } //, nonMember ); f(1); } { function_without_state foo; auto f = overload(foo, // foo should be copied [](std::string str) { BOOST_TEST(false); }, nonMember ); f(1); } { function_without_state foo; auto f = overload(std::move(foo), // foo should be copied [](std::string str) { BOOST_TEST(false); }, [](...) { std::cout << "int(...)" << std::endl; } ); f(1); } { function_with_state foo; BOOST_TEST(! foo.invoked); overload(std::ref(foo), [](std::string str) { BOOST_TEST(false); })(1); BOOST_TEST(foo.invoked); } { overload(function_with_state{}, [](std::string str) { BOOST_TEST(false); })(1); } { function_with_state foo; BOOST_TEST(! foo.invoked); overload(foo, [](std::string str) { BOOST_TEST(false); })(1); BOOST_TEST(! foo.invoked); } { function_with_state foo; BOOST_TEST(! foo.invoked); overload(std::ref(foo), [](std::string str) { })("aaa"); BOOST_TEST(! foo.invoked); } { auto f = overload( [](int ) { std::cout << "int(int)" << std::endl; return 1; }, [](auto const&) { std::cout << "int(auto const&)" << std::endl; return -1; } ); BOOST_TEST(f(std::vector<int>{}) == -1); } { auto f = overload<int>( [](int ) { std::cout << "int(int)" << std::endl; return 1; }, [](auto const&) { std::cout << "int(auto const&)" << std::endl; return -1; } ); BOOST_TEST(f(std::vector<int>{}) == -1); } { auto f = overload( [](std::vector<int>&& ) { std::cout << "int(std::vector<int>&&)" << std::endl; return 1; }, [](...) { std::cout << "int(...)" << std::endl; return -1; } ); BOOST_TEST(f(std::vector<int>{}) == 1); } { auto f = overload<int>( [](std::vector<int>&& ) { std::cout << "int(std::vector<int>&&)" << std::endl; return 1; }, [](...) { std::cout << "int(...)" << std::endl; return -1; } ); BOOST_TEST(f(std::vector<int>{}) == 1); } { auto f = overload( [](int i) { std::cout << "int(int)" << std::endl; return i; }, [](std::string && i) { std::cout << "string(string&&)" << std::endl; return i; }, [](...) { std::cout << "int(...)" << std::endl; return -1; } ); BOOST_TEST(f(1) == 1); BOOST_TEST(f(std::string("1")) == "1"); BOOST_TEST_EQ(f(X{}), -1); } { auto f = overload<int>( [](int i) { std::cout << "int(int)" << std::endl; return i; }, [](std::string && i) { std::cout << "string(string&&)" << std::endl; return i; }, [](...) { std::cout << "int(...)" << std::endl; return -1; } ); BOOST_TEST(f(1) == 1); BOOST_TEST(f(std::string("1")) == "1"); BOOST_TEST_EQ(f(X{}), -1); } { auto f = overload( nonMember #if defined __GNUC__ and ! defined __clang__ , &X::f #endif , [](...) { std::cout << "int(...)" << std::endl; return -1; } ); BOOST_TEST(f(1.0) == 42); #if defined __GNUC__ and ! defined __clang__ X x; BOOST_TEST(f(x, 'c') == x); #endif BOOST_TEST_EQ(f(Y{}), -1); } { auto f = overload<X&>( &X::f ); X x; BOOST_TEST(f(x, 'c') == x); } { auto f = overload<int>( &X::g ); X x; BOOST_TEST(f(x, 'c') == 33); } { auto f = overload( &X::g ); X x; BOOST_TEST(f(x, 'c') == 33); } { auto f1 = overload( nonMember ); BOOST_TEST(f1(1.0) == 42); } { auto f1 = overload<int>( &nonMember ); BOOST_TEST(f1(1.0) == 42); } { auto f1 = overload( //overload/include_pass.cpp:429:12: error: attempt to use a deleted function &nonMember , &X::g ); X x; BOOST_TEST(f1(x, 'c') == 33); #if defined __GNUC__ and ! defined __clang__ BOOST_TEST(f1(1.0) == 42); #endif } { auto f = overload<int>( nonMember //overload/include_pass.cpp:429:12: error: attempt to use a deleted function , &X::g , [](...) { std::cout << "int(...)" << std::endl; return -1; } ); #if defined __GNUC__ and ! defined __clang__ BOOST_TEST(f(1.0) == 42); #endif X x; BOOST_TEST(f(x, 'c') == 33); #if defined __GNUC__ and ! defined __clang__ BOOST_TEST(f(Y{})== -1); #endif } { constexpr auto f = overload(function_without_state{} #if defined __GNUC__ and ! defined __clang__ , [](std::string str) { return 1; } #endif , nonMember ); static_assert(noexcept(f(1)), ""); f(1); } { constexpr auto f = overload(function_without_state2{} #if defined __GNUC__ and ! defined __clang__ , [](std::string str) { return 1; } #endif ); constexpr auto x = f(1); static_assert(1 == x, ""); } { static_assert(noexcept(function_without_state3{}(1)), ""); constexpr auto f = overload(function_without_state3{}); static_assert(noexcept(f(1)), ""); #if 0 constexpr auto x = f(1); // COMPILE ERROR as expected //overload/include_pass.cpp:409:25: erreur: call to non-constexpr function ‘int function_without_state3::operator()(int) const’ // constexpr auto x = f(1); static_assert(1 == x, ""); #endif auto y = f(1); BOOST_TEST(1 == y); } { static_assert(! noexcept(nonMember_throw(1.0)), ""); constexpr auto f = overload(&nonMember_throw); static_assert(! noexcept(f(1.0)), ""); } { //overload/include_pass.cpp:468:9: note: non-literal type '(lambda at overload/include_pass.cpp:468:9)' cannot be used in a constant expression constexpr auto f = overload<int>(function_without_state2{} #if defined __GNUC__ and ! defined __clang__ , [](std::string str) { return 1; } #endif ); f(1); } { // overload noexcept #if defined __GNUC__ and ! defined __clang__ static_assert(noexcept(overload(function_without_state{},function_without_state_x{})), ""); #endif auto f = overload(function_without_state{},function_without_state_x{}); f(1); } { #if defined __GNUC__ and ! defined __clang__ static_assert(noexcept(overload(nonMember)), ""); #endif auto f = overload(nonMember, [](std::string str) noexcept { return 1; } ); auto y = f(1.0); BOOST_TEST(42 == y); } { auto f = overload(function_with_no_ref_q{}); f(1); } { auto f = overload(function_with_lvalue_ref_q{}); f(1); } { BOOST_TEST(1 ==function_with_rvalue_ref_q{}(1)); BOOST_TEST(1 ==detail::wrap_call<function_with_rvalue_ref_q>(function_with_rvalue_ref_q{})(1)); auto f = overload(function_with_rvalue_ref_q{}); BOOST_TEST_EQ(3, f(1)); } { BOOST_TEST(1 ==overload(function_with_rvalue_ref_q{})(1)); } { auto f = overload(function_with_ref_q{}); BOOST_TEST(1 ==f(1)); } { detail::wrap_call<final_function_with_rvalue_ref_q>(final_function_with_rvalue_ref_q{})(1); BOOST_TEST(1 ==overload(final_function_with_rvalue_ref_q{})(1)); } { auto f = overload(final_function_with_rvalue_ref_q{}); BOOST_TEST(3 ==f(1)); } { BOOST_TEST(2 == overload(function_with_ref_q{})(1)); } { auto f = overload(function_with_cv_q{}); BOOST_TEST(0 ==f(1)); } { const auto f = overload(function_with_cv_q{}); BOOST_TEST(1 ==f(1)); } { volatile auto f = overload(function_with_cv_q{}); BOOST_TEST(2 ==f(1)); } { const volatile auto f = overload(function_with_cv_q{}); BOOST_TEST(3 ==f(1)); } { constexpr auto f = overload(function_with_cv_q{}); BOOST_TEST(1 ==f(1)); } { BOOST_TEST(0 ==overload(function_with_cv_q{})(1)); } return boost::report_errors(); }
[ "vicente.botet@wanadoo.fr" ]
vicente.botet@wanadoo.fr
943364c6a7846f38e811a010081e671fd60d6ef6
b8487f927d9fb3fa5529ad3686535714c687dd50
/unittests/Parser/JSONParserTest.cpp
656816857be8f2df770522cf7779fdd5472e05cd
[ "MIT" ]
permissive
hoangtuanhedspi/hermes
4a1399f05924f0592c36a9d4b3fd1f804f383c14
02dbf3c796da4d09ec096ae1d5808dcb1b6062bf
refs/heads/master
2020-07-12T21:21:53.781167
2019-08-27T22:58:17
2019-08-27T22:59:55
204,908,743
1
0
MIT
2019-08-28T17:44:49
2019-08-28T10:44:49
null
UTF-8
C++
false
false
5,278
cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ #include "hermes/Parser/JSONParser.h" #include "hermes/Support/JSONEmitter.h" #include "gtest/gtest.h" using namespace hermes; using namespace hermes::parser; namespace { TEST(JSONParserTest, SmokeTest1) { static const char json[] = "{\n" " '6': null,\n" " '1': null,\n" " '2': null,\n" " '3': null,\n" " '4': null,\n" " '5': null\n" "}"; JSLexer::Allocator alloc; JSONFactory factory(alloc); SourceErrorManager sm; JSONParser parser(factory, json, sm); auto parsed = parser.parse(); ASSERT_TRUE(parsed.hasValue()); } TEST(JSONParserTest, SmokeTest2) { JSLexer::Allocator alloc; JSONFactory factory(alloc); SourceErrorManager sm; JSONParser parser( factory, "{" " 'key1' : 1," " 'key2' : 'value2'," " 'key3' : {'nested1': true}," " \"key4\" : [false, null, 'value2']" "}", sm); // Check basic assumptions. ASSERT_STREQ("key4", factory.getString("key4")->c_str()); ASSERT_STREQ("key3", factory.getString("key3")->c_str()); ASSERT_STREQ("key2", factory.getString("key2")->c_str()); ASSERT_STREQ("key1", factory.getString("key1")->c_str()); ASSERT_STREQ("key0", factory.getString("key0")->c_str()); ASSERT_EQ(factory.getNumber(1.0)->getValue(), 1.0); ASSERT_EQ(factory.getString("key2"), factory.getString("key2")); // Parse an object. auto t1 = parser.parse(); ASSERT_TRUE(t1.hasValue()); auto *o1 = llvm::dyn_cast<JSONObject>(t1.getValue()); ASSERT_NE(nullptr, o1); ASSERT_EQ(4u, o1->size()); ASSERT_EQ(0u, o1->count("key0")); ASSERT_EQ(o1->end(), o1->find("key0")); ASSERT_EQ(1u, o1->count("key1")); auto kv1 = o1->find("key1"); ASSERT_NE(o1->end(), kv1); ASSERT_EQ((*kv1).first, factory.getString("key1")); ASSERT_EQ((*kv1).second, factory.getNumber(1.0)); ASSERT_EQ(o1->at("key1"), (*kv1).second); ASSERT_EQ(o1->operator[]("key1"), (*kv1).second); ASSERT_EQ(1u, o1->count("key2")); auto kv2 = o1->find("key2"); ASSERT_NE(o1->end(), kv2); ASSERT_EQ((*kv2).first, factory.getString("key2")); ASSERT_EQ((*kv2).second, factory.getString("value2")); JSONValue *value2 = (*kv2).second; ASSERT_EQ(1u, o1->count("key3")); ASSERT_EQ(1u, o1->count("key4")); // Keys are ordered in insertion order. auto it = o1->begin(); ASSERT_STREQ("key1", (*it).first->c_str()); ASSERT_EQ(o1->find("key1"), it); ++it; ASSERT_STREQ("key2", (*it).first->c_str()); ASSERT_EQ(o1->find("key2"), it); ++it; ASSERT_STREQ("key3", (*it).first->c_str()); ASSERT_EQ(o1->find("key3"), it); ++it; ASSERT_STREQ("key4", (*it).first->c_str()); ASSERT_EQ(o1->find("key4"), it); ++it; ASSERT_EQ(o1->end(), it); // Check the nested object auto *o2 = llvm::dyn_cast<JSONObject>((*o1)["key3"]); ASSERT_NE(nullptr, o2); auto it2 = o2->begin(); ASSERT_STREQ("nested1", (*it2).first->c_str()); ASSERT_EQ(factory.getBoolean(true), (*it2).second); ++it2; ASSERT_EQ(o2->end(), it2); // Check the array auto *a1 = llvm::dyn_cast<JSONArray>(o1->at("key4")); ASSERT_NE(nullptr, a1); ASSERT_EQ(3u, a1->size()); auto it3 = a1->begin(); ASSERT_EQ(*it3, a1->at(0)); ASSERT_EQ(*it3, (*a1)[0]); ASSERT_EQ(*it3, factory.getBoolean(false)); ++it3; ASSERT_EQ(*it3, a1->at(1)); ASSERT_EQ(*it3, factory.getNull()); ++it3; ASSERT_EQ(*it3, a1->at(2)); ASSERT_EQ(value2, *it3); // This also checks the uniquing ++it3; ASSERT_EQ(a1->end(), it3); } TEST(JSONParserTest, HiddenClassTest) { JSLexer::Allocator alloc; JSONFactory factory(alloc); SourceErrorManager sm; JSONParser parser( factory, "[ {'key1': 1, 'key2': {'key2': 5, 'key1': 6}}, " "{'key2': 10, 'key1': 20}]", sm); auto t1 = parser.parse(); ASSERT_TRUE(t1.hasValue()); auto array = llvm::dyn_cast<JSONArray>(t1.getValue()); ASSERT_NE(nullptr, array); ASSERT_EQ(2u, array->size()); auto o1 = llvm::dyn_cast<JSONObject>(array->at(0)); ASSERT_NE(nullptr, o1); auto o2 = llvm::dyn_cast<JSONObject>(o1->at("key2")); ASSERT_NE(nullptr, o2); ASSERT_EQ(o1->getHiddenClass(), o2->getHiddenClass()); auto o3 = llvm::dyn_cast<JSONObject>(array->at(1)); ASSERT_NE(nullptr, o3); ASSERT_EQ(o1->getHiddenClass(), o3->getHiddenClass()); } TEST(JSONParserTest, EmitTest) { JSLexer::Allocator alloc; JSONFactory factory(alloc); SourceErrorManager sm; std::string storage; llvm::raw_string_ostream OS(storage); JSONEmitter emitter(OS); JSONParser parser( factory, "{" " 'key1' : 1," " 'key2' : 'value2'," " 'key3' : {'nested1': true}," " \"key4\" : [false, null, 'value2']" "}", sm); auto t1 = parser.parse(); ASSERT_TRUE(t1.hasValue()); t1.getValue()->emitInto(emitter); // This intermediate variable is necessary because // MSVC's macro preprocessor does not behave as expected with R-literals. const char *expected = R"#({"key1":1,"key2":"value2","key3":{"nested1":true},)#" R"#("key4":[false,null,"value2"]})#"; EXPECT_EQ(OS.str(), expected); } }; // anonymous namespace
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
b7e580f4d93b85a5727b6437c7638e3200a19db8
f157ec8df33573e770d7cf52a8526d21c72f9b48
/LibMerge/Transform.h
361f1356ab0479d1599607e93a9b4278b583ac40
[]
no_license
a995049470/Zero
c98eec3597fd7f07be9e9c2c23cf9c991ad3c3e5
f5cf7fc92193d5e9a8e4b9ac655678c2d4748d0a
refs/heads/master
2020-12-13T23:28:31.473558
2020-03-03T14:55:20
2020-03-03T14:55:20
234,562,129
0
0
null
null
null
null
MacCentralEurope
C++
false
false
855
h
#pragma once #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Quaternion.h" using namespace glm; #define RIGHT vec3(1, 0, 0) #define UP vec3(0, 1, 0) #define FORWARD vec3(0, 0, 1) class Transform { public: Transform(); void Move(vec3 dis); void SetPosition(vec3 _val); vec3 GetPosition(); void SetScale(vec3 _val); vec3 GetScale(); void SetEulerAngle(vec3 _val); vec3 GetEulerAngle(); vec4 GetQuaternion(); mat4 GetModelMatrix(); vec3 GetUpDir(); vec3 GetFrontDir(); vec3 GetRightDir(); void Rotate(vec3 ag); void Rotate(vec3 aixs, float angle); private: Quaternion m_Qua; vec3 m_Position; vec3 m_Scale; // pitch»∆Right–ż◊™ yaw»∆Up–ż◊™ roll »∆Front–ż◊™ bool m_IsDity; mat4 m_ModelMatrix; vec3 m_UpDir; vec3 m_FrontDir; vec3 m_RightDir; };
[ "17855834269@163.com" ]
17855834269@163.com
eb2735fdfd3ec935fca390d4757fa38f129194f0
6dbc8ca5076f632a697cfb4d4ab06c50f4a7d3dc
/meta-tanowrt/conf/distro/include/tanowrt.inc
bfb522121929c11524ce6a46bc4ceac7fac344c1
[ "MIT", "LicenseRef-scancode-unknown" ]
permissive
tano-systems/meta-tanowrt
97487726127121916ce42896d950522eed0a2809
3ff38a82bce33e6d17bb250399d6e5d289917c81
refs/heads/master
2023-03-09T13:25:10.986084
2023-02-27T19:20:18
2023-02-27T19:20:37
135,370,024
30
20
MIT
2022-11-02T10:08:38
2018-05-30T01:11:44
Shell
UTF-8
C++
false
false
2,498
inc
# # SPDX-License-Identifier: MIT # Copyright (c) 2018-2020 Tano Systems LLC. All rights reserved. # require conf/distro/include/tanowrt-toolchain.inc require conf/distro/include/tanowrt-sdk.inc IMAGE_CLASSES += "tanowrt-image-types" # Required for rrdtool 1.0.50 HOSTTOOLS += "pod2man" # Virtual runtimes VIRTUAL-RUNTIME_dev_manager = "udev" VIRTUAL-RUNTIME_login_manager = "busybox" VIRTUAL-RUNTIME_init_manager = "procd" VIRTUAL-RUNTIME_kmod_manager = "ubox" VIRTUAL-RUNTIME_syslog = "rsyslog" VIRTUAL-RUNTIME_base-utils = "busybox" VIRTUAL-RUNTIME_network_manager = "netifd" # Start with default set of distro features DISTRO_FEATURES = "${DISTRO_FEATURES_DEFAULT} ${DISTRO_FEATURES_LIBC}" DISTRO_FEATURES:append = " swupdate " # Set procd as init manager DISTRO_FEATURES:append = " procd " # Enable cgroups support DISTRO_FEATURES:append = " cgroup " # Seccomp support DISTRO_FEATURES:append = " seccomp " # Enable wifi support DISTRO_FEATURES:append = " wifi " # Enable watchdog support DISTRO_FEATURES:append = " watchdog " # Graphics DISTRO_FEATURES:append = " graphics screen splash opengl wayland " # IPv6 DISTRO_FEATURES:append = " ipv6" # Remove sysvinit and systemd from DISTRO_FEATURES DISTRO_FEATURES_BACKFILL_CONSIDERED:append = " sysvinit systemd" # Clean DISTRO_FEATURES DISTRO_FEATURES:remove = "\ 3g \ nfc \ pulseaudio \ bluetooth \ irda \ pcmcia \ bluez5 \ largefile \ sysvinit \ systemd \ pam \ x11 \ " # Licenses LICENSE_FLAGS_ACCEPTED = "commercial_gst-ffmpeg commercial_gstreamer1.0-libav commercial" # Image IMAGE_FSTYPES:remove = "tar.xz.md5" # Root home path ROOT_HOME ??= "/root" # Set preferred Qt version QT_PROVIDER ?= "qt5" require conf/distro/include/tanowrt-packageconfig.inc require conf/distro/include/tanowrt-prefs.inc require conf/distro/include/tanowrt-repairs.inc require conf/distro/include/tanowrt-mirrors.inc require conf/distro/include/tanowrt-swupdate.inc # Unbreak multimachine builds LICENSE_DIRECTORY = "${DEPLOY_DIR}/licenses/${MACHINE_ARCH}" # Distro maintainer MAINTAINER = "TanoWrt Developers <https://github.com/tano-systems/meta-tanowrt>" DISTRO_EXTRA_RRECOMMENDS += "openssh-sftp-server" # Enable cryptodev/devcrypto engine in OpenSSL PACKAGECONFIG:append:pn-openssl = " cryptodev-linux" INHERIT += "do-populate-lic-deps" INHERIT += "tanowrt-paths" # # QEMU # QEMU_TARGETS = "arm aarch64 i386 x86_64" # # Dynamic includes # include conf/distro/include/tanowrt-hw.inc
[ "a.kikin@tano-systems.com" ]
a.kikin@tano-systems.com
1457ea95ff5e724dcaf814f65ce505d0ff9ab275
834511cf7be1baf12df0d58996ba3a9f2ca67ee0
/FitnessClub.h
28e8eb3312eda2240741c439be172e833b54bb3a
[]
no_license
ammonjerro/Fitness_Club
60921d9224a1f5eaf495a806e857852b783a7d48
277472194a526cd74fba5bc8e253bd0e7360fc71
refs/heads/master
2020-12-06T08:40:51.644135
2020-01-08T03:14:30
2020-01-08T03:14:30
232,412,207
0
0
null
null
null
null
UTF-8
C++
false
false
7,059
h
#ifndef FITNESS_CLUB_FITNESSCLUB_H #define FITNESS_CLUB_FITNESSCLUB_H #include <vector> #include <iostream> #include "Member.h" #include "Trainer.h" #include "Consultant.h" #include "Receptionist.h" #include "Contract.h" using namespace std; class FitnessClub{ private: //basic information string name; string address; string city; int openTime; int closeTime; //finance information float totalBudget; float additionalExpenses; //lists of main objects vector <Employee*> Employees; vector <Member*> Members; vector <Contract*> Contracts; static vector<Product*> Products; //Stores the list of products that can be sold by a receptionist public: //Constructor FitnessClub(string name, string address, string city); //Getters and Setters void SetTotalBudget(float value){totalBudget=value;} //Members management void AddMember(int id, string name, string surname, string address, string gender); //Creates and adds member to the member list void RemoveMember(Member* member); //Removes member from the list, and deallocates memory, can only be performed if member doesn't have an active contract Member* FindMember(int id); // Searches for a member of a given ID in vector of Members and returns pointer to it or NULL if wasn't found //Method FindMember has many overloads, to allow searching by various data //Employment management //Methods with returning type bool return true when operation was successful and false otherwise bool EmployTrainer(string name, string surname, string nip, string address, int id, int rank); //creates new Trainer object, assigns its fields with given values, adds it to Trainer list bool EmployConsultant(string name, string surname, string nip, string address, int id, int rank); //creates new Consultant object, assigns its fields with given values, adds it to Trainer list bool EmployReceptionist(string name, string surname, string nip, string address, int id, int rank); //creates new Receptionist object, assigns its fields with given values, adds it to Trainer list void FireEmployee(Employee* emp); //if they have been associated with any contracts it chooses randomly from other employees and changes the pointers, then removes it from the list of employees, and deallocates memory void ResetEmployees(); //invokes each employee's method ResetValues() resets hours worked etc, usually done at the end of the month Trainer* RandomTrainer(); Consultant* RandomConsultant(); bool IdExistsEmployees(int id); bool IdExistsContracts(int id); bool IdExistsMembers(int id); //Methods Find(**) have many overloads, to allow searching by various data, below examples of ones with ID argument Employee* FindEmployee(int id); //searches vector of Employees for the one of a given ID and returns pointer to it or NULL if wasn't found Trainer* FindTrainer(int id); //searches vector of Employees for the one of a given ID and returns pointer to it or NULL if wasn't found Consultant* FindConsultant(int id);//searches vector of Employees for the one of a given ID and returns pointer to it or NULL if wasn't found Receptionist* FindReceptionist(int id);//searches vector of Employees for the one of a given ID and returns pointer to it or NULL if wasn't found void PrintEmployee(Employee* emp); //Uses given employee's override method GetInformation() and prints it in console //string GetInformation(Employee* emp); //Uses given employee's override method GetInformation() //Contracts management bool AddContract(Member* member, Consultant* consultant, Trainer* trainer, int id, float membershipFee, float trainingFee, float terminationFee, int duration); //First validates the arguments(for example if first 3 are not NULL), then creates new Contract object, associates it with given people setting proper pointers, sets values of other fields, adds it to the Contract list bool TerminateContract(Contract* contract); //executes payment following the terms of terminationFee, sets associated member hasContract value to "false", then removes contract from the list, and deallocates memory bool TransferContract(Member* from, Member* to); //first it checks if both members have contracts and determines if operation is possible, then changes given's contract pointer to the latter member and sets proper hasContract values Contract* FindContract(int id); //searches the list of contracts by ID, returns NULL if contract wasn't found Contract* FindContract(Member* member); //searches the list of contracts by member associated with it, returns NULL if contract wasn't found void DeleteContract(Contract* contract); //Removes contract from the list, deallocates memory //Finances management void ChargeMonthlyFee(Contract* contract); //Adds proper amount of funds to totalBudget void ChargeTrainingFee(Contract* contract); //Adds proper amount of funds to totalBudget bool ChargeMembers(); //executes payments on all members - int fact it just uses the methods above on each member(we assume that members have infinite money) bool ChargeTerminationFee(Contract* contract); //Adds proper amount of funds to totalBudget void GatherFromReceptionists(); //For each receptionist employed acquires proper amount of funds from products sold float GetSalary(Employee* emp); //calculates the salary of a given Employee depending on his role in the club bool PaySalary(Employee* emp); //pays to Employee - in fact it just subtracts specific amount from the totalBudget (calculated by GetSalary()) void PaySalaryToAll(); // pays to all Employees - performs PaySalary() to all employees void PayAdditionalExpenses(); // subtracts the value of AdditionalExpenses from totalBudget, which is a simple representation of such expenses like a rent or electricity of a club void SetAdditionalExpenses(float value); //Organization bool setOpenHours(int open, int closed); //changes values of openTime and closeTime void DecrementContractDurations(); void DeleteExpiredContracts(); void NextMonth(); //charges members, pays salaries, resets hours worked, decrements contracts durations, deletes expired contracts string GetInformation(); //creates a string containing information about a club void PrintInformation(); //uses GetInformation and prints it to the console void PrintEmployees(); void PrintMembers(); //Products static bool AddProduct(int id, string name, float price); //creates new Product and adds it to the Products vector; static void RemoveProduct(Product* product); //remove Product from the list, and deallocates memory static bool ChangeProductPrice(Product* product, float newPrice); //changes given product price static Product* FindProduct(int id); //Searches the list of avaliable products in reception by ID, returns NULL if not found; static void PrintProducts(); }; #endif //FITNESS_CLUB_FITNESSCLUB_H
[ "marclisek@gmail.com" ]
marclisek@gmail.com
afcfb69bf8be0a6b8bcb1d2e58fc1808b3a44ac4
e448cc834e8b12f2fecb4609dfdf06c6cf0e15f6
/KeyBinding.cpp
6a64f28a5f3933482b7b2544c50f0dff5485ced4
[]
no_license
julianh2o/Gravity
8d89bca275e4137f980a5733da2ca239ffeb6804
2f8771f527ed6a66b0f78b3bb762e6381e7ad1bd
refs/heads/master
2020-04-28T20:04:20.360150
2009-09-20T04:21:21
2009-09-20T04:21:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
890
cpp
/* * KeyBinding.cpp * Gravity * * Created by Julian on 8/18/09. * Copyright 2009 Julian Hartline. All rights reserved. * */ // This class manages keybindings, bind() is called with a name for the binding // and the SDLKey to be associated with it. check() uses the given KeyState object // to return a boolean based on the state of the keyboard. #include "KeyBinding.h" KeyBinding::KeyBinding() { } // binds a string name to a SDLKey void KeyBinding::bind(std::string s, SDLKey k) { keys[s] = k; } void KeyBinding::unbind(std::string s) { keys.erase(s); } // Returns the state of the keyboard according to the given keystate bool KeyBinding::check(std::string s) { if (keys.find(s) != keys.end()) { return keyDown(keys[s]); } } bool KeyBinding::check(std::string s, SDL_Event event) { if (keys.find(s) != keys.end()) { return event.key.keysym.sym == keys[s]; } }
[ "julianh2o@gmail.com" ]
julianh2o@gmail.com
061fd53f5111a496075c82f454ac2771d42240ad
c301c81f7560125e130a9eb67f5231b3d08a9d67
/lc/lc/2021_target/core/bt/lc_1485_clone_bt_random_ptr.cpp
d9eeb5a8be02d7bbaf144311adbd16a0d29f0ffb
[]
no_license
vikashkumarjha/missionpeace
f55f593b52754c9681e6c32d46337e5e4b2d5f8b
7d5db52486c55b48fe761e0616d550439584f199
refs/heads/master
2021-07-11T07:34:08.789819
2021-07-06T04:25:18
2021-07-06T04:25:18
241,745,271
0
0
null
null
null
null
UTF-8
C++
false
false
2,143
cpp
/** * Definition for a Node. * struct Node { * int val; * Node *left; * Node *right; * Node *random; * Node() : val(0), left(nullptr), right(nullptr), random(nullptr) {} * Node(int x) : val(x), left(nullptr), right(nullptr), random(nullptr) {} * Node(int x, Node *left, Node *right, Node *random) : val(x), left(left), right(right), random(random) {} * }; */ class Solution { public: void dfs(Node *root, unordered_map<Node*,NodeCopy*> &m) { if (!root) return; m[root] = new NodeCopy(root->val); dfs(root->left, m); dfs(root->right, m); } NodeCopy* copyRandomBinaryTree(Node* root) { unordered_map<Node*,NodeCopy*> m; dfs(root, m); for ( auto it : m) { if (it.first) { it.second->left = m[it.first->left]; it.second->right = m[it.first->right]; it.second->random = m[it.first->random]; } } return m[root]; } }; This can be solved with a simple DFS with a HashMap. First we check if the node is null, if not, we check if it's in our map, if not - we create a copy of our current node and run DFS again on the left, right and random nodes. One edge case to notice is that if there's a cycle in the tree (a random pointer looking at previous visited node) then the map would never be filled. To solve this we need to create the CopyNode, and immediately put it in the map. That way, when there's a cycle - we'd just return the node we put in the map and end the infinite loop. NodeCopy* help(Node* root){ if(root==NULL) return NULL; if(mmap.count(root)==1)return mmap[root]; NodeCopy* newroot=new NodeCopy(root->val); mmap[root]=newroot; newroot->left=help(root->left); newroot->right=help(root->right); newroot->random=help(root->random); return newroot; } NodeCopy* copyRandomBinaryTree(Node* root) { return help(root); } unordered_map<Node*, NodeCopy*> mmap;
[ "codingprepviks@gmail.com" ]
codingprepviks@gmail.com
690401a1f966ec107f72ddded2f261c055754e16
92813adb7d3c96ebf96060fb23bc5f0ceb187d1e
/src/qt/bitcoinaddressvalidator.cpp
f077978ae1188f4c3cd633dd6e971cbfbc7390f5
[ "MIT" ]
permissive
needycoin/needycore
9bbe28cc50a0c7884e466e027eb6a31d74bc936b
05c0ce57f27d66c37696a9c5eb3c067120fd68b8
refs/heads/master
2020-08-27T06:52:45.921084
2020-08-04T21:12:46
2020-08-04T21:12:46
258,763,520
1
1
null
null
null
null
UTF-8
C++
false
false
2,711
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018 The Needycoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoinaddressvalidator.h" #include "base58.h" /* Base58 characters are: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" This is: - All numbers except for '0' - All upper-case letters except for 'I' and 'O' - All lower-case letters except for 'l' */ BitcoinAddressEntryValidator::BitcoinAddressEntryValidator(QObject* parent) : QValidator(parent) { } QValidator::State BitcoinAddressEntryValidator::validate(QString& input, int& pos) const { Q_UNUSED(pos); // Empty address is "intermediate" input if (input.isEmpty()) return QValidator::Intermediate; // Correction for (int idx = 0; idx < input.size();) { bool removeChar = false; QChar ch = input.at(idx); // Corrections made are very conservative on purpose, to avoid // users unexpectedly getting away with typos that would normally // be detected, and thus sending to the wrong address. switch (ch.unicode()) { // Qt categorizes these as "Other_Format" not "Separator_Space" case 0x200B: // ZERO WIDTH SPACE case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE removeChar = true; break; default: break; } // Remove whitespace if (ch.isSpace()) removeChar = true; // To next character if (removeChar) input.remove(idx, 1); else ++idx; } // Validation QValidator::State state = QValidator::Acceptable; for (int idx = 0; idx < input.size(); ++idx) { int ch = input.at(idx).unicode(); if (((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) && ch != 'l' && ch != 'I' && ch != '0' && ch != 'O') { // Alphanumeric and not a 'forbidden' character } else { state = QValidator::Invalid; } } return state; } BitcoinAddressCheckValidator::BitcoinAddressCheckValidator(QObject* parent) : QValidator(parent) { } QValidator::State BitcoinAddressCheckValidator::validate(QString& input, int& pos) const { Q_UNUSED(pos); // Validate the passed Needycoin address CBitcoinAddress addr(input.toStdString()); if (addr.IsValid()) return QValidator::Acceptable; return QValidator::Invalid; }
[ "you@example.com" ]
you@example.com
afd3a3e39f0ca62f16c2ba3f71aea24bc23c9d3a
942bc7a374ced8f96a139feac1a01148cc4e60d7
/include/nsbb/nsedilex.h
e6fb31a75e02cb8af4e32a26c88c2270b75f4bb6
[]
no_license
p-ameline/Episodus
915b0dfa324a0b9374b887f0fc9fd74a599b9ae3
8bba0a26e267cff40a7669c6ae47647c68a30834
refs/heads/master
2022-04-07T12:39:09.224028
2020-03-06T09:20:03
2020-03-06T09:20:03
119,287,108
1
3
null
null
null
null
ISO-8859-1
C++
false
false
3,597
h
#ifndef __NSEDILEX_H #define __NSEDILEX_H // #include <owl\owlpch.h> #include <owl\applicat.h> #include "owl\validate.h" #include <string.h> #include <cstring.h> #include "nsbb\nsdicogl.h" #include "nsbb\nsbb_dlg.h" #include "nsbb\nsbbtran.h" #include "nsbb\nsExport.h" // // // class NSEditLexiqueDerive ; class NSContexte ; class _NSBBCLASSE NSEditLexique : public NSEditDicoGlobal { public: NSControle* pControle ; string sContenuPere ; NSEditLexiqueDerive* pNSEdit ; //fils fictif string sComplement ; bool bWinStd ; // Gestion standard windows // // Constructeur et destructeur // NSEditLexique(TWindow* parent, NSContexte* pCtx, int resourceId, NSDico* pDictio, uint textLimit = 0, string sTypeLexique = "", TModule* module = 0) ; NSEditLexique(TWindow* parent, NSContexte* pCtx, int resourceId, NSDico* pDictio, const char far* text, int x, int y, int w, int h, uint textLimit = 0, bool multiline = false, string sTypeLexique = "", TModule* module = 0) ; ~NSEditLexique() ; // // méthodes // void SetupWindow() ; void UpdateDico() ; void SetPositionLexique() ; void ElementSelectionne() ; void EvChar(uint key, uint repeatCount, uint flags) ; void EvKeyDown(uint key, uint repeatCount, uint flags) ; void EvKeyUp(uint key, uint repeatcount, uint flags) ; void EvRButtonDown(uint modKeys, NS_CLASSLIB::TPoint& point) ; void CmEditPaste() ; uint EvGetDlgCode(MSG far* ) ; void EvKillFocus(THandle hWndGetFocus) ; void EvSetFocus(HWND hWndLostFocus) ; WNDTYPE donneType() { return (isEditLexique) ; } uint Transferer(TTransferDirection direction, CTRL_ACTIVITY* pActif, Message* pMessage = 0) ; uint TempTransferer(CTRL_ACTIVITY* pActif, Message* pMessage = 0) ; void activeControle(int activation, Message* pMessage = 0) ; void CreerEditDerive(string sCode, string sContenu) ; void CreerBBItem() ; bool isFreeTextEnabled() { return _bIsFreeTextEnabled ; } void setFreeTextEnabled(bool bT) { _bIsFreeTextEnabled = bT ; } protected: string getTextAsString() ; bool _bIsFreeTextEnabled ; DECLARE_RESPONSE_TABLE(NSEditLexique) ; }; // //classe du controle fictif crée en choisissant un élément dans le lexique // class NSComboSemantique ; class NSEditLexiqueDerive : public NSRoot { public: string sContenuTransfert ; //label dans le champ edit NSControle* pControle ; string sIdentite ; //code lexique NSContexte* pContexte ; string sComplement ; NSEditLexique* pEditPere ; NSComboSemantique* pComboPere ; // // Constructeur et destructeur // NSEditLexiqueDerive(NSContexte* pCtx, NSEditLexique* pEdit) ; NSEditLexiqueDerive(NSContexte* pCtx, NSComboSemantique* pCombo) ; ~NSEditLexiqueDerive() ; // // méthodes // WNDTYPE donneType() { return(isEditLexiqueDerive) ; } virtual uint Transferer(TTransferDirection direction, CTRL_ACTIVITY* pActif, Message* pMessage = 0) ; uint TempTransferer(CTRL_ACTIVITY* pActif, Message* pMessage = 0) ; void activeControle(int activation, Message* pMessage = 0) ; bool canWeClose() ; }; #endif
[ "philippe.ameline@free.fr" ]
philippe.ameline@free.fr
f6543929105126ba6bd6c5c1f60b54f20107d932
db24d9a142f687fbc19f9a1481144bb3f43bd42d
/src/Map/WorldMap.h
fb3cec715d5305ca4fc872f59853f23d4469b737
[]
no_license
jdoolittle126/Cube-Game
26d6047446cd3678666eaa316e054e26f446b67f
2c906b54122b6076c2069b15d7011b97f4896d9f
refs/heads/master
2021-08-08T14:45:52.474381
2020-08-12T02:19:47
2020-08-12T02:19:47
210,674,126
0
0
null
null
null
null
UTF-8
C++
false
false
1,104
h
#pragma once #include "../Managers/GameManager.h" #include "MapTileManager.h" #include "MapTile.h" class WorldMap { private: std::vector<MapTile*> tiles; MapTileManager tile_manager; GLuint vaoId; void build_vao() { glGenVertexArrays(1, &vaoId); glBindVertexArray(vaoId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, UniqueMapTile::eboId); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, UniqueMapTile::vboId); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, UniqueMapTile::nboId); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindVertexArray(0); } public: WorldMap(GLuint textureId) : tile_manager(textureId){ build_vao(); } ~WorldMap() { while(!tiles.empty()) delete tiles.back(), tiles.pop_back(); } void update(float delta); void display(float delta, GameManager & manager); void create_tile(float x, float y, float z, int tex_x, int tex_y); void destroy_tile(float x, float y, float z); std::vector<cube_bound> get_world_bounds(); };
[ "jdoolittle126@gmail.com" ]
jdoolittle126@gmail.com
ee8c65a55f4e824bc15248e76e662b04569be3fa
1fdb58238276134582516207f8282c21732e0f6d
/build-UNEDUCADED-Desktop_Qt_5_12_2_MSVC2017_64bit-Debug/debug/moc_mainwindow.cpp
12a53eb044b349d1f4d2ffd1cf50f092fe8e4076
[]
no_license
dsmMinseo/UNEDUCADED
777cd352adc5651549f2ff932190f0725b10c59f
ece624cbe98d6bb93c697e0c923b26651bb61a46
refs/heads/master
2020-05-03T19:39:39.699059
2019-06-17T05:33:16
2019-06-17T05:33:16
178,788,157
0
2
null
2019-05-24T01:56:05
2019-04-01T04:55:55
C++
UTF-8
C++
false
false
5,488
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'mainwindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../UNEDUCADED/mainwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mainwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.12.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_MainWindow_t { QByteArrayData data[13]; char stringdata0[264]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = { { QT_MOC_LITERAL(0, 0, 10), // "MainWindow" QT_MOC_LITERAL(1, 11, 21), // "on_undoButton_clicked" QT_MOC_LITERAL(2, 33, 0), // "" QT_MOC_LITERAL(3, 34, 21), // "on_redoButton_clicked" QT_MOC_LITERAL(4, 56, 21), // "on_moveButton_clicked" QT_MOC_LITERAL(5, 78, 23), // "on_rotateButton_clicked" QT_MOC_LITERAL(6, 102, 22), // "on_scaleButton_clicked" QT_MOC_LITERAL(7, 125, 21), // "on_flipButton_clicked" QT_MOC_LITERAL(8, 147, 21), // "on_textButton_clicked" QT_MOC_LITERAL(9, 169, 23), // "on_lengthButton_clicked" QT_MOC_LITERAL(10, 193, 22), // "on_colorButton_clicked" QT_MOC_LITERAL(11, 216, 23), // "on_actionFont_triggered" QT_MOC_LITERAL(12, 240, 23) // "on_actionSave_triggered" }, "MainWindow\0on_undoButton_clicked\0\0" "on_redoButton_clicked\0on_moveButton_clicked\0" "on_rotateButton_clicked\0on_scaleButton_clicked\0" "on_flipButton_clicked\0on_textButton_clicked\0" "on_lengthButton_clicked\0on_colorButton_clicked\0" "on_actionFont_triggered\0on_actionSave_triggered" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainWindow[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 11, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 69, 2, 0x08 /* Private */, 3, 0, 70, 2, 0x08 /* Private */, 4, 0, 71, 2, 0x08 /* Private */, 5, 0, 72, 2, 0x08 /* Private */, 6, 0, 73, 2, 0x08 /* Private */, 7, 0, 74, 2, 0x08 /* Private */, 8, 0, 75, 2, 0x08 /* Private */, 9, 0, 76, 2, 0x08 /* Private */, 10, 0, 77, 2, 0x08 /* Private */, 11, 0, 78, 2, 0x08 /* Private */, 12, 0, 79, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<MainWindow *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->on_undoButton_clicked(); break; case 1: _t->on_redoButton_clicked(); break; case 2: _t->on_moveButton_clicked(); break; case 3: _t->on_rotateButton_clicked(); break; case 4: _t->on_scaleButton_clicked(); break; case 5: _t->on_flipButton_clicked(); break; case 6: _t->on_textButton_clicked(); break; case 7: _t->on_lengthButton_clicked(); break; case 8: _t->on_colorButton_clicked(); break; case 9: _t->on_actionFont_triggered(); break; case 10: _t->on_actionSave_triggered(); break; default: ; } } Q_UNUSED(_a); } QT_INIT_METAOBJECT const QMetaObject MainWindow::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data, qt_meta_data_MainWindow, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0)) return static_cast<void*>(this); return QMainWindow::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 11) qt_static_metacall(this, _c, _id, _a); _id -= 11; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 11) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 11; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "20012011ryu@gmail.com" ]
20012011ryu@gmail.com
f1d55defd6b2afd7ac4fafaf7985dd34be2f1b5a
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.8/cbear.berlios.de/windows/int_ptr.hpp
99b3b1f1769f9193b4ef825c7c4951f66e9407bd
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
386
hpp
#ifndef CBEAR_BERLIOS_DE_WINDOWS_INT_PTR_HPP_INCLUDED #define CBEAR_BERLIOS_DE_WINDOWS_INT_PTR_HPP_INCLUDED #include <cbear.berlios.de/windows/basetsd.h> namespace cbear_berlios_de { namespace windows { // Signed integral type for pointer precision. Use when casting a pointer to an // integer to perform pointer arithmetic. typedef INT_PTR int_ptr_t; } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838
eb61fb621cac61358a38b74a2c3f9c0a0310c984
8cc6d6f590285ef00e0f30e0151c4d407847b651
/build_test/windows-build/Sources/include/armory/trait/ConvexBreaker.h
73c71d61ec87e6029362ef7272ccfffd60f96263
[]
no_license
piboistudios/ArmoryDeformIssues
e087d5097af74f958fd89dd8dd17ca57627bf6d1
84e8b14c5098a4a4db310c5177c5dcd46f40212d
refs/heads/master
2020-03-24T11:42:11.270376
2018-07-28T16:33:45
2018-07-28T16:33:45
142,692,926
0
0
null
null
null
null
UTF-8
C++
false
true
4,230
h
// Generated by Haxe 3.4.4 (git build master @ 99b08bb) #ifndef INCLUDED_armory_trait_ConvexBreaker #define INCLUDED_armory_trait_ConvexBreaker #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS2(armory,trait,ConvexBreaker) HX_DECLARE_CLASS2(armory,trait,CutResult) HX_DECLARE_CLASS2(armory,trait,Line3) HX_DECLARE_CLASS2(armory,trait,Plane) HX_DECLARE_CLASS1(haxe,IMap) HX_DECLARE_CLASS2(haxe,ds,ObjectMap) HX_DECLARE_CLASS2(iron,data,Data) HX_DECLARE_CLASS2(iron,data,MeshData) HX_DECLARE_CLASS2(iron,math,Mat4) HX_DECLARE_CLASS2(iron,math,Vec4) HX_DECLARE_CLASS2(iron,object,MeshObject) HX_DECLARE_CLASS2(iron,object,Object) namespace armory{ namespace trait{ class HXCPP_CLASS_ATTRIBUTES ConvexBreaker_obj : public hx::Object { public: typedef hx::Object super; typedef ConvexBreaker_obj OBJ_; ConvexBreaker_obj(); public: enum { _hx_ClassId = 0x45a066b1 }; void __construct(hx::Null< Float > __o_minSizeForBreak,hx::Null< Float > __o_smallDelta); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="armory.trait.ConvexBreaker") { return hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return hx::Object::operator new(inSize+extra,true,"armory.trait.ConvexBreaker"); } static hx::ObjectPtr< ConvexBreaker_obj > __new(hx::Null< Float > __o_minSizeForBreak,hx::Null< Float > __o_smallDelta); static hx::ObjectPtr< ConvexBreaker_obj > __alloc(hx::Ctx *_hx_ctx,hx::Null< Float > __o_minSizeForBreak,hx::Null< Float > __o_smallDelta); static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); //~ConvexBreaker_obj(); HX_DO_RTTI_ALL; hx::Val __Field(const ::String &inString, hx::PropertyAccess inCallProp); static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp); hx::Val __SetField(const ::String &inString,const hx::Val &inValue, hx::PropertyAccess inCallProp); static bool __SetStatic(const ::String &inString, Dynamic &ioValue, hx::PropertyAccess inCallProp); void __GetFields(Array< ::String> &outFields); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); bool _hx_isInstanceOf(int inClassId); ::String __ToString() const { return HX_HCSTRING("ConvexBreaker","\x25","\x36","\x4a","\x83"); } static void __boot(); static int meshIndex; Float minSizeForBreak; Float smallDelta; ::armory::trait::Line3 tempLine; ::armory::trait::Plane tempPlane; ::armory::trait::Plane tempPlane2; ::iron::math::Vec4 tempCM1; ::iron::math::Vec4 tempCM2; ::iron::math::Vec4 tempVec4; ::iron::math::Vec4 tempVec42; ::iron::math::Vec4 tempVec43; ::armory::trait::CutResult tempCutResult; ::Array< bool > segments; ::haxe::ds::ObjectMap userDataMap; void initBreakableObject( ::iron::object::MeshObject object,Float mass, ::iron::math::Vec4 velocity, ::iron::math::Vec4 angularVelocity,bool breakable); ::Dynamic initBreakableObject_dyn(); ::Array< ::Dynamic> subdivideByImpact( ::iron::object::MeshObject object, ::iron::math::Vec4 pointOfImpact, ::iron::math::Vec4 normal,int maxRadialIterations,int maxRandomIterations); ::Dynamic subdivideByImpact_dyn(); ::iron::math::Vec4 transformFreeVector( ::iron::math::Vec4 v, ::iron::math::Mat4 m); ::Dynamic transformFreeVector_dyn(); ::iron::math::Vec4 transformFreeVectorInverse( ::iron::math::Vec4 v, ::iron::math::Mat4 m); ::Dynamic transformFreeVectorInverse_dyn(); ::iron::math::Vec4 transformTiedVectorInverse( ::iron::math::Vec4 v, ::iron::math::Mat4 m); ::Dynamic transformTiedVectorInverse_dyn(); void transformPlaneToLocalSpace( ::armory::trait::Plane plane, ::iron::math::Mat4 m, ::armory::trait::Plane resultPlane); ::Dynamic transformPlaneToLocalSpace_dyn(); int cutByPlane( ::iron::object::MeshObject object, ::armory::trait::Plane plane, ::armory::trait::CutResult output); ::Dynamic cutByPlane_dyn(); ::iron::data::MeshData makeMeshData(::Array< ::Dynamic> points); ::Dynamic makeMeshData_dyn(); }; } // end namespace armory } // end namespace trait #endif /* INCLUDED_armory_trait_ConvexBreaker */
[ "gabriel.speed.bullock@gmail.com" ]
gabriel.speed.bullock@gmail.com